Fix 2a findings from the #4774 review

- A RubyLLM request from a thread started inside a call wrote no usage
  row: RubyLLM 2.1.1 keeps the workflow in Thread.current. The usage
  subscriber falls back to Sure's call context, which threads inherit.
- An embedding endpoint with static headers is refused: RubyLLM 2.1.1's
  embed can't send them (crmne/ruby_llm#1556).
- A 200 that RubyLLM can't parse (an HTML page, `{}`) is InvalidOutput
  for every probe, not only embeddings.
- A failed request's error that has no Ai::Error is scrubbed before it
  goes on the request event.
- The usage page says call rows include requests outside the dates.
- The Anthropic PDF client's comment says it ignores SSL_VERIFY too.
- Tests: usage from a child thread, an unpriced call in the average,
  the proxy RubyLLM's own connection uses, NO_PROXY cleared in setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
josh-sanders
2026-11-09 23:26:14 +10:00
co-authored by Claude Opus 5.5
parent 4a27814e18
commit 6dd8328ee8
11 changed files with 79 additions and 16 deletions
@@ -18,9 +18,21 @@ class Ai::Instrumentation::UsageSubscriber
end
private
def record_request(payload)
family = payload[:owner]
# RubyLLM 2.1.1 keeps the usage owner and workflow in Thread.current, so a request from a thread
# started inside a call has neither (2.2 moves them to fiber storage, RubyLLM #1327). Sure's
# own call context is in fiber storage, which threads inherit, so it fills the gap.
def owner_and_call(payload)
call = (payload[:workflow_metadata] || {}).to_h.stringify_keys
return [ payload[:owner], call ] if call["call_id"].present?
context = Ai::CallContext.current
return [ payload[:owner], call ] if context.nil?
[ payload[:owner] || (Family.find_by(id: context.family_id) if context.family_id), context.metadata.stringify_keys ]
end
def record_request(payload)
family, call = owner_and_call(payload)
return unless family.is_a?(Family) && call["call_id"].present?
status = STATUSES.fetch(payload[:status], nil)
+6 -4
View File
@@ -28,14 +28,16 @@ class Ai::Transport::Compatible < Ai::Transport::Base
# One vector per text, with the model's dimensions. RubyLLM 2.1.1 doesn't check the row
# count itself (2.2 does, RubyLLM #1297).
# RubyLLM 2.1.1's embed takes no headers (crmne/ruby_llm#1556), so an endpoint that needs
# them is refused rather than probed without them.
def probe_embedding(model, timeout:)
if Ai::Transport::Http.headers(endpoint).any?
raise Ai::Error::Refused, "embedding requests can't carry the endpoint's static headers yet"
end
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)
+3 -1
View File
@@ -69,7 +69,9 @@ module Ai::Transport::Http
::OpenAI::Client.new(**options, &faraday_options(base || OPENAI_BASE))
end
# The anthropic gem's client, for the Anthropic PDF probe, as PDF import uses it. It takes no proxy.
# The anthropic gem's client, for the Anthropic PDF probe, as PDF import uses it. It takes no
# proxy or TLS options, so it ignores HTTPS_PROXY and SSL_VERIFY=false, as PDF import does
# until it moves onto RubyLLM.
def anthropic_client(endpoint, timeout: endpoint.timeout_seconds)
options = { api_key: endpoint.api_key.to_s, max_retries: 0, timeout: }
options[:base_url] = endpoint.base_url if endpoint.base_url.present?
+7 -3
View File
@@ -3,10 +3,12 @@
# after the call's deadline isn't sent, and a failed request's mapped, scrubbed error goes on the
# payload as `:ai_error`, which UsageSubscriber adds to that request's usage row.
class Ai::Transport::Instrumenter
# map_error: turns a raised error into the Ai::Error the transport raises, scrubbed.
def initialize(delegate = ActiveSupport::Notifications, map_error: ->(error) { error })
# map_error: turns a raised error into the Ai::Error the transport raises, scrubbed, or nil.
# scrub: removes the endpoint's secrets from an error that has no Ai::Error.
def initialize(delegate = ActiveSupport::Notifications, map_error: ->(error) { error }, scrub: ->(text) { text })
@delegate = delegate
@map_error = map_error
@scrub = scrub
end
def instrument(name, payload = {}, &block)
@@ -33,7 +35,9 @@ class Ai::Transport::Instrumenter
end
def failure_details(error)
mapped = @map_error.call(error) || error
mapped = @map_error.call(error)
return { error: @scrub.call(error.message), error_class: error.class.name } if mapped.nil?
{ error: mapped.message, error_class: mapped.class.name, http_status_code: mapped.try(:status) }.compact
rescue StandardError
nil
+6 -1
View File
@@ -22,7 +22,7 @@ module Ai::Transport::RubyLlmAdapter
config.http_proxy = Ai::Transport::Http.proxy_for(ruby_llm_api_base)
config.faraday_adapter = Ai::Transport::Http.ruby_llm_adapter
config.auto_upload_large_files = false
config.instrumenter = Ai::Transport::Instrumenter.new(config.instrumenter, map_error: method(:mapped_error))
config.instrumenter = Ai::Transport::Instrumenter.new(config.instrumenter, map_error: method(:mapped_error), scrub: scrubber)
configure_provider(config)
end
end
@@ -68,6 +68,11 @@ module Ai::Transport::RubyLlmAdapter
raise unless refused_by_ruby_llm?(error)
raise scrubbed(Ai::Error::Refused.new(error.message))
rescue NoMethodError, TypeError => error
# RubyLLM parsing a 200 that isn't the API's shape (`{}`, an HTML page); in Sure's own code it's a bug.
raise unless raised_in_ruby_llm?(error)
raise Ai::Error::InvalidOutput, "the response isn't the expected shape"
rescue StandardError => error
mapped = ruby_llm_error(error)
raise mapped ? scrubbed(mapped) : error
+2 -1
View File
@@ -105,7 +105,8 @@
<!-- Recent Usage Table -->
<div>
<h2 class="text-lg font-semibold text-primary mb-3"><%= t(".recent_usage") %></h2>
<h2 class="text-lg font-semibold text-primary mb-1"><%= t(".recent_usage") %></h2>
<p class="text-xs text-secondary mb-3"><%= t(".recent_usage_scope") %></p>
<div class="table-scroll rounded-lg" tabindex="0" role="region" aria-label="<%= t(".recent_usage") %>">
<% if @llm_calls.any? %>
<table class="w-full">
+1
View File
@@ -106,6 +106,7 @@ en:
cost_by_operation: "Cost by Operation"
cost_by_model: "Cost by Model"
recent_usage: "Recent Usage"
recent_usage_scope: "Each call shows all its requests, even ones outside the selected dates, so its total can differ from the totals above, which count only requests in the range."
col_date: "Date"
col_operation: "Operation"
col_model: "Model"
@@ -153,9 +153,12 @@ class AiTransportContractTest < ActiveSupport::TestCase
test "#{protocol}: requests go through the resolved proxy" do
stub_request(:post, spec[:url]).to_return(status: 200, headers: JSON_HEADERS, body: spec[:ok].to_json)
with_env_overrides("HTTPS_PROXY" => "http://proxy.internal:8888", "HTTP_PROXY" => nil) do
with_env_overrides("HTTPS_PROXY" => "http://proxy.internal:8888", "HTTP_PROXY" => nil, "NO_PROXY" => nil, "no_proxy" => nil) do
transport = Ai::Transport.for(endpoint(protocol))
assert_equal "http://proxy.internal:8888", transport.send(:ruby_llm_context).config.http_proxy
# The proxy RubyLLM's own Faraday connection uses (Provider#connection is :nodoc:, read here only).
chat = transport.send(:ruby_llm_chat, ai_model(endpoint: endpoint(protocol)))
assert_equal "http://proxy.internal:8888", chat.instance_variable_get(:@provider).connection.connection.proxy.uri.to_s
host = URI(spec[:url]).host
with_env_overrides("NO_PROXY" => host) do
@@ -213,6 +216,19 @@ class AiTransportContractTest < ActiveSupport::TestCase
assert_raises(Ai::Error::ModelMissing) { probe(:anthropic, :tools) }
end
test "a chat answer that isn't the API's shape, such as an HTML page with a 200, is InvalidOutput" do
stub_request(:post, TRANSPORTS[:compatible][:url]).to_return(status: 200, headers: { "Content-Type" => "text/html" }, body: "<html>login</html>")
assert_raises(Ai::Error::InvalidOutput) { probe(:compatible, :chat) }
end
test "an embedding endpoint with static headers is refused, since RubyLLM 2.1.1 can't send them" do
model_endpoint = ai_endpoint(name: "embed", base_url: "https://llm.example.test/v1", extra_headers: { "X-Gateway-Key" => "k" })
assert_raises(Ai::Error::Refused) { Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), :embedding) }
assert_not_requested :post, "https://llm.example.test/v1/embeddings"
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: "{}")
+19
View File
@@ -35,6 +35,17 @@ class Ai::CallContextTest < ActiveSupport::TestCase
assert_nil Ai::CallContext.current
end
test "a RubyLLM request from a thread started inside a call is recorded for the family and the call" do
call_id = with_ai_call_context(feature: :chat, model: @model, family: @family) do |call|
Thread.new { Ai::Transport.for(@model.endpoint).send(:probe_chat, @model) }.join
call.call_id
end
row = @family.llm_usages.sole
assert_equal call_id, row.call_id
assert_equal "chat", row.operation
end
test "a request that would start after the attempt's budget raises Timeout and isn't sent" do
error = assert_raises(Ai::Error::Timeout) do
with_ai_call_context(model: @model, budget: 0) do
@@ -89,6 +100,14 @@ class Ai::CallContextTest < ActiveSupport::TestCase
end
end
test "an error with no Ai::Error is scrubbed before it goes on the request event" do
instrumenter = Ai::Transport::Instrumenter.new(nil, map_error: ->(_) { }, scrub: ->(text) { text.gsub("sk-secret", "[REDACTED]") })
payload = {}
assert_raises(RuntimeError) { instrumenter.instrument("request.ruby_llm", payload) { raise "failed with sk-secret" } }
assert_equal({ error: "failed with [REDACTED]", error_class: "RuntimeError" }, payload[:ai_error])
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)
+1 -1
View File
@@ -76,7 +76,7 @@ class Ai::Transport::HttpTest < ActiveSupport::TestCase
test "the ruby-openai client gets the endpoint's settings and the resolved proxy" do
endpoint = ai_endpoint(base_url: "https://llm.example.test/v1", extra_headers: { "X-Team" => "home" }, timeout_seconds: 7)
with_env_overrides("HTTPS_PROXY" => PROXY) do
with_env_overrides("HTTPS_PROXY" => PROXY, "NO_PROXY" => nil, "no_proxy" => nil) do
client = Http.openai_client(endpoint)
connection = Faraday.new.tap { client.faraday_middleware.call(_1) }
+3 -2
View File
@@ -48,10 +48,11 @@ class LlmUsage::CallTest < ActiveSupport::TestCase
assert_in_delta 0.02, stats[:avg_cost]
end
test "the average cost comes from the unrounded total" do
test "the average cost comes from the unrounded total, over priced calls only" do
usage(estimated_cost: 0.002)
usage(estimated_cost: nil)
assert_in_delta 0.002, LlmUsage.statistics_for_family(@family)[:avg_cost]
assert_in_delta 0.002, LlmUsage.statistics_for_family(@family)[:avg_cost], 0.00001
end
test "a row the old recorders write with an error in metadata is a failed request" do