AI plumbing 2a: transports and instrumentation

Merged
JO
8d ago
+3224-421

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::Probe builds 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 only HTTPS_PROXY is set, and ignores CIDR entries in
    NO_PROXY.
  • llm_usages records 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_llm 2.1.1 (~> 2.1 during the redesign; the lockfile fixes the version). There is
    no global configuration: every call goes through a RubyLLM.context for its endpoint. RubyLLM's
    usage ledger never gets its table, so it writes nothing.
  • Ai::Transport::Compatible and Ai::Transport::Anthropic. These are thin adapters over
    RubyLLM, and they implement only probe for now. The other calls arrive with their first
    callers: generate in 2c, judge in 2d, embed in 2e and converse in PR 6.
  • Ai::Transport::Http, the one place AI HTTP clients are built:
    • One proxy resolver: HTTPS_PROXY, then HTTP_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.
  • Ai::Error, the §9 taxonomy, including NoCredit (Anthropic's 400, OpenAI's 429
    insufficient_quota, a 402) and ModelMissing. It maps both RubyLLM 2.1.1's errors and
    2.2's ConnectionError. 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 has max_retries set 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::Endpoint and Ai::Config::Model. The
    endpoint and model are the values a transport takes. A transport never reads ENV, Setting
    or ActiveRecord.
  • Ai::CallContext wraps each call in RubyLLM's documented scopes:
    RubyLLM.with_usage_owner(family) and RubyLLM.workflow(..., id: call_id). RubyLLM's own
    events therefore carry the family and the call. Ai::Result and the job's correlation id
    arrive in 2c with their first caller.
  • Instrumentation:
    • one llm_usages row per request, with call_id and status;

    • a DebugLogEntry for every failed call;

    • two tracing modes, chosen from variables operators already set:

      SetMode
      Langfuse keyscontent: Sure's .ai events go to Langfuse
      OTLP_ENDPOINT alonemetadata: 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::Probe runs through the transports and the clients Http builds. 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.md for contributors, linked from AGENTS.md. The
    hosting guide covers tracing modes, usage per request and proxy coverage.

Reviewer guide

Read in this order:

  1. app/models/ai/transport/base.rb: the interface, Sure's retry loop and the .ai event.
  2. app/models/ai/transport/http.rb: the proxy, base URLs and client builders.
  3. app/models/ai/transport/ruby_llm_adapter.rb, then compatible.rb and anthropic.rb.
  4. app/models/ai/call_context.rb and app/models/ai/instrumentation/usage_subscriber.rb.
  5. 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::Openai and the external assistant take their proxy from Http
    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 short OTLP_ENDPOINT and OTLP_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 no strict: 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.yml only. 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 under settings/ai_prompts/.
  • db/schema.rb is trimmed to the llm_usages changes. A local Postgres 16 dumps two
    unrelated check constraints differently.
  • pipelock:ignore: no tags moved or were added.

Upgrade notes

  • llm_usages has one row per request. Queries that count rows as calls should group by
    COALESCE(call_id, id). The migration adds call_id and status, and backfills failed
    where metadata has an error. Old rows count as calls of one request.
  • New optional variables: OTLP_ENDPOINT and OTLP_HEADERS enable 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. An http:// gateway that went direct
    with only HTTPS_PROXY set now goes through the proxy unless NO_PROXY lists 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 use Provider::Openai,
    Provider::Anthropic and their usage recorders, and those rows have no call_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::PdfProcessor and
    Provider::Anthropic::PdfProcessor until 2e, so their failures aren't Ai::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: false explicitly once the gem accepts it.
  • 2.2's ConnectionError maps onto Ai::Error, as 2.1.1's Faraday errors do.
  • Unknown token counts stay unknown rather than becoming 0.
  • tool_calls is 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 (at 181e012eb, before the locale revert and main merge): 15,232 runs, 13 failures. The same 13 fail
    on origin/main in 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-diff of origin/main...HEAD: no findings.
  • Live, AiHealth.new(force_probes: true) through bin/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_credit is covered
      by WebMock tests only.
  • Proxy, through a logging forward proxy: with HTTPS_PROXY only, every OpenAI call and the Anthropic transport
    CONNECT through it; with HTTP_PROXY only, llama.cpp chat, tools and embeddings go through it; NO_PROXY is honoured
    and loopback is skipped.
  • Content mode against a self-hosted Langfuse (v4) with stubbed generate.ai events: prompt, output, usage,
    route, call_id and 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_cassette in 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 anthropic gem, which reads only HTTP_PROXY. Through a logging proxy with only HTTPS_PROXY set, 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 under HTTPS_PROXY, HTTP_PROXY and both NO_PROXY forms, it goes through the proxy each time.
  • 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::Http is the one place AI HTTP clients are built: it resolves the proxy (HTTPS_PROXY, then HTTP_PROXY, NO_PROXY with CIDR blocks, *, and leading-dot entries; loopback never proxied), resolves hostnames before matching them against NO_PROXY CIDR 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::Openai and the external assistant take their proxy from here too.
  • Ai::Error maps RubyLLM and Faraday errors onto the taxonomy, including NoCredit and ModelMissing. 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 an ArgumentError RubyLLM raises for an option it refuses maps onto Refused; a wrong call in Sure's own code stays a bug.
  • Sure owns retries: RubyLLM contexts set max_retries to 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 a Timeout.
  • Ai::CallContext wraps 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_usages row per request with call_id and status, a debug-log entry per failed call, and traces in content mode (Langfuse) or metadata mode (OpenTelemetry to OTLP_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, becomes InvalidOutput; Ollama's name:latest listing counts as the alias. OTLP_HEADERS values 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 latest aliases allowed); an Anthropic lookup that answers with another model's record fails. Anthropic's 404 model: <name> is ModelMissing on chat and tool probes too. The tool probe sends its tool as strict, as the assistant declares; the embedding probe posts to EMBEDDING_URI_BASE as 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_usages gets call_id and status (succeeded, failed, or cancelled); the migration marks only rows whose metadata holds 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 by COALESCE(call_id, id).
  • Optional OTLP_ENDPOINT and OTLP_HEADERS enable 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 only HTTPS_PROXY set now goes through the proxy unless NO_PROXY lists 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.