Repository navigation
fix(offload): start a prefix-ask summary after this turn is stashed - #724
Conversation
A detached cache_aware_summarizer commission on the prefix-ask path started at Offload time, about 1 ms before the host stashed this turn's forwarded body. Its coverage check then read the previous turn's shorter body and refused it, so every detached summary ended as stale_prefix (3 of 3 on a clean session) and only the keep-alive substitute could ever commit one. The commission now waits in the deferral registry the cold path already uses. The host's hook dispatches it once the turn's request ends, after its 200 put this turn's body into the stash. The deferral now carries the trigger and reserve flag, so a warm commission keeps its own. The messages-model path, which reads no stash, still starts at once. The turn still replays a stale summary as before. Fixes #722 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 5bc5938ab067 |
approve |
Verdict: approve
Findings
None blocking. The fix is correct on the path it claims to fix. See Non-blocking for three narrow gaps.
Non-blocking
components/offload/cache_aware_cold.go:119— a full deferral registry reintroduces the #722 decline for new sessions.maxColdDeferredis 256. Before this PR only cold turns entered the registry. Now every warm prefix-ask turn that passes the gates enters it, and an entry lives until its own request ends. On a busy shared proxy, 256 concurrent in-flight commissioning requests makedeferSummaryfirestartAsyncSummaryat Offload time for each new session — the exact broken order this PR fixes. The cost is one forgone summary, not a wrong answer:AskCovered's coverage check refuses before any HTTP call. The drop counter (cacheAwareColdDeferredDropped) still says "cold", so an operator cannot tell this shape from a cold one. Suggest a separate counter or an event when you next touch this file.components/offload/cache_aware_cold.go:188— a hook dispatch thatstartAsyncSummaryrefuses is invisible.ResolveDeferredCacheAwareSummarydrops the returned gate name. The old inline path put it on the triggering turn'srep.Gate(#703 was exactly a skip with no reason). An in-flight refusal ("summary_already_in_flight") has no counter at all. This gap already existed for the cold path; this PR widens it to every warm prefix-ask turn.components/offload/cache_aware_summarizer.go:972— narrow window for a duplicate paid call. Between Offload and the host hook, the idle keeper can dispatch the registered candidate (commissionSync) and commit. The hook then dispatches the deferral unconditionally;startAsyncSummarychecks in-flight but not for an existing checkpoint, so the same span is paid twice. The old inline dispatch held the flight slot from Offload time, so this window did not exist. It needs a keeper ping to land inside one request's window with a stash that already covers the span, so I rate it rare. One wasted cache-read call; no wrong answer.
What I checked
- The host ordering claim, in the proxy code.
proxy/proxy.go:1771stashes the body when upstream answers 200, inside the round loop.proxy/proxy.go:1695calls the hook inserve's defer, which runs only after the loop. So the put always precedes the hook on every 200 path, streaming included. The claim in the new comment holds. - Fail-open on the non-200 path. A failed forward skips the put but still resolves the deferral. The commission then runs
AskCoveredagainst the previous body. The count/hash check declines it (ErrStalePrefix) or the prefix is byte-identical and the summary is correct. No wrong answer is reachable;snapshotCoveringchecks before it pays. - The 90 s fallback timer. It can fire while a long request is still streaming. The put happens at the 200 status line, before the body streams, so the fallback still reads this turn's body. No defect.
- The rename.
deferColdSummary→deferSummary: no remaining references.triggerandreservedare threaded unchanged through all three exits (registry full, fallback timer, host hook). The cold path passes"cold_deferred"andfalse, as before, so dashboard attribution is preserved. - The new branch's placement. It sits after the stash-room check, after
registerKeepAliveCandidate, and after the cold branch. A cold prefix-ask turn still takes the cold branch.reservedis computed before the branch and passed through, matching what the old inlinestartAsyncSummarycall passed. The turn still returnsdeclineButReplayStale(), as before. - The lite Ctx.
deferSummarycopies Session, Thread, Store and Ctx.startAsyncSummaryandeffectiveModeread only those. Thecallclosure captured the asker and instruction at build time, so nothing mutable is aliased. - The new test. I traced it end to end: the stash holds
end-1messages at Offload time, the deferral holds the call until the hook, the put raises the stash tolen(in), the dispatch commits. If the code regressed to fire at Offload time, the test fails on both the stale-prefix count and the missing checkpoint. The fixture, gates and phases reach the new branch (8 messages,min_request_frac: 0, phase Unknown, no MessagesModel, PrefixAsk set). - Every test that drives a prefix-ask commission. All call the hook after Offload:
cache_aware_prefixask_test.go(4 sites),cache_aware_stale_prefix_test.go(5),thread_prefixask_test.go(1). The two tests without the hook decline before the commission (system_role_unsupported_via_prefix_ask,cache_state_declined_warm), so no deferral is left pending. No other test incomponents/offload,components/allorapplydrives this path;apply-level tests use a MessagesModel, andproxyintegration tests get the hook fromserveitself. - Other hosts. The bifrost adapter wires no
PrefixAsk, and the observe shadow run wires none either, so the prefix-ask branch cannot fire there. Only the proxy host has a stash. - Repo rules. Fail-open holds on every new path. Reversibility is unchanged (the deferral holds the same span copy the cold path already held). The PR states its data dependence ("no change"), which matches what the code does.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 5bc5938ab067 |
blocking |
Verdict: blocking
The fix itself is right for the proxy, and the new test drives the real race. Two defects remain at the edges of the mechanism it now relies on. Both are fail-open, but both silently undo the compaction this component exists to deliver.
Findings
-
components/offload/cache_aware_cold.go:132 — a replaced deferral restarts the 90 s fallback, so a host without the hook never dispatches a warm commission.
- What fails: a host that sets
Ctx.PrefixAskbut never callsResolveDeferredCacheAwareSummary(a library consumer ofapply, or the downstream plugin) loses every warm prefix-ask commission on an active thread. Each new turn re-commissions, because the starved commission never commits, sotryReusekeeps failing and the gates keep passing.deferSummarythen stops the previous timer and writes a fresh 90 s timer (cache_aware_cold.go:129-133). Turns less than 90 s apart replace the deferral forever. The fallback's own comment (cache_aware_cold.go:58-64) promises it prevents "losing the compaction forever"; for this path it no longer does. - Proof: cache_aware_summarizer.go:972-975 defers on every warm prefix-ask commission.
grepshows only proxy/proxy.go:1695 callsResolveDeferredCacheAwareSummary; nothing else removes a pending deferral, andClearStaleKeepAliveCandidatedoes not touch it. ThedeferSummarycomment's claim that "a real request clears the deferral" (cache_aware_cold.go:90-92) is true only in a host that calls the hook. No in-repo host regresses: the proxy calls the hook, andadapters/bifrostnever setsPrefixAsk. But CLAUDE.md makes the core importable and the hosts thin, so this is the library contract. Before this PR, such a host dispatched at Offload time and committed whenever the previous stash covered the span — a turn that added ≤keep_last_turnsmessages (default 10, cache_aware_summarizer.go:421), which is the common case:end = len(msgs) − keep_last_turns(summarize_pairing.go:150) stays at or below the previous turn's stashed count whenever the turn adds fewer than 10 messages. - Fix: when
deferSummaryreplaces a pending deferral for the same conv, do not drop the old one silently. Either dispatch it at once (the stash now covers its span), or at least count it as dropped. Also state the host contract wherePrefixAskis documented: a host that sets it must callResolveDeferredCacheAwareSummary.
- What fails: a host that sets
-
components/offload/cache_aware_cold.go:119 — the 256-entry cold registry now holds one warm deferral per in-flight request, so load forces the exact early dispatch this PR fixes.
- What fails: more than 256 concurrent commissioning prefix-ask threads. That is the Anthropic incoming-model traffic this path exists for. Each deferral occupies a slot from Offload until its own request ends. At the cap,
deferSummaryfires the commission at once (cache_aware_cold.go:119-127) — at Offload time, against the previous turn's stash. That is the stale_prefix failure #722 describes. Under load, the fix becomes a no-op for new sessions, silently, except for the dropped counter. - Proof: a deferral leaves the registry only through the serve-time hook (proxy.go:1695) or the 90 s fallback. Commissioning requests are the long ones — they must pass
min_request_tokens— so each slot is held for seconds.maxColdDeferred = 256(cache_aware_cold.go:56) was sized for "a few hundred sessions simultaneously arriving cold" (cache_aware_cold.go:53-55). Cold arrivals are rare. Warm commissions are per-turn on every qualifying Anthropic thread. - Fix: give warm deferrals their own, larger bound, or count cold and warm occupancy separately so the cap is visible before it silently inverts the fix.
- What fails: more than 256 concurrent commissioning prefix-ask threads. That is the Anthropic incoming-model traffic this path exists for. Each deferral occupies a slot from Offload until its own request ends. At the cap,
Non-blocking
- The commissioning turn's
Reportcan no longer carrysummary_already_in_flightorsummary_concurrency_full.startAsyncSummary's gate return is discarded at dispatch time (cache_aware_cold.go:161, 188). Only the process-wide counters see the refusal. Previously the gate was filed on the turn (cache_aware_summarizer.go:982-983). CacheAwareColdDeferralStatscounts warm deferrals in cold-named counters.startedwithoutresolvednow also counts silently-replaced deferrals, which weakens that pair's "a deferral is being lost" signal.- docs/data-dependence.md:201 says memory copies are kept "for summaries during idle time and after a cold turn". A warm deferral now also holds a span copy from Offload until the request ends. Short-lived and bounded, but the row should say so. The PR description should also state the data dependence (unchanged: content, same stash reads) — I did not read the PR body, so I could not check that it does.
- The new test's comment says "7 required against 5 stashed" (cache_aware_after_stash_test.go:48-49). The fixture gives 6 required: 8 messages,
keep_last_turns: 2, soend = 6. - The dispatch now starts after the response completes, not at Offload time. On a long streamed answer, the checkpoint lands one round trip later than before, so the next turn can miss a summary it would previously have found in flight. This trade-off is inherent to the fix.
- Observe mode: the shadow pipeline defers too, and resolves only at the thread's next request hook, or the 90 s fallback. A shadow run slower than the turn cadence has its deferral replaced before dispatch, so observe can under-report prefix-ask compaction. Measurement only.
What I checked
- The full diff
a0e5f9e5..5bc5938a, and the commit message (conventional title,Assisted-By:,Signed-off-by:all present). - The Offload control flow in cache_aware_summarizer.go: gate order, the cold branch before the new prefix-ask branch,
declineButReplayStale,reserved,coveredCount. - The deferral registry: replacement and timer restart,
takeColdDeferralexclusivity (hook vs fallback vs drop path cannot double-dispatch), the 90 s fallback, the cap path. - Proxy ordering: the stash put on 200 inside the round loop (proxy.go:1771) runs before the hook in
serve's defer (proxy.go:1695); every request that runs the pipeline reachesserve(proxy.go:1427), so in the proxy the deferral always resolves. - Single-flight:
inFlightguards a double dispatch between the deferral, the keep-alive substitute (commissionSync), and a later turn. - Hosts: only the proxy sets
PrefixAskand calls the hook;adapters/bifrostdoes neither for PrefixAsk. - Tests: the new after-stash test models the real race (previous stash one message short of the span, resolution only after the host's put). The updated prefix-ask tests must call
ResolveDeferredCacheAwareSummary, or the 90 s fallback would break their 5 s waits — the updates are correct, not cosmetic. - docs/data-dependence.md and the metrics doc comments for statements the change makes stale.
- I did not read the PR body, other reviews, or comments, per the round 1 independence rule. Live tests were not approved; I read the code only.
…n bound Review of #724: - A warm prefix-ask deferral that a newer request on the same thread replaced was dropped and its fallback restarted. A host that never calls the hook then never dispatched one on a thread with turns under the fallback apart. A replaced deferral is now dispatched at once: the older request has ended, so its body is in the stash. - Warm deferrals shared the 256-slot cold registry, so under load the cap forced the early dispatch #722 removes. They now have their own registry (4096) and counters. - A deferred commission whose span a checkpoint already covers (the keep-alive committed it meanwhile) is skipped, not paid twice. A dispatch startAsyncSummary refuses is counted. - Ctx.PrefixAsk documents the host contract. data-dependence.md notes the short-lived span copy. Fixes #722 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
A host now dispatches a prefix-ask commission from its request-end hook, which can run after the client already has its response. A test that waited right after its request returned could see nothing in flight yet and read its counters before the summary started; the proxy's stale-prefix integration test failed this way under a full -race run. The test hook now first waits until no deferral is pending for the thread. No production code changes. Refs #722 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
|
Replies to round 1, at head Reviewer 2, finding 1 (a replaced deferral restarts the fallback; a host without the hook starves): fixed.
Reviewer 2, finding 2 (warm deferrals share the 256-slot cold registry): fixed.
Reviewer 1, non-blocking:
Reviewer 2, non-blocking:
One more fix found by the full -race run: How it was tested (eval box):
|
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | 17a844efba0d |
approve |
Verdict: approve
Findings
None. Both round-1 findings are fixed, and I verified each fix by trace, not by the author's word.
Earlier findings
- My finding 1 (a replaced deferral restarts the fallback; a hook-less host starves): fixed.
deferWarmnow dispatches a deferral it replaces (cache_aware_cold.go:196-200), after stopping its timer, so exactly one of replacement-dispatch and fallback ever runs. I traced the starvation loop again: on a hook-less host each new turn now dispatches the previous commission, so the thread no longer needs the 90 s fallback to make progress. The dispatch reads a stash that already holds the older turn's body, because a newer request on the same thread implies the older one answered. The host contract is documented onCtx.PrefixAsk(components/component.go:613-617) and onResolveDeferredCacheAwareSummary(cache_aware_cold.go:268-271).TestAReplacedWarmDeferralIsDispatchedWithoutTheHookdrives it with the hook never called, and discards the newer deferral at the end so no timer leaks into the suite. - My finding 2 (warm deferrals share the 256-slot cold registry): fixed. Warm deferrals now live in
warmDeferredwithmaxWarmDeferred= 4096 and their own counters (cache_aware_cold.go:144-172). The cold registry is untouched.TestAWarmCommissionDefersWhenTheColdRegistryIsFullfills the cold registry to its cap, then asserts the warm commission still defers; the primary assertion (takeWarmDeferralmust return the deferral) is what catches a regression to the shared registry. - Reviewer 1's three non-blocking items: fixed. I checked each myself. (1) The registry cap now has its own
fullcounter and a 16× bound. (2) A dispatchstartAsyncSummaryrefuses is counted inrefused(cache_aware_cold.go:233-235). (3) The duplicate paid call is fixed for the warm path:dispatchDeferredskips a commission whose span a checkpoint already covers (cache_aware_cold.go:230-238). I verified the hash basis:commitAsyncSummarystoresCoveredHash: spanHash(span)(cache_aware_async.go:245), the same function the skip compares, and the keeper's substitute commits through that same function, so a keeper-committed span produces the exact hash the skip checks.loadCheckpoint's parent fallback is safe here too: a parent checkpoint with the same span hash is one this thread'stryReusewould itself splice, so skipping the paid call is correct. False skips need an identical span hash, which means the same span. - My round-1 non-blocking items: all addressed. Refusals are counted; warm has its own counters; the data-dependence row now names the request-lifetime span copy (#722); the test comment was reworded; the two agreed trade-offs are stated as such in the author's reply.
- The author rejected nothing. Every round-1 item was fixed or agreed.
Non-blocking
- The duplicate-pay skip exists only on the warm dispatch paths. The cold dispatch paths (the hook's cold branch,
resolveFallback, and the cold registry's drop path) still callstartAsyncSummarydirectly, so the same keeper-commits-first window can pay twice there. Pre-existing, narrow, one wasted call. - Rare race on the warm fallback: if the 90 s timer fires while
deferWarmholds the mutex for a replacement, the blockedresolveWarmFallbackthen takes and dispatches the NEW deferral early, counted as fallback. One commission refused by the coverage check, fail-open. The cold path'stakeColdDeferralhas the same shape. maxWarmDeferred= 4096 entries, each holding a span copy that can be most of a transcript. Occupancy is one request lifetime in a host that calls the hook, but 90 s on one that does not. Finite and fail-open; the cold registry's 256 was sized with memory in mind, so this is worth remembering if the bound is ever raised.CacheAwareWarmDeferralStatsis exported but nothing in-repo consumes it, same as the cold pair. The counters are reachable only by a library user. Fine as a seam; noting it so it is a decision, not an oversight.
What I checked
- Last review: round 1,
5bc5938ab067440cdf017de765315842aecfb61b, 2026-10-25T23:38:53Z. - New commits read: 2 —
9a759819fix(offload): dispatch a replaced warm deferral, and give warm its own bound;17a844eftest(offload): wait out a deferred commission in WaitForSummaryForTest. - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files; the inline file is empty).
- New items since my last review: the author's reply comment (all items addressed as above), commit
9a759819(deferWarm, warm registry and counters, dispatchDeferred with the dup skip, host-contract docs, data-dependence row, 3 new tests), commit17a844ef(test hook only). - The full diff
5bc5938a..17a844ef, and each changed file around the changes:deferWarm/takeWarmDeferral/resolveWarmFallback/dispatchDeferredlocking and exclusivity, bothdeferSummarycall sites (cold passeswarm: false, prefix-ask passeswarm: true),ResolveDeferredCacheAwareSummarynow draining both registries. - The duplicate-skip hash basis against
commitAsyncSummaryand the keeper's commit path, andloadCheckpoint's parent-thread fallback for the skip's read. - The three new tests, traced end to end: what each mutation would break, what each asserts, and that no fallback timer leaks into the rest of the suite (
takeWarmDeferralat each test's end stops it). - The test-hook change:
WaitForSummaryForTestnow spins ondeferralPendingbefore peekinginFlight, with the deadline shared across both waits. Verified the key it polls matches the deferral keys the tests pass. - The commit messages (conventional titles,
Assisted-By:,Signed-off-by:present on both). - Live tests were not approved; I read the code only, and the author's eval-box results as reported, not re-run.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | 17a844efba0d |
approve |
Verdict: approve
Findings
None. Both round-1 blocking findings (reviewer 2) and all three of my non-blocking items are fixed, and the fixes are correct. See Non-blocking for two small notes on the new code.
Earlier findings
- Reviewer 2, finding 1 (a replaced deferral restarts the fallback; a hookless host starves): fixed.
deferWarmnow dispatches a deferral it replaces (cache_aware_cold.go:198-201), instead of dropping it. I checked the reasoning: a newer request on the thread reached Offload, so the older request ended and its body is in the stash. The dispatch is correct in a sequential host, and in a concurrent same-thread overlap the coverage check declines — fail-open. The host contract is now documented onCtx.PrefixAsk(components/component.go) and onResolveDeferredCacheAwareSummary.TestAReplacedWarmDeferralIsDispatchedWithoutTheHookdrives it with the hook never called. - Reviewer 2, finding 2 (warm deferrals share the 256-slot cold registry): fixed. Warm deferrals have their own registry (
warmDeferred, bound 4096) and their own counters (CacheAwareWarmDeferralStats). The cold registry, its bound and its counters are unchanged.TestAWarmCommissionDefersWhenTheColdRegistryIsFullfills the cold registry to its cap and proves a warm commission still defers. - My non-blocking 1 (full registry reintroduces #722, counter says "cold"): fixed by the same split — own bound, own
fullcounter. - My non-blocking 2 (a hook dispatch that
startAsyncSummaryrefuses is invisible): fixed for warm.dispatchDeferredcounts a refusal intorefused. The cold path still discards it, but that gap predates this PR and the author's reason (no turn Report is left to file it on) is right. - My non-blocking 3 (duplicate paid call when the keep-alive commits the span first): fixed.
dispatchDeferredskips a commission whose span a checkpoint already covers, counted asskipped_dup.TestADeferredCommissionSkipsASpanACheckpointAlreadyCoversdrives it. - Reviewer 2's non-blocking items: the data-dependence row now names the request-lifetime span copy (verified in the diff), the test comment is reworded, and the rest are accepted trade-offs. All addressed.
Non-blocking
components/offload/cache_aware_cold.go:194— a fallback timer that already fired can dispatch the NEW deferral early.deferWarmstopsprev.timerunder the lock, but a timer whose goroutine already fired and is blocked onwarmDeferredMuproceeds after the swap:resolveWarmFallbacktakeswarmDeferred[conv], which is now the new deferral, and dispatches it before its request ends. The coverage check then declines it, so the cost is one forgone commission, counted asfallback. This is the same take-by-key pattern the cold path has always had, copied into the warm path. Fix when convenient: have the timer callback check that the entry it took is the one it was scheduled for.components/offload/cache_aware_cold.go:226— the duplicate skip matches only the exact same span. A checkpoint that covers a strictly larger span does not skip the dispatch, because itsCoveredHashhashes more messages. Reaching that needs a keep-alive commit of a different turn's larger span inside one request's window, so I rate it contrived. One wasted call at most; no wrong answer.
What I checked
- Last review: round 1, 5bc5938, 2026-10-25T23:38:28Z.
- New commits read: 2 —
9a759819(fix: dispatch a replaced warm deferral, and give warm its own bound),17a844ef(test: wait out a deferred commission in WaitForSummaryForTest). - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
- New items since my last review: reviewer 2's round-1 review (read in full this round, as round 2 allows); the author's reply comment at 2026-10-26T00:12:46Z (checked each claim against the code, above); the two new commits (full diff and the files around each change).
- The warm registry.
deferWarmholdswarmDeferredMuonly around the map operations; both dispatches (full-registry and replaced) run after the unlock, sostartAsyncSummaryandloadCheckpointnever run under the lock. The replacement dispatch cannot double-fire with the hook: both paths remove or replace the entry under the same mutex. - The duplicate skip.
cp.CoveredCount >= d.coveredCount && cp.CoveredHash == spanHash(d.span)reduces to an exact-span match, which is the case the keep-alive substitute produces (its candidate and the deferral come from the same turn's registration). A reserved checkpoint with the same span skips correctly — dispatching it would produce the same reserved checkpoint again. - The test-hook change.
WaitForSummaryForTestnow first waits until no deferral is pending for the thread, then waits on the flight channel with the remaining budget. I checked it against the cold fallback test (cache_aware_trigger_test.go:330), which shrinks the fallback to 50 ms and sleeps past it before waiting: the deferral is gone from the registry by then, so the new wait is a no-op there. It is bounded (returns false at the deadline), so a test that leaves a deferral pending cannot hang. - The new tests. I traced all three: the replaced-deferral test (stash put between turns, hook never called, checkpoint must land), the cold-registry-full test (fills
coldDeferredwith 256 dummy entries, cleans up its own keys), and the duplicate-skip test (checkpoint seeded with the exact span, zero calls allowed). Each fails under the mutation the author names. - Thread and memory bounds. One warm entry per thread with a commissioning request in flight, removed by hook, replacement, or the 90 s fallback — the map cannot leak. The 4096 bound with the span copy per entry is documented in
docs/data-dependence.md, which now matches the code. - Commit rules. Both commits carry
Signed-off-byandAssisted-By:, conventional titles, and the author as repo owner.
…atch gap Review round 3 of #727: - expand's in-place restore on the Responses route accepted any stashed object with a role or a type. A cache_aware_summarizer stash holds normalized chat messages, so a span with a tool exchange would splice a role=tool message and tool_calls into `input` (a 400 from the Responses API). It now restores in place only real Responses input items; anything else is answered as the flattened string, as before. - CI failure TestCacheAwareRealContentChangeInsideSpanStillDeclines: the host's hook took a deferral out of its registry and then started it, and in between it was neither registered nor in flight. A test waiting right after its request could see nothing pending and read its counters before the call ran. A taken deferral is now marked as dispatching under the registry lock until startAsyncSummary returns, and WaitForSummaryForTest waits for that mark. The stale-prefix guard itself is unchanged. - The #724 tests stash one message short of the RETREATED span, so they still catch an Offload-time start after #723 shortened the span. Fixes #723 Assisted-By: Claude Signed-off-by: DAVID AMID <[email protected]>
fix(offload): keep and mark the last tool exchange after a splice
After cache_aware_summarizer spliced a summary in, every following turn
re-wrote the whole kept history to the cache. The provider never reads a
cache entry that ends at a text turn on the next request; it reads one
that ends at a tool_result. The splice folded every tool exchange into
the summary, so the kept history was text turns only.
Two parts, only when the summarizer splices:
- A fresh summary span now ends before the last tool exchange, so that
tool_use and its tool_result stay verbatim (retreatPastLastToolExchange).
- The summarizer names that tool_result in Ctx.CacheAnchorToolID, and
apply's count-changing rebuild writes one {"type":"ephemeral"}
cache_control onto it in the raw body.
The breakpoint is added only if the rebuilt body has fewer than 4, the
provider's cap; otherwise it is skipped and counted. /stats gains
cache_anchor_written, cache_anchor_no_slot and cache_anchor_not_found.
Live, on real Claude Code traffic: the turn after a splice read 20,975
(system, tools, summary and the kept exchange) and wrote 134, against a
read of 13,438 and a write of 992 before.
Fixes #723
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
test(offload,apply): follow the new span rule in 3 summarizer tests
cache_aware_summarizer now keeps the last tool exchange outside a fresh
span (#723). Three tests still asserted the old span:
- the split-group rebuild test expected the group summarized away; it is
the last tool exchange, so it is now kept whole (still never split);
- the marker-text span test computed its expected span without the
retreat;
- the duplicate-skip test saved a checkpoint for the un-retreated span.
Refs #723
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(apply): anchor an equal-count splice too, and only on Anthropic shapes
Review of #727:
- A one-message span keeps the message count, so the rebuild ran only
if summaryStructureChanged recognised the summary message. It knew
summarize's header and not cache_aware_summarizer's, so that splice
went through the per-message writeback and got no anchor. Both headers
are now constants in schema, used by the builders and the check.
- The anchor search is for tool_result blocks, which an OpenAI-shaped
body has none of, so every OpenAI splice counted as not found. The
anchor now runs only for Anthropic, Bedrock and Vertex bodies.
- Two comments said bifrost leaves an Anthropic tool_use out of
ToolCalls; apply's normalize puts it there. Corrected.
Fixes #723
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(apply,expand): find a cache-aware summary in every rebuild and restore
Review round 2 of #727: the equal-count gate now accepted
cache_aware_summarizer's header, but the Responses-route rebuild still
looked for summarize's only. It found no summary, returned not-ok, and
a one-message cache-aware splice on that route was dropped instead of
written, as it had been before.
apply now has one test for a spliced summary, isSummaryHeader, used by
the gate and by rebuildResponsesCountChanged. expand's in-place restore
on the Responses route accepts both headers too, from local constants a
test pins to schema's (expand imports no context-guru package).
Fixes #723
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
fix(expand,offload): restore only wire items in place; close the dispatch gap
Review round 3 of #727:
- expand's in-place restore on the Responses route accepted any stashed
object with a role or a type. A cache_aware_summarizer stash holds
normalized chat messages, so a span with a tool exchange would splice
a role=tool message and tool_calls into `input` (a 400 from the
Responses API). It now restores in place only real Responses input
items; anything else is answered as the flattened string, as before.
- CI failure TestCacheAwareRealContentChangeInsideSpanStillDeclines:
the host's hook took a deferral out of its registry and then started
it, and in between it was neither registered nor in flight. A test
waiting right after its request could see nothing pending and read
its counters before the call ran. A taken deferral is now marked as
dispatching under the registry lock until startAsyncSummary returns,
and WaitForSummaryForTest waits for that mark. The stale-prefix guard
itself is unchanged.
- The #724 tests stash one message short of the RETREATED span, so they
still catch an Offload-time start after #723 shortened the span.
Fixes #723
Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
Summary
A detached
cache_aware_summarizersummary on the prefix-ask path (every Anthropic incoming-model session) never committed. It ended asstale_prefixevery time, so only the keep-alive substitute could ever produce a summary. The commission now waits until the host has stashed this turn's body, then starts.What we found
Reproduced on the real
a0e5f9e5binary in a clean session (no restart, no model switch): 3 of 3 detached commissions ended asstale_prefix.stale_prefix, 1 ms after the commissionWhy it happens
startAsyncSummarystarts the call at once, about 1 ms later.AskCovered), which first checks that the stash covers the span to summarize.proxy/proxy.go), seconds later.ErrStalePrefix). The span always reaches into this turn's new messages, so this happens on every turn.What changed
components/offload/cache_aware_summarizer.go: on the prefix-ask path, the commission goes into the deferral registry the cold path already uses (deferSummary), notstartAsyncSummary. The host's existing hook (ResolveDeferredCacheAwareSummary, at the end of the request, after the stash put) starts it. The turn still replays a stale summary as before. New event:summary_deferred_to_stash.components/offload/cache_aware_cold.go:deferColdSummarybecomesdeferSummaryand carriestriggerandreserved, so a warm commission keeps its own trigger and reserve flag. The cold path passes"cold_deferred"andfalse, as before.How it was tested
All runs are on the eval box.
TestCacheAwareDetachedPrefixAskCommitsAfterTheTurnIsStashed(×3)origin/main+ testended stale_prefix 1 time(s): it read the previous turn's stashgo test -race ./components/...go test -race ./proxy/...go vet,gofmt -lThe new test models the host's stash: it holds the previous turn's shorter body when the turn arrives, and this turn's body only after Offload returns. A detached call started at Offload time finishes before that put, as it does live.
Data dependence
No change. The deferral holds the same commission material the cold path already holds, for the length of one request.
Not in this PR
cheapmodel/anthropic.goorextract_sweep.go.insertAskMessage, so after Prefix questions (sweep, summary substitute) miss the cache: the breakpoint stays on Claude Code's trailing system message #721 lands its cache read improves too.Fixes #722
🤖 Generated with Claude Code