Skip to content

feat(offload): give cache_aware_summarizer a real trigger and feed the keep-alive - #402

Merged
amiddavid merged 14 commits into
mainfrom
feat/cache-aware-summarizer-trigger
Oct 8, 2026
Merged

amiddavid merged 14 commits into
mainfrom
feat/cache-aware-summarizer-trigger

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

The problem, in plain terms

We looked at real usage on a developer machine running the xhigh preset and found three problems with how long sessions get summarized.

  1. The summarizer in use today pays full price and only sees part of the history. xhigh uses summarize. 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.
  2. The cache-friendly summarizer, cache_aware_summarizer, exists but isn't usable.
  3. The best moment to summarize, just before the cache expires, is usually taken by the idle keep-alive ping. With keep-alive on, the ping lands in exactly that last minute, so a "fire just before expiry" setting almost never sees a real request. The ping is the natural moment to do the summary instead.

When it fires: today vs. with this PR

Today With this PR
Size threshold None. Fires once there are about 11 messages and a ~500-token middle section to summarize. Fires once the previous request reached 90% of the model's context window (trigger.min_request_frac, new default 0.9), the same point summarize uses. Setting it explicitly still wins, and 0 brings back the old behaviour.
trigger.cache_state: any (new default) Ignored Fires on any turn past the threshold, whether the cache is warm or cold, and is spliced into the very next request, warm or cold
trigger.cache_state: pre_expiry Ignored Prepares for a cold return instead of firing on a schedule: a summary made in the last minute before the cache expires (trigger.pre_expiry_seconds, default 60) is held in reserve, not applied, until the cache actually goes cold — see "Two ways to use cache_state" below
When the summary is used On the next request any: 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 untouched
Triggering turn arrives after the cache expired Summary call races the request and both rewrite the cache The summary call waits until that turn has rewritten the cache, then reads from it
Idle keep-alive Always a plain ping When a ping is due for a session past the threshold with no CURRENT summary, the summary call is sent instead of the ping. It reads the same cached conversation, so it refreshes the cache exactly as a ping would. It counts as the ping, stays within the per-ping dollar cap, and falls back to a normal ping if it fails or would cost too much. Under pre_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.
Turns the trigger skips after a summary exists Sent the full history again, which forced a cache rewrite any: keep sending the existing summary. pre_expiry: keep sending the full history until the reserve graduates on a cold turn
Anthropic traffic Never runs (#275) Runs: when there's no model that can take the whole conversation in one call, it asks one question against the exact request the previous turn already sent, the same "stored request plus one appended question" shape extract_llm_sweep already uses on this traffic
A reply cut off mid-generation Repaired to look like a complete summary and spliced into history as a fragment Detected before any repair and rejected — treated as a failed call, no checkpoint written, the full transcript keeps forwarding until a later turn succeeds

Two ways to use cache_state

Full 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 way
a ping does, and never adds an extra one.

  • any — summarize and apply immediately. The cheapest way to shrink an oversized
    conversation: 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. Splicing
    a 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_expiry avoids ever paying that: a summary made in the last minute before expiry is held in
    reserve 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 TURN
re-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_tokens keeps its
original 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 checked
against 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_state shipped two more values once — cold and pre_expiry_or_cold — that waited for the
cache to go cold before firing at all. Both were withdrawn before this PR, for three reasons
(components/trigger.go's own removedCacheStates): firing on a warm cache and getting it wrong
cost 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 summarize is the better choice

A 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 again
from the next one. While the idle keep-alive keeps pinging a session, its cache never goes cold,
so a pre_expiry reserve sits unused (refreshed only when it's worth it) until pinging stops.

Prefer summarize instead when: a much cheaper model should write the summary (this component
must 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. xhigh still uses summarize. Switching a preset to cache_aware_summarizer is a separate decision, made after it has been measured live.

  • To try it, add cache_aware_summarizer to the pipeline in place of summarize, and optionally set:

    components:
      cache_aware_summarizer:
        resummarize_tokens: 6000    # default; how stale a `pre_expiry` reserve may get before
                                     # a keep-alive ping refreshes it instead of staying plain
        trigger:
          min_request_frac: 0.9     # default; lower to summarize earlier
          cache_state: pre_expiry   # or `any` (default) — see "Two ways to use cache_state" above
  • 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_tokens conflict in internal/cheapmodel/anthropic.go that this
    path 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 main ahead of this PR. Verified live end to end: commission → splice → the spliced
    request read warm (cache_read=32393); cache_state: pre_expiry correctly declined on warm
    turns.


Implementation details

Summary

cache_aware_summarizer embedded a components.Trigger but shipped no defaults for it (a zero
Trigger fires on any request past ~11 messages and a 500-token span —
components/trigger.go:20,266), never called Trigger.CacheAllows/Ctx.CachePhase, and could
only call a model through components.MessagesModel — which, on Anthropic traffic with the
default model.source: incoming, does not exist (internal/cheapmodel.Anthropic implements only
Complete; only internal/cheapmodel/openai.go has CompleteMessages). This PR:

  1. Trigger defaults. min_request_frac defaults to 0.9, cache_state to any, sharing
    summarize's raw-YAML presence probe (triggerKeysPresent, factored out of
    applySummarizeTriggerDefaults) rather than a second copy of it. An explicit
    min_request_frac: 0 still wins over the default.
  2. Honours cache_state. The fresh-commission gates (sized, resolvable via
    Trigger.FracResolvable, phased via Ctx.CachePhase/Trigger.CacheAllows) now decide only
    whether 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. tryReuse now reports stale (mirroring summarize.tryReuse's own shape) and a new
    replayStale re-emits an existing-but-stale checkpoint on every decline from here on
    (cache_aware_summarizer.go).
  3. Guarantees the side call reads warm. A turn whose own cache is COLD (cache_state: any
    permits 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 from
    proxy/proxy.go's serve defer next to h.keeper.record); a bounded fallback timer (90s)
    resolves it even if a host never calls the hook.
  4. Lets the component stand in for the idle keep-alive ping. A turn with real commission
    material registers it (cache_aware_keepalive.go) regardless of whether cache_state let it
    fire that turn — a turn cache_state: pre_expiry declines on a warm phase is exactly the
    session whose next ping is about to arrive in the pre-expiry window. proxy/keepalive.go's
    keeper substitutes it for a due ping when the candidate has no CURRENT checkpoint yet, a
    pre_expiry candidate's OWN window is actually live right now (not merely whenever the keeper
    happens 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 —
    sweep already increments e.pings before dispatch, so the substitute path books only the
    dollar/dashboard side), and falls back to an ordinary ping on any failure, missing candidate,
    a current checkpoint, phase mismatch, or over-budget projection.
  5. Holds a pre_expiry checkpoint in reserve instead of applying it immediately. A checkpoint
    commissioned while Ctx.CachePhase is PreExpiry is marked sumCheckpoint.Reserved and is
    NOT spliced into a warm turn (cacheAwareApplyPhase/tryReuse in
    cache_aware_summarizer.go and state.go) — splicing it would be the exact cache-destructive
    rewrite pre_expiry exists to avoid paying for while the cache is still live. It graduates
    (splices, and Reserved clears) on the first turn whose phase is Cold. cache_state: any
    never sets Reserved and is unaffected — its checkpoint still applies on the very next
    request, warm or cold, exactly as before this PR.
  6. Only refreshes a reserve when the refresh pays for itself (cache_aware_summarizer: refresh a reserved summary only when it pays for itself #415). While reserved, the
    keep-alive substitute's lookup (checkpointRefreshOpportunity in cache_aware_keepalive.go,
    replacing an earlier checkpointCurrent) reports any nonempty tail as an opportunity
    (KeepAliveCandidateInfo.IsRefresh/RefreshTailTokens) without judging whether it is WORTH
    refreshing — that judgment moved to proxy/keepalive.go's fireSummarySubstitute, the only
    side 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_tokens keeps
    its 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 log
    naming 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.
  7. Runs on Anthropic incoming-model traffic (cache_state: pre_expiry has no working configuration — cache_aware_summarizer ignores the key, and cannot run on Anthropic traffic at all #275). When model resolution finds no
    MessagesModel — which on this deployment's own traffic is every Anthropic request with
    model.source: incoming — the component falls back to Ctx.PrefixAsk
    (components.PrefixAsker), the SAME mechanism extract_llm_sweep already uses: one question
    appended 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: system is told so
    explicitly (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 a
    mid-conversation system message. components.ErrNoPrefix (nothing stashed yet — every
    session'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 own
    sweep_ask_failed (fix(offload): imply block_fallback under debug logging, WARN on ask failure #401).

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.

Fixes #400. Closes #275 — both the inert cache_state (part 1) and the inability to reach
Anthropic incoming-model traffic at all (part 2, via PrefixAsk). Closes #415 — a pre_expiry
refresh 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

  • Why tryReuse runs before the gates, unconditionally. Mirrors summarize.Offload's own
    fix 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_state is anything other than always-permit.
  • Cold-turn ordering, concretely. Offload (components/offload/cache_aware_summarizer.go)
    builds the call it will make, then branches on Ctx.CachePhase: CachePhaseCold calls
    deferColdSummary (stores the material in a session-keyed map,
    components/offload/cache_aware_cold.go) instead of startAsyncSummary. proxy/proxy.go's
    serve already observes this turn's own usage/usageOK in the same defer that calls
    h.keeper.record(...) — offload.ResolveDeferredCacheAwareSummary(session) is called right
    after, so the side call never races the forwarded request. Only CachePhaseCold is deferred;
    CachePhaseUnknown is permitted to fire immediately (per Trigger.CacheAllows's own
    Unknown-permits rule) because there is no established double-rewrite to avoid there.
  • One call abstraction for both model paths. summaryCaller (cache_aware_async.go) is a
    func(ctx) (string, error) built exactly once in Offload, on the request's own goroutine —
    either mm.CompleteMessages(ctx, "", ask) or a closure over c.PrefixAsk.Ask(ctx, session, instructionText). Everything downstream (the detached async path, the cold-turn deferral, the
    keep-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 underlying
    CompletePrefixed/CompletePrefixedResponses already calls the same cheapmodel. recordUsageCache that CompleteMessages does, so deferUsage/takeDeferredUsage and
    commissionSync's own sink read work unmodified for either path.
  • How the keeper and the component coordinate. The component registers a
    keepAliveCandidate keyed 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 from proxy/proxy.go next to h.keeper.arrive) so a
    stale candidate from a superseded turn can never be dispatched. proxy/keepalive.go's
    keeper.fire calls k.fireSummarySubstitute first; it looks up offload.KeepAliveSubstitute
    (which itself refuses if a checkpoint already exists, and now also returns
    KeepAliveCandidateInfo{CacheState, PreExpirySeconds}), checks the candidate's OWN pre-expiry
    window against the keeper's own idle-time knowledge (cachePhaseAt, using the entry's
    prevStartedAt — captured in sweep before it stamps e.startedAt for the ping about to be
    sent, 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 shares startAsyncSummary's
    single-flight registry and concurrency bound so the two callers can never race to summarize the
    same span). sweep already increments e.pings/stamps e.startedAt before dispatch regardless
    of which path fire takes, so "counted once as the ping" falls out of the existing structure
    rather than needing a second increment.
  • The pre-expiry approximation from the first review round is fixed, not just flagged. The
    keeper no longer assumes its own ping timing happens to fall inside a pre_expiry candidate's
    window; it recomputes the phase from the entry's own last-touch time and TTL tier
    (cachePhaseAt) and declines the substitution (counted as
    keepalive_summary_substitute_phase_mismatch, falling back to an ordinary ping) when it does
    not.
  • Why the reserve lives in the existing sumCheckpoint, not a second store key. Reserved is
    one new bool field (state.go) in the struct summarize and cache_aware_summarizer already
    share under the same store.SumPrefix+session key — summarize never sets it and
    cache_aware_summarizer only sets it for cache_state: pre_expiry, so a zero value always
    means "apply immediately", exactly how both components already behaved before this field
    existed. cacheAwareApplyPhase is the one place that reads it: a warm phase with Reserved set
    returns declineButReplayStale's warm-side twin (forward full history, do not splice); a cold
    phase splices and clears Reserved on write-back regardless of the flag's starting value, so a
    stale Reserved left over from a config that has since switched to any cannot wedge a session
    — the very next cold turn clears it.
  • checkpointRefreshOpportunity is deliberately conservative, and deliberately not a staleness
    verdict.
    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 CoveredCount not fitting the candidate's
    span, 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 fireSummarySubstitute something to price rather than silently going stale forever. It
    no longer consults resummarize_tokens at 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 on
    a 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 candidate
    registration (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, ErrNoPrefix counted apart from a real
    failure (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, counted
    once, produces a checkpoint), fallback to an ordinary ping on a failed call, the $ cap
    refusing 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
    (HeadTTL1h makes this a real divergence from the keeper's own Idle timing, not a contrived
    one) and that the SAME candidate fires once the window is live.
  • Existing components/offload/proxy suites updated only where the new 0.9 default required an
    explicit min_request_frac: 0 to isolate the behaviour each pre-existing test was already about
    (same convention summarize's own tests use), and where KeepAliveSubstitute's signature
    gained a third return value.
  • The reserve redesign (cache_aware_trigger_test.go):
    TestCacheAwarePreExpiryReserveDoesNotSpliceOnAWarmTurn (a pre_expiry checkpoint commissioned
    on a PreExpiry-phase turn is marked Reserved and a later WARM turn forwards full history
    untouched, with no second model call), TestCacheAwarePreExpiryReserveSplicesOnAColdTurn (the
    same reserve graduates — splices and clears Reserved — on a turn whose phase is Cold, with
    no 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 — KeepAliveSubstitute refuses
    with KeepAliveReasonCheckpointExists, same as any), TestKeepAliveSubstituteRefreshesAStaleReserve
    (once a later, gated turn grows the registered candidate's span past the reserve's own covered
    prefix, KeepAliveSubstitute offers a dispatch at the offload layer — the proxy-side tests below
    cover whether the keeper actually TAKES that offer), and
    TestCacheAwareAllowsResummarizeTokensZeroUnderEitherCacheState (construction succeeds with
    resummarize_tokens: 0 under both cache_state values — the config-time refusal an earlier
    revision 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 (replay
    unconditionally on a cache-state decline) was correct for any — where it is now unreachable,
    since any never declines on cache state — but was exactly backwards for pre_expiry, which is
    the only mode that ever reaches that decline and whose semantics this PR changes.
  • The refresh money gate, issue cache_aware_summarizer: refresh a reserved summary only when it pays for itself #415 (proxy/keepalive_summarysubstitute_test.go):
    TestKeepAliveRefreshBelowBreakEvenPingsNormally (a tail whose expected cache-write saving
    falls 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 (the
    identical 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 the
    real 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.
  • The keep-alive pin, "the preset never overrides the cache strategy"
    (proxy/keepalive_summarysubstitute_test.go): TestKeepAliveSummaryCallCountsAsExactlyOnePing
    (MaxPings: 2 — ping 1 creates the session's first reserve, ping 2 finds it already current
    and falls back to a plain ping, there is no ping 3) and
    TestKeepAliveSummaryCallCountsAsOnePingWithThreeMaxPings (the same shape with MaxPings: 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:

go build ./... && go vet ./...
go test ./components/offload/... ./proxy/... ./config/... ./components/...
go test -race ./components/offload/... ./proxy/...

All green, including the reserve-redesign and refresh-money-gate tests above. Re-run again
(foreground, no backgrounding) after rebasing onto main to pick up #406/#413:
go test -race on components/offload/proxy: 149.9s / 351.5s, both clean. go test ./...
(full repo) also green except for two pre-existing context-guru-plugin failures
(TestInstallRefusesAnUnverifiedDownload, TestInstallReportsPATHFromTheSourceFallbackToo) that
this change does not touch — reproduced identically against an unmodified origin/main checkout
on the same box (git archive origin/main into a second directory, per this repo's own eval-box
procedure), confirming they are this shared box's documented defect (a root-owned
/usr/local/bin/context-guru-proxy short-circuits install.sh's download path) rather than
anything in this PR. Two other plugin tests
(TestAFailedReinstallKeepsTheWorkingInstallsPortRecord,
TestUserScopeInstallEnableStepTakesNoPostRoutingBackup) each failed once on port contention from
a 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 -race findings along the way, both fixed before this PR, neither a race in the shipped
code: 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 with t.Cleanup in the
test helper), and the pre-expiry-timing bug described above (found while implementing the fix the
first review round asked for, not by -race itself). The final -race run on
components/offload and proxy is clean.

Found during live testing, and fixed

Live testing on real Claude Code traffic (Anthropic, model.source: incoming) found two real
gaps in the first two commits, both fixed here:

  1. 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 aggregate
    LLM-cost ledger. deferredUsage (summarize_async.go, shared with summarize's own detached
    calls) now carries a bounded per-call detail list — model, tokens, component, path
    (messages/prefix_ask), trigger (turn/cold_deferred/keepalive_substitute), latency —
    and takeDeferredUsage turns each entry into one components.ModelCall on 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 per-call detail list is capped (4
    entries). Also added four /stats counters:
    cache_aware_summarizer_cache_read_tokens/_cache_write_tokens (the direct, process-wide
    answer to "is the call actually reading warm" — this component's whole argument) and
    _no_prefix/_prefix_ask_used (is PrefixAsk actually activating on this traffic).

  2. A registration-ordering bug, found by reasoning through why a live session whose turns all
    declined with cache_state_declined_warm had registered no keep-alive candidate at all: the
    no_stash_room check ran BEFORE registerKeepAliveCandidate, so a transient store-capacity
    hiccup 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 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. New test:
    TestCacheAwareRegistersAKeepAliveCandidateEvenWhenTheStashIsRefused.

    The silent if !ok { return false } this bug hid behind is also fixed:
    offload.KeepAliveSubstitute now returns a KeepAliveSubstituteReason
    (no_candidate/checkpoint_exists), and KeepAliveSummaryResult carries one too
    (in_flight/concurrency_full, for a Dispatch that ran and could not even start) — four new
    keeper 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 a
    candidate 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's
stop_reason: max_tokens guard, which used to turn a cut-off reply into an error, was reverted
there (it was costing extract_llm_sweep a full-price fallback it should not pay). With that
reverted, a truncated reply reaches cache_aware_summarizer as ordinary text — and
sanitizeSummary/ensureSummaryTags would turn it into a checkpoint that looks exactly like a
finished summary: sanitizeSummary strips any </summary> tag as an untrusted control string
(see its own doc), and ensureSummaryTags then unconditionally adds one back, so a cut-off reply
and 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 /stats field), 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 same
theoretical exposure — checked and NOT fixed here, deliberately. ensureSummaryTags/
sanitizeSummary are summarize's long-shipped, deliberately lenient contract: it already accepts
a 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: TestCacheAwareRejectsATruncatedSummaryOnTheAsyncPath and
...OnTheKeepAliveSubstitutePath — a fake caller returns a reply missing the closing tag; both
assert 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 a
candidate WAS registered. Two real bugs, both found and fixed.

Bug 1: every real request deleted its own registration. proxy.go registered a session's
keep-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.ClearStaleKeepAliveCandidate instead takes a instant
captured 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: TestARealRequestsKeepAliveCandidateSurvivesAndAPingDispatchesIt drives two real HTTP
requests 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 a
cache 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/get in
proxy/prefixask.go) read and write the full, current byte slice on every call, with no
caching, 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 old
copy.

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

@amiddavid
amiddavid force-pushed the feat/cache-aware-summarizer-trigger branch from 957bfa3 to c2c9521 Compare October 6, 2026 13:05
amiddavid added a commit that referenced this pull request Oct 7, 2026
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 added a commit that referenced this pull request Oct 8, 2026
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]>
@amiddavid
amiddavid force-pushed the feat/cache-aware-summarizer-trigger branch from b001c92 to 8365907 Compare October 8, 2026 09:59
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. 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.
  2. 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 ./... and go vet ./...: pass.
  • go test -count=1 ./...: pass, except 2 context-guru-plugin tests (TestInstallRefusesAnUnverifiedDownload, TestInstallReportsPATHFromTheSourceFallbackToo). These 2 also fail on an unmodified origin/main on 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-5 traffic through the plain litellm gateway, with an 11.6k-token cached system prompt. I ran the same script against the PR proxy and a main proxy (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: full the 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)

  • recordSummarySubstitute passes 0 as the 1h-write argument to CostWithCacheWrite1h. record1 passes u.CacheWrite1h. With the 1-hour-head strategy, the substitute's 1h cache writes are priced at the 5-minute rate. KeepAliveSummaryResult has no field for 1h writes.
  • fireSummarySubstitute runs the summary call (up to cacheAwareTimeout, 300 s) while it holds the tenant limiter slot from AcquireSpare. 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:87 still 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Thank you for the detailed review and the probe tests. Both findings fixed, plus the smaller points. Pushed to feat/cache-aware-summarizer-trigger at e52851d.

Finding 1 (High), the stale body. Fixed in two parts, matching your suggestion.

sentStash.put now deletes a session's entry when it skips a body over the 1.5 MB cap, instead of keeping the old one. A missing stash gives ErrNoPrefix on the next ask — the ordinary, already-handled first-turn case — instead of a wrong answer dressed as a right one.

For the general case (including the race you noted), a new components.PrefixCoverage interface lets a PrefixAsker report whether its stashed body covers a given prefix (message count plus a content hash, components.SpanHash). cache_aware_summarizer checks this immediately before the call actually runs, not synchronously inside Offload: at that point in Offload, the host has only the PREVIOUS turn's stash, because the triggering turn's own body is not stashed until after Offload returns — a check there would decline every ordinary turn whose span simply grew past the older stash, not only a genuinely stale one. Checking at call time (the closure startAsyncSummary/commissionSync eventually invoke) is correct and free of that false-positive, and declines with a new components.ErrStalePrefix sentinel, counted separately as cache_aware_summarizer_stale_prefix from cache_aware_summarizer_no_prefix.

extract_llm_sweep was deliberately left alone, per the task. It goes through the same stash via the same PrefixAsker, so it has the identical exposure in principle — but it does not write a checkpoint that claims coverage, so a stale read there degrades to a worse-quality adjudication rather than a silently wrong one. Flagging it rather than fixing it, since it is out of this PR's scope.

Tests: TestCacheAwareDeclinesOnAStalePrefix (unit, drives the guard directly through a fake asker) and TestCacheAwareStalePrefixThroughARealOversizedTurn (through the real serve() path — a 1.6 MB turn 2 declines safely with zero ask calls; a 10 KB control still reads the cache and covers turn 2).

Finding 2 (Medium), the registry that never drained. ClearKeepAliveCandidate always worked when called; nothing on the keeper's own exit paths (retire, forget, evictLocked) ever called it. All three now do (plus Stop, for symmetry). Also fixed the stale comment claiming the registry evicted its oldest entry at capacity — it never did, it refused the new one, which the comment now says — and added an age-based prune on registration as a fallback for a deployment that embeds this package without the keeper.

Test: proxy/keepalive_candidate_drain_test.go exercises retire, forget and evictLocked directly, plus your own probe (2,048 ended sessions, then one live registration that must still succeed).

Smaller points.

(a) cheapmodel.Sink now tracks the 1h-tier subset of cache-write tokens (parsed off cache_creation.ephemeral_1h_input_tokens, same field name proxy's own usage parser already reads off the agent's response), threaded through KeepAliveSummaryResult.CacheWrite1h into recordSummarySubstitute's CostWithCacheWrite1h call.

(b) fireSummarySubstitute now releases the tenant's AcquireSpare slot right after the eligibility check, before the substitute call runs, and acquires a fresh one only for 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).

(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 e52851d: go build ./..., go vet ./..., gofmt -l . all clean. go test -count=1 ./components/offload/... ./proxy/... and go test -race -count=1 ./components/offload/... ./proxy/... both pass.

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.

amiddavid added a commit that referenced this pull request Oct 8, 2026
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 amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ./... and go 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-plugin box-defect tests as before (result=present). They also fail on origin/main.
    • dash TestJanitorPassCheckpointsWAL failed once under full-suite load. Alone it passes 5 of 5 on this PR and 5 of 5 on main, so it is a flaky test, not caused by this PR (the PR does not change dash).
  • Live aws/claude-sonnet-5 traffic 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 as 45bd937.

@amiddavid
amiddavid merged commit 8db1275 into main Oct 8, 2026
6 checks passed
@amiddavid
amiddavid deleted the feat/cache-aware-summarizer-trigger branch October 8, 2026 21:18
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 8, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
…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]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
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 added a commit that referenced this pull request Oct 11, 2026
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]>
amiddavid added a commit that referenced this pull request Oct 11, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

1 participant