Repository navigation
feat(dash): per-model prices, prompt-cache savings, gate reasons, and a host dashboard - #83
Merged
Merged
Conversation
added 11 commits
August 19, 2026 00:14
…cache savings Three cost figures were wrong or missing. PRICES. Rates came only from the public LiteLLM map, which prices the public API. ete-litellm bills aws/claude-sonnet-5 at $1.52/MTok in where anthropic.com bills $3.00, so every dollar on the dashboard for that gateway was about twice the truth, and a model the public map has never heard of — a preview id, or Bob every request, whose model is the server-resolved tier `premium-ide` — read as unpriced, which is why a Bob session shows tokens but no cost. MODEL_PRICES points at an operator price list, consulted first; deploy/service/prices.example.yaml is the ete-litellm table. Rates are per MILLION tokens there, because a per-token float in a hand-edited file is a factor-of-1000 typo nothing would catch. While there: LiteLLM.Price fell back to the first key of a Go map range that contained the id, so which price `gpt-5` resolved to was randomised per process. Shortest containing key now wins. THE RE-SENT REMAINDER. A removal was always valued at the cache-read rate on the turns that re-sent it, on the reasoning that a re-sent transcript is served from cache. True only when the cache HIT. On production traffic, turns whose cache had expired were 4% of requests and 31% of spend, all of it cache_creation — their savings were valued 12.5x too low, on exactly the turns where removal is worth most. Priced by the outcome the request actually had: read on a hit, write on a miss, fresh where nothing cached. THE PROMPT CACHE. Its savings appeared nowhere, so cachesplit had nothing to show in dollars for the one thing it does. cache_saved_usd is a request cache reads against the fresh rate; the overview reports it, the part of it landing on requests where one of our cache components acted, and both savings together. Kept OUT of net savings on purpose: the baseline already assumes the cache behaved as it did, so adding it there would double-count. The column is added by ALTER TABLE on open, not a schemaVersion bump, which would rename the live database aside and discard every request row to gain one column. Signed-off-by: Osher-Elhadad <[email protected]>
"I can see the stats but no components ever ran" is the report, and the dashboard had no way to answer it. Every component records WHY it turned each candidate away — `no_filter_match`, `no_obvious_noise`, `below_output_floor` — and that map went to /stats (service-wide, so useless for one session) and to the log line (per request, so it needs Loki and a LogQL selector). The dashboard, which is what someone actually opens, showed a table of zeros with nothing beside them. Measured on a real Bob run through a local proxy: 4 requests, 87k tool tokens, one component acted. The gates say exactly why — cmdfilter `no_filter_match=15`, extract `no_obvious_noise=14`, format `not_json_shaped=19` — because the offload heuristics were written against Claude Code's tool-output shapes and Bob frames its `read_file` output differently. That is a tuning finding, and it was invisible. Stored as JSON on request_components (added by ALTER TABLE, no version bump), summed with json_each rather than decoding a map per row in Go, and shown as a "Why declined" column in both the components table and the request drawer. A row written before the column reads "unknown", never "gated nothing". Signed-off-by: Osher-Elhadad <[email protected]>
…its own accounting Read the gateway's /v1/models: it serves ids the admin table does not show, with mixed case (`Azure/gpt-4o`) and with no provider prefix at all (`claude-opus-4-8`, `gemini-2.5-pro`). Case normalises on lookup; the missing prefix does not, so those fell through to the public map. Family entries catch them, and a test asserts all 39 live ids price — an unpriced id is a dashboard row reading "cost unknown". Bob's `premium` tier is fitted rather than assumed: against the session_costs Bob prints for itself on two real runs it lands -18% and +39%, the two runs imply in-rates $2.17 and $3.67/MTok, and no single rate reproduces both because Bob's figure is not linear in the tiers the gateway reports. $3.00 sits between them and is a published rate. The file says so, with both measurements. Signed-off-by: Osher-Elhadad <[email protected]>
Nothing here answered "is this box healthy". The proxy cannot answer it about itself either: out of memory, out of disk or out of CPU all look like a slow upstream from inside the request path, which is why "it felt slow" was never diagnosable from the dashboards. So install.sh grafana now also runs node_exporter — the standard exporter rather than a /proc reader of our own, so the queries are the ones every runbook already uses — loopback only, host /proc and /sys read-only, and a `node` scrape job. context-guru-host has 18 panels: CPU by mode, memory including swap, filesystem fill per mountpoint, disk and network throughput, file descriptors against the kernel limit, context switches, and systemd's own view of the context-guru and nginx units, which still answers during a crash loop because it reads the unit. The service dashboard gains the prompt-cache saving beside the compaction one, and a total. Cache savings are the series that falls when compaction rewrites a live prefix, so it belongs next to spend, not in a corner. Also a test: every cg_* metric a dashboard queries must appear in the rendered exposition. A panel querying a metric we do not export renders EMPTY, which is indistinguishable from a healthy idle system — the drift between hand-written exporter and provisioned JSON had nothing watching it. Three families are listed as deliberately conditional, with the condition. Signed-off-by: Osher-Elhadad <[email protected]>
config.md gains the MODEL_PRICES section — why the public map is not enough (wrong rates for a gateway that discounts, no rates at all for a preview id or a server-resolved tier), the file format, and the warning that a tier's rate is an estimate with an error bar rather than a price. dashboard.md explains the two counterfactuals and why they are added rather than nested: compaction savings prices removals at the rate the request actually paid, prompt-cache savings prices cache reads against the fresh rate, and folding the second into the first would double-count a baseline that already assumes the cache behaved as it did. Also the "Why declined" column, which is the answer when act rate reads 0%. hosted.md carries the install steps for the price list on the box, and the host dashboard's URL beside the other three. Signed-off-by: Osher-Elhadad <[email protected]>
On a turn whose cache hit this is usually the largest money figure on the row — $0.087 billed against $0.305 saved by the cache, on a real four-request Claude Code session — and it appeared nowhere. The request row already stores it; the drawer now reads it beside actual and baseline cost. Signed-off-by: Osher-Elhadad <[email protected]>
node_exporter's systemd collector needs /run/systemd/private mounted WRITABLE, and
that socket is full control of systemd on the host. One panel colouring the
context-guru unit's state is not worth handing that to a metrics exporter, and
up{job="context-guru"} on the SLO dashboard answers the same question from outside
the process.
The slot goes to pressure-stall instead, which node_exporter reports for free and
which no utilisation graph can substitute for: 100% CPU with no pressure is a box
working, a few percent of pressure at moderate utilisation is a box already
queueing. All 66 dashboard expressions were checked against a live Prometheus for
parse errors before this landed.
Signed-off-by: Osher-Elhadad <[email protected]>
An A/B between a shallow and a deep pipeline reads the deep one as the winner on compaction savings alone. If it rewrote a live prefix to get there, the money went into cache writes, and the column that shows it was missing from the comparison this project actually uses to choose a preset. Signed-off-by: Osher-Elhadad <[email protected]>
Both scan request_components — one an EXISTS per request, one a json_each expansion — so either could have turned a dashboard load into a table scan without anything noticing. Measured at the live service's scale, 200,000 rows: 199 ms and 143 ms, inside an Overview of 1.31 s and a Components of 1.14 s that were already dominated by the aggregates that were there before. The test runs at a twentieth of that so the suite stays quick under -race. Signed-off-by: Osher-Elhadad <[email protected]>
`go build ./cmd/...` writes its binaries into the WORKING DIRECTORY, not into bin/, so a release-sized artifact sat at the repo root and was committed with the first commit on this branch. .gitignore covered /bin/ and not that path. The blob is still in this branch's history; squash-merging keeps it out of main's. Signed-off-by: Osher-Elhadad <[email protected]>
…tribution
PRICE LOOKUP, two ways to be confidently wrong (both measured against the shipped
list, both worse than a miss because Table.Price returned ok=true and the public map
was never consulted):
- A family beat a more specific entry, because "longest wins" only held WITHIN a
pass and a bare id could only be reached in the third one. `gemini-2.5*` (Flash,
$0.30) won over `gemini-2.5-pro` ($1.25) for gcp/gemini-2.5-pro-preview-05-06 — a
Pro deployment priced at Flash's rate, 4x under. Prefix and containment now
compete in one pass ordered by length.
- Bob's tier names are ordinary English words, and containment on them claimed
every id that happened to contain one: azure/gpt-5.2-fast priced at Bob's `fast`
estimate, ten times under. Containment now applies only to entries that look like
a model id (carrying a `/` or a `.`), and the tiers are enumerated rather than
globbed, so `standard-diffusion-xl` is not a Bob tier either.
MODEL_INFO=off silently discarded MODEL_PRICES: the early return sat above the load,
so the file was never opened, never validated and never logged, and every row priced
as `partial`. `off` disables the fetched public map — a network dependency — and must
not throw away a local file the operator named.
cache_saved_protected_usd was structurally $0.00 on every deployment. The volatile-tail
split happens in apply, because it edits the top-level `system` array that components
never see, so `cachesplit` unconditionally reported Skipped — and `mutated` is derived
from that. The measured -34.1%-cost mechanism read "declined" on the requests where it
had just run. Recorded where the fact is known: apply marks the report when the split
fires. Proven to fail without the fix.
repeatRate over-claimed on a common shape: `cache_write > 0` does not mean the prompt
was cached — one breakpoint after `tools` bills cache_creation=2k, input=100k — so the
write rate now requires the written part to be at least the fresh part. A 25%
overstatement in the inflating direction the comment claimed to avoid.
Gates: "gated nothing" is stored as {} and no longer omitted from the JSON, so a
healthy component reads "—" instead of "unknown" — the confusion the column existed to
remove. The aggregation uses json_valid() rather than relying on the planner to
evaluate `gates <> ''` before entering json_each, which aborts a whole statement on a
malformed value.
The protected-cache term folded into the existing aggregate (one scan, not two; it was
199 ms of its own over 200k rows), and the stale copy corrected: the baseline and
compaction waterfall steps still told the reader the re-sent remainder is priced at the
cache-read rate, which this branch had just stopped doing, and the write/read spread is
12.5x, not 11.5x. The total-avoided step and tile now say what they include —
disjoint token sets, not a fully-uncached counterfactual, and traffic context-guru
never touched.
Signed-off-by: Osher-Elhadad <[email protected]>
added 17 commits
August 19, 2026 06:24
… that says so
Both were caught by installing this on the box and asking Prometheus for each panel's
data — PromQL that PARSES is no evidence, and all 66 expressions parsed.
- Load per core divided a labelled `node_load5` by a bare aggregate. An aggregate
without `by` carries no labels, so vector matching matched nothing and the panel
was empty. Wrapped in scalar().
- The pressure-stall panel needs /proc/pressure, which this RHEL 9 kernel does not
expose: node_scrape_collector_success{collector="pressure"} is 0. Replaced with
disk utilisation (rate(node_disk_io_time_seconds_total[5m])), which answers the
same "is something starved?" question from what this kernel does report. If PSI is
enabled on your host those series are worth a panel; the description says so.
And the reason this is not just two edits: an empty panel is indistinguishable from a
healthy idle box, so nothing would have reported either of them. `grafana-status` now
checks EVERY host panel for data and prints the ones that would draw nothing, with why.
Verified both ways on the box — "all panels return data" after the fixes, and it names
both failure modes when fed a dashboard that has them.
Signed-off-by: Osher-Elhadad <[email protected]>
The previous commit amended cachesplit's report after `pipe.Run` returned. That fixed the dashboard and left /stats and cg_component_runs_total still reporting the component as skipped, because the pipeline emits each report to the metrics aggregator as it goes — two surfaces disagreeing about the same fact, which is exactly the failure this project keeps a dedicated test for. apply already knows the answer before the run (splitVolatileTail runs first), so the fact travels on Ctx.SystemSplit and Cachesplit.Reformat reports from it. One version of the truth, and every consumer gets it. Verified live on the box: /stats had cachesplit mutated=0 over 140 production requests while the dashboard was crediting it — which is how this was found. Signed-off-by: Osher-Elhadad <[email protected]>
…ving It was labelled "of which on our breakpoints", which reads as a claim. It is not one: it locates the share of cache money billed on requests where one of our cache components had just rewritten the prefix, and the agent places most breakpoints itself. Co-occurrence, not cause. Two things it now says instead. Causation needs an A/B, and the split has one (-34.1% cost, 0% -> 96.7% hit on the same traffic) — this figure points at where to look. And it is a FLOOR: a stable prefix is a property of the session, while this counts only the turns the component acted on, and the turn a boundary is placed on is often the turn that WRITES the cache, with the reads arriving on later turns nobody credits. On live traffic it reads 1.7% of the total, which is what that undercount looks like. Signed-off-by: Osher-Elhadad <[email protected]>
The dashboard led with "Prompt-cache savings", which was the PROVIDER's whole
prompt cache priced against the fresh rate, plus a second tile for the subset
that happened to land on requests where one of our components had acted.
Neither was a saving of ours. The agent places most of the breakpoints itself,
and co-occurrence is not cause.
Replaced by one figure that is measured. A request contributes only when the
volatile-tail split actually ran on it, the provider then READ that prefix from
cache, and it was the session's FIRST request -- the one that would have missed.
Later turns in a session hit whether or not the tail was ever split, because the
environment snapshot does not change mid-session.
The amount is the stable half the split moved, not the request's whole
cache_read. That came out of running the control arm rather than reasoning about
it. Four real Claude Code sessions through ete-litellm, each started after a
fresh commit so the snapshot genuinely differed, first request of each session:
cache_read cache_write
cachesplit on 54,304 1,063
cachesplit off 45,805 9,555
The control still hit -- the breakpoints before that block match whatever we do
-- so crediting the whole read overstated it ~9.6x. The split now reports the
size of the half it moved (split_stable_tokens, 5,654 BPE tokens there) and that
is what gets priced, which is smaller still than the 8,499-token difference the
provider reported. Under-crediting is the only safe direction.
Priced against a cache MISS, not fresh input: those tokens carry cache_control,
so a miss bills them as creation at 1.25x fresh. total_saved_usd is now
compaction plus this, both ours.
cache_saved_usd stays in the API and in Prometheus as a DIAGNOSTIC, labelled as
one: it is the number that collapses when a pipeline rewrites deep history, so
watching it fall is how a too-deep pipeline gets caught. It is off every tile,
out of the savings waterfall, and out of the per-model savings column.
Verified live end to end: $0.009883 on the one qualifying request of a two-session
run, against $0.225776 for the provider figure over the same four requests --
23x, which is the size of the claim this removes.
Signed-off-by: Osher-Elhadad <[email protected]>
…ed writing YAML
Two accounts could not save their extract_llm settings at all:
Not saved: tenant: config rejected: config: yaml: line 3: did not find expected key
Reproduced, and it was ours. The settings page built the configuration document
with regular expressions in the browser, replacing the whole `pipeline:` line
with a flow-style one. On a config whose pipeline was written as a block
sequence that orphaned the items under it:
mode: sync mode: sync
preset: general -> preset: general
pipeline: pipeline: [extract_llm]
- format - format
- extract - extract
The server refused the result, correctly, which left the old document stored for
the next attempt to mangle again -- so it failed on every save, with no way out
from the UI. A `preset:` document lost its entire pipeline the same way and did
it SILENTLY, because the regex found no flow-style line to read the existing
names out of.
So the page posts fields (`config` on PUT /api/me) and the server applies them
with a real YAML library, validates by building the result, and stores it only
then. config.ParseForm resolves presets, so the grid finally shows what a
tracking account actually runs instead of an empty pipeline. Keys the form does
not own -- model:, strategy, marker_mode, another component's block -- survive
the round trip; comments and key order do not, which is the trade for never
emitting a broken document.
Enum values are validated here too. extract_llm's own loader is non-strict, so
`aggressiveness: aggressive` did nothing at all and said nothing about it.
~190 lines of YAML surgery deleted from app.js along with the textarea. Anything
the fields do not cover is still set through the account editor, which takes a
document and validates it strictly.
Verified live against a hosted proxy: reproduced the exact error from the exact
starting state, then saved the same account through the fields and read the
values back.
Signed-off-by: Osher-Elhadad <[email protected]>
The savings figure could still over-claim in three ways, and the settings form could still lose configuration in three more. Over-claiming: * A cache HIT does not mean OUR half was the thing served. On the first request after the stable half itself changed -- someone edited CLAUDE.md, the tool list moved -- an earlier agent breakpoint still hits, so cache_read > 0 while our half is billed as CREATION on that very request. Now the read must be at least the size of the half we split off AND the write must be smaller than it. Neither test can isolate our breakpoint from the usage block, so both are blunt and both refuse rather than guess. * "Session's first request" meant "first this PROCESS has seen". The recency map is in memory and started empty, so every restart mid-conversation handed out one bonus credit per live session; the 20,000-entry bound then did it to every session at once by emptying the map. Fixed at the source: the map is seeded from the database at startup, and it is pruned by AGE, where forgetting is genuinely correct because a session silent that long has lost its cache anyway. The pruning also fixes cache_miss_reason, which reported a cold start for everything in flight across a restart. * A partial hit was clamped to what was served; it is refused instead. Losing configuration: * A bare `preset:` resolves to a pipeline containing extract_llm and carries no per-component block, so "no block" was read as "switched off" -- the form drew both switches off for an account that runs it, and the next save wrote a pipeline with the component REMOVED. Silently, which is the exact failure class the form replaced. * Switching the component off deleted its whole block, taking `model:` with it, so re-enabling it ran on the expensive default. Only the keys the form owns go now; leaving it out of the pipeline is what stops it. * `llm_max_per_session: 0` means UNLIMITED to the component, and a plain int could not tell that from an unset key -- so the form displayed 20 and the next save wrote 20 over a deliberate no-cap. The document fields are pointers now. A zero SIZE threshold is refused outright: that is a removed brake, not a setting. * A document that fails the strict load now says so on the form (parse_error) and cannot be saved from -- 409 server-side, disabled client-side. A save from a best-effort read, over an already-broken document, on a page with no YAML box, would have been a worse version of the bug this set out to fix. Also: the load-bearing evidence numbers disagreed between the files that carried them (8,478 vs 5,654 tokens, 6.4x vs 7.5x, 1,041 vs 1,065). All of them now say what was measured. The comment claiming SessionFirst is recoverable from cache_miss_reason was wrong -- AttributeCache short-circuits to "hit" on every qualifying row -- and cacheinject.go still named a consumer this work deleted. The A/B table shows the new column instead of hiding it behind the old one. The seeding call was missing from main.go entirely until a real restart was checked for its log line; the method and its test existed and nothing called them. Signed-off-by: Osher-Elhadad <[email protected]>
…er is small Osher asked for cachesplit's real saving over the stored sessions. Extracting it found that the figure I had shipped was structurally near zero, for a reason that had nothing to do with the component. The old condition was "the session's FIRST request". Over 1,127 stored sessions, 1,105 of those first requests read ZERO tokens from cache: the previous session's prefix had expired under the provider's 5-minute TTL before the next session began. Only 9 session starts had a warm prefix to hit at all. So the figure reported ~$0 while the split was demonstrably serving the system prompt from cache on hundreds of mid-session turns. The condition that actually makes a hit ours is that the environment snapshot MOVED since that session's previous request. With the block unsplit, a moved snapshot re-creates the whole thing; a tail that did not move would have been served from cache either way. So the split now hashes the volatile half it moves the breakpoint off, that hash is stored per request, and the comparison is per-session and survives a restart (seeded from the table, like session recency). The realised number, extracted from the stored history: $0.0298 across 1,127 sessions and 11,361 requests. Three independent measurements say why it is small, and none of them is a defect: * The snapshot is captured ONCE per session. A nine-turn session in which the agent created and committed four files produced ONE distinct tail hash -- Claude Code does not refresh that block mid-session, even after commits. Within a session there is nothing to protect. * Session starts are almost always cold, per the 1,105 of 1,127 above. * On the 9 warm starts it works exactly as designed: 3 qualified at ~$0.010 each, matching the controlled cachesplit-on/off measurement to the cent. The regime where this pays is back-to-back sessions inside the TTL, which is what the SWE-bench A/B (-34.1% cost, 0% -> 96.7% hit) was measuring. Benchmark and production differ by three orders of magnitude without either being wrong. So the page now carries the three counts behind the dollar figure -- requests the split ran on, snapshot had moved, served from cache -- because a small saving with no counts beside it is indistinguishable from a broken component. That is not hypothetical: it is what the previous version looked like. Verified live: two sessions started inside the TTL with a commit between them are credited $0.009864 each on their first request and $0.00 on their second, with the tail hash constant within a session and different across the two. Signed-off-by: Osher-Elhadad <[email protected]>
Three of this deployment's larger accounts run cachesplit on 125, 1,035 and 1,972 requests and it has acted on NONE of them: their system prompt carries no volatile tail to split, either because the big block is under the 1,024-token floor or because it holds none of the snapshot markers. Agents run outside a git repository are the common case. That is a fact about their prompt, not a fault, and it is a different zero from "it acted and the snapshot never moved". The tile said "Requests it ran on", which was simply wrong -- the component runs on every request and does nothing on most. Signed-off-by: Osher-Elhadad <[email protected]>
…tal cost Two things Osher asked for. 1. The cachesplit saving over the stored history now appears on the page. It could not before: the two facts the figure needs -- the size of the half the split moved and the identity of the tail it moved off -- are recorded per request only since that instrumentation shipped, so every earlier row priced at $0.00. On the dashboard that is indistinguishable from "the component did nothing", which is exactly the reading it invited. So the API values those rows on READ (dash.DB.CachesplitHistoricalUSD) and the Prefix split group shows it as "Before we recorded it". NOTHING IN HISTORY IS REWRITTEN -- the first version of this was a one-time UPDATE over the requests table and that was the wrong instinct: it would have injected inferred figures into other people's rows permanently. Recomputing from the stored rows on every query costs one indexed pass, keeps history exactly as recorded, and there is a test asserting no stored row changes. What makes a retroactive value legitimate rather than a guess: the stable half is a property of the AGENT'S SYSTEM PROMPT, not of the request, and it is measurably constant -- per model on this deployment the recorded minimum and maximum are the same number. CachesplitSizeSpread reports both so that gets checked, not assumed. Three limits, all under-crediting: only the session's FIRST request (crediting a mid-session turn needs the tail hash those rows do not carry), only models whose stable half was actually measured, and the same read/write test as the live path. A floor on a floor. Absent rather than zero when it cannot be priced. 2. Total cost of all requests, in Grafana: cg_tenant_total_cost_usd, the provider's billed cost plus our own compaction-model spend. Every other money panel there is a difference against a baseline; this is the number on the invoice. Its own stat, first on the row -- which is now seven stats at w=3 rather than six at w=4, because at w=4 the seventh collided with the sixth at x=20. Verified end to end against a database carrying a planted pre-instrumentation row: measured $0.019728, historical $0.009864 on 1 session start, counters consistent (acted 4 >= moved 2 >= credited 2), and all four metrics exported. Signed-off-by: Osher-Elhadad <[email protected]>
…and stop the roster reading "components:"
Three complaints from one account, all the same shape: the settings page described a
configuration it did not actually cover.
The roster's configuration column showed the document's FIRST LINE. Since the settings form
started writing that document through a YAML marshaller its keys come out alphabetically, so
line one is the word `components:` for every account that has ever saved — a cell that reads
as "configured with no components" on precisely the accounts that are configured. It shows
the resolved pipeline now, which is the fact anyone opens that column for.
`extract_llm` did nothing for that account, and nothing on the page could explain it. Two
keys were in the stored document and on neither the form nor the page, and each one is
independently fatal:
* `model.source: config` selects an operator-configured compaction model, and hosted mode
deliberately has none — staticModel() withholds the operator's credential from tenant
traffic. So the component had no model and silently never called anything: 251 requests,
zero calls. GET /api/options now reports `compaction_model`, and the field's hint says
so in as many words on a deployment where it is false.
* `allow_on_caching_backend` absent means false, and the economic gate then hard-declines
every candidate whose tokens are prompt-cached. On Claude Code against Anthropic that is
the whole workload.
Both are controls now, with `strategy`, `llm_every_n_requests` and
`trigger.min_request_tokens` — the other keys real documents already carried and the form
could not show. `model` and `trigger` are shared blocks, so the form sets one key inside each
and switching the component off leaves them alone rather than deleting a base_url with them.
The form is a subset of what a document can say and always will be, so the whole document is
on the page too, read-only. Not a textarea: that is the regex-rewriting writer this page was
rebuilt to remove.
The drift itself is fixed rather than re-listed: the UI contract test now reads the field
names off config.ExtractLLMForm by reflection, so a field added on the server and missing
from the page is a failing test naming it.
Empty enum strings normalize to the component's own defaults instead of 400ing. A browser
holding a cached bundle does not know about a field added since, and answering its save with
`model_source "" is not incoming or config` would break the settings page for as long as that
cache lives.
Also drops failed_run from the default pipeline. It acted ZERO times on every workload
measured here — 251 requests and 843 ms of scanning on one account, 28.8 s on the
Terminal-Bench arm — so it was latency with a name. Still registered, still available to
anyone whose traffic re-sends superseded failures.
Verified against a copy of the real stored document, through the real page: every control
renders, the page reads all fifteen fields back faithfully, a save posts all of them, and the
resulting document is the original plus exactly the two keys that were changed.
Signed-off-by: Osher-Elhadad <[email protected]>
…g actually runs
Production logged this on every start since the tail hash landed:
dashboard: could not recover session recency; the first turn of each live session will
be reported as a cold start — sql: Scan error on column index 2, name "split_tail_hash":
converting driver.Value type int64 ("-1392166818831166011") to a uint64: invalid syntax
SQLite's INTEGER is signed. A hash above 2^63 stores and returns as a negative int64, and
scanning that straight into a uint64 fails — not one row, the whole query, so SeedSessions
returned nothing and every session in flight across a restart went back to being reported as
a cold start with a bonus tail-change credit. Exactly what that function was added to stop.
Scan into int64 and convert; the bits were never wrong, only the container.
The test passed throughout because it used 0xBBBB. FNV-1a puts half of all real hashes above
2^63, so the fixture now has the top bit set and fails without the fix.
Signed-off-by: Osher-Elhadad <[email protected]>
…urn's duration
Reported as "continue on an hour-old session, four or five minutes, then an API error", and
suspected to be the compaction-model component. It was not: on the eleven requests that failed
this way, context-guru's own time was 25-84 ms, extract_llm made zero model calls, and
cg_llm_cost_usd was $0.0000. Every one of them was a STREAMING request, and upstream_ms clustered
on 297,9xx — our own ceiling, hit exactly.
The default upstream client was http.Client{Timeout: 5 * time.Minute}. That timeout covers
reading the response body, so on a streaming dialect it is not a liveness check, it is a cap on
how long a generation may last. Claude Code streams with thinking enabled; a long turn on a large
session runs past five minutes of legitimate token production and we cut the connection, which
surfaces to the agent as an API error after minutes of apparently healthy work. 160 shorter
streamed turns from the same account through the same upstream succeeded in the same window,
which is why this looked like a component and not a timeout.
ResponseHeaderTimeout is the right shape: it bounds waiting for the FIRST byte, so a dead
upstream is still caught, and a stream is never interrupted for having produced tokens for a
while. It also still bounds a non-streaming request end to end, because those headers do not
arrive until the answer is generated — hence a generous 10m default rather than a tight one,
tunable with --upstream-header-timeout / UPSTREAM_HEADER_TIMEOUT.
The test drives a real server whose stream outlives a deliberately tiny header budget, so it
does not wait five minutes: a long stream must complete, a silent upstream must still fail, and
the handler's default client must carry no whole-request Timeout at all.
Signed-off-by: Osher-Elhadad <[email protected]>
…did the work Three defects in cg_llm_cost_usd, found by chasing why a measured cold-cache sweep looked like it lost money. Each is pinned by a test that fails without its fix. 1. It was priced at the AGENT's rate, not the compaction model's, with a comment calling a cheap model "close enough". A coding agent runs opus and a sensible compactor is haiku; on this deployment's rate card that is 4.75x. The usage sink now records which model made the calls, and a scope that mixed several falls back to the agent's rate rather than picking one arbitrarily, because no single rate is honest for it. 2. It passed 0 for both cache tiers. Our own calls are prompt-cached too, and a cold sweep sends the whole transcript, so cache-WRITE is the largest part of what it costs. On a synthetic cached call the omission is 15.5x. Wrong in the flattering direction is the worse way for a cost to be wrong: it argues for spending. 3. extract_llm replaced its rate card with the agent's rates whenever model.source was `incoming`. That was right when `incoming` could only mean "the agent's model compacts". It is wrong now that model.model can re-point an incoming-source client at a cheap model on the same endpoint, and it is what made the Components tab disagree with the request row by exactly 4.75x. Extracted as pricingFor so the decision is testable rather than inline. Defects 1 and 2 point in opposite directions and partly cancelled, which is why nothing looked broken and why two of them survived a previous pass over this same figure. Evidence, five real Claude Code sessions against a local proxy, cold sweep with a haiku compactor: the per-call figure and the per-request figure now agree to 0.02% ($0.2402 vs $0.24015 over three sweep calls), where before they were 4.75x apart. Agreement between two independently computed paths is the check that was missing; the number itself was never the problem. Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
Measured over 14,298 production requests and five fresh Claude Code CLI sessions. Each of these is independent and each was, on its own, enough to sink the component. The model was writing Python. Starlark is a Python SUBSET with no generator expressions, so `any(k in ln for k in ids)` — the most natural way to write the filter — is a syntax error. claude-haiku-4-5 returned a plausible program on essentially every call and the sandbox discarded 12 of 13. The contract now states what Starlark is not, naming the constructs models actually reach for. On the same real 33,932-character file read: 0/3 produced output before, 3/3 after, at 56%, 83% and 55% reduction. Every failure reported the same reason. RunExtractionDetail collapsed a sandbox syntax rejection, a transport error and "the model never replied" into one string. Three causes with opposite fixes, indistinguishable — which is precisely why the Pythonism above survived: the component looked ignored when it was being answered and thrown away. The reason now escapes to the call record. The gate under-priced its own calls by 21-31x. callCost modelled the prompt as preamble + min(candidate, 5000) + 200, at most 6,663 tokens. Under `context: full` the rendered transcript IS the prompt: five production calls on one request each sent ~138,000 tokens. For a 3,433-token candidate the gate weighed $0.0077 of saving against $0.0046 of estimated cost and allowed a call that cost $0.1422 and removed nothing. The true figure sat two lines away as promptOverhead, discarded. Our own calls were not prompt-cached. Those five calls carried cache_read = 0 and cache_write = 0: the same transcript sent fresh five times. The context is computed once per request and is identical across its candidates, but it sat in the user message. It is now a trailing cacheable system block — and only when the request will make more than one call, because a cache write costs 1.25x fresh and paying that for a single call is a 25% loss with nothing to read it back. Verified live: cache_creation 30007, then cache_read 30007 on every repeat, 67% cheaper on a five-call request. It also lifts the prefix over haiku's 4,096-token minimum, below which nothing was being cached at all. Not fixed here, because no code change can: 94% of the losing spend was made against this gate's own written advisory. `fire_on: size` demotes it and leaves the caps as the only brake. Signed-off-by: Osher-Elhadad <[email protected]>
format and toon were near-inert on real Claude Code traffic for one reason. Tool
results arrive wrapped:
{"ok": true, "exit_code": 0, "stdout": "{\n \"total\": 50, … \"tasks\": [ … ]}"}
format parsed the outer envelope, re-encoded it and saved 9 tokens of 6,459 (0.1%).
toon saw the outer object, concluded not_uniform_object_array and never descended.
The uniform record array toon exists for is one level down, inside a JSON-ESCAPED
string. This single fact accounts for format's not_json_shaped at 98.4% of
candidates and toon's not_uniform_object_array at 72.8%.
Measured: of the large low-reduction JSON blobs, 673/673 carry their payload in a
stdout string, and 537 of them — 2,098,762 tokens, 89% of that mass — contain a
repeated-record array.
Both now descend a string field that cheaply looks like JSON, transform, and
re-escape. toon needs two levels because the array is a field of a wrapper object
inside the string. The field name is not special-cased; stdout is recorded in a
comment as the measured case. Depth is structural rather than a counter, and a blob
is left untouched unless the whole result shrinks, so nothing leans on the
pipeline's never-worse guard. Sibling envelope fields round-trip byte-exact —
UseNumber so large integers are not rewritten in exponent form, and escaping off so
untransformed siblings do not grow <.
On the envelope fixture: toon 1,784 -> 483 tokens (72.9%), format 1,784 -> 872
(51.1%). Both were previously zero.
Signed-off-by: Osher-Elhadad <[email protected]>
Evaluated locally under the cg_skeleton tag only. Nothing is enabled, the build tag stays, and no preset or default pipeline changes. Three ways it could lose content unrecoverably, all now closed. effectiveMode silently degraded full -> off when the store could not persist, eliding code bodies with no stash and no resolvable marker; the pass now declines instead. marker_mode summary|off did the same by configuration and is now rejected at construction. And a suite-style body elided to a bare "…" is VALID Python — Ellipsis — so a write-back would stub every function with no compile error; the placeholder is now a syntax error in every supported language. Line numbering is preserved: a multi-line body collapsed to one line moved every signature below it, and an agent that greps a line number and then edits it is a concrete failure mode. Preservation costs 317 tokens, 0.7% of the saving, so there is no knob for it. Measured on a real capture: as shipped it removes nothing at all — 0 of 66 tool outputs, because the v1 fence-only matcher never sees the unfenced, line-numbered text a real file read actually is. With the gutter stripped and the grammar sniffed, 15 of 18 source reads skeletonize: 68,680 -> 22,310 tokens, 67.5% of those reads and 27.6% of all tool tokens in the capture. That is the largest deterministic lever measured anywhere in this pass. It stays off regardless. Every other lossy component drops output the agent can re-derive; this one drops the content the agent's NEXT ACTION is derived from, and an elided body is indistinguishable from an empty one, so a broken rewrite is silent. Reversibility does not answer that: expanding is something the model must choose to do, and it has no signal that it needs to. The four conditions that would have to hold before revisiting are written on the component's page. Signed-off-by: Osher-Elhadad <[email protected]>
added 17 commits
August 19, 2026 18:30
The complaint that started this: users saw what extract_llm COST and concluded the
product was worthless. They were reading a real number with no counterpart. The
per-request accounting was already correct — independently reproduced against
production data to 1.8% — but there was no per-component dollar attribution, so the
UI improvised one client-side with hardcoded sonnet-class rates on a deployment that
runs opus (27% wrong) and no amortization at all, though replay is ~93% of realized
value.
Per component, per request, at the tier the request actually paid:
saved_usd = u*CacheWrite + (g - u)*tier(r)
g = saved_gross, u = min(saved_unique, g)
tier(r) = CacheRead when cache_read > 0 (warm: replay served from cache)
= CacheWrite when the prompt re-billed (cold/TTL)
= Input otherwise (non-caching backend)
The sum over turns IS the amortization: realized turn by turn as the frozen
reduction replays, not projected. repeatRate is reused rather than re-implemented,
and the identity sum_c saved_usd == baseline - cost is now a test. It holds exactly
on fixtures.
Its doc comment was also over-general: it claimed cache-aware removals would have
been billed fresh rather than as a read. True of the unique term, which is already
priced at the write rate; false of the replay term this function actually prices,
which sits deep inside the cached prefix. Acting on it as written would have
inflated warm-turn savings ~6x.
saved_usd is an additive column with a default, so no schemaVersion bump and no
history discarded. Sessions gain in_flight: a young session with one extraction call
has an incomplete amortization, not a verdict.
Overview gains prefix_change_cost_usd, deliberately NOT netted. On transcripts over
60k tokens a turn following one of our own mutations is ~3x more likely to take a
prefix_change cache miss, at roughly $24 excess over this window — larger than every
saving on the dashboard. Mutation is not randomly assigned, so it ships as a
labelled diagnostic until an A/B settles it. Invisible was the wrong answer;
subtracted would have been dishonest.
Signed-off-by: Osher-Elhadad <[email protected]>
The mechanism was already there and tested: scope() resolves one scope per request from the cookie principal, and every read funnels through Filter.where(). Only the default was wrong — a manager with no ?tenant= got their own id — so the aggregate they were signed in to see was one query parameter away and nothing in the UI could produce it. An absent tenant param now means service-wide for a manager, and ?tenant=me narrows back. The narrowing assignment stays above the manager branch and stays an overwrite, which is what stops a non-manager widening; nothing client-supplied can widen scope. Setting Tenant to empty when widening is load-bearing beyond tidiness: captureState(f.Tenant) was reporting the MANAGER's own content-capture consent as the session's whenever scope was wide. events() had its own duplicate ?tenant= parsing — a second copy of the widening rule, next to an SSE hub that streams every tenant's session ids when told to. It now derives its scope from the same resolver, which is the actual one-mechanism win. A wide-scope single-session transcript is pinned to the first turn's tenant. SessionEvents deliberately returns both tenants' turns for a shared session id, so without the pin a manager's diff would interleave two people's code under one id. Sessions rows carry tenant_id, without which an all-accounts list is unattributable. Signed-off-by: Osher-Elhadad <[email protected]>
cachesplit read as a dead component in Grafana. cg_component_runs_total emitted ran,
acted and reverted — and cachesplit is Mutated-never-Acted BY DESIGN, because the
split removes no content tokens, it moves them out of the hashed prefix. So the hit
rate panel computed acted/ran = 0% and painted red the one component with a measured
-34.1% cost effect, while Prometheus held no series that could say otherwise.
mutated and discarded are now exported and the panel counts activity.
Gate declines are now cg_component_gate_declines_total{component,gate}. "acted: 0" is
the one number a diagnosis cannot use: it cannot tell a component with nothing to do
from one whose guard is misfiring. toon's 14,675 not_uniform_object_array over 18,288
candidates is the whole story and was unreadable. Names are constants, so cardinality
is bounded by code; label values are escaped, with an adversarial gate name in the
test. The Loki panel that should have shown this hard-errored with "maximum of series
(500) reached", because the log line packs the counts into the label value — it now
reads Prometheus, and formatGates is untouched.
ExtractStats was fully computed and served on /stats and exported nowhere.
cg_extract_net_value_usd is currently negative and was unmonitored.
Two panels actively lied. "Total avoided this month" had one threshold step, at null,
so a net of -$10 rendered green — an honest negative must LOOK negative. And the
spend panel put a $0.03 series on a shared axis with $2,523, pinning it invisibly to
the x-axis; it has its own tile, so the target is dropped rather than adding a second
y-axis the dashboard's design rules forbid.
Four cg_tenant_* families were typed counter but are month-to-date AND shrink when
rows migrate to archival, so rate() spikes on the reset. Retyped as gauges with the
caveat in HELP. Names kept, because renaming breaks every existing panel and scrape.
The per-tenant table grew ghost rows: cg_tenant_disabled comes from the registry (13
series) while every other column comes from this month's rows (11), so two accounts
appeared blank-but-present. Joined on the request series.
A per-tenant CachesplitHistoricalUSD error used break, so one unpriceable tenant
silently zeroed the figure for every tenant after it in the slice — two lines below a
comment promising the opposite.
Alert rules exist for the first time, and install.sh now actually installs them: it
created provisioning/alerting/ and copied nothing into it, which is exactly why that
directory was empty. Without this line the rules would have been dead on arrival.
Signed-off-by: Osher-Elhadad <[email protected]>
`preset: coding` was format -> skeleton -> cmdfilter -> cachesplit. skeleton lives behind the cg_skeleton build tag because it is the only cgo component, so it is not registered in a normal binary — and Build therefore failed with `components: unknown component "skeleton"`. Every user who selected that preset got no pipeline at all. TestEveryPresetBuilds existed and deliberately SKIPPED any preset naming a tag-gated component, three lines under a comment explaining that such a typo otherwise "fails at BOOT in production". That is exactly what happened, and the skip suppressed it. A preset is a promise that one word of config works, resolved in whatever binary the user is running, so a preset depending on a tag-gated component is broken for every user of the default build. The skip is now a failure. coding becomes the deterministic components measured to actually act on this traffic. skeleton remains available in a cg_skeleton build, needs an explicit pipeline entry, and remains not recommended for reasons on its own page. Signed-off-by: Osher-Elhadad <[email protected]>
…ffic Comparing two live agent sessions compares two different conversations, so a difference cannot be attributed to the CONFIG. These hold the traffic fixed. TestSweepCapture replays one capture of real requests through a table of whole config documents and reports, per variant, what each component actually removed, every gate that declined, and each LLM call's cost, latency, rejection and gate verdict. Gated on CG_SWEEP, following the CONTEXT_GURU_CAPTURE convention the neighbouring benchmark already uses — captures hold real traffic and are never committed. CG_SWEEP_IDLE advances the injected clock so a cold sweep fires; CG_SWEEP_CALLS dumps per-call detail. It is what produced the numbers in this branch: 85.8% of a real Claude Code request frozen by cache safety, zero tokens removed by the deterministic pipeline on that traffic, and the identical saving under four different aggressiveness and threshold settings — which is how it became clear the LLM was contributing nothing and the deterministic fallback was doing all of the work. TestDiagStarlarkOnRealOutput runs the real code-strategy prompt against a real gateway on one real tool output and prints the reply and what the sandbox did with it. It exists because the four-value return collapses several very different failures into one reason string, and it is what caught the model answering in Python. Signed-off-by: Osher-Elhadad <[email protected]>
A measurement pass over 14,298 production requests and five fresh Claude Code CLI sessions, written to be uncomfortable where the numbers are uncomfortable. At the start of it context-guru was net -$10.23 — $6.96 saved against $17.22 of our own LLM spend — and a Grafana tile was reporting that in green. The page covers why the deterministic components look weak and are not (85.8% of a real request is frozen by cache safety, and the freeze is arithmetically correct); the two candidate causes that were checked and discarded rather than repeated (skip_file_reads AUTO fires 23 times in the whole corpus, and no gate is misfiring); how our pricing convention compares to the neighbouring projects', including that adopting theirs would multiply our published figure by 4.65x with no code change and why we should not; the one sibling advantage that is architectural rather than a measurement artifact; and the largest unclaimed saving on the page, which is left deliberately gated with the reason recorded. Also documents the accounting model now served per component, and corrects the intuition that motivated it: the first request after a TTL expiry is not a wash. A cache miss re-bills the whole prompt in proportion to transcript size, so a token removed on a cold turn saves 12.5x what the same token saves on a warm one. The code had this right; the verbal argument had it backwards. Signed-off-by: Osher-Elhadad <[email protected]>
…e did not tune aggressiveness low/medium/high removed identically 9,633 tokens on the same replayed capture, because the saving was coming from the deterministic fallback and the reapplied frozen result rather than from the level asked for. That comparison was measuring nothing and is worth re-running now the LLM path returns programs. Signed-off-by: Osher-Elhadad <[email protected]>
… real range The complaint this answers: a user saw what extract_llm COST, had no way to see what it saved, and concluded the product was worthless. They were reading a true number with no counterpart. Components now carry Saved $ and Net $ from the server, next to the existing cost. The client-side rate table is DELETED — AGENT_FRESH_PER_MTOK, AGENT_CACHE_READ_PER_MTOK, AGENT_CACHE_WRITE_PER_MTOK, componentNetUSD, savedTokenUSD. It hardcoded sonnet-class rates on a deployment that bills opus, 27% wrong, and valued only what the calls removed once while ~93% of the realized value arrives as replay. verdict() reads net_usd instead of re-deriving it. The drawer's per-extraction-call figure loses those constants too and is based on the request's own (baseline − cost) per token removed — the same rule the server uses — returning "—" rather than zero when token accounting is incomplete. ExtractionRow still has no saved_usd of its own; pricing it at write time like the others is the follow-up. A session gains an "in flight" pill, because a young session with one extraction call has an incomplete amortization and not a verdict. prefix_change_cost_usd appears as a labelled diagnostic beside the cache-miss panel, explicitly netted against nothing. It is deliberately not a tile: it is larger than every saving on the page and mutation is not randomly assigned, so a number that looked netted would be worse than one that is absent. The range picker is front-end only — since/until already parsed and predicated server-side, and the UI simply never sent until. state.range is replaced by state.from/state.to, each a relative token or absolute ms, Grafana's own model. refresh() stamps state.nowMs ONCE, which also fixes a real bug: one refresh firing stats, series and breakdown produced three slightly different windows. Legacy range=<ms> URLs still parse. The 10s poll stops while the window is absolute, because repolling a frozen past is pure waste. Sorting: Components only, and deliberately. /api/components returns every row, so that is a genuine global sort. Sessions and Requests are LIMIT 25 and 50 server side, so a client-side sort would label a column "Net saved $" and show the top spender of an arbitrary page. Making the header live only when the result set happens to fit one page is a control whose meaning changes without saying so, which is worse than no control. They stay unsorted until ?sort=/?dir= exists in SQL, and the contract test FAILS if either is wired client-side in the meantime. A manager gets an account selector and, on wide scope, an Account column on Sessions and Requests. The roster is fetched once and only for a manager. TestUINeverShowsABareCost reflects over ComponentRow, SessionRow and Overview json tags and asserts each is rendered, so the contract breaks on a rename in either direction rather than drifting silently. Signed-off-by: Osher-Elhadad <[email protected]>
…e never compared A resumed session produced a request the dashboard labelled ttl_expiry, with cache_read 0 and cache_write 168,576, while extract_llm declined every candidate as cached_prefix because the idle gap sat just under the 6-minute predictive threshold. 96.9% of that transcript stayed frozen to protect a cache that had already expired. cache_read == 0 is a post-hoc ground truth stored on every request, and nothing compares it against what the predictor concluded. Both values are already there, so the comparison is nearly free, and coldMargin is an un-calibrated guess until it is made. It is also the gate in front of the largest unclaimed saving on that page. The local run itself used a ~350s gap against a 360s threshold, so the sweep not firing was correct behaviour on a mis-specified test. The finding is the absent comparison, not a defect in the predictor. Signed-off-by: Osher-Elhadad <[email protected]>
…not a defect cacheIsCold compares with >=, so a sub-second difference decided it. That sharpens rather than weakens the point: the provider had already expired the cache at the same instant the predictor was still deciding, and the column that records the provider's answer is read for nothing. Signed-off-by: Osher-Elhadad <[email protected]>
…d it incomingModel rebuilt the extraction client with the caller's provider credential and WITHOUT the scheme it arrived under, so the Anthropic client fell back to its x-api-key default. A caller authenticating with `Authorization: Bearer <token>` — which is what Claude Code does when it is given ANTHROPIC_AUTH_TOKEN rather than ANTHROPIC_API_KEY — had its bearer token re-sent in the wrong header, and a gateway that authenticates with bearer tokens answered 401 to every one. `model.source: incoming` is the DEFAULT and is what both configured accounts use, so for that whole class of caller extract_llm could never complete a single call. It failed silently, because until this branch the failure was reported as "no usable program or reply" — indistinguishable from the model declining to answer. Found by a real cold-cache sweep on a resumed Claude Code session: the sweep fired correctly on a turn with cache_read 0 and cache_write 254,170, made its two calls, and both came back `status 401`. CallerAuthScheme walks the same header list in the same order as CallerKey and reports the slot the credential came from, so the two cannot disagree about which credential is being described. Bearer is the only Authorization scheme our client can emit, so a caller using another one (BobShell sends `Apikey <key>`) still gets the right header with a different scheme rather than the wrong header outright. The scheme is captured before the fallback to a server-held key, which is presented the operator's way and not the caller's. Signed-off-by: Osher-Elhadad <[email protected]>
…tatus A bare "status 401" is undiagnosable, and this is the second time in this branch that collapsing distinct failures into one string cost real investigation. A 401 from a gateway can be a wrong auth scheme, an expired or revoked key, a model the key is not entitled to, or a policy refusal — four causes with four different fixes and one message. The error now carries the response body, clipped to 512 bytes and whitespace-collapsed so a gateway that answers with an HTML page cannot flood a log line. Body only, never the request: an auth failure's body does not echo the credential, and the request headers would. Signed-off-by: Osher-Elhadad <[email protected]>
`ModelSpec.For("incoming")` falls back to the static model when there is no incoming
client, and said nothing about it. The substitution is not cosmetic: `source: incoming`
means "spend on the model and credential the caller is already paying for", and the
fallback spends a DIFFERENT credential against a DIFFERENT endpoint. An operator whose
config reads `model.source: incoming` had no way to learn that none of their calls went
there.
It cost a real investigation. A local run's extraction calls failed authentication with
"API key is invalid", and because the fallback is invisible there was no way to tell
which of the two credentials had been presented — so the wrong one was ruled out by
elimination instead of by evidence.
ForSource / ForModelSource return the source actually used; For and ForModel keep their
signatures and behaviour exactly. extract_llm gates on the difference, so the decline
histogram now carries model_source_fell_back_to_config and an authentication failure is
attributable to a credential rather than to a guess.
Signed-off-by: Osher-Elhadad <[email protected]>
…ic endpoint
modelConfig.Client() treated ANY `model:` value as a request to pin a dedicated
endpoint. With no base_url that endpoint defaults to the provider's PUBLIC API, and with
no api_key the credential comes from the process environment — so
`model: {source: incoming, model: claude-haiku-4-5}`, which is exactly the shape that
names the cheap model to compact WITH, silently built a client to api.anthropic.com and
presented an IBM gateway token there as x-api-key. Every call returned
`authentication_error: API key is invalid.` and `source: incoming` was never consulted.
Measured end to end: before, two cold-sweep calls on a real resumed Claude Code session
returned 401 with no usage and no cost. After, the same reproduction makes a real priced
call — 11,422 prompt tokens, 519 completion, $0.014 — reaching the gateway that `source`
resolves to.
The hosted service escaped this only by accident: AllowEnvModelKey is false there, so the
same block found no key, returned nil, and fell through to the correct client. The two
deployments were taking different paths through this function for the same config.
Pinning now requires something to pin TO — a base_url or an api_key. `model` on its own
means "let source resolve the client, then re-point it at this model id", which is what
ModelSpec.ForModel already does and what the key was added to express.
This also chased out two other things worth having, committed separately: the client now
reports the upstream's message instead of a bare status, and the source fallback is no
longer silent.
Signed-off-by: Osher-Elhadad <[email protected]>
… declare The form exposed 18 of ~106 configurable keys, all of them in one component of fifteen. Everything else was hand-edit-only YAML, and per-component blocks were unmarshalled NON-strictly, so `min_tokns: 5000` on any component was silently ignored. Hand-writing ~100 fields twice — a Go struct and a JS renderer — is a couple of thousand lines that must be edited in three places for every new knob, with no compiler and no test able to notice an omission. The 18-key version already carried the drift: the UI's defaults were a hand-copied duplicate of the server's, and the strategy whitelist had already fallen behind the engine. So each component declares its own []Field beside the config struct it belongs to, with the hint prose lifted from the doc comments already written there. Shared blocks (`trigger`, `model`, `marker_mode`) are declared once. Keys are dotted paths, so nesting needs no nesting in the descriptor. Nothing about pipeline behaviour moves: descriptors are metadata for the form. Coverage is now 97 keys across 14 components, served on /api/options as component_fields with a separate `recommended` block — because the component DEFAULT (what an absent key means) and the RECOMMENDED prefill (what we suggest you spend) are different things, and conflating them is how a form writes recommendations over deliberate values. managedKeys is now DERIVED from the declared keys, which fixes a real bug structurally rather than by hand: the delete list held the whole `cold_cache` block, so switching the component off destroyed the min_idle_seconds and max_calls that the enable path carefully preserved. And a second real bug: the strategy whitelist omitted `deterministic`, which the engine accepts. A stored `strategy: deterministic` therefore did not match, fell back to the default, and the next save WROTE `strategy: code` over it — silently converting an LLM-free configuration into one that makes model calls. The allowed values now come from the same constant the engine parses, pinned by a test that also fails if an unknown name stops falling through. Per-component decoding is strict now, which is what makes a descriptor-driven form trustworthy. It immediately found three fixture typos, one of which meant an observe-vs-sync agreement test had been masking at the default keep_recent rather than the 1 its comment claimed. Three anti-drift tests carry this: reflection parity between descriptor keys and struct yaml tags in both directions; a sweep that perturbs every declared field and asserts a whole-document diff shows that path and nothing else, that it reads back, and that applying twice is idempotent; and a switch-off leg. Plus a stored credential is never echoed into the parsed form. Signed-off-by: Osher-Elhadad <[email protected]>
…m field names One function with no field names in it: renderComponentFields draws a section per component from /api/options.component_fields, keyed by component+key because 97 fields share only 55 distinct key strings (marker_mode, min_tokens and the whole trigger/model blocks repeat). The four existing widget builders are now driven by a switch on the declared type; an unknown type draws NO control and says so, because a text box there would post a string where the server wants a number. Absent is not zero. State is seeded only from what the document actually states; numbers and text render EMPTY with the default as placeholder, enums offer an explicit "default" option, and clearing a box deletes the key. A stated 0 renders as 0. That distinction is the whole reason a previous save wrote 20 over a deliberate "unlimited". `min` is enforced client-side with the right prose per case — a threshold's 0 removes a brake, a cap's 0 means unlimited — so a refused value never reaches the server as an unactionable 400. Secrets are write-only three times over: password input, never populated, empty omitted from the POST, and declared secret keys dropped while seeding so even a payload that leaked one could not put it in the DOM. There is deliberately no "clear the key" control: an explicit empty string is a deletion server-side, and offering it is one keystroke from destroying a credential on every save. Recommended values are an explicit action, never a silent prefill — and the old hand-copied default table is deleted, which is the duplication this whole refactor exists to remove. The component-level warnings are derived from the descriptors rather than listed, so the "this calls a model and can be net negative" note now reaches agentdiet and summarize too; the hand-written form only ever covered one component. The contract test is INVERTED: it walks components.AllFields() and fails if app.js names a declared key, with a four-entry allowlist that each states its reason. A form that hardcodes a field name can no longer pass. Both switches off is not an error server-side — it silently removes the component from the pipeline — so the client refusal is about honesty: it flips the sibling back and says to untick the component instead, which is what the server would have done without telling anyone. Signed-off-by: Osher-Elhadad <[email protected]>
…lost on this transcript A real resumed session after a 547s gap: the sweep fired on a genuinely cold turn, one of two calls was accepted, 1,571 tokens removed, saved_unique 1,545 recorded and priced. The mechanism works. It also lost money — 27,570 tokens is far too small for two calls at ~$0.06 to repay, against the earlier measurement that paid by removing 42x as much. Same arithmetic, which is why the gate must stay binding. Two incidental findings recorded: the sandbox rejection now names line and column of the Python-ism that slipped the contract, so the remaining prompt work is reading failures rather than guessing; and the request immediately after the compaction took a prefix_change miss writing 86,130 tokens, which is the diagnostic from section 5 observed in a controlled run instead of inferred. Signed-off-by: Osher-Elhadad <[email protected]>
This was referenced Sep 3, 2026
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.
Per-model prices from the operator's own rate card, an honest prefix-cache saving, gate reasons on the components table, host metrics in Grafana, and the settings page rebuilt as fields.
Cost accounting, per model
MODEL_PRICESnames a YAML rate card that is consulted before the public LiteLLM map, because a gateway does not charge the public API's prices:ete-litellmbillsaws/claude-sonnet-5at $1.52/MTok in where anthropic.com bills $3.00, so every dollar figure for that gateway was about twice the truth. It is also the only way to price a model the public map has never heard of — a preview id, or a server-resolved tier like Bob'spremium, which is not a model id at all.deploy/service/prices.example.yamlships the 42 entries for this deployment.Savings already accumulated correctly per request; the error was the rate. The re-sent remainder of a removal was always priced at the cache-read rate, on the reasoning that a re-sent transcript is served from cache. That is true only of a request whose cache actually hit. TTL-expired turns were 4% of production requests and 31% of spend, every token of it
cache_creation, and their savings were valued ~12× too low — on exactly the turns where removing content is worth the most.The cache saving, and the one this replaces
The dashboard led with "Prompt-cache savings": the provider's whole prompt cache priced against the fresh rate, plus a second tile for the subset that happened to co-occur with one of our components. Neither was ours. The agent places most of the breakpoints itself, and co-occurrence is not cause.
One measured figure replaces both. A request contributes only when all of these hold:
split_stable_tokens > 0);The amount is the stable half the split moved, not the request's whole
cache_read. That came out of running the control arm, not from reasoning:cache_readcache_writeThe control still hit. Crediting the whole 54,304 would have booked the agent's own cache placement as ours — 7.5× in dollars. Priced against a cache miss (creation rate, 1.25× fresh), because those tokens carry
cache_control.cache_saved_usdstays in the API and in Prometheus as a diagnostic, labelled as one: it is the number that collapses when a pipeline rewrites deep history, so watching it fall is how a too-deep pipeline gets caught. It is off every tile and out of every total.total_saved_usd = net_saved_usd + cachesplit_saved_usd. Two disjoint token sets, both ours.Gate reasons: "act rate 0%, why?"
Gate counts existed in
/statsservice-wide and in the per-request log line, and never reached the dashboard — the components table was a column of zeros with no explanation. They are now a Why declined column, per component and per request. On Bob traffic almost every row is a gate name, because the offload heuristics were tuned on Claude Code's output shapes. An empty map renders as—("gated nothing") and a missing one asunknown("predates the column"); those are different facts.The Bob accounting bug
Reported as "stats but no components and no cost". Two independent defects, found by running Bob rather than by reading:
premium-ide), which no price map knows, so every Bob request priced at $0.00 and read aspartial;Bob's own
result.stats.session_costsand the gateway's tiers imply in-rates of $2.17 and $3.67/MTok on two runs, so no single rate reproduces both; the shipped entry is $3.00, a published rate. Read a Bob row's cost as right to within about a third — that error bar carries into every absolute figure derived from it, and not into the before/after ratio, where a uniform rate error cancels.Machine metrics
A new
context-guru-hostGrafana dashboard, 18 panels fromnode_exporter(loopback only, no systemd collector): CPU by mode, memory, filesystem, disk throughput and busy, network, fds, context switches, load per core. Two panels drew nothing on the real box and were fixed — load-per-core divided a labelled series by a bare aggregate, and PSI needs/proc/pressure, which this kernel does not have.install.sh grafana-statusnow queries every panel's expression against Prometheus and names the ones with no data, so that failure mode is visible instead of looking like an idle system.Settings: fields, not YAML
Two accounts could not save their
extract_llmconfiguration at all:Reproduced, and it was ours. The page built the document with regular expressions in the browser, replacing the whole
pipeline:line with a flow-style one — which orphaned the items of a block sequence under it. The server refused the result, correctly, leaving the old document stored for the next attempt to mangle again, so it failed on every save with no way out from the UI. Apreset:document lost its entire pipeline the same way, silently.The page posts fields now; the server applies them with a real YAML library, validates by building the result, and stores it only then. Keys the form does not own survive the round trip. A document that fails the strict load is reported on the form and cannot be saved from. ~190 lines of YAML surgery and the textarea are gone; the account editor remains the escape hatch for anything the fields do not cover.
Schema
cache_saved_usd,cachesplit_saved_usd,split_stable_tokensandrequest_components.gatesare added byALTER TABLEon open. AschemaVersionbump renames the database aside and discards every request row — on the live service a hundred thousand of them, to gain a column. The additive path is narrowed, not broken: a new column with a default may use it; anything that alters an existing column still needs a bump.Verification
Real Claude Code sessions against
ete-litellmthrough a local proxy, and a hosted-mode proxy driven through its own dashboard in a headless browser:cg_tenant_cachesplit_saved_usdand the diagnostic both present in/metrics;sessions=2) — which is how the missing wiring for it was found.make test(-race),go vet,node --check,mkdocs build --strictall pass.Reviewed
A subagent review of the savings and settings commits found 13 issues, 8 real, all fixed in
03f99dc: a hit that did not establish our half was served; "session first" meaning "first this process has seen" (restart and map-overflow both handing out credits); a bare preset reading as switched-off and then dropping the component; switching off destroyingmodel:; a0cap displayed as the default and then written back; an unloadable document editable through a misread form; a false claim aboutcache_miss_reason; and the evidence numbers disagreeing between the files that carried them.Squash-merge this. An intermediate commit on the branch has a 37 MB binary that
go buildleft in the working tree (untracked since473d8d4,.gitignored), andcc62570alone ships a dashboard reading a field it removed.Follow-up: the settings page, a streaming timeout, and three wrong cost figures
Reported by two accounts, and the diagnosis moved twice before it settled.
The roster read
components:for every configured accountThat cell showed the document's first line. Since the form writes YAML through a marshaller
its keys come out alphabetically, so line one is
components:for everyone who has ever saved —a cell that reads "configured with no components" on exactly the accounts that are configured.
It shows the resolved pipeline now.
Three keys decided whether
extract_llmcould act, and none was on the pageAn account whose
extract_llmwas fully configured ran it on 251 requests and acted 0 times:model.source: config— hosted mode has no operator compaction model by design, so thisresolved to no model and the component silently never called anything.
/api/optionsnowreports
compaction_modeland the field says so where it is false.allow_on_caching_backend— absent means false, so the economic gate hard-declines everyprompt-cached candidate. On Claude Code against Anthropic that is the whole workload.
skip_file_reads— AUTO skips file reads on cached traffic, and those are most of a codingagent's large outputs.
All three are controls now, with
strategy,llm_every_n_requestsandtrigger.min_request_tokens. The UI-contract test reads field names offconfig.ExtractLLMFormby reflection, so this class of drift fails a test naming the fieldrather than being found by a user. The whole document is on the page read-only, since the fields
are a subset and always will be.
"Four minutes then an API error" was our own timeout, not a component
Eleven requests on one account: context-guru's own time 25–84 ms, zero model calls,
upstream_msclustered on 297,9xx. The upstream client carriedhttp.Client{Timeout: 5 * time.Minute}, and that timeout covers reading the response body —on a streaming dialect it is a ceiling on generation length, not a liveness check. 160 shorter
streamed turns from the same account through the same upstream succeeded in the same window.
Now
ResponseHeaderTimeout(--upstream-header-timeout, default 10m).cg_llm_cost_usdwas wrong three waysChasing why a working sweep looked unprofitable:
extract_llmforced the agent's rates wheneversource: incoming1 and 2 point opposite ways and partly cancelled, which is why nothing looked broken and why two
survived an earlier pass over this same figure. Each now has a test that fails without its fix.
A cheap compactor, and what it actually nets
model.modelnames the model to compact with, on the source's endpoint and credential —the only way a hosted tenant gets a cheap compactor without the operator paying. Optional
components.Remodelerinterface, value receivers, so the swap is a struct copy.Five real Claude Code sessions, cold sweep only, each resumed after a genuine >5-minute gap:
claude-haiku-4-5The check that matters more than either number: the per-call and per-request figures now agree to
0.02% ($0.2402 vs $0.24015), where they were 4.75× apart.
Also
failed_runis out of the default pipeline. It acted zero times on every workload measuredhere — 251 requests and 843 ms of scanning on one account, 28.8 s on the Terminal-Bench arm.
Still registered and selectable.
SeedSessionsscannedsplit_tail_hashinto auint64; SQLite INTEGER is signed, so half ofall FNV hashes came back negative and failed the whole query. Production logged "could not
recover session recency" on every start; it now recovers 591 sessions.
Note for the reviewer
3f64736's message describes the pricing fixes but the commit also contains themodel.modelfeature — they were committed together and the message was not amended, since the commit was
already pushed. Both halves are described above.
Round 2 — a measurement pass, and the five defects it found
Measured over 14,298 production requests and a set of fresh Claude Code CLI sessions driven
through a local proxy. Full write-up:
docs/results/measured-2026-08.md.The headline, stated plainly
At the start of this pass context-guru was net −$10.23: $6.96 saved against $17.22 of its
own LLM spend and $0.03 from the prefix split. A Grafana tile was rendering that in green,
because its only threshold step was at
null. The loss was one account, and within it one401-request session.
Why the deterministic components look weak, and why that is not fixable by compacting harder
85.8% of a real Claude Code request is frozen by cache safety (locally measured:
tokens_before557,445,attempted79,323,frozen478,122; deployment-wide 45.95% frozenand 1.85% of the attempted remainder removed). 90.74% of all input tokens bill as cache reads
at $0.342/MTok — 12.6× cheaper than a cache write.
The freeze is arithmetically correct: re-anchoring a 150k prefix costs ~$0.71 against
~$0.0076/turn, so it needs ~93 further turns to break even. It stays.
Two candidate causes were checked and discarded rather than repeated:
skip_file_readsinAUTO fires 23 times in the entire corpus (it sits behind gates that already removed every
candidate), and no gate is misfiring — every histogram says "nothing matched", with zero
component errors across 14,262 requests.
extract_llm: five defects, each sufficient on its ownany(k in ln for k in ids)is a syntax error.claude-haiku-4-5returned a plausibleprogram on essentially every call and the sandbox discarded 12 of 13. On the same real
33,932-character file read: 0/3 produced output before, 3/3 after, at 56%/83%/55%.
reply" were one string. That is why (1) survived. Now surfaced per call.
while production calls sent ~138,000. The true figure sat two lines away as
promptOverhead, discarded.same ~138k transcript fresh. Now a trailing cacheable system block, gated on >1 call
because a cache write costs 1.25×. Verified live:
create=30007, thenread=30007on everyrepeat — 67% off a five-call request.
bearer token was re-sent as
x-api-key. Correct on its own merits and tested — but see theopen item below: it did not resolve the 401 it was found chasing.
Not fixable in code: 94% of the losing spend was made against this gate's own written
advisory, because
fire_on: sizedemotes it and leaves the caps as the only brake.Other measured fixes
format/toonnever descended the tool-runner envelope. 537 of 673 large blobs(2,098,762 tokens, 89% of that mass) hide a uniform record array inside a JSON-escaped
stdoutstring. Now 72.9% and 51.1% on the envelope fixture; both were zero.preset: codingcould not start at all — it namedskeleton, which is behind a buildtag and absent from a normal binary.
TestEveryPresetBuildsskipped it, three linesunder a comment explaining that such a typo "fails at BOOT in production". The skip is now a
failure.
cachesplitread as a dead component becauseMutatedwas never exported; it isMutated-never-Acted by design. Plus gate declines,
ExtractStats, the green-negative tile,four mis-typed counters, ghost table rows, and alert rules that
install.shcreated adirectory for and never installed.
saved_usd/net_usdserver-side, valued at the tierthe request actually paid, reconciling to
baseline − costexactly on fixtures. The UI'shardcoded sonnet-class rates are deleted.
prefix_change_cost_usdships as a labelleddiagnostic, netted against nothing.
reflection parity test. Fixed two round-trip bugs: a delete list that clobbered a
partially-owned block, and
strategy: deterministicbeing silently rewritten tocode—which converted an LLM-free config into one that spends money. Strict per-component decoding
found three real fixture typos.
the default was wrong. Wide-scope single-session views are pinned to one tenant.
skeletonstays compiled out. 67.5% on source reads — the largest deterministic levermeasured — with three unrecoverable-elision paths fixed and an honest recommendation against
enabling it.
Open, evidenced, not fixed
A 401 on the
source: incomingextraction path in a local single-tenant setup. The coldsweep fires correctly (verified twice on real 508-second idle gaps,
cache_read: 0,cache_write: 254,170) and both its calls return 401. Ruled out by direct test: the model id,the token itself,
cache_control, large prompts, and same-token concurrency all return 200.Production calls demonstrably succeeded, so this may be specific to the caller-pays harness.
The client now reports the upstream's message, which is what a follow-up needs.
The largest unclaimed saving is deliberately left gated.
Ctx.TailOnly()never readsColdCache, so a TTL-expired turn still freezes ~93% of a transcript to protect a cache thatis gone — 3.4% of requests carrying 21% of all spend.
ColdCache's own comment shows this wasa considered blast-radius decision and agrees the rewrite would be safe. It wants an opt-in
switch and an A/B, and first the calibration below.
coldMarginis an un-calibrated guess. A resumed session produced a turn the dashboardlabelled
ttl_expirywhile the component called it warm, decided by a 360-second gap againsta 360-second threshold.
cache_read == 0is a post-hoc ground truth stored on every requestand nothing compares it against the prediction.
Reviewer notes
This branch is now 40 commits and spans components, dash, proxy, metrics, config and docs.
Squash-merge or split by area; an intermediate commit carries a build artifact, and
3f64736's message covers only the pricing half of its content. Each commit is scoped to onearea and its message states the measurement behind it.