Skip to content

Upstream check-up: model consistency, input usage vs the local estimate, cache reads per upstream - #246

Merged
fylorn merged 2 commits into
mainfrom
upstream-health
Oct 1, 2026
Merged

fylorn merged 2 commits into
mainfrom
upstream-health

Conversation

@fylorn

@fylorn fylorn commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Summary

An upstream check-up for Lite: per upstream, the facts that tell whether a relay is honest — does it serve the model it claims, does it inflate input usage, does prompt caching work through it — laid out with evidence and sample sizes, never verdicts. Core reports facts and reference values; the UI words them.

Two new facts per request (request store SCHEMA 22 → 23; the store rebuilds by design, no migration)

  • answered_model — the model the upstream named in its answer: Anthropic model (JSON) / message_start.message.model (stream), Chat Completions model, Responses model / response.model, Gemini modelVersion (model_version). Read by the usage sniffer (tw_dialect::usage::Sniffer::model()) in the same pass over the upstream's raw bytes, before any conversion. It tracks JSON nesting instead of parsing values, so only the answer level counts: a model key inside a tool call's input (which a relay that sorts keys puts before the top-level model) is never taken. Stops at the first non-empty name, or after 8 frames without one. Bedrock Converse does not name the model, so Bedrock rows have none.
  • input_estimate — the local estimate of the input tokens as sent, carried on RequestStarted. Rule rewrites only touch model / max_tokens / thinking, conversion re-encodes the same IR content, and redaction swaps a few values (well inside the estimator's error), so the routing estimate is the estimate of what was sent — reused, no second pass. Requests that do not decode (non-generating, or relying on server-side state like previous_response_id) have none.
  • sent_model — the model sent to the upstream after rule rewrites (the last attempt's model). RequestRow.model holds the client's original model; the check-up compares against sent_model. The pricing page (unpriced_recent) now reads this column instead of json_extract on the routing JSON.

One input estimator for all of core

Routing used bytes/4 (CJK undercounted, images 0, thinking counted); count_tokens used ASCII/4 + one per other char + 1,600 per image/file. Now there is one, tw_engine::estimate_tokens (the count_tokens algorithm, made allocation-free: tool schemas and tool inputs are counted while serializing into a counting writer). Routing's input_tokens therefore changes slightly (images and files now count, CJK counts a token per character, thinking is excluded); the five replay fixtures' input_tokens_estimate were updated accordingly.

GET /upstreams/health — ep::UpstreamHealth, Window query (from_ms / to_ms), default the last 7 days

One UpstreamCheckup per upstream with rows in the window (most requests first), each number with its sample size:

  • Requests / failed / cancelled — failed is error IS NOT NULL (same as Summary::failed); cancelled requests are counted apart and not in requests; local answers and refusals that reached no upstream are left out.
  • Model consistency — answers that named a model, how many differed from sent_model after normalization, up to three example pairs sent → answered with counts (pairs that normalize to the same substitution are merged; the most common spelling is shown).
  • Input vs the local estimate — over successful requests with reported usage and an estimate ≥ 1,000 tokens: median of reported / estimate (nearest-rank, to 0.001), overall and per normalized model, each model next to the pooled median of the other upstreams serving it (others, other_upstreams).
  • Prompt caching — over turns that should hit a cache: a later turn of a session sent to the same upstream with the same model within 5 minutes of the previous turn's start, both turns ≥ 4,096 input tokens (the largest minimum cacheable prefix among the major providers), current turn successful. Turns, turns with zero cache reads, total input and cache-read tokens (share = read / input), overall and per model with the other upstreams' tally for reference.
  • TTFT and generation speed — medians with the same samples as latency_by_provider / token_rate_by_provider (a test pins them equal).

The window is read once, in (at_ms, id) order (the previous turn of a session is just the last one seen): ~70 ms on 100k rows in a release build, vs ~425 ms for the six separate queries I started with (summary alone is ~57 ms). That matters because the store mutex is held during the query and the recorder waits on it.

Normalization (tw_store::model_name::normalize) — conservative: a false "mismatch" accuses an honest upstream

  1. trim, lowercase
  2. keep the last / segment: models/, vendor prefixes (anthropic/, openai/, google/, openrouter/anthropic/…), Bedrock ARNs, Vertex resource paths
  3. drop @… (Vertex @20250929, @001)
  4. drop OpenRouter variants :free, :thinking, :nitro, :beta, :extended, :online, :floor, :exacto — only these words (Ollama's :7b vs :72b are different models)
  5. Bedrock: geo prefix (us., eu., apac., jp., au., us-gov., global. — the list now exported from tw_pricing::name), known vendor prefix (anthropic., amazon., meta.…), then -v1:0 / -v1 / :200k (only after a vendor prefix: deepseek-v3 keeps its -v3)
  6. trailing snapshot markers, repeatedly: [1m], -latest, dates -20250929 / -2025-09-29 / four-digit -0613 (MMDD) or -2507 (YYMM) — each must be a real date, so -8192 stays — and dated previews -preview-05-20 / -preview-09-2025 / -exp-0827 (undated -preview stays: o1-preview ≠ o1)
  7. . between digits → - (4.5 = 4-5)
  8. Claude only: both name orders become one (claude-3-5-sonnet = claude-sonnet-3-5, claude-4-sonnet = claude-sonnet-4), relay suffixes -thinking / -1m dropped, minor version 0 dropped (claude-opus-4-0 = claude-opus-4)

Family, size, generation and variant are never touched (opus/sonnet, 4/4-5, gpt-5/gpt-5-mini, flash/flash-lite, thinking/instruct Qwen, kimi-k2/kimi-k2-thinking stay different). Two dated snapshots of the same model compare equal — the cost of matching aliases to snapshots. A name that normalizes to empty is never counted as a mismatch.

How input is counted per format

All formats are stored as three non-overlapping numbers at parse time (tw_dialect usage()), so billed input = input_tokens + cache_read_tokens + cache_write_tokens for every format:

  • Anthropic: input_tokens + cache_read_input_tokens + cache_creation_input_tokens (already disjoint)
  • Bedrock Converse: inputTokens + cacheReadInputTokens + cacheWriteInputTokens (already disjoint)
  • Chat Completions: prompt_tokens includes cached_tokens (and cache_write_tokens) → stored minus them; the sum is prompt_tokens
  • Responses: input_tokens includes cached_tokens → same; the sum is input_tokens
  • Gemini: promptTokenCount + toolUsePromptTokenCount includes cachedContentTokenCount → same

Protocol note for the version comment (CONTROL_API_VERSION is not bumped here)

New endpoint GET /upstreams/health ([UpstreamHealth]); RequestStarted gains input_estimate, and RequestFinished / RequestFailed / RequestCancelled gain answered_model (both optional, omitted when absent). A UI written for 30 does not see the check-up. Suggested text for the doc comment:

/// **31 起有上游体检**:新端点 `GET /upstreams/health`([`UpstreamHealth`]:每家上游的请求、
/// 失败、取消,回答里写的模型名和发出去的对不对得上,上游报的输入和本地估算之比、本该读得到
/// 缓存的轮次读到了多少,各带样本数和别家服务同一个模型时的参照,以及首 token 和生成速度的
/// 中位数)。[`Event::RequestStarted`] 多了 `input_estimate`,三种结局多了 `answered_model`。
/// 照 30 写的界面看不到体检。

The request store SCHEMA is bumped (22 → 23), so upgrading clears request history. If another change in the same release also bumps it, the later one needs 24.

Uncertain / limits

  • Failover attributes a row to the last tried upstream (existing behavior), so an upstream that fails and is always failed over shows no failures here. Counting per attempt from the routing JSON is possible later.
  • Whether a cache can hit also depends on the client marking breakpoints (Anthropic, Bedrock); the per-model reference from other upstreams is what makes the cache share meaningful. The store does not record whether a request carried cache_control.
  • Bedrock's prompt-router trace (invokedModelId) is deliberately not read: a router is expected to pick a different model than the router ARN.
  • Relay-specific aliases beyond the rules above (e.g. gpt-5-high) will show as differing; the UI shows the pairs so users can judge.

Test plan

  • cargo fmt --all -- --check, cargo clippy --workspace --all-targets -- -D warnings
  • env -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy cargo test --workspace — 1959 passed, 0 failed
  • cargo clippy -p tw-api --all-targets --features ts -- -D warnings, cargo test -p tw-api --features ts, export_ts + tsc --noEmit --strict
  • scripts/smoke.sh — 66 passed, 0 failed (the existing 37 MB memory warning only); new checks: /upstreams/health with and without a window, and the answered model of the fake upstream reaching the check-up as consistent
  • New tests: answered model for each format, stream and JSON, byte-by-byte, nested model keys, broken frames, Azure's empty first chunk, Gemini JSON-array streams, Bedrock (none); the gateway end to end (passthrough, converted Anthropic → Chat, streamed, no model, previous_response_id without an estimate); recorder (sent_model after a rewrite, answered_model on all three endings, input_estimate); normalization (equivalents that must match, substitutions that must not, multibyte names); every metric on hand-built rows with references and sample sizes, empty windows, local answers / refusals / cancellations excluded, the previous turn before the window; the endpoint's 7-day default and JSON shape; TypeScript shape
  • 100k-row benchmark (release, not committed): ~70 ms

🤖 Generated with Claude Code

fylorn and others added 2 commits October 1, 2026 19:38
…te and cache reads per upstream

Relays are the main worry of Lite users after credentials and tool calls:
does the relay serve the model it claims, does it inflate input usage, does
prompt caching work through it. This adds the facts to answer that, with
evidence and sample sizes and no verdicts.

Recorded per request (request store SCHEMA 22 -> 23; the store rebuilds):
- answered_model: the model the upstream named in its answer (Anthropic
  `model` / `message_start.message.model`, Chat `model`, Responses
  `model` / `response.model`, Gemini `modelVersion`). The usage sniffer reads
  it in the same pass over the upstream's raw bytes by tracking JSON nesting,
  so only the answer level counts; a `model` key inside a tool call's input
  is never taken. Bedrock Converse does not name the model.
- input_estimate: the local estimate of the input as sent, carried on
  RequestStarted.
- sent_model: the model sent to the upstream after rule rewrites
  (RequestRow.model is the client's). The pricing page reads it too instead
  of json_extract on the routing JSON.

One input estimator for all of core: routing's `input_tokens`, local
count_tokens answers and the check-up now share the count_tokens algorithm
(tw_engine::estimate_tokens, allocation-free). Routing computes it once per
request and RequestStarted reuses that number. Routing's estimate changes
slightly: images and files count 1,600 each, CJK one token per character,
thinking excluded; replay fixtures updated.

GET /upstreams/health (default window: the last 7 days) gives per upstream:
requests, failures and cancellations; answers that named a model and how many
differed from the model sent after normalization, with up to three example
pairs; the median of reported input / local estimate per model next to the
other upstreams' median for the same model; cache reads over turns that
should hit a cache next to the other upstreams' share; median time to first
token and generation speed. It reads the window once (about 70 ms on 100k
rows).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The history-search tests landed on main first and build request rows
by hand: give them the sent model, answered model and input estimate
this branch adds (the bulk insert must set the NOT NULL sent_model).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fylorn
fylorn merged commit 10388fb into main Oct 1, 2026
4 checks passed
@fylorn
fylorn deleted the upstream-health branch October 1, 2026 12:13
@fylorn fylorn mentioned this pull request Oct 1, 2026
fylorn added a commit that referenced this pull request Oct 1, 2026
Release for #244, #245 and #246.

- Bump the workspace version to 0.57.0
- Control-plane protocol 30 -> 31, with the version comment for the
  upstream check-up, history search and the personal-number matchers
- release-notes/0.57.0.md

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant