Repository navigation
feat(extract_llm): cold-cache sweep, tunable prompt, size triggering, and per-call observability - #82
Merged
Merged
Conversation
added 12 commits
August 18, 2026 20:33
…pend The derived pressure trigger only fires above 60% of the context window (or 25% while growing fast), which is the right default and the wrong behaviour for an operator who wants extraction to run whenever a tool output is big enough. fire_on: size makes the candidate's own size the whole decision. Because that is the operator taking the spending decision away from the economic gate, it also demotes the gate and the caching-backend guard to ADVISORY: both still evaluate and record what they would have refused, as the economic_gate_advisory gate and an 'advisory: ...' reason at /stats, but neither blocks. The counterfactual is the only way anyone later sees what the override cost. That leaves the caps as the only brakes, and the existing ones cannot bound a long session: llm_every_n_requests throttles requests and llm_max_per_request caps one turn, so 2 calls x 300 turns is 600 calls. llm_max_per_session reserves slots before the calls are made, so two concurrent turns of one session cannot both spend the last one. A size trigger with no size deliberately does not inherit the legacy 300-token min_tokens: almost every tool output clears 300, so it would fire every turn -- the 271-call, $3.26, 82x-underwater behaviour the gate exists to prevent. It takes 2000 instead, roughly the largest output observed on Terminal-Bench. Signed-off-by: Osher-Elhadad <[email protected]>
…only pays Two changes that share a mechanism. The extraction system prompt becomes two ordered blocks: the general contract (sandbox API, verbatim-preservation rules, the source-file skeleton rule) and a compaction target with its own worked examples. The target is low | medium | high and it is TAUGHT rather than configured, because how hard to cut is a judgement and few-shot examples express it better than a number can. Every level's examples span the shapes real traffic contains -- JSON, bash/test logs, prose, and a source file read -- and every one of them sets SUMMARY, since an example that omits the digest teaches the model to omit it too. General-first is load-bearing: a provider caches a PREFIX, so the half that is byte-identical for every tenant has to come first or it is shared with nobody. Aggressiveness joins PromptVersion and the config fingerprint, so switching level MISSES the global result cache instead of replaying the other level's answer. The cache breakpoint is now conditional. It was placed whenever a system prompt existed, and a mark below the provider's minimum cacheable prefix is not an error and not visibly a no-op -- the response just reports cache_creation_input_tokens: 0. Measured: ~1.5k tokens on claude-haiku-4-5 gives write=0 read=0, the same prefix on claude-sonnet-5 caches. So the mark goes on only when the prefix clears the model's floor (4096 haiku-class, 1024 sonnet/opus-class, and the larger figure for any id we cannot place -- including a gateway alias). Measured result: the new preamble is 1325-1782 tokens, which caches on the hosted default path (extraction runs on the agent's own model) and is correctly left unmarked on a haiku cheap model. The prompt is not padded to reach 4096; filler would buy cache eligibility with text that teaches the model nothing. Also caps the SUMMARY at one line of 120 runes. It had no bound at all, and an over-long one did not produce a long marker -- it produced NO compaction, because the marker-inclusive never-worse check abandons the whole splice. Signed-off-by: Osher-Elhadad <[email protected]>
…prompt carries The model is asked to reduce one tool output toward what the agent needs next, so what it is told about the conversation IS the basis of that judgement. That was a fixed three-part string: the first user turn, the last assistant turn, the last user turn. It is now a mode. goal - the old behaviour, the cheapest useful signal recent - every user turn plus the last N (7) non-tool messages, the new default full - the entire transcript, tool outputs included recent is the default because the corrections a user makes mid-session are exactly the signal that decides what may be deleted, and goal mode keeps only the first and last user turn -- so 'it must default to 30s, not 10s' three turns ago was invisible to the model that then chose whether to keep the line saying so. The last-N window is counted over the messages that are RENDERED, not raw indices: most messages in agent traffic are tool results, so counting indices would make 'the last 7' resolve to nothing but the output being cut anyway. recent excludes tool results for the same reason -- they are the bulk this component removes, and putting them in the prompt multiplies the cost of every call. full includes them, because completeness is its whole purpose, and the existing context guard declines a call whose prompt cannot fit rather than truncating the conversation. Clipping now keeps the TAIL and says so in the text. The old backstop sliced 8000 bytes off the front, which both dropped the newest turns -- the ones that answer the prompt's question -- and could split a multi-byte rune into a prompt we send. Signed-off-by: Osher-Elhadad <[email protected]>
…as expired The biggest identifiable waste in this deployment, measured over 1.4 days of real traffic: turns whose prompt cache had expired were 219 of 5,596 requests (4%) but $360 of $1,173 of spend (31%) -- $1.64 each against $0.144 for a warm turn, an 11x difference -- because all 56.7M of their tokens billed as cache_creation at 1.25x the fresh rate. The shipped pipeline saved 0.015% of it. Two things are true only on such a turn. Rewriting deep history is free, because there is no live cached prefix left to invalidate. And a removed token is worth the cache-WRITE rate: 12.5x what it is worth on a warm turn, where it saves only the cache-read rate. So this is not compacting harder, it is taking the one window where the arithmetic is overwhelmingly in favour. Detection is per provider and deliberately conservative, because the errors are not symmetric. Calling a warm cache cold makes a component rewrite the prefix and forces a cache-write of the whole suffix; calling a cold cache warm merely forgoes a saving. So: the Anthropic family reads the TTL out of the request itself (exact -- and every one of ~5,000 captured real requests carries a bare ephemeral mark, i.e. the 5m tier), anything else takes the documented one-hour outer bound, a minute of margin covers clock skew, and no previous turn on record reads WARM rather than cold so a proxy restart cannot invalidate a live cache. Ctx.ColdCache is information, not an automatic lifting of the tail gate. Every offloader could safely rewrite at depth on such a turn, but flipping TailOnly would change what mask, failed_run and collapse do on live traffic the moment this shipped, for deployments that asked for none of it. So the gate stays and a component opts in. The sweep has its own switch, its own floor, its own cap, and does not draw on the hot path's per-request or per-session allowance -- the two halves have opposite economics and are meant to be enabled independently. per_output: false gives the sweep alone, which is the configuration whose economics are unambiguous. It also gets the full transcript as context regardless of the configured mode, and escalates to the agent's own model when the transcript will not fit the extraction model's window; a result derived by an escalated model is kept session-scoped rather than published under the configured model's global cache key. Signed-off-by: Osher-Elhadad <[email protected]>
… what it bought The whole record of an extraction call used to be one dollar figure per request, priced at the AGENT model's rate, with no count of calls, no candidate, no verdict, and no before/after. For the one component that can be net-negative, that is the difference between answering 'was that worth it?' and guessing -- and the components view had no dollars in it at all, so it judged the one component that can lose money on tokens and latency and could describe a $3 loss as 'expensive for its yield'. Now one row per call: the candidate's size, what the call removed, its own prompt and completion tokens split by cache tier, its cost at the EXTRACTION model's rates, its latency, whether the result was accepted, and what the economic gate concluded -- including when that conclusion was overridden, which is the counterfactual an operator who overrode it needs to see. Per-call token attribution needed a narrower accounting window than the per-request sink, so sinks now nest: a child records one call and every ancestor still sees it, so installing one never costs the request its own bill. The table is created by an ADDITIVE ddl that runs on every open, not by bumping schemaVersion. A bump renames the database aside and discards every requests, request_components and request_content row, which for a purely new table buys nothing. It carries the FK and cascade the other child tables have, so retention, session eviction, archive migration and a manager purge all clean it up. Before/after text is transcript content and follows the same per-account capture consent as the diff view, through the same redactor. The NUMBERS are kept either way: consent is about storing transcripts, and dropping the cost of a call would leave an account unable to answer the question this record exists for. The verdict is now stated in dollars where there are any, valuing what the CALLS removed -- not the component's total savings, most of which come from frozen results replayed with no call at all (~93% on measured traffic), and crediting that replay to the calls would make any amount of spending look profitable. Cold-sweep calls are valued at the cache-write rate and warm ones at the cache-read rate, the ~12.5x spread, so a component whose calls are mostly cold is judged on the right basis. Signed-off-by: Osher-Elhadad <[email protected]>
Ran a real Claude Code session through a local proxy with the new knobs on. The per-call records immediately showed four things wrong, three of them pre-existing. 1. skip_file_reads did not implement its documented default. Unset meant "always reduce", while this file's own config comment and the component's docs both define unset as AUTO: skip line-numbered source dumps when the request is prompt-cached. The default therefore defeated the whole measured rationale for the flag (+30% billed cost on a ~98%-cached agent, because a file read already bills at the cache-read rate). Live: a ~7k-token Go file read went to the model, which spent 40s on a reply that hit the output cap and saved nothing. AUTO now works, with the cold sweep as the deliberate exception -- there nothing is cached and file reads are the largest mass being re-billed at the write rate. 2. Every call was priced at claude-haiku rates while the shipped model.source is "incoming", the agent's own model. A call recorded at $0.0276 had really cost about $0.083, and the economic gate spends on that number. The host now resolves the request model's real rates and the component prices its own calls with them, falling back to the constant only when the model cannot be named. 3. A truncated reply was invisible and indistinguishable from "the model declined to compact" -- opposite fixes, same empty return value. It is the worst outcome available: full price, zero result. Now counted, recorded on the call, and the reply budget is raised to 4096 and taken from the client's own constant so the two cannot drift again (they had). 4. Recorded calls said component="" and model="", which the record exists to answer. And the cache breakpoint could still waste money after the size floor: two calls in one request run CONCURRENTLY, so neither could read what neither had written yet and both paid the 1.25x creation premium -- measured cache_write=5228, cache_read=0. An entry that is only ever written is worse than no breakpoint at all. A call now marks the prefix only when a read can follow it: one write slot per (model, prefix), freed on every exit path, and every call marks once an entry demonstrably exists. Signed-off-by: Osher-Elhadad <[email protected]>
…ream extract_llm has fourteen knobs and every one was reachable only by hand-editing raw YAML in a textarea, with no validation until save. Worse, the component's own loader unmarshals its block NON-strictly, so a misspelled key there is silently ignored rather than rejected -- and this is the one component that spends money, so a typo is not a typo, it is a bill. So: a form with the recommended defaults filled in, two switches that say plainly which half of the component they turn on and what each one costs, and hints that carry the measured economics rather than restating the key names. The YAML textarea stays as Advanced and still wins when edited, because it is the only way to express what the form does not cover. The form writes YAML by string surgery, with no YAML library in the browser -- what makes that acceptable is that the server already validates strictly (KnownFields plus a real pipeline build) and answers 400 naming the offending key, so a mangled document is refused rather than stored. A new config test pins the other half of that contract: the documents this form actually produces must be accepted, and the keys it writes must be ones the components really have. Also names the default upstream explicitly. Once a deployment lists more than one gateway of a dialect -- an internal and an external hostname for the same service -- "the first entry wins" is an accident of file order that decides where every new account's traffic goes. CG_DEFAULT_ANTHROPIC_UPSTREAM (and the openai/bob equivalents) names it instead; an unknown name warns and is ignored, because the allow-list is the authority on what exists and a typo in an optional default must not stop the service from starting. Every entry stays selectable per account whatever the default is. Signed-off-by: Osher-Elhadad <[email protected]>
…ompactions Two findings from measuring a real session, and the second doubled the success rate. RunExtractionSummary reported "none" for every failure alike. A reply that never arrived, a program the sandbox refused, a result that did not shrink and a result the acceptance check rejected were indistinguishable in the return value -- and they have opposite fixes: raise the reply budget, fix the prompt, stop calling, loosen the keep-set. Four calls in one live session spent ~$0.27 and 100 seconds to tell me "none" four times. RunExtractionDetail now reports which strategy failed and how, the per-call record carries it, and the dashboard shows it on the call. With that visible, the real defect showed itself: "rejected by the acceptance check" on half the calls, because the model had compacted TOO WELL. The recall rule requires an identifier the agent referenced to survive verbatim, which is right for a needle -- an error code, a path mentioned once, a test name. It is wrong for an identifier that appears on every line of the noise. Measured live on an access log whose 900 routine lines each carried handler=src/api/users.py, the exact path from the user's request: a reduction keeping only the ERROR line necessarily dropped that id and was refused, so 3 of 6 calls paid full price for nothing, and the ones that passed were the ones that kept sample noise. An id repeated more than twenty times in one output is structure, not a reference at risk: the marker's summary names what went, the original is recoverable via expand, and the transcript the id was harvested FROM still contains it. Measured on the same workload, before and after, five identical requests each: acceptance rate 2/5 -> 5/5 tokens 32,508 -> ~200 per request when accepted (99.4%) latency 7.8s mean per call cost $0.019 per call preamble cache 5 reads, 0 writes The honest part stays honest: those 130,162 saved tokens are worth $0.039 at the warm cache-read rate against $0.096 spent, so the warm path is still net negative. The same reduction on a cold-cache turn is worth $0.488 -- which is the whole argument for the sweep, now measured rather than asserted. Signed-off-by: Osher-Elhadad <[email protected]>
Documents what the code now does: the cold-cache sweep with the production numbers that justify it (TTL-expired turns are 4% of requests and 31% of spend on this deployment, and the shipped pipeline saves 0.015% of it), the compaction target and context modes, the size trigger and the caps, and the per-call view in the dashboard. Two corrections to claims this documentation was making: - hosted.md said IBM LiteLLM does not report cache tiers. Measured directly against the gateway, it does -- cache_creation_input_tokens, cache_read_input_tokens, and even the ephemeral_5m / ephemeral_1h split. A panel reading n/a is more likely the streaming path or an unnameable model than the gateway's silence. - extract_llm.md documented skip_file_reads as AUTO when unset. The code did not implement that until this branch, so the note now says so rather than describing a behaviour nobody had. Also adds the enable instructions, deliberately ordered: the cold sweep first, because its economics are unambiguous; then read the per-call records; then consider the per-output half, with the caps set first. And the per-account upstream choice, which is how a laptop that can reach only one of two gateway hostnames gets pointed at it. Signed-off-by: Osher-Elhadad <[email protected]>
…he tool output
This is what made `context: full` -- and therefore every cold-cache sweep -- work.
The keep-list means "identifiers the agent referenced recently, so do not lose them".
It was harvested from whatever context the prompt carried, which for context: full is the
whole transcript INCLUDING the tool output being reduced. Every unique token in the noise
then becomes an identifier the result must reproduce verbatim: one timestamp appearing
once inside a 900-line log makes any reduction of that log un-acceptable.
Measured live on the same 26k-token access log, four samples per arm:
keep-ids from the full transcript 0/6 accepted (two runs), "rejected by the
acceptance check"
keep-ids from the conversation 3/4 accepted with a full-sized context,
3/4 with a small one -- identical
So the prompt may carry the whole transcript (that is what full is for, and what the
sweep needs to judge what a message from three hours ago may lose) while the keep-list
stays what it was always meant to be: the agent's own references.
Sits on top of the pervasive-identifier exemption in the previous commit. That one lets
a boilerplate id vanish with the noise it lives in; this one stops the noise from
generating ids at all. Both were the same failure wearing different clothes: the
acceptance check refusing a reduction for removing something nobody would miss.
Signed-off-by: Osher-Elhadad <[email protected]>
A truncated reply is the worst outcome an extraction call has -- full price, zero result -- and it parses as nothing, which is indistinguishable from a model that declined to compact. The counter existed but nothing served it, so the one failure whose fix is a config change rather than a decision to stop calling stayed invisible. Signed-off-by: Osher-Elhadad <[email protected]>
Reviewed the branch before pushing; every finding was real. 1. Any manager settings save rewrote the whole extract_llm block from the form's own fields, silently DELETING rewrite, marker_mode, model, economic_gate, trigger, skip_file_reads and llm_every_n_requests. Unticking an unrelated component in the grid would have reset somebody's deliberate compaction configuration. The form now preserves every key it does not manage, nested blocks included. 2. Worse, in the same place: fire_on was derived from per_output, so ticking "reduce large tool outputs" quietly demoted the economic gate AND the caching-backend guard to advisory -- it removed the spending brakes as a side effect. That is now its own switch, off by default, and its hint says what it licenses. 3. clipRunesTail tested utf8.ValidString on a SINGLE BYTE, which is only true for ASCII, so it advanced past every leading multi-byte rune: a CJK or accented transcript clipped to nothing and the extraction model got the elision marker and no conversation at all. utf8.RuneStart is the correct test, and the second loop it had was already redundant. 4. cacheIsCold trusted a timestamp the bypass path never wrote. A bypassed request is forwarded IN FULL, so the provider caches it -- but the bypass branch called Turn(), which records the length and not the time. A session bypassing for ten minutes read as ten minutes idle, and a sweep would then rewrite a prefix the provider had just cached: exactly the 1.25x churn this design exists to avoid. Now proven by a test that goes through apply, and that fails without the fix. 5. The form read the cold sweep's floor with a regex that matched the FIRST min_tokens in the block -- the hot-path threshold -- so the sweep's floor displayed wrong and was overwritten on save. It now reads the cold_cache sub-block. 6. Model escalation swapped in the agent's model AFTER pricing and the recorded model id were fixed to the configured one, so escalated calls -- the most expensive the component makes -- were recorded and gated at understated cost under the wrong model id. Both are re-derived on escalation. 7. The belief that a cache entry exists was sticky for the process lifetime. The provider's ephemeral entry expires after a few minutes unused, so after any idle gap every concurrent caller marked again and each paid a full creation charge -- the double-write waste the claim protocol prevents, returning on the first burst after every quiet period. It now expires at four minutes, under the provider's five. Also: clipGoal gated on bytes while trimming runes, so it did not bound non-ASCII input at all. Signed-off-by: Osher-Elhadad <[email protected]>
…red file read Found by comparing the three compaction targets on real traffic: at LOW -- the most conservative level -- a 3,598-token source file came back as the single character "1", accepted, by strategy "deterministic". At the level whose whole point is to keep more. Two defects compounded. parseBody turns ` 1\timport json...` into the JSON NUMBER 1, and the deterministic projection of 1 is the string "1". buildCodeUserPart already guards this exact case for the text it SHOWS the model -- the comment there even names it -- but the deterministic strategy had no guard, so it projected over a number parsed out of a source file. The guard now lives with the strategy rather than in one of its callers. And the identifier that should have caught it did not, because HarvestIdentifiers had swallowed the sentence period: "fix parse_config." yields the id "parse_config." which appears nowhere in the body, and the recall check skips any id absent from the body. So the one identifier the agent had actually named protected nothing. Trailing ./- are now trimmed, while a path like src/api/users.py still survives whole -- which is why '.' is allowed inside an identifier in the first place. Measured after the fix, same bodies, two samples per level: source file read, 3,598 tok low 64.8% removed medium 90.0% high 90.4% access log, 8,722 tok low declined medium 98.8% high 98.1% low now keeps 3.5x more than medium on code, which is what the level is for. The access-log row is documented rather than fixed: low is told that returning the input unchanged is acceptable, so on an almost-all-noise shape it may decline -- and a declined call still costs its money. Signed-off-by: Osher-Elhadad <[email protected]>
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.
What this is
extract_llmis the only component that spends money to save money, and it shippedhard-disabled on prompt-caching backends because the measurements were brutal: 271 calls,
$3.26, ~1,592 s of latency, to remove tokens worth $0.04.
This branch makes it usable, and adds the saving the old design missed entirely.
The measurement that motivated it
Production, 1.4 days of real traffic, from
requests.cache_miss_reason:hitttl_expiryprefix_changecold_startTurns that resume after the prompt cache expires are 4% of requests and 31% of spend —
$1.64 each against $0.144 for a warm turn — because their whole transcript is re-billed as
cache creation at 1.25x the fresh rate. The shipped pipeline saved 0.015% of it
(
baseline_cost_usd$360.14 against an actual $360.09).Two things are true only on such a turn: a removed token is worth 12.5x its warm-turn value
(cache-write rate vs cache-read rate), and rewriting deep history is free, because there is no
live cached prefix left to invalidate.
What changed
transcript: tail gate lifted, full transcript as context, saved tokens priced at the
cache-write rate, escalation to the agent's own model when the transcript will not fit the
extraction model's window. Its own switch, floor and cap;
per_output: falsegives the sweepalone. Detection is per provider and errs toward "still warm", because calling a warm cache
cold is the expensive mistake.
fire_on: sizemakes the candidate's own size thewhole decision and demotes the economic gate to advisory — it still records what it would
have refused, so the counterfactual is visible instead of the loss being invisible.
llm_max_per_sessionis the outer bound the per-request cap could never provide.shared by every account, then
low|medium|highwith worked examples across JSON, logs, proseand source reads. General-first because a provider caches a prefix.
goal | recent | full, defaultrecent.provider's minimum cacheable prefix is silently ignored, and a mark whose entry nothing reads
is a 1.25x write for nothing. Now gated on both the size floor and a one-writer claim.
tier, cost at the extraction model's real rates, latency, whether it was accepted and why not
if it was not, plus the before/after diff. New table via additive DDL, so no history is
wiped. The components view finally states an expensive component's verdict in dollars.
gateway hostname (
CG_DEFAULT_ANTHROPIC_UPSTREAMnames the default for new accounts).Defects this found and fixed
Most of these were pre-existing, and measurement is what surfaced them:
skip_file_readsnever implemented its documented AUTO default, so it did the opposite ofthe +30%-billed-cost finding it exists to act on.
model: a call recorded at $0.0276 had cost ~$0.083, and the gate spends on that number.
price, zero result. Now counted (
llm_truncatedat/stats), and the budget is raised andtied to the client's own constant so the two cannot drift.
RunExtraction*reported"none"for every failure alike; four live calls spent ~$0.27 and100 s to say nothing. Failures are now named.
referenced to survive verbatim — right for a needle, wrong for one appearing on every line of
the noise. Keep-ids are now harvested from the agent's own words only, and a pervasive id may
vanish with the noise it lived in.
Evidence
Real Claude Code sessions and real requests through a local proxy to the live gateway.
Reliability, same 26k-token access log, five identical requests:
Keep-id source, four samples per arm: with keep-ids harvested from the full transcript,
0/6 accepted across two runs; harvested from the conversation alone, a full-sized context
accepts 3/4 — the same as a small one. That was the difference between the sweep working and
being an expensive no-op.
Cold sweep, end to end, on
per_output: falsewith a real 400 s idle gap:The honest part
On a warm turn this is still usually net negative, and the numbers here say so: a 99.6%
reduction of a 26k-token output is worth $0.0078 at the cache-read rate against $0.019 spent.
The same reduction on a cold turn is worth $0.098. That asymmetry is the whole argument for
the sweep, and it is why the two halves are separate switches with the sweep recommended first.
Measured latency is 5-15 s per call, not the "+117 ms" the settings warning used to claim (that
figure is the deterministic
extract); the warning is fixed. Acceptance is ~75-100% dependingon content, because the model is sampled — a rejected call still costs its money and its
seconds, which is now visible per call rather than inferred.
Verification
go test -race ./...,go vet,gofmt,node --check dash/ui/app.js,mkdocs build --strictall clean. The form's generated documents are validated by a
configtest, since the browserwrites YAML by string surgery and the server is the strict validator.
Reviewed before pushing; the review produced seven findings and all seven are fixed in
fix: seven defects from the review of this branch— including one where a plain settings savewould silently delete unmanaged config keys, and another where ticking a checkbox removed the
spending brakes as a side effect.
Deployed state
Live on the hosted service, disabled: 53 production requests since the restart show
extract_llm: absent,llm_calls: 0. The 11 accounts that track the server default areunaffected — the default pipeline does not include the component. Enabling instructions are in
docs/hosted.md, ordered sweep-first.