Repository navigation
Upstream check-up: model consistency, input usage vs the local estimate, cache reads per upstream - #246
Merged
Conversation
fylorn
force-pushed
the
upstream-health
branch
from
October 1, 2026 11:18
fcc5c12 to
cb8ab7c
Compare
…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
force-pushed
the
upstream-health
branch
from
October 1, 2026 11:52
cb8ab7c to
405c7f4
Compare
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
SCHEMA22 → 23; the store rebuilds by design, no migration)answered_model— the model the upstream named in its answer: Anthropicmodel(JSON) /message_start.message.model(stream), Chat Completionsmodel, Responsesmodel/response.model, GeminimodelVersion(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: amodelkey inside a tool call'sinput(which a relay that sorts keys puts before the top-levelmodel) 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 onRequestStarted. 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 likeprevious_response_id) have none.sent_model— the model sent to the upstream after rule rewrites (the last attempt's model).RequestRow.modelholds the client's original model; the check-up compares againstsent_model. The pricing page (unpriced_recent) now reads this column instead ofjson_extracton the routing JSON.One input estimator for all of core
Routing used bytes/4 (CJK undercounted, images 0, thinking counted);
count_tokensused 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'sinput_tokenstherefore changes slightly (images and files now count, CJK counts a token per character, thinking is excluded); the five replay fixtures'input_tokens_estimatewere updated accordingly.GET /upstreams/health—ep::UpstreamHealth,Windowquery (from_ms/to_ms), default the last 7 daysOne
UpstreamCheckupper upstream with rows in the window (most requests first), each number with its sample size:failediserror IS NOT NULL(same asSummary::failed); cancelled requests are counted apart and not inrequests; local answers and refusals that reached no upstream are left out.sent_modelafter normalization, up to three example pairssent → answeredwith counts (pairs that normalize to the same substitution are merged; the most common spelling is shown).others,other_upstreams).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 (summaryalone 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/segment:models/, vendor prefixes (anthropic/,openai/,google/,openrouter/anthropic/…), Bedrock ARNs, Vertex resource paths@…(Vertex@20250929,@001):free,:thinking,:nitro,:beta,:extended,:online,:floor,:exacto— only these words (Ollama's:7bvs:72bare different models)us.,eu.,apac.,jp.,au.,us-gov.,global.— the list now exported fromtw_pricing::name), known vendor prefix (anthropic.,amazon.,meta.…), then-v1:0/-v1/:200k(only after a vendor prefix:deepseek-v3keeps its-v3)[1m],-latest, dates-20250929/-2025-09-29/ four-digit-0613(MMDD) or-2507(YYMM) — each must be a real date, so-8192stays — and dated previews-preview-05-20/-preview-09-2025/-exp-0827(undated-previewstays:o1-preview≠o1).between digits →-(4.5=4-5)claude-3-5-sonnet=claude-sonnet-3-5,claude-4-sonnet=claude-sonnet-4), relay suffixes-thinking/-1mdropped, 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_dialectusage()), so billed input =input_tokens + cache_read_tokens + cache_write_tokensfor every format:input_tokens+cache_read_input_tokens+cache_creation_input_tokens(already disjoint)inputTokens+cacheReadInputTokens+cacheWriteInputTokens(already disjoint)prompt_tokensincludescached_tokens(andcache_write_tokens) → stored minus them; the sum isprompt_tokensinput_tokensincludescached_tokens→ same; the sum isinput_tokenspromptTokenCount + toolUsePromptTokenCountincludescachedContentTokenCount→ sameProtocol note for the version comment (
CONTROL_API_VERSIONis not bumped here)New endpoint
GET /upstreams/health([UpstreamHealth]);RequestStartedgainsinput_estimate, andRequestFinished/RequestFailed/RequestCancelledgainanswered_model(both optional, omitted when absent). A UI written for 30 does not see the check-up. Suggested text for the doc comment:The request store
SCHEMAis 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
cache_control.invokedModelId) is deliberately not read: a router is expected to pick a different model than the router ARN.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 warningsenv -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy cargo test --workspace— 1959 passed, 0 failedcargo clippy -p tw-api --all-targets --features ts -- -D warnings,cargo test -p tw-api --features ts,export_ts+tsc --noEmit --strictscripts/smoke.sh— 66 passed, 0 failed (the existing 37 MB memory warning only); new checks:/upstreams/healthwith and without a window, and the answered model of the fake upstream reaching the check-up as consistentmodelkeys, 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_idwithout an estimate); recorder (sent_modelafter a rewrite,answered_modelon 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🤖 Generated with Claude Code