AI plumbing 2a: transports and instrumentation
Part 2a of the AI plumbing series, stacked: 2a → 2b → 2c → 2d (#4765) → 2e (#4771). Merge them in that order. This one is first and depends on nothing.
Part 2a of the AI plumbing redesign proposed in #4440. Split out of #4765, which held 2a to 2d and now holds 2d only. Implementation plan:
pr-2a-transports-and-instrumentation.md; its place in the series is in
§19.
Problem
Each AI feature in Sure builds its own HTTP client, maps errors its own way and records usage its
own way. Today that causes these problems:
- The admin health probes test a different code path from production (drift bug 6).
AiHealth::Probebuilds its own OpenAI, Anthropic and Faraday clients. A probe can pass while
the production call fails, for example on extra headers or the proxy. - The proxy is read differently by each client. The external assistant sends requests to an
http://gateway directly when onlyHTTPS_PROXYis set, and ignores CIDR entries in
NO_PROXY. llm_usagesrecords one row per call, whatever was retried. Retried requests and resent
requests are never counted.- There is no correlation between a job and its AI requests, and no way to trace cost and
latency without sending prompts to Langfuse.
What this adds
flowchart TB
subgraph Web["Admin system health (web request, until PR 3)"]
AH["AiHealth<br/>builds Ai::Config::Endpoint + Model"] --> PR["AiHealth::Probe<br/>cache, redaction, confirming_tools_refusal"]
end
PR -->|"probe(model, :models / :chat / :tools / :embedding)"| T["Ai::Transport.for(endpoint)<br/>Compatible | Anthropic"]
PR -->|"PDF, vector-store probes"| HC["Http.openai_client / anthropic_client"]
T --> CC["Ai::CallContext.call<br/>RubyLLM.with_usage_owner(family)<br/>RubyLLM.workflow(feature, id: call_id)"]
CC --> CTX["RubyLLM.context per endpoint<br/>timeout, max_retries 0, http_proxy, no auto-upload,<br/>system role, explicit protocol, instrumenter"]
CTX --> INS["Ai::Transport::Instrumenter<br/>attempt budget; PR 4 adds the gate"]
INS --> NET[("model server")]
HC --> NET
flowchart LR
U["usage.ruby_llm<br/>(per attempt; owner, workflow_*)"] --> US["UsageSubscriber"] --> LU[("llm_usages<br/>call_id, status")]
AI["*.ai<br/>(per call; route, output, error)"] --> LF["LangfuseSubscriber<br/>(content mode)"] --> LFS[("Langfuse")]
AI --> DL["DebugLogSubscriber"] --> DLE[("DebugLogEntry")]
OT["RubyLLM::OpenTelemetry.enable<br/>(metadata mode)"] --> SM["ProbeSampler<br/>drops probe spans"] --> OTLP[("OTLP_ENDPOINT")]
LU --> PAGE["Usage page: one row per call,<br/>click shows its requests"]
ruby_llm2.1.1 (~> 2.1during the redesign; the lockfile fixes the version). There is
no global configuration: every call goes through aRubyLLM.contextfor its endpoint. RubyLLM's
usage ledger never gets its table, so it writes nothing.Ai::Transport::CompatibleandAi::Transport::Anthropic. These are thin adapters over
RubyLLM, and they implement onlyprobefor now. The other calls arrive with their first
callers:generatein 2c,judgein 2d,embedin 2e andconversein PR 6.Ai::Transport::Http, the one place AI HTTP clients are built:- One proxy resolver:
HTTPS_PROXY, thenHTTP_PROXY,NO_PROXY(CIDR included), and
loopback is never proxied. - ruby-openai's base URL rule, so URLs configured today keep working.
- Static headers and TLS options.
- One proxy resolver:
Ai::Error, the §9 taxonomy, includingNoCredit(Anthropic's 400, OpenAI's 429
insufficient_quota, a 402) andModelMissing. It maps both RubyLLM 2.1.1's errors and
2.2'sConnectionError. Mapped messages are scrubbed of keys.- Sure owns retries. RubyLLM retries inside one request and offers no hook before a retry,
so every RubyLLM context hasmax_retriesset to 0. The transport retries up to the endpoint's
limit, stops at once on a spent balance, and respects the attempt's time budget. Ai::Tokens,Ai::Config::EndpointandAi::Config::Model. The
endpoint and model are the values a transport takes. A transport never reads ENV,Setting
or ActiveRecord.Ai::CallContextwraps each call in RubyLLM's documented scopes:
RubyLLM.with_usage_owner(family)andRubyLLM.workflow(..., id: call_id). RubyLLM's own
events therefore carry the family and the call.Ai::Resultand the job's correlation id
arrive in 2c with their first caller.- Instrumentation:
-
one
llm_usagesrow per request, withcall_idandstatus; -
a
DebugLogEntryfor every failed call; -
two tracing modes, chosen from variables operators already set:
Set Mode Langfuse keys content: Sure's.aievents go to LangfuseOTLP_ENDPOINTalonemetadata: RubyLLM's OpenTelemetry spans, with no prompts or answers
-
- The usage page shows one row per call. A call with several requests opens to show each
request's status, tokens, cost and error. The statistics count calls. AiHealth::Proberuns through the transports and the clientsHttpbuilds. It builds no
client of its own. Every LLM probe lists models by default, so it makes no chat call. That
includes OpenAI-compatible servers, which used to get a chat completion. Choosing the chat
check becomes an endpoint setting in PR 7. New failure codes:no_credit,unauthorized,
unreachable.- Docs:
docs/llm-guides/ai-pipeline.mdfor contributors, linked fromAGENTS.md. The
hosting guide covers tracing modes, usage per request and proxy coverage.
Reviewer guide
Read in this order:
app/models/ai/transport/base.rb: the interface, Sure's retry loop and the.aievent.app/models/ai/transport/http.rb: the proxy, base URLs and client builders.app/models/ai/transport/ruby_llm_adapter.rb, thencompatible.rbandanthropic.rb.app/models/ai/call_context.rbandapp/models/ai/instrumentation/usage_subscriber.rb.test/architecture/ai_transport_contract_test.rb, the contract every transport passes.
Deleted: AiHealth::Probe's openai_client, anthropic_client, embedding_client,
openai_model_ids and its hand-built tool payloads; Assistant::External::Client#resolve_proxy
and #host_bypasses_proxy?.
Decided during development of #4440 (@josh-sanders):
- Proxy reach.
Provider::Openaiand the external assistant take their proxy fromHttp
now, so OpenAI-compatible calls get the fix in this PR. This is an exception to the
"no temporary code" principle: a few lines that 2e and PR 6 delete. - Tracing mode. It's inferred from existing variables. No AI ENV is added; the new variables
are the shortOTLP_ENDPOINTandOTLP_HEADERS. - Probes list models by default on every protocol.
Worth a look:
- The function-calling probe now sends RubyLLM's tool payload. That's the path chat moves to
in PR 6, and it has nostrict: true, which today's chat sends. - The embedding probe uses the shared base URL rule. A URL without "v1" now gets
/v1
added, where production embeddings would post to<url>/embeddings. This is rare, and 2e
moves production embeddings onto the same rule. - Usage-page strings are new in
en.ymlonly. Other locales fall back to English until
translated. - The settings locale split moved to its own PR, #4815. This PR's locale diff is only its
own small edits; #4815 should merge before 2c, which adds strings undersettings/ai_prompts/. db/schema.rbis trimmed to thellm_usageschanges. A local Postgres 16 dumps two
unrelated check constraints differently.pipelock:ignore: no tags moved or were added.
Upgrade notes
llm_usageshas one row per request. Queries that count rows as calls should group by
COALESCE(call_id, id). The migration addscall_idandstatus, and backfillsfailed
wheremetadatahas an error. Old rows count as calls of one request.- New optional variables:
OTLP_ENDPOINTandOTLP_HEADERSenable metadata-only tracing
when Langfuse keys aren't set. - Proxy. OpenAI-compatible calls and the external assistant follow
HTTPS_PROXY, then
HTTP_PROXY, for any scheme, and never proxy loopback. Anhttp://gateway that went direct
with onlyHTTPS_PROXYset now goes through the proxy unlessNO_PROXYlists it.
Still on old code
- Every AI call except the health probes: generations (2c), Jev (2d), documents and
embeddings (2e), and chat (PR 6). These calls still useProvider::Openai,
Provider::Anthropicand their usage recorders, and those rows have nocall_id. - Per-provider Langfuse tracing: until 2e.
- Anthropic's production client still goes direct, without the proxy. The gem takes no
proxy option; these calls get one when they move onto RubyLLM. - Probes run on the web thread with
AiHealth::Probe.timeout, until PR 3. Its default of
5 s is too short for a model on CPU; the hosting guide now says to raise it. - The PDF probes still use
Provider::Openai::PdfProcessorand
Provider::Anthropic::PdfProcessoruntil 2e, so their failures aren'tAi::Errors and the
Anthropic one bypasses the proxy.
RubyLLM 2.2
All 458 commits from v2.1.1 to main were read. The ones that touch this work are tabulated
in the plan, and they are PR 5's upgrade checklist. 2a is built to survive them:
- Metadata tracing passes
content: falseexplicitly once the gem accepts it. - 2.2's
ConnectionErrormaps ontoAi::Error, as 2.1.1's Faraday errors do. - Unknown token counts stay unknown rather than becoming 0.
tool_callsis read whether it arrives as a Hash or a collection.- A "RubyLLM surface" test fails if a public method Sure uses disappears.
Validation
Run on this PR alone at 163b4763a (main merged in), 2026-11-09:
-
bin/rails test test/architecture test/models/ai test/models/ai_health* test/i18n_test.rb: 177 runs, 0 failures. -
bin/rails test(at181e012eb, before the locale revert and main merge): 15,232 runs, 13 failures. The same 13 fail
onorigin/mainin the same environment (Wise, Binance, budget and FinanceKit-demo date tests); none touches AI code. - Settings system tests (
test/system/settings_test.rb,test/system/settings/): 45 runs, 0 failures. -
bin/rubocop,bundle exec erb_lint --lint-all,npm run lint,bin/brakeman: clean. - Pipelock 3.6.0
git scan-diffoforigin/main...HEAD: no findings. - Live,
AiHealth.new(force_probes: true)throughbin/rails runner:- llama.cpp (
qwen3.6-35b-a3b, CPU): models, chat, tools, PDF text and embedding (granite, 384 dims) pass;
PDF vision fails as it should (text-only model). - Errors: a bad key →
unauthorized; a refused port →unreachable; an unknown model →model_not_available,
both from the model list and from a 200 answered by another model. - Anthropic and OpenAI: the keys available are revoked/expired, so both map to
unauthorized.no_creditis covered
by WebMock tests only.
- llama.cpp (
- Proxy, through a logging forward proxy: with
HTTPS_PROXYonly, every OpenAI call and the Anthropic transport
CONNECT through it; withHTTP_PROXYonly, llama.cpp chat, tools and embeddings go through it;NO_PROXYis honoured
and loopback is skipped. - Content mode against a self-hosted Langfuse (v4) with stubbed
generate.aievents: prompt, output, usage,
route,call_idand error class arrive; keys are[REDACTED]; an error is level ERROR. - Metadata mode (OTLP to Langfuse) with a live RubyLLM call: a generation span with model and tokens and a
workflow span, no prompt or answer; the probe made no span. - Live cassettes arrive with
with_ai_cassettein 2c.
Fixed after live testing (2026-11-07)
These were found when the spike's remaining live checks ran on 2e (#4771). They're fixed here and merged forward into 2b, 2c, 2d and 2e.
- Anthropic's models probe ignored
HTTPS_PROXY(cad0f8518).- The cause: it went through the
anthropicgem, which reads onlyHTTP_PROXY. Through a logging proxy with onlyHTTPS_PROXYset, every other client used the proxy and the probe went direct. Behind an HTTPS-only egress proxy it could fail while the calls it checks work. - The fix: the probe is now a GET built by
Ai::Transport::Http, with the resolved proxy and TLS options. Re-run live underHTTPS_PROXY,HTTP_PROXYand bothNO_PROXYforms, it goes through the proxy each time.
- The cause: it went through the
- Metadata tracing lost its last batch at exit (
f63d10d06).- The cause: the batch span processor exports on a timer and nothing flushed it. Live against Langfuse, a process that made three calls and exited sent no spans at all.
- The fix:
start_tracing!now shuts the provider down at exit. Re-run live without an explicit flush, every span arrives, still without content.
🤖 Generated with Claude Code
https://claude.ai/code/session_016zAWUV2Sxn9CgsmcUqojAZ
Summary by cubic
Moves all AI calls and health probes onto Ai::Transport, thin adapters over RubyLLM 2.1.1, with one proxy resolver, an Ai::Error taxonomy, Sure-owned retries, usage rows and tracing. Probes now exercise the same client settings, headers, proxy and error mapping as production calls, so they can't drift.
Ai::Transport::Httpis the one place AI HTTP clients are built: it resolves the proxy (HTTPS_PROXY, thenHTTP_PROXY,NO_PROXYwith CIDR blocks,*, and leading-dot entries; loopback never proxied), resolves hostnames before matching them againstNO_PROXYCIDR blocks, and applies the result explicitly to every RubyLLM request, so a direct request can't fall back to Faraday's ENV lookup. OpenRouter endpoints resolve their proxy against OpenRouter;Provider::Openaiand the external assistant take their proxy from here too.Ai::Errormaps RubyLLM and Faraday errors onto the taxonomy, includingNoCreditandModelMissing. Provider messages are scrubbed of keys and static header values a gateway could echo back, and Langfuse masks fields named like credentials whatever the value. Only anArgumentErrorRubyLLM raises for an option it refuses maps ontoRefused; a wrong call in Sure's own code stays a bug.- Sure owns retries: RubyLLM contexts set
max_retriesto 0 and the transport retries up to the endpoint's limit. Every attempt checks the call's budget first, each request's timeout is cut to the exact budget left, no retry is made whose wait would outlast it, and an answer that arrives after the deadline is aTimeout. Ai::CallContextwraps every call in RubyLLM's usage-owner and workflow scopes, so each event carries the family, call id, and job correlation id. The usage subscriber falls back to Sure's call context for requests from threads RubyLLM doesn't inherit.- Instrumentation records one
llm_usagesrow per request withcall_idandstatus, a debug-log entry per failed call, and traces in content mode (Langfuse) or metadata mode (OpenTelemetry toOTLP_ENDPOINT, no prompts or answers). RubyLLM's logger never runs at debug, which would log raw responses before Sure's redactor. Each failed request's row keeps its own error cause; the prompt total counts cache writes; cached input outside Anthropic is priced as input; a negative or non-finite cost is dropped and the row's cost estimated. Health probes are dropped from metadata traces by a sampler, and the metadata-mode exporter flushes at exit. A garbled 2xx, a models list with non-object entries, an embedding with a null or non-finite component, or one RubyLLM can't parse, becomesInvalidOutput; Ollama'sname:latestlisting counts as the alias.OTLP_HEADERSvalues are percent-decoded with the exporter's own decoder, so a literal+in a header value survives. The usage page shows one row per call with requests summed beneath it; a call keeps all its requests even when one falls outside the selected dates, and a cancelled call is marked as such. - Probes list models by default on every protocol, so no probe makes a chat call. The answering model must match the asked-for one (vendor prefixes, snapshot dates, and
latestaliases allowed); an Anthropic lookup that answers with another model's record fails. Anthropic's 404model: <name>isModelMissingon chat and tool probes too. The tool probe sends its tool as strict, as the assistant declares; the embedding probe posts toEMBEDDING_URI_BASEas given, without adding/v1. New failure codes:no_credit,unauthorized,unreachable; an unsupported provider, and probe failures from the client gems, return failing results instead of raising.
Migration
llm_usagesgetscall_idandstatus(succeeded,failed, orcancelled); the migration marks only rows whosemetadataholds an error as failed (null, empty, whitespace-only,false,{}, or[]errors stay succeeded, including Unicode spaces), under a string or symbol key. Queries counting rows as calls should group byCOALESCE(call_id, id).- Optional
OTLP_ENDPOINTandOTLP_HEADERSenable metadata-only tracing when Langfuse keys aren't set; a malformed percent-encoding in a header value stays as written rather than raising at boot. - An
http://gateway that went direct with onlyHTTPS_PROXYset now goes through the proxy unlessNO_PROXYlists it; loopback is never proxied.
Summary by CodeRabbit
- New Features
- AI health checks support compatible and Anthropic endpoints, with clearer classifications for common provider errors.
- AI usage reporting groups retries into calls, shows expandable request details, and includes cancelled calls. Cost statistics are calculated per call.
- AI tracing supports content and metadata-only modes; metadata-only traces omit prompts, answers, and tool results.
- AI requests use shared proxy handling, timeout budgets, and retry behavior. Sensitive values are redacted from logs and traces.
- Documentation
- Added guidance on AI tracing, usage reporting, proxy behavior, health-check timeouts, and AI development practices.