From 5f04861ed428e549c230964012270891f3eaced7 Mon Sep 17 00:00:00 2001 From: josh-sanders Date: Mon, 9 Nov 2026 22:04:43 +1000 Subject: [PATCH 1/2] Fix CodeRabbit's transport findings; equal-length names differed - NO_PROXY=* sends every host direct (Ruby's use_proxy? proxies it). - Every attempt checks the call's budget first, so requests RubyLLM doesn't send (the models list) aren't sent once it's spent, and each request's timeout is cut to what's left of the budget. - same_model? used minmax_by, which returns one element for both ends when the names are the same length, so any two equal-length names matched. Two qualified ids now keep their namespaces. - Anthropic's 404 "model: " is ModelMissing on chat and tool probes too, not only the models lookup. - A negative or non-finite cost is dropped, so the usage row is kept and its cost estimated. - An embedding response RubyLLM can't parse is InvalidOutput. Co-Authored-By: Claude Opus 5.5 --- app/models/ai/tokens.rb | 6 +++- app/models/ai/transport/anthropic.rb | 7 ++-- app/models/ai/transport/base.rb | 26 ++++++++++++-- app/models/ai/transport/compatible.rb | 4 +++ app/models/ai/transport/http.rb | 4 +-- app/models/ai/transport/ruby_llm_adapter.rb | 13 ++++++- .../ai_transport_contract_test.rb | 34 ++++++++++++++++++- test/models/ai/call_context_test.rb | 17 ++++++++++ test/models/ai/tokens_test.rb | 6 ++++ test/models/ai/transport/http_test.rb | 5 +++ 10 files changed, 109 insertions(+), 13 deletions(-) diff --git a/app/models/ai/tokens.rb b/app/models/ai/tokens.rb index 0848c8db78..1002cedc2d 100644 --- a/app/models/ai/tokens.rb +++ b/app/models/ai/tokens.rb @@ -21,10 +21,14 @@ Ai::Tokens = Data.define(:input_tokens, :output_tokens, :cache_read_tokens, :cac output_tokens: tokens&.output, cache_read_tokens: tokens&.cache_read, cache_write_tokens: tokens&.cache_write, - cost: reported || total + cost: valid_cost(reported) || valid_cost(total) ) end + # A negative or non-finite cost would fail LlmUsage's validation and lose the row; without + # one the subscriber estimates from the tokens. + def self.valid_cost(value) = value.is_a?(Numeric) && value.finite? && value >= 0 ? value : nil + def known? = [ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens ].any? def prompt_tokens = sum(sum(input_tokens, cache_read_tokens), cache_write_tokens) diff --git a/app/models/ai/transport/anthropic.rb b/app/models/ai/transport/anthropic.rb index 3ec42cee39..04aee97d47 100644 --- a/app/models/ai/transport/anthropic.rb +++ b/app/models/ai/transport/anthropic.rb @@ -38,14 +38,11 @@ class Ai::Transport::Anthropic < Ai::Transport::Base end end - # Anthropic answers an unknown model with a 404 `not_found_error` whose message is - # "model: "; any other 404 (a wrong base URL, a gateway's own page) maps by its status. # A body that isn't Anthropic's error shape still maps by its status. def models_error(status, body) error = body.is_a?(Hash) ? body["error"] : nil - type, message = error.is_a?(Hash) ? error.values_at("type", "message") : [ nil, error&.to_s ] - message = message.presence || "HTTP #{status}" - return Ai::Error::ModelMissing.new(message, status:) if status == 404 && type == "not_found_error" && message.start_with?("model:") + message = (error.is_a?(Hash) ? error["message"] : error&.to_s).presence || "HTTP #{status}" + return Ai::Error::ModelMissing.new(message, status:) if missing_model?(status, body) Ai::Error.from_status(status, message, body:) end diff --git a/app/models/ai/transport/base.rb b/app/models/ai/transport/base.rb index f09a74b86f..a3bbaa73f8 100644 --- a/app/models/ai/transport/base.rb +++ b/app/models/ai/transport/base.rb @@ -35,7 +35,7 @@ class Ai::Transport::Base raise ArgumentError, "unknown probe check #{check.inspect}" unless PROBE_CHECKS.include?(check) Ai::CallContext.call(feature: :probe, model:, budget: timeout) do - instrument("probe", model:, request: { check: }) { attempt { run_probe(model, check, timeout:) } } + instrument("probe", model:, request: { check: }) { attempt { run_probe(model, check, timeout: within_budget(timeout)) } } end end @@ -49,6 +49,7 @@ class Ai::Transport::Base tries = 0 begin tries += 1 + check_budget! yield rescue *Ai::Error::RETRYABLE => error delay = retry_delay(tries) @@ -60,6 +61,19 @@ class Ai::Transport::Base end end + # Requests RubyLLM doesn't send, such as the models list, aren't checked by its instrumenter. + def check_budget! + return unless Ai::CallContext.current&.expired? + + raise Ai::Error::Timeout, "the attempt's time budget was spent before the request was sent" + end + + # A request's timeout, cut to what's left of the call's budget, so a retry can't outlast it. + def within_budget(timeout) + remaining = Ai::CallContext.current&.remaining + remaining ? [ timeout, remaining.ceil ].min : timeout + end + def retry_delay(tries) = [ 0.5 * (2**(tries - 1)), 8 ].min * (0.75 + rand * 0.5) # One `.ai` event per call, carrying what subscribers need: the route, the @@ -100,10 +114,16 @@ class Ai::Transport::Base # The same model under a vendor prefix (openai/gpt-4.1), a snapshot date (gpt-4.1-2025-04-14, # claude-sonnet-4-5-20250929, gpt-4-0613) or for a `latest` alias. Any other difference is # another model: gpt-4.1-mini isn't gpt-4.1, nor gpt-4o gpt-4. + # Two qualified ids (org-a/model, org-b/model) keep their namespaces. def same_model?(asked, answered) - short, long = [ asked, answered ].map { model_stem(_1) }.minmax_by(&:length) + qualified = [ asked, answered ].all? { _1.to_s.include?("/") } + short, long = [ asked, answered ].map { model_stem(_1, qualified:) }.sort_by(&:length) short == long || (long.start_with?(short) && long.delete_prefix(short).match?(SNAPSHOT_SUFFIX)) end - def model_stem(name) = name.to_s.downcase.split("/").last.to_s.delete_suffix(":latest").delete_suffix("-latest") + def model_stem(name, qualified: false) + stem = name.to_s.downcase + stem = stem.split("/").last.to_s unless qualified + stem.delete_suffix(":latest").delete_suffix("-latest") + end end diff --git a/app/models/ai/transport/compatible.rb b/app/models/ai/transport/compatible.rb index 1442cc2b19..6880f7a4a5 100644 --- a/app/models/ai/transport/compatible.rb +++ b/app/models/ai/transport/compatible.rb @@ -32,6 +32,10 @@ class Ai::Transport::Compatible < Ai::Transport::Base embedding = mapping_errors do ruby_llm_context(timeout:).embed(Ai::Transport::Base::PROBE_EMBEDDING_INPUT, model: model.name, provider: ruby_llm_provider, assume_model_exists: true) + rescue NoMethodError, TypeError => error + raise unless raised_in_ruby_llm?(error) + + raise Ai::Error::InvalidOutput, "the embedding response isn't the expected shape" end vectors = embedding.vectors vectors = [ vectors ] if vectors.first.is_a?(Numeric) diff --git a/app/models/ai/transport/http.rb b/app/models/ai/transport/http.rb index 9144b7d490..34d0f9cecf 100644 --- a/app/models/ai/transport/http.rb +++ b/app/models/ai/transport/http.rb @@ -17,7 +17,7 @@ module Ai::Transport::Http # The proxy URL for a request to `url`, or nil to go direct: HTTPS_PROXY, then HTTP_PROXY, # whatever the target's scheme, so a setup that sets only one still covers every call. # Loopback is never proxied, as Ruby's own lookup does; NO_PROXY matches a host exactly as - # written, so `127.0.0.1` doesn't cover `localhost`. + # written, so `127.0.0.1` doesn't cover `localhost`, and `*` means every host, as curl reads it. def proxy_for(url, env: ENV) uri = parse(url) return if uri&.host.blank? || loopback?(uri.host) @@ -26,7 +26,7 @@ module Ai::Transport::Http return if proxy.nil? no_proxy = env["NO_PROXY"].presence || env["no_proxy"].presence - return if no_proxy && !URI::Generic.use_proxy?(uri.host, uri.host, uri.port, no_proxy) + return if no_proxy && (no_proxy.strip == "*" || !URI::Generic.use_proxy?(uri.host, uri.host, uri.port, no_proxy)) proxy end diff --git a/app/models/ai/transport/ruby_llm_adapter.rb b/app/models/ai/transport/ruby_llm_adapter.rb index 0f88668297..59796a7d03 100644 --- a/app/models/ai/transport/ruby_llm_adapter.rb +++ b/app/models/ai/transport/ruby_llm_adapter.rb @@ -77,9 +77,11 @@ module Ai::Transport::RubyLlmAdapter # a request every model would refuse. Any other ArgumentError, such as a wrong call from Sure's # own code, is a bug and stays one. def refused_by_ruby_llm?(error) - error.backtrace_locations&.first&.path.to_s.start_with?(RUBY_LLM_PATH) && !error.message.match?(ARITY_ERROR) + raised_in_ruby_llm?(error) && !error.message.match?(ARITY_ERROR) end + def raised_in_ruby_llm?(error) = error.backtrace_locations&.first&.path.to_s.start_with?(RUBY_LLM_PATH) + # A raised error as mapping_errors would raise it, or nil when it has no Ai::Error. def mapped_error(error) mapped = error.is_a?(Ai::Error::Base) ? error : ruby_llm_error(error) @@ -110,11 +112,20 @@ module Ai::Transport::RubyLlmAdapter klass ||= connection_error_class(error) return klass.new(error.message, status:) if klass + return Ai::Error::ModelMissing.new(error.message, status:) if missing_model?(status, body) return Ai::Error.from_status(status || 400, error.message, body:) if error.is_a?(RubyLLM::Error) Ai::Error.from_exception(error) end + # Anthropic answers an unknown model with a 404 `not_found_error` whose message is + # "model: "; any other 404 (a wrong base URL, a gateway's own page) maps by its status. + def missing_model?(status, body) + body = JSON.parse(body) rescue nil if body.is_a?(String) + error = body.is_a?(Hash) ? body["error"] : nil + status == 404 && error.is_a?(Hash) && error["type"] == "not_found_error" && error["message"].to_s.start_with?("model:") + end + # RubyLLM 2.2 raises RubyLLM::ConnectionError (with `timeout?`) where 2.1.1 lets Faraday's # errors through (RubyLLM #1407); Ai::Error.from_exception handles the 2.1.1 ones. def connection_error_class(error) diff --git a/test/architecture/ai_transport_contract_test.rb b/test/architecture/ai_transport_contract_test.rb index 65e8a5f9fd..a49ad7b950 100644 --- a/test/architecture/ai_transport_contract_test.rb +++ b/test/architecture/ai_transport_contract_test.rb @@ -104,7 +104,8 @@ class AiTransportContractTest < ActiveSupport::TestCase end test "#{protocol}: a dated snapshot of the model passes the probe; a sibling model doesn't" do - { "test-model-2025-04-14" => true, "vendor/test-model-20250929" => true, "test-model-mini" => false, "test-model2" => false }.each do |answered, same| + { "test-model-2025-04-14" => true, "vendor/test-model-20250929" => true, "test-model-mini" => false, "test-model2" => false, + "test-model-o" => false }.each do |answered, same| stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].merge(model: answered).to_json) if same @@ -188,6 +189,37 @@ class AiTransportContractTest < ActiveSupport::TestCase end end + test "two qualified ids are the same model only within one namespace" do + transport = Ai::Transport.for(ai_endpoint(name: "gw", base_url: "https://llm.example.test/v1")) + + assert transport.send(:same_model?, "org-a/model-x", "org-a/model-x-2025-04-14") + assert_not transport.send(:same_model?, "org-a/model-x", "org-b/model-x") + assert transport.send(:same_model?, "model-x", "org-b/model-x") + end + + test "two different names of the same length are different models" do + transport = Ai::Transport.for(ai_endpoint(name: "gw", base_url: "https://llm.example.test/v1")) + + assert_not transport.send(:same_model?, "gpt-4o", "gpt-41") + assert_not transport.send(:same_model?, "test-model", "loaded-mod") + end + + test "anthropic: a chat probe for a model the API doesn't have is ModelMissing" do + stub_request(:post, TRANSPORTS[:anthropic][:url]).to_return( + status: 404, headers: JSON_HEADERS, body: TRANSPORTS[:anthropic][:error].("model: test-model", "not_found_error").to_json + ) + + assert_raises(Ai::Error::ModelMissing) { probe(:anthropic, :chat) } + assert_raises(Ai::Error::ModelMissing) { probe(:anthropic, :tools) } + end + + test "an embedding response that isn't the expected shape is InvalidOutput" do + model_endpoint = ai_endpoint(name: "embed", base_url: "https://llm.example.test/v1") + stub_request(:post, "https://llm.example.test/v1/embeddings").to_return(status: 200, headers: JSON_HEADERS, body: "{}") + + assert_raises(Ai::Error::InvalidOutput) { Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), :embedding) } + end + test "a models list with an entry that isn't an object is InvalidOutput" do Ai::Transport::Http.stubs(:openai_client).returns(stub(models: stub(list: { "data" => [ nil ] }))) model_endpoint = ai_endpoint(name: "listing", base_url: "https://llm.example.test/v1") diff --git a/test/models/ai/call_context_test.rb b/test/models/ai/call_context_test.rb index e08c6db1d7..89bbcf920b 100644 --- a/test/models/ai/call_context_test.rb +++ b/test/models/ai/call_context_test.rb @@ -60,6 +60,23 @@ class Ai::CallContextTest < ActiveSupport::TestCase assert_equal 1, tries end + test "a request outside RubyLLM, such as the models list, isn't sent once the budget is spent" do + model = ai_model(name: "test-model") + Ai::Transport::Http.expects(:openai_client).never + + with_ai_call_context(model:, budget: 0) do + assert_raises(Ai::Error::Timeout) { Ai::Transport.for(model.endpoint).send(:attempt) { Ai::Transport::Http.openai_client(model.endpoint) } } + end + end + + test "each attempt's request timeout is cut to what's left of the budget" do + model = ai_model(name: "test-model") + transport = Ai::Transport.for(model.endpoint) + + with_ai_call_context(model:, budget: 3) { assert_operator transport.send(:within_budget, 60), :<=, 3 } + assert_equal 60, transport.send(:within_budget, 60) + end + test "the instrumenter forwards every event to RubyLLM's own instrumenter" do delegate = mock delegate.expects(:instrument).with("chat.ruby_llm", { a: 1 }).yields.returns(:done) diff --git a/test/models/ai/tokens_test.rb b/test/models/ai/tokens_test.rb index 08fc9f1a5e..b9f7e1f3eb 100644 --- a/test/models/ai/tokens_test.rb +++ b/test/models/ai/tokens_test.rb @@ -30,4 +30,10 @@ class Ai::TokensTest < ActiveSupport::TestCase assert_in_delta 0.0042, Ai::Tokens.from_ruby_llm(tokens, 9.99).cost assert_in_delta 0.5, Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1), 0.5).cost end + + test "a negative or non-finite cost is dropped, so the row is kept and its cost estimated" do + assert_in_delta 0.5, Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1, reported_cost: -0.1), 0.5).cost + assert_nil Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1), -1).cost + assert_nil Ai::Tokens.from_ruby_llm(RubyLLM::Tokens.new(input: 1), Float::NAN).cost + end end diff --git a/test/models/ai/transport/http_test.rb b/test/models/ai/transport/http_test.rb index 8ee3388f5d..d05f7ba02d 100644 --- a/test/models/ai/transport/http_test.rb +++ b/test/models/ai/transport/http_test.rb @@ -28,6 +28,11 @@ class Ai::Transport::HttpTest < ActiveSupport::TestCase assert_equal PROXY, Http.proxy_for("http://other.lan:8080", env:) end + test "NO_PROXY=* sends every host direct" do + assert_nil Http.proxy_for("https://api.openai.com", env: { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "*" }) + assert_nil Http.proxy_for("http://llm.lan:8080", env: { "HTTP_PROXY" => PROXY, "no_proxy" => " * " }) + end + test "the models list goes to the same server as the chat calls it checks" do full = Ai::Config::Endpoint.new(name: "gw", protocol: :compatible, base_url: "https://gw.example.test/v1/chat/completions", api_key: "k") openrouter = Ai::Config::Endpoint.new(name: "or", protocol: :compatible, preset: :openrouter, api_key: "or-key") From 4a27814e18b4a0545d1abb85d7861a060844c03b Mon Sep 17 00:00:00 2001 From: josh-sanders Date: Mon, 9 Nov 2026 22:34:13 +1000 Subject: [PATCH 2/2] Don't round a retry's timeout up; a late answer is a Timeout within_budget rounded the remaining budget up, so 0.2 s left gave a retry a full second, and attempt accepted an answer that arrived after the deadline. The timeout is now the exact time left, and attempt checks the budget again once the answer is in. Co-Authored-By: Claude Opus 5.5 --- app/models/ai/transport/base.rb | 11 +++++++---- test/models/ai/call_context_test.rb | 14 +++++++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/app/models/ai/transport/base.rb b/app/models/ai/transport/base.rb index a3bbaa73f8..ac14904357 100644 --- a/app/models/ai/transport/base.rb +++ b/app/models/ai/transport/base.rb @@ -50,7 +50,9 @@ class Ai::Transport::Base begin tries += 1 check_budget! - yield + result = yield + check_budget!(after: true) + result rescue *Ai::Error::RETRYABLE => error delay = retry_delay(tries) remaining = Ai::CallContext.current&.remaining @@ -62,16 +64,17 @@ class Ai::Transport::Base end # Requests RubyLLM doesn't send, such as the models list, aren't checked by its instrumenter. - def check_budget! + # After an attempt too, so an answer that arrives late isn't taken as a pass. + def check_budget!(after: false) return unless Ai::CallContext.current&.expired? - raise Ai::Error::Timeout, "the attempt's time budget was spent before the request was sent" + raise Ai::Error::Timeout, "the attempt's time budget was spent #{after ? "before the answer arrived" : "before the request was sent"}" end # A request's timeout, cut to what's left of the call's budget, so a retry can't outlast it. def within_budget(timeout) remaining = Ai::CallContext.current&.remaining - remaining ? [ timeout, remaining.ceil ].min : timeout + remaining ? [ timeout, remaining ].min : timeout end def retry_delay(tries) = [ 0.5 * (2**(tries - 1)), 8 ].min * (0.75 + rand * 0.5) diff --git a/test/models/ai/call_context_test.rb b/test/models/ai/call_context_test.rb index 89bbcf920b..49eff1fd14 100644 --- a/test/models/ai/call_context_test.rb +++ b/test/models/ai/call_context_test.rb @@ -73,10 +73,22 @@ class Ai::CallContextTest < ActiveSupport::TestCase model = ai_model(name: "test-model") transport = Ai::Transport.for(model.endpoint) - with_ai_call_context(model:, budget: 3) { assert_operator transport.send(:within_budget, 60), :<=, 3 } + with_ai_call_context(model:, budget: 0.2) { assert_operator transport.send(:within_budget, 60), :<=, 0.2 } assert_equal 60, transport.send(:within_budget, 60) end + test "an answer that arrives after the budget is spent is a Timeout, not a pass" do + model = ai_model(name: "test-model") + transport = Ai::Transport.for(model.endpoint) + + with_ai_call_context(model:, budget: 1) do |call| + error = assert_raises(Ai::Error::Timeout) do + transport.send(:attempt) { Ai::CallContext.stubs(:now).returns(call.deadline + 0.1); :ok } + end + assert_match(/before the answer arrived/, error.message) + end + end + test "the instrumenter forwards every event to RubyLLM's own instrumenter" do delegate = mock delegate.expects(:instrument).with("chat.ruby_llm", { a: 1 }).yields.returns(:done)