Repository navigation
feat(offload): give cache_aware_summarizer a real trigger and feed the keep-alive - #402
Conversation
957bfa3 to
c2c9521
Compare
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…e keep-alive cache_aware_summarizer embedded a components.Trigger but shipped no defaults for it (a zero Trigger fires on every request past ~11 messages/500 tokens) and never called Trigger.CacheAllows/Ctx.CachePhase, so trigger.cache_state was silently inert — the defect summarize.go's own docstring already flagged (#400). - Default min_request_frac to 0.9 and cache_state to any, mirroring summarize's own defaults and sharing its raw-YAML presence probe (triggerKeysPresent) rather than a second copy of it. - Honour cache_state via Trigger.CacheAllows/Ctx.CachePhase. The fresh-commission gates (size, window-resolvability, cache phase) now decide only whether to PAY for a new summary; an existing checkpoint still replays on a turn they decline, stale or not (tryReuse/replayStale), so a declining turn never forwards the full transcript and flips the provider's cached prefix. - Guarantee the side call reads warm: a turn whose own cache is COLD defers the commission (cache_aware_cold.go) until the forwarded request's own usage confirms the rewrite, instead of racing it to rewrite the same prefix twice. A bounded fallback timer resolves it even if the host never calls the hook. - Let the component stand in for the idle keep-alive's bare cache-read ping (cache_aware_keepalive.go, proxy/keepalive.go): a turn with real commission material registers it regardless of whether cache_state let it fire that turn; the keeper substitutes it for a due ping when no checkpoint exists yet and the projected cost is inside the per-ping $ cap, counted once as the ping, and falls back to an ordinary ping on any failure or over-budget projection. No preset changes; xhigh still uses summarize. Adopting cache_aware_summarizer there would additionally want a verified instruction_role/model_id (the shipped system_models allow-list is empty) and a measured min_tokens/resummarize_tokens pair, the same tuning summarize's own presets already carry. Fixes #400. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…efixAsk The trigger/cache_state/cold-ordering/keep-alive work from the previous commit was correctly implemented but inert on the deployment's own traffic: cache_aware_summarizer requires components.MessagesModel, and on Anthropic incoming-model requests the host wraps the client as internal/cheapmodel.Anthropic, which implements only Complete (#275 part 2). Add a second call path through components.PrefixAsker (Ctx.PrefixAsk) — the same "stored request plus one appended question" shape extract_llm_sweep already uses on this traffic, reading the previous turn's actually-sent body rather than rebuilding a prompt. Both paths converge on one summaryCaller closure built once in Offload, so the detached async path, the cold-turn deferral and the keep-alive substitute all carry it opaquely; PrefixAsker.Ask's underlying CompletePrefixed/CompletePrefixedResponses already records usage into the same ambient sink CompleteMessages does, so no extra accounting was needed. PrefixAsker always sends its question as a trailing USER message, so a pinned instruction_role: system is refused loudly (system_role_unsupported_via_prefix_ask) rather than silently sent as user. components.ErrNoPrefix (nothing stashed yet) is counted apart from a real failure; a real failure is now WARN-logged with the provider's error on every path that can hit one, matching the fix already shipped for extract_llm_sweep's sweep_ask_failed (#401). Also fixes a timing bug found while wiring the keep-alive substitute's cache_state: pre_expiry check: the keeper's own ping-due timing is a different question from whether a candidate's configured pre-expiry window is actually live, and by the time a ping fires sweep has already overwritten the entry's startedAt with the ping's own not-yet-sent start — so the check now reads the entry's PREVIOUS startedAt (captured in sweep before the overwrite) rather than computing against a value that always reads back as "nearly the full TTL remaining". Closes #275 (both the inert cache_state and the Anthropic MessagesModel gap). Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
registration gap, and distinguish keep-alive substitute decline reasons Live testing of the previous two commits on real Claude Code traffic found two real gaps: 1. The summary call's own usage (fresh input, cache_read, cache_write, output, cost, latency, which model path, which trigger) was invisible on any dashboard. It never lands on the triggering turn's own Report (the call hasn't happened yet) nor the splicing turn's synchronous work (the call ran on a different goroutine) — the only channel out was deferUsage/takeDeferredUsage's existing usage-replay, which only ever fed the aggregate LLM-cost ledger. deferredUsage now carries a bounded per-call detail list (deferredCall: model, tokens, component, path, trigger, latency), appended by deferUsage and turned into one components.ModelCall per entry by takeDeferredUsage onto the REPLAYING request's own Report — the ledger total it was already replaying is untouched and never truncated, so money accounting cannot regress even if the detail list is capped. Also added process-wide /stats counters (cache_aware_summarizer_cache_read_tokens/_cache_write_tokens, _no_prefix, _prefix_ask_used) so "is the call actually reading warm" and "is PrefixAsk actually activating on this traffic" are each one number, not a dashboard query away. 2. Registration-ordering bug, found by reasoning about why a live session whose turns all declined with cache_state_declined_warm had registered no keep-alive candidate at all: the stash-room check ran BEFORE registerKeepAliveCandidate, so a transient store-capacity hiccup on the turn that otherwise had everything needed (model resolved, instruction built) silently cost the candidate for that turn — indistinguishable, from the outside, from a session the component had never touched. Moved the check to AFTER registration: it is a moment-dependent resource constraint that commitAsyncSummary re-checks anyway before writing anything, unlike the model/role checks above it, which are permanent for the session as configured and correctly still block registration. Also replaced KeepAliveSubstitute's silent two-value return with a KeepAliveSubstituteReason (no_candidate | checkpoint_exists, plus in_flight | concurrency_full on KeepAliveSummaryResult for a Dispatch that ran and did not commit) and matching keeper counters — the exact "ok=false branch is silent" gap flagged in review, and the mechanism that would have made the registration-ordering bug diagnosable without reading code. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Struct field alignment drifted after adding deferredCall's Component field in the previous commit; make lint caught it in CI (gofmt -l reported the file). Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
A model reply can stop early. The model's token budget or thinking budget can run out before the reply ends. The summarizer prompt asks the model to close its reply with a `</summary>` tag. A reply that stops early does not have this tag. Two existing functions hide this problem. sanitizeSummary removes the `</summary>` tag from every reply, because the tag is also a control string an untrusted reply must not forge. ensureSummaryTags then adds the tag back if it is missing. Together, these two steps turn a cut off reply into text that looks complete. The checkpoint built from this text would then replace real history with a fragment. This commit checks the reply for the `</summary>` tag before either of those two functions runs. A reply with no closing tag is now treated as a failed call. The call is counted (cache_aware_summarizer_truncated), logged as a warning, and no checkpoint is written. The turn still forwards the full transcript, exactly as any other failed call does. The check runs on both paths that can produce a checkpoint: the detached async path and the keep-alive substitute path. summarize's own prompt asks for the same tag, so the same risk exists there in theory. This commit does not change summarize. Many of summarize's own tests use reply text with no `</summary>` tag at all, on the strength of ensureSummaryTags' existing, accepted leniency. Adding the same strict check to summarize would break those tests and change a long-shipped contract. That is a separate decision for a separate change, not a shared-helper fix. Also discovered live: the Anthropic prefix-ask response can carry `stop_reason: max_tokens` and no readable reply at all when the model's thinking budget exceeds the ping's old 16000-token cap. #406 fixes that cap. This commit's check is the second, independent guard: even once #406 raises the cap, a reply can still stop early for other reasons, and this check catches that case too. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
cache_state: pre_expiry previously applied a commissioned checkpoint on the very next request, warm or cold -- splicing a summary into a WARM turn is exactly the cache-destructive rewrite this mode exists to defer (it forces the provider to re-write the whole suffix at ~1.25x instead of a cheap cache read). Redefine pre_expiry as "prepare for a cold return": a checkpoint commissioned while the cache is still believed live is marked Reserved and held without being spliced into any forwarded body. Warm turns keep forwarding full history untouched. The idle keep-alive's substitute path (KeepAliveSubstitute) keeps a current reserve as a plain ping, and once the tail since the reserve reaches resummarize_tokens, refreshes it with a fresh summary covering the larger span instead of a bare ping. The reserve finally graduates -- splices, and stops being Reserved -- on the first turn whose cache phase is Cold. cache_state: any is unchanged: commission on a threshold-crossing turn, splice on the very next request regardless of phase. Reject resummarize_tokens: 0 together with cache_state: pre_expiry at config-build time: a zero threshold would make every keep-alive ping see the reserve as stale and pay for an identical fresh summary forever, which is strictly worse than the ping it replaces. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
… cost A `cache_state: pre_expiry` reserve used to be refreshed at a keep-alive ping whenever its tail reached resummarize_tokens -- a threshold tuned for the unrelated turn-based re-summarize decision, not for a refresh's own economics. On a 900k-token session a single refresh costs about $0.20; the 6,000-token default threshold saves only a few cents on the eventual cold return, so an idle session paid far more than it got back. Gate the refresh on money instead: fireSummarySubstitute now compares the expected saving (the new tail's own tokens at the model's cache-write rate -- the write that tail avoids on the cold return) to the call's own projected cost (the same projection already used for the per-ping $ cap), and pings normally when the saving does not cover the cost. offload.KeepAliveSubstitute no longer makes this decision itself: checkpointRefreshOpportunity (replacing checkpointCurrent) reports any nonempty tail as an opportunity, tagged IsRefresh/RefreshTailTokens on KeepAliveCandidateInfo, and leaves pricing it to the keeper, which is the only side that has a price list. resummarize_tokens keeps its original, turn-based meaning unchanged. Each decision is counted (keepalive_summary_substitute_refresh_paid / _refresh_not_worth_it) with a DEBUG log naming the tail size, expected saving, and projected cost, so the gate's own behaviour is visible on real traffic. The config-time refusal of resummarize_tokens: 0 with cache_state: pre_expiry is removed: it guarded against exactly the token-threshold trap this money gate replaces, and 0 is no longer special under either cache_state. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Add a plain-English section to the component's doc page covering the two cache_state modes: when each fires, when the summary gets used, what keep-alive pings do, and when a reserve refreshes (#415). Include a cost table at 900k tokens on Sonnet 5 prices, a "which to choose" list, why there is no "fire on every turn, apply only when cold" value (cold and pre_expiry_or_cold were withdrawn before this PR, for reasons already in components/trigger.go), the limits a proxy restart and keep-alive pinging put on pre_expiry, and when summarize is still the better choice. Move the page's existing deep-dive content under one "Technical notes" heading so the plain-English write-up leads. Extend the /stats counters table with the fields this PR's prior commits added (no_prefix, prefix_ask_used, cache_read/write_tokens, truncated) and name the two keep-alive refresh counters from proxy's own /stats. Link the new section from docs/components.md's component table and from docs/reference/presets.md's note on why `high` does not use pre_expiry with summarize. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
b001c92 to
8365907
Compare
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Add the test the pin needed: a cache_aware_summarizer summary call replaces one keep-alive ping, counts toward keepalive_max_pings the same way a plain ping does, and never extends it. With MaxPings: 2, ping 1 creates the session's first reserve and ping 2 -- finding that reserve already current, with nothing new to weigh -- falls back to a plain ping; there is no ping 3. The same shape holds with MaxPings: 3 (one summary call, then two plain pings, then nothing). sweep already increments e.pings and gates on MaxPings before fire() ever decides between a summary call and a plain ping, so this was already true of the shipped code; the test pins it so a later change cannot regress it silently. Document the same guarantee in the component's doc page: the summarizer never changes how long the cache stays warm -- that is the cache strategy's job. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
A live test of #402 found keep-alive substitution never ran. Two real bugs, both found and fixed here. 1. proxy.go cleared a session's keep-alive candidate AFTER running the pipeline that had just registered it. Every real request therefore deleted its own registration a few lines after writing it. The gate only ever saw reason=no_candidate; every substitute counter stayed at zero. offload.ClearStaleKeepAliveCandidate replaces the unconditional clear with one gated on a timestamp: a candidate is dropped only if it was registered BEFORE the current request's own pipeline ran, never the one that run itself just wrote. The timestamp is captured in proxy.go before the pipeline runs, since the session key the old unconditional clear used is not resolved until after it (apply derives it from the request's own tenant/header/body). 2. A registered candidate's stored context was the REGISTERING request's own context, cancelled by net/http the moment that request's handler returns. Any later keep-alive ping that tried to dispatch it failed every single time with "context canceled" -- this is why the fix above alone did not make substitution succeed end to end. The candidate now stores context.WithoutCancel(c.Ctx), the same detachment startAsyncSummary's own goroutine already needed for the identical reason. Added a real end-to-end regression test (TestARealRequestsKeepAliveCandidateSurvivesAndAPingDispatchesIt) that drives two real HTTP requests through the actual Mux()/serve() path and a real keep-alive ping. It fails with reason=no_candidate against the code before fix 1, and with a call-failed/context-canceled log line against the code before fix 2 -- every other keep-alive- substitute test in this package registers a candidate directly and so could not have caught either bug. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Appending this component's own instruction is a non-tool-result message after the whole conversation. On a model that keeps only the last turn's thinking block -- claude-haiku-4-5 is the one measured -- sending that message strips every EARLIER thinking block from the model's own context the moment it arrives, per Anthropic's own "Thinking block preservation by model" doc page. The backend's cached prefix then matches only up to that earlier block, so the read this component exists to produce is smaller than expected -- silently. Live-measured on claude-haiku-4-5: the commission's own cache read landed about 2,100-2,150 tokens short of the real turn immediately before it, in two separate sessions, both landing on exactly their own session's SECOND turn (the turn before the first thinking block existed). The same test on Sonnet 5 (keep-all) matched exactly. Add a small allow-list, same shape as the existing system-role one: summarizer_model_profiles.yaml's thinking_last_turn_models names a model as last-turn-only; an unmatched model keeps the current behaviour (keep-all is the default and the safe direction -- declining when nothing would actually be stripped only costs a compaction opportunity, where proceeding when something would costs a silently smaller read). Only claude-haiku-4-5 is named; every Opus/Sonnet entry already in this file is at or past its own family's keep-all cutoff. When the request's own model matches and an earlier (not the last) message carries a thinking block, cache_aware_summarizer declines with gate thinking_would_be_stripped, counts it (cache_aware_summarizer_thinking_would_strip), and DEBUG-logs the model. No call is made either way -- fail open, nothing paid for. extract_llm_sweep has the identical exposure and is not touched here; tracked separately. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
thinking_last_turn_models named only claude-haiku-4-5, but Anthropic's
"Thinking block preservation by model" doc page's cutoffs ("Opus 4.5
and later Opus models", "Sonnet 4.6 and later Sonnet models") put the
whole bare Opus 4 / Opus 4.1 and bare Sonnet 4 / Sonnet 4.5 generations,
plus Claude 3.7 Sonnet, in the same last-turn-only bucket as Haiku
through 4.5 -- none of them were covered, so the gate this component
relies on to avoid a silently smaller cache read missed every one of
them.
Matching is a plain case-insensitive substring test (same as
system_models), which makes the bare generation the one that bites: a
plain "claude-opus-4" or "claude-sonnet-4" match string is also a
substring of claude-opus-4-5/-6/-7/-8 and claude-sonnet-4-5/-6, which
are the keep-all models this list must NOT catch. Name the bare
generation by its two actual wire forms instead -- the undated alias
(claude-opus-4-0, claude-sonnet-4-0) and the dated id's year prefix
(claude-opus-4-2025, claude-sonnet-4-2025) -- neither of which is a
substring of a sub-versioned id (claude-opus-4-1-2025... reads
"4-1-2025", not "4-2025"). Opus 4.1 and Sonnet 4.5 each get an exact
match on their own full sub-version.
Added a direct test of the match list (not routed through Offload)
against every documented last-turn-only wire form (dated id and alias)
and against the keep-all ids a careless bare-generation match would
have caught (opus-4-5/4-6, opus-5, sonnet-4-6, sonnet-5, haiku-5-5).
go build/vet, go test ./components/offload/... ./proxy/... ./config/...
./components/..., and go test -race ./components/offload/...
./proxy/... all clean on the eval box.
Assisted-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Summary
Request changes: 2 bugs to fix before merge. The core of the PR works. On live Anthropic traffic, cache_aware_summarizer now runs through PrefixAsk, and its summary call reads the warm cache. main declines every turn. I found 2 bugs. Both are silent, and both are confirmed by a test that goes through the real serve() path.
- On a request body over 1.5 MB, the summary is written from an old body (High). The checkpoint then claims to cover messages that the model never saw.
- The keep-alive candidate registry never drains (Medium). After 2,048 sessions, no new session can register, until the proxy restarts.
What I ran
Eval box, PR head 45bd937:
go build ./...andgo vet ./...: pass.go test -count=1 ./...: pass, except 2context-guru-plugintests (TestInstallRefusesAnUnverifiedDownload,TestInstallReportsPATHFromTheSourceFallbackToo). These 2 also fail on an unmodifiedorigin/mainon the same box, so the cause is the box, not this PR.go test -race -count=1 ./components/offload/... ./proxy/...: pass (153 s, 364 s).- Live traffic. I sent 4 turns of real
aws/claude-sonnet-5traffic through the plain litellm gateway, with an 11.6k-token cached system prompt. I ran the same script against the PR proxy and amainproxy (control).
| PR | main (control) |
|
|---|---|---|
| Component result | commissioned 1 summary, committed 1 | declined, no_messages_model |
prefix_ask_used |
1 | 0 |
| Summary call cache read | 11,603 tokens (warm) | no call |
On turn 4, the PR's splice was reverted. This is expected: the test conversation was too small for a summary to save tokens. It is not a finding.
Finding 1 (High): a body over 1.5 MB gives a summary of an old body
What happens. The PrefixAsk path writes the summary from h.sent, the last body sent for the session. sentStash.put (proxy/prefixask.go:71) skips every body over maxSentBody (1.5 MB) and keeps the old entry. The summary call then appends its instruction to that old body. But the checkpoint records CoveredCount/CoveredHash for the current span. The model never saw the messages after the old body, and the summary does not tell anyone that they are missing.
Why it matters. The default trigger is min_request_frac: 0.9. On a 1M-window model, that is about 900k tokens, which is several MB of JSON. So on the 1M-window sessions that this PR is written for, every triggering request is over the cap. The stash stops at the last body under 1.5 MB (about 375k tokens), and every summary after that is written from it:
- The summary leaves out everything after that point and still claims to cover it. With
marker: fullthe originals are still in the stash, but the model has no signal to expand them. - The summary call reads a prefix that is many turns old. That cache entry has probably expired, so the call pays a full cache write instead of the cache read this component depends on.
Proof. The test sends 3 real HTTP requests through Mux()/serve() with a mock upstream. Turn 2 carries a 1.6 MB user message, and turn 3 triggers the summary.
| Turn 2 size | Summary call body | Has turn 1 | Has turn 2 | Result |
|---|---|---|---|---|
| 10 KB (control) | 11,152 B | yes | yes | correct |
| 1.6 MB | 1,031 B | yes | no | the checkpoint covers turn 2, but the model saw only turn 1 |
Suggested fix. Make the PrefixAsk path decline when the stash does not cover the span. Count the decline (for example, cache_aware_summarizer_stale_prefix). For example, store each stashed body's message count and a hash of its messages, and compare them with msgs[:end] before the call. Raising maxSentBody alone does not solve the problem, because any cap gives the same silent result.
Related, lower severity. The same guard also covers a race. The commission starts during turn N's pipeline, before turn N is stashed, so the call reads turn N−1's body. With keep_last_turns: 1, the span includes the last assistant message, which turn N−1 did not have. My small control shows this (hasT3=false). With the default keep_last_turns: 10 this cannot happen, so it is a note only.
Finding 2 (Medium): the candidate registry never drains
What happens. An entry in keepAliveCand is removed only by ClearStaleKeepAliveCandidate, on the same session's next request. When a session ends, its entry stays forever. keeper.retire does not clear it, and nothing removes old entries. After maxKeepAliveCandidates (2,048) sessions, registerKeepAliveCandidate refuses every new session until the proxy restarts. The refusal is counted as keepalive_summary_substitute_no_candidate, which looks the same as the normal case.
The comment on maxKeepAliveCandidates is wrong. It says "the oldest registration is simply overwritten". The code refuses the new registration and keeps the oldest one.
Memory. Each entry holds a copy of the span. On the messages path it also holds the ask closure over the full msgs. The copy is a shallow slice copy, so each entry keeps the parsed request content in memory. For large sessions that is several MB per entry, with up to 2,048 entries, held after the sessions end.
Proof. The test registers 2,048 sessions that then end. KeepAliveSubstitute for a new, live session then returns ok=false reason="no_candidate".
Suggested fix. Clear the candidate in keeper.retire (and anywhere else the keeper stops tracking a session). Also add an age limit or LRU eviction, so that a host without the keeper does not fill the registry.
Smaller points (from reading the code, not tested)
recordSummarySubstitutepasses0as the 1h-write argument toCostWithCacheWrite1h.record1passesu.CacheWrite1h. With the1-hour-headstrategy, the substitute's 1h cache writes are priced at the 5-minute rate.KeepAliveSummaryResulthas no field for 1h writes.fireSummarySubstituteruns the summary call (up tocacheAwareTimeout, 300 s) while it holds the tenant limiter slot fromAcquireSpare. An ordinary ping holds the slot for about 1–2 s. With tight concurrency limits, real requests can lose slack for minutes.- The doc comment at
components/offload/cache_aware_summarizer.go:87still says a ping refreshes the reserve "once the reserve's own tail grows past resummarize_tokens". Since #415 the money gate decides this, so the comment is out of date.
Technical notes
Probe tests (not committed). File: proxy/review402_stash_test.go
// Finding 1: turns t1 (3 msgs), t2 (5 msgs, last user message 10 KB or 1.6 MB), t3 (7 msgs).
// Config: keep_last_turns 1, min_tokens 1, trigger {min_messages 7, min_request_tokens 1,
// min_request_frac 0, cache_state any}. The test selects the upstream body that contains
// "Output ONLY the summary" and checks for the MARK-T2 string.
// 10 KB : asks=1 len=11152 hasT2=true
// 1.6 MB: asks=1 len=1031 hasT1=true hasT2=false -> FAIL
// Finding 2:
for i := 0; i < 2048; i++ {
offload.RegisterKeepAliveCandidateForTest(fmt.Sprintf("ended-%d", i), st, call, "messages", span, 1, "any", 0)
}
offload.RegisterKeepAliveCandidateForTest("live", st, call, "messages", span, 1, "any", 0)
_, _, reason, ok := offload.KeepAliveSubstitute("live") // ok=false reason="no_candidate"If xhigh switches to cache_aware_summarizer later (the PR says this is a separate decision), Finding 1 will apply to xhigh by default.
…nswering from an old body Review of PR #402 (finding 1, High) found that cache_aware_summarizer's PrefixAsk path could silently commit a checkpoint whose summary did not cover what the checkpoint claimed. The commission answers from the host's stash of the last body it forwarded for the session (proxy's sentStash). sentStash.put skipped a body over its 1.5 MB cap and kept the OLDER body in place, so the next commission could append its instruction to a transcript that did not include everything since. The checkpoint it wrote still recorded the correct CoveredCount/CoveredHash, because those come from the live transcript, not from what the model actually read — only the summary text itself was wrong. Fix, in two parts: 1. sentStash.put now DELETES a session's entry when it skips an oversized body, instead of leaving the old one in place. A missing stash is the routine, already-handled "no prefix yet" case (components.ErrNoPrefix); a wrong one is not. 2. A new components.PrefixCoverage interface lets a PrefixAsker report whether its stashed body covers a given prefix of the conversation (count of normalized messages plus a content hash, components.SpanHash). cache_aware_summarizer checks this immediately before the PrefixAsk call actually runs — not synchronously inside Offload, where the host has not yet had the chance to stash the triggering turn's own body — and declines with the new components.ErrStalePrefix sentinel on a mismatch, counted separately (cache_aware_summarizer_stale_prefix) from the ordinary first-turn case. proxy's sentStash, and the prefixAsker/responsesPrefixAsker wrapper types the pipeline actually receives, implement the new interface by re-normalizing the stashed body (apply.NormalizeMessages, newly exported) and hashing it the same way the component hashes its own span. Also fixes a stale doc comment in cache_aware_summarizer.go: a reserved checkpoint's refresh has been decided by the money gate since #415, not by a token-count comparison against resummarize_tokens. Tests: a unit test drives the guard directly through a fake PrefixAsker; an integration test runs 3 real turns through the actual serve() path with a 1.6 MB turn-2 body (declines safely, no wrong summary call) against a 10 KB control (still works, cache read exercised). Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
… its substitute calls right Review of PR #402, finding 2 (Medium) and two smaller points. Finding 2: the keep-alive candidate registry (cache_aware_summarizer's own, session-keyed map of material a ping may substitute a summary for) was never drained when the KEEPER itself stopped tracking a session. ClearKeepAliveCandidate always existed and always worked when called; nothing on the keeper's own exit paths — retire, forget, evictLocked — ever called it. After maxKeepAliveCandidates (2,048) sessions had ever registered, every later session's registration was refused, permanently, with no counter telling that apart from "nothing here uses this component". Fixed by calling ClearKeepAliveCandidate from all three exit paths (and from Stop, for symmetry). cache_aware_keepalive.go also gets a correction to a comment that claimed the registry evicted its oldest entry at capacity — it never did, it refused the new one — and a maxKeepAliveCandidateAge fallback that prunes stale entries on registration, so a deployment embedding this package without proxy's keeper is not exposed to the same unbounded growth. Smaller point (a): recordSummarySubstitute priced every substitute call's cache writes at the five-minute rate, passing a hardcoded 0 for the one-hour tier where record1 (an ordinary ping) passes the real figure. KeepAliveSummaryResult had no field for it. cheapmodel.Sink now tracks the 1h-tier subset of cache-write tokens (parsed off Anthropic's cache_creation.ephemeral_1h_input_tokens, the same field proxy's own usage parser already reads off the agent's own response), threaded through KeepAliveSummaryResult.CacheWrite1h to recordSummarySubstitute's CostWithCacheWrite1h call. Smaller point (b): fireSummarySubstitute held the tenant's AcquireSpare slot for the whole substitute call — up to cacheAwareTimeout (300s) — where an ordinary ping holds it for a single round trip. The slot is now released immediately after the eligibility check and before the substitute call runs; a fresh one is acquired only if the call was not attempted (the ordinary ping fallback). The substitute call needs no slot of its own to stay bounded — it already shares cache_aware_summarizer's own concurrency gate (summarySlots). Tests: proxy/keepalive_candidate_drain_test.go exercises retire, forget and evictLocked directly, plus the reviewer's own probe (2,048 ended sessions, then one live registration that must still succeed). Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Thank you for the detailed review and the probe tests. Both findings fixed, plus the smaller points. Pushed to Finding 1 (High), the stale body. Fixed in two parts, matching your suggestion.
For the general case (including the race you noted), a new
Tests: Finding 2 (Medium), the registry that never drained. Test: Smaller points. (a) (b) (c) Fixed — the comment now says the money gate (#415) decides a reserved checkpoint's refresh, not a token-count comparison. Verification on the eval box, PR head No user-visible behavior change to the plain-English part of the description — these are correctness and cost-accounting fixes to the mechanism already described there. |
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
Summary
Re-review of e52851d: both bugs are fixed. OK to merge from my side, with 1 low-severity note. Each fix is confirmed by a test through the real serve() path.
What I checked
| Earlier finding | Status | Evidence |
|---|---|---|
| 1. Summary written from an old stashed body (> 1.5 MB) | Fixed | Turn 2 = 1.6 MB: 0 summary calls go upstream (it was 1 call that did not see turn 2). put now deletes the old entry, so the call gets ErrNoPrefix. |
| 2. Candidate registry never drains | Fixed | retire/forget/evictLocked/Stop clear the candidate, and a 2 h age limit prunes the registry when it is full. The PR's own drain tests cover this. |
| 1h cache writes priced at the 5-minute rate | Fixed | CacheWrite1h now flows from CompletePrefixed to recordSummarySubstitute. |
| Limiter slot held for the whole summary call | Fixed | The slot is released before the summary call. The fallback ping takes a new slot. |
| Out-of-date doc comment | Fixed |
I also checked that the new stale-prefix guard does not block normal traffic. It compares the incoming messages with the stored forwarded body, so a proxy change to the forwarded body could make every check fail. Results:
| Case | Summary calls | stale_prefix |
|---|---|---|
keep_last_turns: 2, no moving cache_control |
1 | 0 |
keep_last_turns: 10 (default), cache_control moves to the last message each turn (Claude Code style), 13 turns |
1 | 0 |
| Re-summarize after a checkpoint was spliced (6 forwarded bodies carried the marker) | 2 | 0 |
keep_last_turns: 2, cache_control moves to the last message each turn |
0 | 3 |
Note (Low): small keep_last_turns plus a moving cache_control blocks every summary
What happens. The previous turn's body has cache_control on its last message. In the current request that message has no marker, so the hash of msgs[:end] differs from the stored body. The span reaches that message whenever keep_last_turns is about 2 or less. Then every commission declines as stale_prefix, and the component makes no summaries. With the default of 10 this does not happen, and the decline is counted, so it is not silent.
Suggested fix (optional, can be a follow-up). Remove cache_control from both sides before SpanHash, or hash only the message content. If you do not fix it, a line in the docs about keep_last_turns is enough.
What I ran
Eval box, head e52851d:
go build ./...andgo vet ./...: pass.go test -race -count=1 ./components/offload/... ./proxy/...: pass (153 s, 367 s).go test -count=1 ./...: pass, except:- The same 2
context-guru-pluginbox-defect tests as before (result=present). They also fail onorigin/main. dashTestJanitorPassCheckpointsWALfailed once under full-suite load. Alone it passes 5 of 5 on this PR and 5 of 5 onmain, so it is a flaky test, not caused by this PR (the PR does not changedash).
- The same 2
- Live
aws/claude-sonnet-5traffic through the plain gateway, same script as the first review. Result: 1 summary commissioned and committed through PrefixAsk, with a non-zero cache read. Same as45bd937.
Resolve the conflicts with #402 (cache_aware_summarizer keep-alive substitution) and make that substitution thread-aware. The substitution registry is keyed by session, but the keep-alive is now per thread, and a candidate's span is one thread's conversation. Without a fix, a subagent's ping could run the main thread's summary call (refreshing the wrong prefix), and a subagent's request or entry retirement could clear the main thread's candidate. The keeper now records which thread registered the candidate (noteCandidate, via offload.KeepAliveCandidateRegisteredSince). Only that thread's ping may use it, and only that thread's request or retirement clears it. A session with no recorded owner keeps the pre-#423 rule. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Address the PR #426 re-review of the #402 merge. - Key cache_aware_summarizer's keep-alive candidate registry by thread.Key(session, thread) instead of by session. This removes the timestamp-based ownership (noteCandidate / candThread), which a concurrent request of another thread could win, and stops a later thread's registration from replacing another thread's candidate. - Resolve the thread inside apply, once the session id is known and before the pipeline runs (apply.Opts.ThreadOf), and expose it on components.Ctx.Thread, so the component can key by it. - Book a substituted ping with its thread (recordSummarySubstitute). The summarizer's checkpoint and in-flight guard are still per session; that is a follow-up. Refs #423 Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…ker and the pipeline order PR #402 added a guard that declines a cache_aware_summarizer commission (gate stale_prefix) when the stashed forwarded body does not cover the span the commission is about to claim as summarized. Two re-reviews found that the guard's own hash was wrong in two separate ways. What we found. 1. The guard's hash included each message's cache_control marker. A client that moves a single cache breakpoint to the last message every turn (Claude Code does this) resends an earlier message with the marker gone. The content is the same; only the marker moved. At keep_last_turns 2 or less, the summarized span reached that message on every turn, so the hash never matched and the guard declined every commission. Live: 3 of 3 commissions declined, 0 summaries. 2. extract_llm_sweep reads the same host stash through the same PrefixAsker construction, with no coverage check of its own. 3. A second review (of PR #414, which switches the xhigh preset to cache_aware_summarizer) found that a pipeline component downstream of cache_aware_summarizer rewrites a message before the request is forwarded. The guard compared the summarizer's own span - computed from the message set the pipeline first received - against the FORWARDED body, which a later component may have already rewritten. The two bodies disagreed on every turn such a component acted. Live xhigh: 5 of 5 commissions declined, 0 summaries; through [cache_aware_summarizer, textclean], 12 of 12 declined. What we changed. - components.SpanHash now strips cache_control before hashing a message, on both sides of every comparison that uses it. A moved marker no longer looks like a content change. - extract_llm_sweep gained the same stale-prefix guard cache_aware_summarizer already had, scoped to candidates the component believes already sit inside the cached prefix (i <= MaxCachedIdx). A candidate in the turn's own new, not-yet-cached tail is a separate, already-tracked gap (#122), not this guard's job - checking it there would decline a normal turn's own newest content, not only a stale one. - proxy's sentStash now keeps two bodies per session: the one actually forwarded (what Ask appends its question to, because that is what the provider's cache holds) and the one the pipeline received before any component ran. The stale-prefix guard, on both callers, now checks coverage against the PRE-pipeline body, so a downstream component's rewrite can no longer make the guard see a stale prefix that was never stale. How it was tested. Eval box, CGO_ENABLED=1: go build ./... pass go vet ./... pass gofmt -l . no files go test ./components/offload/... ./proxy/... pass go test -race ./components/offload/... ./proxy/... pass New tests, each confirmed to fail without its matching fix and pass with it, through the real serve() path: - TestCacheAwareClaudeCodeStyleMovingCacheControlIsNotStale: three turns with the marker moving to the last message each turn, keep_last_turns 2. Fails without the SpanHash fix (0 ask calls); passes with it (1). - TestCacheAwareRealContentChangeInsideSpanStillDeclines: same shape, but a real text change inside the span. Still declines either way, so the SpanHash fix does not blind the guard to an actual change. - TestCacheAwarePipelineOrderMinimalTextCleanCase and TestCacheAwarePipelineOrderXHighEquivalent: [cache_aware_summarizer, textclean] and the full pipeline PR #414 switches xhigh to (spelled out in the test; #414 is not merged yet). Both fail without the pre/post pipeline stash split (0 ask calls, reproducing the live finding) and pass with it (1). Unit tests in components/offload: TestSweepDeclinesOnAStalePrefix, TestSweepAsksNormallyWhenPrefixCovers, TestSweepStaleGuardStaysOutOfTheWayWithNoKnownBoundary. References #402 (its own re-review found finding 1) and #414 (its review found finding 3; this change unblocks it). Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
xhigh used summarize for its summarizer. summarize builds a new prompt for its summary call. This prompt does not reuse the cached conversation. Every summary call pays full price. cache_aware_summarizer does the same job a different way. It sends the conversation itself, plus one short instruction at the end. This lets the call reuse the cache the agent's own turn already wrote. The call pays full price only for the one short instruction, not for the whole conversation. This commit swaps summarize for cache_aware_summarizer in the xhigh preset only. high keeps summarize unchanged. cache_aware_summarizer's own default trigger (fire at 90% of the context window, on any cache state) is used as is. No trigger values are pinned in the preset. high was left alone on purpose. cache_aware_summarizer needed three separate fixes before it could do anything on real Anthropic traffic: a working trigger and keep-alive integration (#402), a header-size fix for its side call (#406), and a message-order fix for the same call (#413). high's own use of summarize never needed any of these. Moving both presets at once would have mixed two unrelated changes into one commit. Also updated: the preset's own comments in config/config.go, the preset tables in docs/reference/presets.md and docs/components.md, the plugin's own copy of the preset pipeline table (context-guru-plugin/scripts/insights.py, pinned against config.go by TestPluginPresetPipelinesAgreeWithConfig) and its component description table (context-guru-plugin/skills/insights-components/ SKILL.md). docs/components.md's own description of cache_aware_summarizer said it declines without a MessagesModel; that sentence was already stale after #402 added the prefix-ask fallback, so it is corrected here too. This PR must merge after #402, #406 and #413, in that order. It is based on #402's branch so its own diff shows only the preset change. It needs to be retargeted to main once all three are merged. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Issue #424's RECORD half scanned the pristine body (waitcause.Tracker. Observe, ~11ms on a 783 KB body) before forwarding the request upstream. Move it to finish(), after the response has already gone out, by stashing the body (one slice-header copy) with noteWaitBody instead of scanning it inline. The request path's own cost is now independent of body size — see BenchmarkNoteWaitBodyLargeBody alongside internal/waitcause's own BenchmarkObserveLargeBody. Also adds a test pinning that keep-alive ping rows (plain, and the cache_aware_summarizer's #402 summary-substitute) never get a waiting_for or wake_cause: both reach dash.Event construction through dashEmitter. KeepAlivePing, which holds no *waitcause.Tracker at all, so there was never a path from a ping to this package's state. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Issue #424's RECORD half scanned the pristine body (waitcause.Tracker. Observe, ~11ms on a 783 KB body) before forwarding the request upstream. Move it to finish(), after the response has already gone out, by stashing the body (one slice-header copy) with noteWaitBody instead of scanning it inline. The request path's own cost is now independent of body size — see BenchmarkNoteWaitBodyLargeBody alongside internal/waitcause's own BenchmarkObserveLargeBody. Also adds a test pinning that keep-alive ping rows (plain, and the cache_aware_summarizer's #402 summary-substitute) never get a waiting_for or wake_cause: both reach dash.Event construction through dashEmitter. KeepAlivePing, which holds no *waitcause.Tracker at all, so there was never a path from a ping to this package's state. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
The problem, in plain terms
We looked at real usage on a developer machine running the
xhighpreset and found three problems with how long sessions get summarized.xhighusessummarize. To write its summary it builds a brand-new prompt, so it can never reuse the conversation the provider already has cached, and every summary is billed at the full input rate. It also sends only the most recent ~280,000 characters, with tool outputs hidden. On a long session, the oldest part never makes it into the summary. One real session hit 903k of a 1M-token window. Summarizing still saved about $4 overall, but the summary call itself cost $0.24 at full price, on a cut-down history.cache_aware_summarizer, exists but isn't usable.cache_statesetting and then silently ignores it.When it fires: today vs. with this PR
trigger.min_request_frac, new default0.9), the same pointsummarizeuses. Setting it explicitly still wins, and0brings back the old behaviour.trigger.cache_state: any(new default)trigger.cache_state: pre_expirytrigger.pre_expiry_seconds, default 60) is held in reserve, not applied, until the cache actually goes cold — see "Two ways to usecache_state" belowany: on the next request, warm or cold, unchanged.pre_expiry: held in reserve until a request actually arrives cold; every warm request before that keeps forwarding full history untouchedpre_expiry, a reserve that already covers everything new stays a plain ping; once there IS new material, a ping refreshes the reserve only when the refresh is expected to earn back more than it costs (see "The refresh has to pay for itself" below) — otherwise it stays a plain ping too.any: keep sending the existing summary.pre_expiry: keep sending the full history until the reserve graduates on a cold turnextract_llm_sweepalready uses on this trafficTwo ways to use
cache_stateFull write-up, with a cost table and a "which to choose" section:
docs/components/advanced-offload.md § Two ways to use
cache_state.The summarizer never changes how long the cache stays warm. That is set by the cache
strategy (
keepalive_max_pings). A summary call takes the place of one ping, counts the same waya ping does, and never adds an extra one.
any— summarize and apply immediately. The cheapest way to shrink an oversizedconversation: as soon as a turn crosses the size threshold, summarize it and splice the summary
into the very next request, whatever the cache's own state happens to be. This is the mode to
reach for when the goal is simply "stop sending the whole history every turn".
pre_expiry— prepare for a cold return, don't pay for a cache you're still using. Splicinga summary into a WARM turn forces the provider to re-write the entire suffix instead of reading
it from cache — on a 900k-token session that is roughly $2.25 (re-write) against $0.18
(a warm read of the same 900k), repeated on every subsequent turn until the next re-summarize.
pre_expiryavoids ever paying that: a summary made in the last minute before expiry is held inreserve rather than applied, warm turns keep reading the full, already-cached history for
about $0.18, and the reserve is only spliced in on the turn that is cold anyway — at that point
the provider is re-writing the suffix regardless, so splicing a reserve first means that
re-write is sized against the SUMMARY (roughly $0.20 for an 80k rewrite) instead of the full
transcript ($2.25 for 900k).
The refresh has to pay for itself (#415)
The reserve itself is kept fresh at no EXTRA cost: the idle keep-alive already reads the cache
every few minutes, so a stale reserve can be refreshed on a ping that was happening anyway rather
than needing a call of its own. But a refresh is not free — a 900k-token session's refresh costs
about $0.20 every time (it reads the whole cached conversation to write the new summary) — so
it must only happen when it earns that back.
The first version of this PR refreshed once the reserve's own untouched tail reached
resummarize_tokens(default 6,000) — a knob chosen for a different decision (when a TURNre-summarizes), not for a refresh's economics. 6,000 new tokens are only worth about $0.015 on
the eventual cold return — paying $0.20 to save $0.015 on an idle session, repeatedly, forever.
This PR instead refreshes only when the saving is expected to be worth at least as much as the
refresh itself: the new tokens since the reserve, priced at the model's cache-WRITE rate (what
the cold return avoids writing), compared against the same cost projection already used for the
per-ping dollar cap. On an idle session that never grows much, pings simply stay plain pings
forever — which is correct: there is nothing worth refreshing.
resummarize_tokenskeeps itsoriginal job of deciding when a TURN re-summarizes; it no longer has anything to do with when a
PING refreshes. Each decision is counted
(
keepalive_summary_substitute_refresh_paid/_refresh_not_worth_it) so the rule can be checkedagainst real traffic.
Creating a session's FIRST reserve (there is nothing to compare it against yet, only the full
rewrite it is meant to avoid) is not subject to this gate — only refreshing an existing one is.
Why there's no "summarize on every turn, apply only when cold"
cache_stateshipped two more values once —coldandpre_expiry_or_cold— that waited for thecache to go cold before firing at all. Both were withdrawn before this PR, for three reasons
(
components/trigger.go's ownremovedCacheStates): firing on a warm cache and getting it wrongcost about $0.84 across a whole measured corpus — small; firing on a warm cache and getting it
right pays back in 2-3 turns; and because committing a summary always takes two turns, a
cold-gated version pays the first full rewrite anyway, so it never even avoids the thing it waited
for. There is no config value today that fires on every turn but only ever applies on a cold
return.
Limits, and when
summarizeis the better choiceA proxy restart loses every in-progress checkpoint/reserve (memory only) and, on Anthropic
traffic, the previous request this component reuses — the first request after a restart goes
through unchanged (
cache_aware_summarizer_no_prefix), and the component can summarize againfrom the next one. While the idle keep-alive keeps pinging a session, its cache never goes cold,
so a
pre_expiryreserve sits unused (refreshed only when it's worth it) until pinging stops.Prefer
summarizeinstead when: a much cheaper model should write the summary (this componentmust reuse the SAME model's cache); there is no previous request yet to build on; your gateway
won't accept resending the previous request's bytes plus one message; a very large thinking
budget is in play; or tool output should be left out of the summary. See the doc page for the
reasoning behind each.
What changes for users
A cut-off summary can no longer replace real history. If a reply stops before its closing tag — the model ran out of its own token or thinking budget — it is now treated the same as any other failed call rather than spliced in as a seemingly-complete summary.
No config changes are required. Only the defaults above change.
No preset changes.
xhighstill usessummarize. Switching a preset tocache_aware_summarizeris a separate decision, made after it has been measured live.To try it, add
cache_aware_summarizerto the pipeline in place ofsummarize, and optionally set:The Anthropic/PrefixAsk path is verified live, thinking included. fix(cheapmodel): raise max_tokens above thinking.budget_tokens on prefix asks #406 (merged) fixed a
max_tokens-vs-thinking.budget_tokensconflict ininternal/cheapmodel/anthropic.gothat thispath depends on; fix(cheapmodel): insert the prefix ask before a trailing system message #413 (merged) fixed a trailing-system-message conflict in the same path. Both
land in
mainahead of this PR. Verified live end to end: commission → splice → the splicedrequest read warm (
cache_read=32393);cache_state: pre_expirycorrectly declined on warmturns.
Implementation details
Summary
cache_aware_summarizerembedded acomponents.Triggerbut shipped no defaults for it (a zeroTriggerfires on any request past ~11 messages and a 500-token span —components/trigger.go:20,266), never calledTrigger.CacheAllows/Ctx.CachePhase, and couldonly call a model through
components.MessagesModel— which, on Anthropic traffic with thedefault
model.source: incoming, does not exist (internal/cheapmodel.Anthropicimplements onlyComplete; onlyinternal/cheapmodel/openai.gohasCompleteMessages). This PR:min_request_fracdefaults to 0.9,cache_statetoany, sharingsummarize's raw-YAML presence probe (triggerKeysPresent, factored out ofapplySummarizeTriggerDefaults) rather than a second copy of it. An explicitmin_request_frac: 0still wins over the default.cache_state. The fresh-commission gates (sized,resolvableviaTrigger.FracResolvable,phasedviaCtx.CachePhase/Trigger.CacheAllows) now decide onlywhether to pay for a new summary — never whether an existing checkpoint stays in the body.
Those were one decision until now, which is cache-destructive: a turn the gate declines used
to forward the full transcript, diverging from the cached prefix at the first summarized
message.
tryReusenow reportsstale(mirroringsummarize.tryReuse's own shape) and a newreplayStalere-emits an existing-but-stale checkpoint on every decline from here on(
cache_aware_summarizer.go).cache_state: anypermits firing there) defers the commission instead of racing the forwarded request to
rewrite the same prefix twice — both would otherwise pay the full 1.25x rewrite. Deferral is
released by the proxy right after that turn's own usage confirms the rewrite
(
cache_aware_cold.go,offload.ResolveDeferredCacheAwareSummary, called fromproxy/proxy.go'sservedefer next toh.keeper.record); a bounded fallback timer (90s)resolves it even if a host never calls the hook.
material registers it (
cache_aware_keepalive.go) regardless of whethercache_statelet itfire that turn — a turn
cache_state: pre_expirydeclines on a warm phase is exactly thesession whose next ping is about to arrive in the pre-expiry window.
proxy/keepalive.go'skeeper substitutes it for a due ping when the candidate has no CURRENT checkpoint yet, a
pre_expirycandidate's OWN window is actually live right now (not merely whenever the keeperhappens to ping — see "Design notes" below), and the projected cost (a conservative
2000-output-token guess, since this call generates a full summary rather than a ping's one
token) is inside the per-ping
$cap. It is counted once as the ping (never double-pinged —sweepalready incrementse.pingsbefore dispatch, so the substitute path books only thedollar/dashboard side), and falls back to an ordinary ping on any failure, missing candidate,
a current checkpoint, phase mismatch, or over-budget projection.
pre_expirycheckpoint in reserve instead of applying it immediately. A checkpointcommissioned while
Ctx.CachePhaseisPreExpiryis markedsumCheckpoint.Reservedand isNOT spliced into a warm turn (
cacheAwareApplyPhase/tryReuseincache_aware_summarizer.goandstate.go) — splicing it would be the exact cache-destructiverewrite
pre_expiryexists to avoid paying for while the cache is still live. It graduates(splices, and
Reservedclears) on the first turn whose phase isCold.cache_state: anynever sets
Reservedand is unaffected — its checkpoint still applies on the very nextrequest, warm or cold, exactly as before this PR.
keep-alive substitute's lookup (
checkpointRefreshOpportunityincache_aware_keepalive.go,replacing an earlier
checkpointCurrent) reports any nonempty tail as an opportunity(
KeepAliveCandidateInfo.IsRefresh/RefreshTailTokens) without judging whether it is WORTHrefreshing — that judgment moved to
proxy/keepalive.go'sfireSummarySubstitute, the onlyside with a price list: it compares the tail's expected saving (tail tokens × the model's
cache-write rate) against the call's own projected cost (the same number already used for the
per-ping
$cap) and pings normally when the saving falls short.resummarize_tokenskeepsits original, turn-based meaning and plays no part in this comparison. Each decision is
counted (
keepalive_summary_substitute_refresh_paid/_refresh_not_worth_it) with a DEBUG lognaming the tail size, expected saving, and projected cost. Creating a session's FIRST reserve
is not gated this way — it has no existing reserve to compare against, only the full rewrite
it is meant to avoid.
MessagesModel— which on this deployment's own traffic is every Anthropic request withmodel.source: incoming— the component falls back toCtx.PrefixAsk(
components.PrefixAsker), the SAME mechanismextract_llm_sweepalready uses: one questionappended to the exact bytes the previous turn sent upstream, which the provider's cache was
actually populated by. This path can only ever send the question as a trailing USER message
(the interface's own contract), so an operator who pinned
instruction_role: systemis told soexplicitly (
system_role_unsupported_via_prefix_ask) rather than silently downgraded —consistent with
summarizer_model_profiles.yaml's own note that Sonnet 5 does not accept amid-conversation system message.
components.ErrNoPrefix(nothing stashed yet — everysession's first turn) is counted and handled apart from a real failure, which is now WARN-logged
with the provider's error on every path that can hit it (async, cold-deferred, and the
keep-alive substitute), matching the fix already shipped for
extract_llm_sweep's ownsweep_ask_failed(fix(offload): imply block_fallback under debug logging, WARN on ask failure #401).No preset changes —
xhighstill usessummarize. Adoptingcache_aware_summarizerthere wouldadditionally want a verified
instruction_role/model_id(the shippedsystem_modelsallow-list is empty) and a measured
min_tokens/resummarize_tokenspair.Fixes #400. Closes #275 — both the inert
cache_state(part 1) and the inability to reachAnthropic incoming-model traffic at all (part 2, via
PrefixAsk). Closes #415 — apre_expiryrefresh now pays for itself instead of comparing a token count tuned for a different decision.
Issue #416 (additive refresh — folding the tail in rather than re-deriving the whole summary) is
a follow-up, not part of this PR.
Design notes
tryReuseruns before the gates, unconditionally. Mirrorssummarize.Offload's ownfix for the identical bug class: the gates answer "is a fresh summary worth paying for", and
conflating that with "does the existing checkpoint stay in the forwarded body" flips the cache
on every declined turn once
cache_stateis anything other than always-permit.Offload(components/offload/cache_aware_summarizer.go)builds the call it will make, then branches on
Ctx.CachePhase:CachePhaseColdcallsdeferColdSummary(stores the material in a session-keyed map,components/offload/cache_aware_cold.go) instead ofstartAsyncSummary.proxy/proxy.go'sservealready observes this turn's ownusage/usageOKin the samedeferthat callsh.keeper.record(...)—offload.ResolveDeferredCacheAwareSummary(session)is called rightafter, so the side call never races the forwarded request. Only
CachePhaseColdis deferred;CachePhaseUnknownis permitted to fire immediately (perTrigger.CacheAllows's ownUnknown-permits rule) because there is no established double-rewrite to avoid there.
summaryCaller(cache_aware_async.go) is afunc(ctx) (string, error)built exactly once inOffload, on the request's own goroutine —either
mm.CompleteMessages(ctx, "", ask)or a closure overc.PrefixAsk.Ask(ctx, session, instructionText). Everything downstream (the detached async path, the cold-turn deferral, thekeep-alive substitute) carries this one value and neither knows nor needs to know which model
path it is. Usage recording needs no extra plumbing either way:
PrefixAsker.Ask's underlyingCompletePrefixed/CompletePrefixedResponsesalready calls the samecheapmodel. recordUsageCachethatCompleteMessagesdoes, sodeferUsage/takeDeferredUsageandcommissionSync's own sink read work unmodified for either path.keepAliveCandidatekeyed by session on every turn that reaches real commission material(
registerKeepAliveCandidate), cleared by the proxy at the next real request's arrival(
offload.ClearKeepAliveCandidate, called fromproxy/proxy.gonext toh.keeper.arrive) so astale candidate from a superseded turn can never be dispatched.
proxy/keepalive.go'skeeper.firecallsk.fireSummarySubstitutefirst; it looks upoffload.KeepAliveSubstitute(which itself refuses if a checkpoint already exists, and now also returns
KeepAliveCandidateInfo{CacheState, PreExpirySeconds}), checks the candidate's OWN pre-expirywindow against the keeper's own idle-time knowledge (
cachePhaseAt, using the entry'sprevStartedAt— captured insweepbefore it stampse.startedAtfor the ping about to besent, since reading the already-stamped value would always read back as "nearly the full TTL
remaining"), checks a cost projection (
projectedSummaryUSD) against the policy's$ceiling,and only then calls the blocking
Dispatch(→offload.(*CacheAwareSummarizer).commissionSync, which sharesstartAsyncSummary'ssingle-flight registry and concurrency bound so the two callers can never race to summarize the
same span).
sweepalready incrementse.pings/stampse.startedAtbefore dispatch regardlessof which path
firetakes, so "counted once as the ping" falls out of the existing structurerather than needing a second increment.
keeper no longer assumes its own ping timing happens to fall inside a
pre_expirycandidate'swindow; it recomputes the phase from the entry's own last-touch time and TTL tier
(
cachePhaseAt) and declines the substitution (counted askeepalive_summary_substitute_phase_mismatch, falling back to an ordinary ping) when it doesnot.
sumCheckpoint, not a second store key.Reservedisone new
boolfield (state.go) in the structsummarizeandcache_aware_summarizeralreadyshare under the same
store.SumPrefix+sessionkey —summarizenever sets it andcache_aware_summarizeronly sets it forcache_state: pre_expiry, so a zero value alwaysmeans "apply immediately", exactly how both components already behaved before this field
existed.
cacheAwareApplyPhaseis the one place that reads it: a warm phase withReservedsetreturns
declineButReplayStale's warm-side twin (forward full history, do not splice); a coldphase splices and clears
Reservedon write-back regardless of the flag's starting value, so astale
Reservedleft over from a config that has since switched toanycannot wedge a session— the very next cold turn clears it.
checkpointRefreshOpportunityis deliberately conservative, and deliberately not a stalenessverdict. It only ever answers "is there anything new since the EXISTING checkpoint, for the
LATEST registered candidate span" — the empty-tail case is the one one it refuses outright, so a
session that has registered nothing new since its reserve was written is never even offered to
the money gate. Everything else (the checkpoint's own
CoveredCountnot fitting the candidate'sspan, or the covered prefix's hash no longer matching — the conversation diverged) is treated as
an opportunity rather than a refusal, so a wedged or ambiguous state always resolves toward
giving
fireSummarySubstitutesomething to price rather than silently going stale forever. Itno longer consults
resummarize_tokensat all — see "The refresh has to pay for itself" above.Tests added
components/offload/cache_aware_trigger_test.go: trigger defaults and their opt-out, replay ona cache-state decline (not a full-transcript flip), the fill conjunct's five cases, cold-turn
deferral (asserts the side call does not fire until
ResolveDeferredCacheAwareSummary/the fallback timer releases it), keep-alive candidateregistration (including "not registered when too small" and "cleared on a real request's
arrival").
components/offload/cache_aware_prefixask_test.go: the Anthropic/PrefixAsk path end to end —commissions and splices through a fake
PrefixAsker,ErrNoPrefixcounted apart from a realfailure (and does not write a checkpoint), a genuine failure counted and WARN-logged, a pinned
system role declining loudly rather than being silently sent as user, and the keep-alive
substitute working off a PrefixAsk-built candidate.
proxy/keepalive_summarysubstitute_test.go: the substitution itself (replaces the ping, countedonce, produces a checkpoint), fallback to an ordinary ping on a failed call, the
$caprefusing the substitute (and never dispatching it) while still falling back to a ping, and the
pre-expiry phase check — both that it refuses a candidate whose window is not actually live
(
HeadTTL1hmakes this a real divergence from the keeper's own Idle timing, not a contrivedone) and that the SAME candidate fires once the window is live.
components/offload/proxysuites updated only where the new 0.9 default required anexplicit
min_request_frac: 0to isolate the behaviour each pre-existing test was already about(same convention
summarize's own tests use), and whereKeepAliveSubstitute's signaturegained a third return value.
cache_aware_trigger_test.go):TestCacheAwarePreExpiryReserveDoesNotSpliceOnAWarmTurn(apre_expirycheckpoint commissionedon a
PreExpiry-phase turn is markedReservedand a later WARM turn forwards full historyuntouched, with no second model call),
TestCacheAwarePreExpiryReserveSplicesOnAColdTurn(thesame reserve graduates — splices and clears
Reserved— on a turn whose phase isCold, withno model call spent on the graduation itself, and a THIRD warm turn then replays the
already-graduated checkpoint exactly like
any),TestKeepAliveSubstituteRefusesACurrentReserve(a reserve just commissioned with no tail yet reads as current —
KeepAliveSubstituterefuseswith
KeepAliveReasonCheckpointExists, same asany),TestKeepAliveSubstituteRefreshesAStaleReserve(once a later, gated turn grows the registered candidate's span past the reserve's own covered
prefix,
KeepAliveSubstituteoffers a dispatch at the offload layer — the proxy-side tests belowcover whether the keeper actually TAKES that offer), and
TestCacheAwareAllowsResummarizeTokensZeroUnderEitherCacheState(construction succeeds withresummarize_tokens: 0under bothcache_statevalues — the config-time refusal an earlierrevision had here is gone now that cache_aware_summarizer: refresh a reserved summary only when it pays for itself #415's money gate, not a token count, decides whether a
refresh is worth dispatching). This set replaces an earlier test,
TestCacheAwareReplaysItsCheckpointOnATurnTheCacheStateDeclines, whose assertion (replayunconditionally on a cache-state decline) was correct for
any— where it is now unreachable,since
anynever declines on cache state — but was exactly backwards forpre_expiry, which isthe only mode that ever reaches that decline and whose semantics this PR changes.
proxy/keepalive_summarysubstitute_test.go):TestKeepAliveRefreshBelowBreakEvenPingsNormally(a tail whose expected cache-write savingfalls short of the refresh's own projected cost stays a plain ping, with the model never even
called — the gate refuses BEFORE dispatch) and
TestKeepAliveRefreshAboveBreakEvenRefreshes(theidentical setup with a larger tail clears break-even: the summary call replaces the ping,
counted once as the ping and once as
_refresh_paid). Both drive real token counts through thereal BPE tokenizer (varied filler text, not a repeated single character, which compresses far
more aggressively under BPE) rather than asserting against an assumed token-per-character ratio.
(
proxy/keepalive_summarysubstitute_test.go):TestKeepAliveSummaryCallCountsAsExactlyOnePing(
MaxPings: 2— ping 1 creates the session's first reserve, ping 2 finds it already currentand falls back to a plain ping, there is no ping 3) and
TestKeepAliveSummaryCallCountsAsOnePingWithThreeMaxPings(the same shape withMaxPings: 3—one summary call, then two plain pings, then nothing), confirming a summary call consumes
exactly one ping slot and the reserve existing never extends
keepalive_max_pings.Test command and result
Run on the shared eval box (
~/cgssh2), Go is not available locally:All green, including the reserve-redesign and refresh-money-gate tests above. Re-run again
(foreground, no backgrounding) after rebasing onto
mainto pick up #406/#413:go test -raceoncomponents/offload/proxy: 149.9s / 351.5s, both clean.go test ./...(full repo) also green except for two pre-existing
context-guru-pluginfailures(
TestInstallRefusesAnUnverifiedDownload,TestInstallReportsPATHFromTheSourceFallbackToo) thatthis change does not touch — reproduced identically against an unmodified
origin/maincheckouton the same box (
git archive origin/maininto a second directory, per this repo's own eval-boxprocedure), confirming they are this shared box's documented defect (a root-owned
/usr/local/bin/context-guru-proxyshort-circuitsinstall.sh's download path) rather thananything in this PR. Two other plugin tests
(
TestAFailedReinstallKeepsTheWorkingInstallsPortRecord,TestUserScopeInstallEnableStepTakesNoPostRoutingBackup) each failed once on port contention froma concurrent run on the shared box and passed cleanly re-run alone — box-sharing flakes, not
regressions. The rebase itself was conflict-free; this branch does not touch
internal/cheapmodel/, so nothing needed resolving in main's favour.Two
-racefindings along the way, both fixed before this PR, neither a race in the shippedcode: a test-isolation bug of mine (a keep-alive candidate left registered under the shared
"sess-1"session name hijacked a later, unrelated ping test — fixed witht.Cleanupin thetest helper), and the pre-expiry-timing bug described above (found while implementing the fix the
first review round asked for, not by
-raceitself). The final-racerun oncomponents/offloadandproxyis clean.Found during live testing, and fixed
Live testing on real Claude Code traffic (Anthropic,
model.source: incoming) found two realgaps in the first two commits, both fixed here:
The summary call's own usage was invisible on any dashboard. It never lands on the
triggering turn's own Report (the call hasn't happened yet) nor the splicing turn's
synchronous work (the call ran on a different goroutine) — the only channel out was
deferUsage/takeDeferredUsage's existing usage-replay, which only ever fed the aggregateLLM-cost ledger.
deferredUsage(summarize_async.go, shared withsummarize's own detachedcalls) now carries a bounded per-call detail list — model, tokens, component, path
(
messages/prefix_ask), trigger (turn/cold_deferred/keepalive_substitute), latency —and
takeDeferredUsageturns each entry into onecomponents.ModelCallon the REPLAYINGrequest's own Report. The ledger total it was already replaying is untouched and never
truncated, so money accounting cannot regress even if the per-call detail list is capped (4
entries). Also added four
/statscounters:cache_aware_summarizer_cache_read_tokens/_cache_write_tokens(the direct, process-wideanswer to "is the call actually reading warm" — this component's whole argument) and
_no_prefix/_prefix_ask_used(isPrefixAskactually activating on this traffic).A registration-ordering bug, found by reasoning through why a live session whose turns all
declined with
cache_state_declined_warmhad registered no keep-alive candidate at all: theno_stash_roomcheck ran BEFOREregisterKeepAliveCandidate, so a transient store-capacityhiccup on a turn that otherwise had everything needed (model resolved, instruction built)
silently cost the candidate for that turn — looking, from outside, identical to a session the
component had never touched. Moved the stash-room check to AFTER registration: it is a
moment-dependent resource constraint
commitAsyncSummaryre-checks anyway before writinganything, unlike the model/role checks above it, which are permanent for the session as
configured and correctly still block registration. New test:
TestCacheAwareRegistersAKeepAliveCandidateEvenWhenTheStashIsRefused.The silent
if !ok { return false }this bug hid behind is also fixed:offload.KeepAliveSubstitutenow returns aKeepAliveSubstituteReason(
no_candidate/checkpoint_exists), andKeepAliveSummaryResultcarries one too(
in_flight/concurrency_full, for aDispatchthat ran and could not even start) — four newkeeper counters (
keepalive_summary_substitute_no_candidate/_checkpoint_exists/_in_flight/_concurrency_full) plus a DEBUG log naming the reason, so a session that SHOULD have acandidate and does not is diagnosable instead of looking identical to one the component never
ran on at all.
A truncated reply, found live, and fixed
Live testing surfaced a related risk from a dependent fix, #406 (merged):
CompletePrefixed'sstop_reason: max_tokensguard, which used to turn a cut-off reply into an error, was revertedthere (it was costing
extract_llm_sweepa full-price fallback it should not pay). With thatreverted, a truncated reply reaches
cache_aware_summarizeras ordinary text — andsanitizeSummary/ensureSummaryTagswould turn it into a checkpoint that looks exactly like afinished summary:
sanitizeSummarystrips any</summary>tag as an untrusted control string(see its own doc), and
ensureSummaryTagsthen unconditionally adds one back, so a cut-off replyand a complete one are byte-indistinguishable by the time either function has run.
cacheAwareSummaryIncomplete(cache_aware_async.go) checks the RAW reply for</summary>before either function runs — the one point where "did the model actually finish" is still
answerable. A missing closing tag is treated as a failed call on both paths that can produce a
checkpoint (the detached async path and the keep-alive substitute), counted
(
cache_aware_summarizer_truncated, new/statsfield), WARN-logged, and refused: no checkpoint,fail open, the full transcript keeps forwarding exactly as any other failed call.
summarize's own prompt asks for the identical<summary></summary>format, so it has the sametheoretical exposure — checked and NOT fixed here, deliberately.
ensureSummaryTags/sanitizeSummaryare summarize's long-shipped, deliberately lenient contract: it already acceptsa model that never wraps in tags at all, and roughly fifteen of its own tests fix their model
stubs to untagged text on the strength of that leniency. Retrofitting a strict completeness gate
onto an already-shipped, separately-tested contract is a bigger behaviour change than a
shared-helper fix, so it belongs in its own, separately-reviewed change rather than riding this
one. The check added here is local to
cache_aware_summarizer.Tests:
TestCacheAwareRejectsATruncatedSummaryOnTheAsyncPathand...OnTheKeepAliveSubstitutePath— a fake caller returns a reply missing the closing tag; bothassert no checkpoint is written and the new counter increments by exactly one (draining every
async goroutine the test itself commissions, including a cold-started session's second-turn
recommission, so the shared process-wide counter cannot leak into another test).
Keep-alive substitution never fired on real traffic — found live, and fixed
A live test found the substitute counters all stayed at zero on real traffic, every time, even
on turns the gates showed declining with
cache_state_declined_warm— which should mean acandidate WAS registered. Two real bugs, both found and fixed.
Bug 1: every real request deleted its own registration.
proxy.goregistered a session'skeep-alive candidate by running the pipeline, THEN cleared it — meant to drop a candidate left
over from an EARLIER, now-superseded turn, but placed after the pipeline that had just written
THIS turn's own candidate a few lines earlier in the same call. Every request therefore deleted
what it had just registered, and no ping ever found anything to use.
The fix is a timestamp, not a reordering: the session key a clear-by-key would need is not
resolved until the pipeline runs (it comes from the request's own tenant/header/body), so the
clear cannot simply move earlier.
offload.ClearStaleKeepAliveCandidateinstead takes a instantcaptured BEFORE the pipeline runs, and drops the candidate only if it was written before that
instant — never the one the pipeline just wrote during this same call.
Bug 2: a dispatched candidate's own call failed with "context canceled", always. A
candidate's stored context was the REGISTERING request's own — and completing a request cancels
its context, which is why a candidate is only ever used much later, once the session has gone
idle. Every dispatch therefore failed. Fixed the same way the existing detached-commission path
already had to be: the candidate now stores a context stripped of that cancellation
(
context.WithoutCancel).Test:
TestARealRequestsKeepAliveCandidateSurvivesAndAPingDispatchesItdrives two real HTTPrequests through the actual request-handling path and a real keep-alive ping — every other
keep-alive-substitute test registers a candidate directly and so could not have caught either
bug. It fails against the code before each fix, for each fix's own reason.
Haiku keep-alive substitute reads an old prefix — found live, not yet fixed
The same live test found the keep-alive substitute's own call, on
claude-haiku-4-5, reading acache prefix noticeably smaller than the real agent turn immediately before it — short by about
2,100-2,150 tokens in two separate sessions, both landing within one token of each other
(32,806 and 32,807) despite the two sessions' own, more-current prefixes differing by more than
that. Checked against each session's own request log: that number matches what the SECOND real
turn of each session read, not any later one — as if the stashed body this call reads from had
stopped updating a few turns in and never caught up.
Ruled out: the stash's own read and write functions (
sentStash.put/getinproxy/prefixask.go) read and write the full, current byte slice on every call, with nocaching, memoization, or capacity limit anywhere near being reached at this traffic volume. The
asker (
prefixAsker.Ask) reads the stash fresh on every call too — nothing here caches an oldcopy.
Not yet explained: why the two sessions converge on the SAME, specific earlier value rather
than drifting apart the way their later, real traffic does. Checked and not confirmed: the
detached commission's own goroutine starts while the SAME triggering request's own upstream call
is still in flight, and that request only stashes its own body AFTER that call returns — a
timing race that would explain "reads something older," but not why both sessions land on
exactly their own second turn's figure rather than varying turn to turn. Needs a direct
comparison of the stashed body against the forwarded body for the SAME turn (dashboard/DEBUG) to
pin down, not yet done. Not fixed here, per instruction to report before changing anything.
Open questions
summaryOutputBudgetGuess(2000 tokens) for the keep-alive substitute's cost projection is anunmeasured, deliberately conservative guess — flagged the same way
pingUSD's own disclaimeris. It now also sets the floor the cache_aware_summarizer: refresh a reserved summary only when it pays for itself #415 refresh gate has to clear, so an overestimate there
makes the gate slightly more conservative (refuses a few refreshes that would narrowly have
paid off) rather than less safe.
refresh avoids on the cold return, deliberately a lower bound — it does not credit the saving
from later turns reading a larger reserve instead of a smaller one, since how many turns follow
a cold return is not knowable at ping time. Issue cache_aware_summarizer: refresh by adding to the previous summary, not rewriting it #416 (an additive refresh — folding the tail
into the existing summary instead of re-deriving the whole thing) would also lower the refresh's
own cost side of this comparison; tracked separately, not part of this PR.
docstring, unverified on live traffic — this PR makes the pairing expressible and measurable
(see the new dashboard rows and
/statscounters above) on the traffic that matters (Anthropicincoming-model). Live testing confirmed the mechanism itself works — commission, splice, and a
spliced request reading warm, thinking included (fix(cheapmodel): raise max_tokens above thinking.budget_tokens on prefix asks #406, fix(cheapmodel): insert the prefix ask before a trailing system message #413, both merged) — but a savings
number on real agent traffic end to end is still open.