mirror of
https://github.com/we-promise/sure.git
synced 2026-12-03 10:49:07 +08:00
Apply Sure's proxy decision to every RubyLLM request; tighten checks
From the review on #4774: - RubyLLM sets a proxy only when given one, so a request Sure's resolver sent direct fell back to Faraday's ENV lookup, which ignores the port in a NO_PROXY entry and could send the key through HTTP_PROXY. The RubyLLM adapter now sets the resolved proxy, or none, on every request. - An OpenRouter endpoint without a URL resolves its proxy against OpenRouter, not api.openai.com. - A retry whose wait would outlast the attempt's budget isn't made. - Langfuse content is scrubbed of the endpoint's own key and header values, through a scrubber in the event payload, not the secrets. - A models list with non-object entries, and an embedding with a null or non-finite component, are InvalidOutput, not a NoMethodError or a pass. - The usage backfill judges the JSON value: false, {} and [] are blank. - The tracing docs say health probes aren't traced; the OpenAI proxy test clears NO_PROXY. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016zAWUV2Sxn9CgsmcUqojAZ
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
0f8a1b8a62
commit
a07d7af0de
@@ -14,8 +14,9 @@ class Ai::Instrumentation::LangfuseSubscriber
|
||||
return if @client.nil? || SKIPPED.include?(event.name)
|
||||
|
||||
payload = event.payload
|
||||
input = plain(payload[:request])
|
||||
output = payload[:error] ? { error: payload[:error], message: payload[:error_message] } : plain(payload[:output])
|
||||
scrub = payload[:scrub] || Ai::Instrumentation::Redactor.method(:scrub)
|
||||
input = plain(payload[:request], scrub)
|
||||
output = payload[:error] ? { error: payload[:error], message: payload[:error_message] } : plain(payload[:output], scrub)
|
||||
level = payload[:error] ? "ERROR" : nil
|
||||
|
||||
trace = @client.trace(name: "#{payload[:feature] || "ai"}.#{event.name.delete_suffix(".ai")}", input:,
|
||||
@@ -43,13 +44,14 @@ class Ai::Instrumentation::LangfuseSubscriber
|
||||
Time.current
|
||||
end
|
||||
|
||||
# Value objects become plain hashes, all the way down; keys are scrubbed from strings.
|
||||
def plain(value)
|
||||
# Value objects become plain hashes, all the way down; the endpoint's key and header values,
|
||||
# and anything shaped like a key, are scrubbed from strings.
|
||||
def plain(value, scrub)
|
||||
case value
|
||||
when Data then plain(value.to_h)
|
||||
when Hash then value.transform_values { plain(_1) }
|
||||
when Array then value.map { plain(_1) }
|
||||
when String then Ai::Instrumentation::Redactor.scrub(value)
|
||||
when Data then plain(value.to_h, scrub)
|
||||
when Hash then value.transform_values { plain(_1, scrub) }
|
||||
when Array then value.map { plain(_1, scrub) }
|
||||
when String then scrub.call(value)
|
||||
else value
|
||||
end
|
||||
end
|
||||
|
||||
@@ -51,16 +51,19 @@ class Ai::Transport::Base
|
||||
# Sure retries, not RubyLLM (whose contexts all have max_retries 0): RubyLLM retries inside
|
||||
# one `request.ruby_llm`, with no hook before a retry, so only here can a spent balance
|
||||
# (OpenAI's 429 insufficient_quota) stop the retries and the attempt budget be checked
|
||||
# between tries. Each try is one HTTP request and one `usage.ruby_llm` event.
|
||||
# between tries, wait included: no retry starts after the budget runs out. Each try is one
|
||||
# HTTP request and one `usage.ruby_llm` event.
|
||||
def attempt
|
||||
tries = 0
|
||||
begin
|
||||
tries += 1
|
||||
yield
|
||||
rescue *Ai::Error::RETRYABLE => error
|
||||
raise if tries > endpoint.max_retries || Ai::CallContext.current&.expired?
|
||||
delay = retry_delay(tries, error)
|
||||
remaining = Ai::CallContext.current&.remaining
|
||||
raise if tries > endpoint.max_retries || (remaining && remaining <= delay)
|
||||
|
||||
sleep(retry_delay(tries, error))
|
||||
sleep(delay)
|
||||
retry
|
||||
end
|
||||
end
|
||||
@@ -72,7 +75,8 @@ class Ai::Transport::Base
|
||||
def instrument(name, model:, request:)
|
||||
call = Ai::CallContext.current
|
||||
payload = { feature: call&.feature, call_id: call&.call_id, correlation_id: call&.correlation_id,
|
||||
family_id: call&.family_id, endpoint: endpoint.to_event, route: model.to_event, request: }
|
||||
family_id: call&.family_id, endpoint: endpoint.to_event, route: model.to_event, request:,
|
||||
scrub: scrubber }
|
||||
|
||||
ActiveSupport::Notifications.instrument("#{name}.ai", payload) do
|
||||
result = yield
|
||||
@@ -86,6 +90,13 @@ class Ai::Transport::Base
|
||||
end
|
||||
end
|
||||
|
||||
# Scrubs a string of this endpoint's key and header values, for a subscriber that sends
|
||||
# content elsewhere. A function, so the payload never holds the secrets themselves.
|
||||
def scrubber
|
||||
secrets = endpoint.secrets
|
||||
->(text) { Ai::Instrumentation::Redactor.scrub(text, secrets:) }
|
||||
end
|
||||
|
||||
def event_attachments(attachments) = Array(attachments).map { { filename: _1.filename, bytes: _1.data.bytesize } }
|
||||
|
||||
# The model that answered differs from the one asked for: LM Studio answers a request for a
|
||||
|
||||
@@ -18,6 +18,7 @@ class Ai::Transport::Compatible < Ai::Transport::Base
|
||||
def probe_models(model, timeout:)
|
||||
response = mapping_errors { Ai::Transport::Http.openai_client(endpoint, timeout:).models.list }
|
||||
raise Ai::Error::InvalidOutput, "the models list has no data" unless response.is_a?(Hash) && response["data"].is_a?(Array)
|
||||
raise Ai::Error::InvalidOutput, "the models list has entries that aren't objects" unless response["data"].all?(Hash)
|
||||
|
||||
ids = response["data"].filter_map { _1["id"] || _1[:id] }
|
||||
raise Ai::Error::ModelMissing, "#{model.name} isn't listed" unless ids.include?(model.name)
|
||||
@@ -35,6 +36,9 @@ class Ai::Transport::Compatible < Ai::Transport::Base
|
||||
vectors = embedding.vectors
|
||||
vectors = [ vectors ] if vectors.first.is_a?(Numeric)
|
||||
raise Ai::Error::InvalidOutput, "expected 1 vector, got #{vectors.size}" unless vectors.size == 1
|
||||
unless vectors.first.is_a?(Array) && vectors.first.all? { _1.is_a?(Numeric) && _1.finite? }
|
||||
raise Ai::Error::InvalidOutput, "the embedding has components that aren't finite numbers"
|
||||
end
|
||||
|
||||
dimensions = vectors.first.size
|
||||
expected = model.embedding_dimensions
|
||||
@@ -51,7 +55,11 @@ class Ai::Transport::Compatible < Ai::Transport::Base
|
||||
# other compatible servers.
|
||||
def ruby_llm_protocol = endpoint.responses_api ? :responses : :chat_completions
|
||||
|
||||
def ruby_llm_api_base = Ai::Transport::Http.compatible_base(endpoint.base_url)
|
||||
# An OpenRouter endpoint without a URL is OpenRouter's, as for ruby-openai's client.
|
||||
def ruby_llm_api_base
|
||||
base = endpoint.base_url.presence || (Ai::Transport::Http::OPENROUTER_BASE if ruby_llm_provider == :openrouter)
|
||||
Ai::Transport::Http.compatible_base(base)
|
||||
end
|
||||
|
||||
def configure_provider(config)
|
||||
config.openai_use_system_role = true # both providers read it; otherwise system prompts go as "developer"
|
||||
|
||||
@@ -112,13 +112,18 @@ module Ai::Transport::Http
|
||||
end
|
||||
end
|
||||
|
||||
# Net::HTTP with Sure's TLS settings (SSL_VERIFY, SSL_CA_FILE) on every https request.
|
||||
# RubyLLM 2.1.1 builds its own Faraday connections and takes only an adapter, so this is how
|
||||
# a self-hosted server with its own certificate is reached by RubyLLM as by every other client.
|
||||
# Net::HTTP with Sure's TLS settings (SSL_VERIFY, SSL_CA_FILE) and Sure's proxy decision on
|
||||
# every request. RubyLLM 2.1.1 builds its own Faraday connections and takes only an adapter,
|
||||
# so this is how a self-hosted server with its own certificate is reached by RubyLLM as by every
|
||||
# other client. RubyLLM sets a proxy only when given one; without this, a request
|
||||
# Ai::Transport::Http.proxy_for sends direct would fall back to Faraday's own ENV lookup, which
|
||||
# ignores the port in a NO_PROXY entry such as `10.0.0.5:8080`.
|
||||
class TlsNetHttp < Faraday::Adapter::NetHttp
|
||||
def build_connection(env)
|
||||
ssl = Ai::Transport::Http.faraday_ssl_options
|
||||
env[:ssl] = env[:ssl] ? env[:ssl].merge(ssl) : Faraday::SSLOptions.from(ssl) if ssl.present?
|
||||
proxy = Ai::Transport::Http.proxy_for(env[:url].to_s)
|
||||
env[:request][:proxy] = proxy && Faraday::ProxyOptions.from(proxy)
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
@@ -10,9 +10,19 @@ class AddCallIdAndStatusToLlmUsages < ActiveRecord::Migration[8.1]
|
||||
add_check_constraint :llm_usages, "status IN (#{STATUSES.map { "'#{_1}'" }.join(", ")})", name: "chk_llm_usages_status"
|
||||
|
||||
# The per-provider recorders mark a failed request by putting its error in metadata. An error
|
||||
# that's missing, null or only whitespace was never shown as a failure and isn't one now, as
|
||||
# LlmUsage's `present?` check has it.
|
||||
execute "UPDATE llm_usages SET status = 'failed' WHERE COALESCE(metadata->>'error', '') ~ '[^[:space:]]'"
|
||||
# that's blank by LlmUsage's `present?` check (missing, null, false, only whitespace, an
|
||||
# empty object or array) was never shown as a failure and isn't one now.
|
||||
execute <<~SQL
|
||||
UPDATE llm_usages SET status = 'failed'
|
||||
WHERE CASE jsonb_typeof(metadata->'error')
|
||||
WHEN 'string' THEN metadata->>'error' ~ '[^[:space:]]'
|
||||
WHEN 'object' THEN metadata->'error' <> '{}'::jsonb
|
||||
WHEN 'array' THEN metadata->'error' <> '[]'::jsonb
|
||||
WHEN 'boolean' THEN (metadata->'error')::boolean
|
||||
WHEN 'number' THEN true
|
||||
ELSE false
|
||||
END
|
||||
SQL
|
||||
end
|
||||
|
||||
def down
|
||||
|
||||
+3
-2
@@ -1077,8 +1077,9 @@ All LLM operations will now be logged to Langfuse, including:
|
||||
|
||||
### Tracing modes: content or metadata
|
||||
|
||||
AI calls made through Sure's AI transports (the health probes today; more features as they move
|
||||
over) are traced in one of two modes, never both. The mode follows the variables you already set:
|
||||
AI calls made through Sure's AI transports are traced in one of two modes, never both. Health
|
||||
probes aren't traced in either: they carry no family data and run each time an admin opens the
|
||||
health page. The mode follows the variables you already set:
|
||||
|
||||
| You set | Mode | What leaves the server |
|
||||
|---|---|---|
|
||||
|
||||
@@ -164,6 +164,37 @@ class AiTransportContractTest < ActiveSupport::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
# Faraday's own ENV lookup drops the port before matching NO_PROXY, so it would proxy a
|
||||
# request Sure's resolver sends direct. RubyLLM's adapter applies Sure's decision instead.
|
||||
test "RubyLLM's adapter connects as Sure's proxy resolver decides, port-qualified NO_PROXY included" do
|
||||
with_env_overrides("HTTP_PROXY" => "http://proxy.internal:8888", "HTTPS_PROXY" => nil, "NO_PROXY" => "10.0.0.5:8080") do
|
||||
adapter = Ai::Transport::Http::TlsNetHttp.new(->(_env) { })
|
||||
connect = ->(url) { adapter.send(:build_connection, Faraday::Env.from(url: URI(url), request: Faraday::RequestOptions.new)) }
|
||||
|
||||
assert_not connect.("http://10.0.0.5:8080/v1/chat/completions").proxy?, "NO_PROXY's host:port goes direct"
|
||||
proxied = connect.("http://10.0.0.6:8080/v1/chat/completions")
|
||||
assert_equal [ "proxy.internal", 8888 ], [ proxied.proxy_address, proxied.proxy_port ]
|
||||
assert_not connect.("http://127.0.0.1:8080/v1/chat/completions").proxy?, "loopback goes direct"
|
||||
end
|
||||
end
|
||||
|
||||
test "an OpenRouter endpoint without a URL resolves its proxy against OpenRouter" do
|
||||
model_endpoint = ai_endpoint(name: "router", preset: :openrouter, base_url: nil, api_key: "k")
|
||||
with_env_overrides("HTTPS_PROXY" => "http://proxy.internal:8888", "HTTP_PROXY" => nil, "NO_PROXY" => "openrouter.ai") do
|
||||
transport = Ai::Transport.for(model_endpoint)
|
||||
|
||||
assert_equal "https://openrouter.ai/api/v1", transport.send(:ruby_llm_api_base)
|
||||
assert_nil transport.send(:ruby_llm_context).config.http_proxy
|
||||
end
|
||||
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")
|
||||
|
||||
assert_raises(Ai::Error::InvalidOutput) { Ai::Transport.for(model_endpoint).probe(ai_model(endpoint: model_endpoint), :models) }
|
||||
end
|
||||
|
||||
test "only Ai::Transport::Http builds HTTP clients under app/models/ai" do
|
||||
offenders = Dir[Rails.root.join("app/models/ai/**/*.rb")].reject { _1.end_with?("ai/transport/http.rb") }.select do |path|
|
||||
File.read(path).match?(/(OpenAI::Client|Anthropic::Client|Faraday)\.new\b/)
|
||||
|
||||
@@ -9,7 +9,13 @@ class AddCallIdAndStatusToLlmUsagesMigrationTest < ActiveSupport::TestCase
|
||||
ERRORS = {
|
||||
"HTTP 500" => "failed",
|
||||
{ "message" => "busy" } => "failed",
|
||||
[ "busy" ] => "failed",
|
||||
true => "failed",
|
||||
429 => "failed",
|
||||
"" => "succeeded",
|
||||
{} => "succeeded",
|
||||
[] => "succeeded",
|
||||
false => "succeeded",
|
||||
" " => "succeeded",
|
||||
"\t\n" => "succeeded",
|
||||
nil => "succeeded"
|
||||
|
||||
@@ -49,6 +49,20 @@ class Ai::CallContextTest < ActiveSupport::TestCase
|
||||
assert_not_requested :post, "https://llm.example.test/v1/chat/completions"
|
||||
end
|
||||
|
||||
test "a retry whose wait would outlast the attempt's budget isn't made" do
|
||||
model = ai_model(name: "test-model", endpoint: ai_endpoint(name: "test", base_url: "https://llm.example.test/v1", max_retries: 3))
|
||||
transport = Ai::Transport.for(model.endpoint)
|
||||
transport.stubs(:retry_delay).returns(5)
|
||||
transport.expects(:sleep).never
|
||||
tries = 0
|
||||
|
||||
with_ai_call_context(model:, budget: 2) do
|
||||
assert_raises(Ai::Error::Upstream) { transport.send(:attempt) { tries += 1; raise Ai::Error::Upstream, "busy" } }
|
||||
end
|
||||
|
||||
assert_equal 1, tries
|
||||
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)
|
||||
|
||||
@@ -60,6 +60,20 @@ class Ai::Instrumentation::SubscribersTest < ActiveSupport::TestCase
|
||||
ends.each { assert_equal({ name: "Netflix", notes: [ "billed with [REDACTED]" ] }, _1[:output]) }
|
||||
end
|
||||
|
||||
test "Langfuse content is scrubbed of the endpoint's own secrets, whatever their shape" do
|
||||
log = []
|
||||
subscriber = Ai::Instrumentation::LangfuseSubscriber.new(client: FakeLangfuse.new(log))
|
||||
scrub = ->(text) { Ai::Instrumentation::Redactor.scrub(text, secrets: [ "opaque-gateway-token" ]) }
|
||||
payload = { feature: "bill_setup", call_id: "c1", route: { endpoint: "gateway", model: "m" }, scrub:,
|
||||
request: { input: "use opaque-gateway-token" }, output: { text: "echo opaque-gateway-token" } }
|
||||
|
||||
subscriber.call(event("generate.ai", payload))
|
||||
|
||||
trace = log.find { _1.first == :trace }.last
|
||||
assert_equal({ input: "use [REDACTED]" }, trace[:input])
|
||||
assert_equal({ text: "echo [REDACTED]" }, log.find { _1.first == :end }.last[:output])
|
||||
end
|
||||
|
||||
test "a failed call writes a debug log entry with its route and error, never its key" do
|
||||
payload = { feature: "categorize", call_id: "c1", correlation_id: "rule_run:7", family_id: families(:dylan_family).id,
|
||||
endpoint: { name: "gpu", protocol: :compatible, location: :local }, route: { endpoint: "gpu", model: "qwen3-8b" },
|
||||
|
||||
@@ -465,6 +465,20 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
|
||||
assert_requested request
|
||||
end
|
||||
|
||||
test "embedding probe fails on a vector with a component that isn't a finite number" do
|
||||
stub_request(:post, "http://ollama:11434/v1/embeddings").to_return(
|
||||
status: 200, headers: { "Content-Type" => "application/json" },
|
||||
body: { data: [ { embedding: [ 0.1, nil, 0.3 ] } ], model: "nomic-embed-text", usage: { prompt_tokens: 4, total_tokens: 4 } }.to_json
|
||||
)
|
||||
Rails.logger.stubs(:error)
|
||||
DebugLogEntry.stubs(:capture)
|
||||
|
||||
result = @probe.embedding(endpoint: "http://ollama:11434/v1", access_token: nil, model: "nomic-embed-text", dimensions: 3)
|
||||
|
||||
assert result.failing?
|
||||
assert_equal :invalid_response, result.failure_code
|
||||
end
|
||||
|
||||
test "embedding probe fails when returned dimensions do not match configuration" do
|
||||
stub_request(:post, "http://ollama:11434/v1/embeddings").to_return(
|
||||
status: 200, headers: { "Content-Type" => "application/json" },
|
||||
|
||||
@@ -1114,7 +1114,7 @@ class Provider::OpenaiTest < ActiveSupport::TestCase
|
||||
|
||||
|
||||
test "the client takes its proxy from Ai::Transport::Http, never proxying loopback" do
|
||||
ClimateControl.modify(HTTPS_PROXY: "http://proxy.internal:8888", HTTP_PROXY: nil) do
|
||||
ClimateControl.modify(HTTPS_PROXY: "http://proxy.internal:8888", HTTP_PROXY: nil, NO_PROXY: nil, no_proxy: nil) do
|
||||
cloud = Faraday.new.tap { Provider::Openai.new("token").send(:client).faraday_middleware.call(_1) }
|
||||
local = Faraday.new.tap { Provider::Openai.new("token", uri_base: "http://127.0.0.1:8080/v1", model: "qwen3").send(:client).faraday_middleware.call(_1) }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user