Skip to content

fix(offload): start a prefix-ask summary after this turn is stashed - #724

Merged
amiddavid merged 3 commits into
mainfrom
fix/summary-after-stash
Oct 26, 2026
Merged

amiddavid merged 3 commits into
mainfrom
fix/summary-after-stash

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

A detached cache_aware_summarizer summary on the prefix-ask path (every Anthropic incoming-model session) never committed. It ended as stale_prefix every 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 a0e5f9e5 binary in a clean session (no restart, no model switch): 3 of 3 detached commissions ended as stale_prefix.

Turn Commission covered Stash held Result
8 messages 7 messages the previous turn, 5 messages stale_prefix, 1 ms after the commission

Why it happens

  1. Offload commissions the summary and startAsyncSummary starts the call at once, about 1 ms later.
  2. The call goes through the host's prefix stash (AskCovered), which first checks that the stash covers the span to summarize.
  3. The host stashes this turn's body only when its upstream answers 200 (proxy/proxy.go), seconds later.
  4. So the call sees the previous turn's shorter body, and the check refuses it (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), not startAsyncSummary. 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: deferColdSummary becomes deferSummary and carries trigger and reserved, so a warm commission keeps its own trigger and reserve flag. The cold path passes "cold_deferred" and false, as before.
  • The messages-model path, which reads no stash, still starts at once. It is unchanged.
  • 3 test files: the tests that drive a prefix-ask commission now call the host's hook after Offload, as a real host does.

How it was tested

All runs are on the eval box.

Run Tree Result
TestCacheAwareDetachedPrefixAskCommitsAfterTheTurnIsStashed (×3) origin/main + test FAIL 3 of 3: ended stale_prefix 1 time(s): it read the previous turn's stash
the same this branch PASS
mutation: no deferral on the prefix-ask path this branch FAIL
go test -race ./components/... this branch PASS
go test -race ./proxy/... this branch PASS (452 s)
go vet, gofmt -l this branch clean

The 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

Fixes #722

🤖 Generated with Claude Code

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 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.

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. maxColdDeferred is 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 make deferSummary fire startAsyncSummary at 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 that startAsyncSummary refuses is invisible. ResolveDeferredCacheAwareSummary drops the returned gate name. The old inline path put it on the triggering turn's rep.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; startAsyncSummary checks 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:1771 stashes the body when upstream answers 200, inside the round loop. proxy/proxy.go:1695 calls the hook in serve'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 AskCovered against 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; snapshotCovering checks 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. trigger and reserved are threaded unchanged through all three exits (registry full, fallback timer, host hook). The cold path passes "cold_deferred" and false, 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. reserved is computed before the branch and passed through, matching what the old inline startAsyncSummary call passed. The turn still returns declineButReplayStale(), as before.
  • The lite Ctx. deferSummary copies Session, Thread, Store and Ctx. startAsyncSummary and effectiveMode read only those. The call closure 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-1 messages at Offload time, the deferral holds the call until the hook, the put raises the stash to len(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 in components/offload, components/all or apply drives this path; apply-level tests use a MessagesModel, and proxy integration tests get the hook from serve itself.
  • 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 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.

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

  1. 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.PrefixAsk but never calls ResolveDeferredCacheAwareSummary (a library consumer of apply, 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, so tryReuse keeps failing and the gates keep passing. deferSummary then 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. grep shows only proxy/proxy.go:1695 calls ResolveDeferredCacheAwareSummary; nothing else removes a pending deferral, and ClearStaleKeepAliveCandidate does not touch it. The deferSummary comment'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, and adapters/bifrost never sets PrefixAsk. 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_turns messages (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 deferSummary replaces 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 where PrefixAsk is documented: a host that sets it must call ResolveDeferredCacheAwareSummary.
  2. 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, deferSummary fires 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.

Non-blocking

  • The commissioning turn's Report can no longer carry summary_already_in_flight or summary_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).
  • CacheAwareColdDeferralStats counts warm deferrals in cold-named counters. started without resolved now 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, so end = 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, takeColdDeferral exclusivity (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 reaches serve (proxy.go:1427), so in the proxy the deferral always resolves.
  • Single-flight: inFlight guards a double dispatch between the deferral, the keep-alive substitute (commissionSync), and a later turn.
  • Hosts: only the proxy sets PrefixAsk and calls the hook; adapters/bifrost does 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1, at head 17a844efba0d.

Reviewer 2, finding 1 (a replaced deferral restarts the fallback; a host without the hook starves): fixed.

  • deferWarm now dispatches a deferral it replaces, instead of dropping it. A newer request on the same thread reached Offload, so the older request has ended and its body is in the stash, which is all the older commission waited for.
  • Host contract documented on Ctx.PrefixAsk (components/component.go) and on ResolveDeferredCacheAwareSummary: a host that sets PrefixAsk must stash each request's body and call the hook when the request ends.
  • New test TestAReplacedWarmDeferralIsDispatchedWithoutTheHook: 2 turns, the stash updated between them, the hook never called. A checkpoint must commit.
  • Mutation: drop the replaced deferral. The test fails with the replaced warm deferral was dropped instead of dispatched.

Reviewer 2, finding 2 (warm deferrals share the 256-slot cold registry): fixed.

  • Warm deferrals have their own registry (warmDeferred, bound maxWarmDeferred = 4096) and their own counters (CacheAwareWarmDeferralStats: started, resolved, replaced, fallback, full, refused, skipped_dup). The cold registry, its bound and its counters are unchanged.
  • New test TestAWarmCommissionDefersWhenTheColdRegistryIsFull: with the cold registry at its cap, a warm commission is still deferred, not dispatched early.
  • Mutation: route warm into the cold registry. The test fails.

Reviewer 1, non-blocking:

  • A full registry reintroduces Summarizer: a detached summary always ends stale_prefix, because it starts before this turn's stash put #722, and the drop counter says "cold": covered by finding 2 (own bound, own full counter).
  • A hook dispatch that startAsyncSummary refuses is invisible: now counted (refused, in the warm counters). There is no turn Report left to file it on at that point, so a counter is the visible form.
  • A duplicate paid call when the keep-alive commits the span first: fixed. dispatchDeferred skips a commission whose span a checkpoint already covers (same count, same hash), counted as skipped_dup. New test TestADeferredCommissionSkipsASpanACheckpointAlreadyCovers; the mutation "no skip" fails it (paid 1 call(s)).

Reviewer 2, non-blocking:

  • The turn's Report no longer carries summary_already_in_flight / summary_concurrency_full: true; the refusal now lands in the refused counter (see above).
  • Cold-named counters count warm deferrals: no longer; warm has its own.
  • data-dependence.md: the cache_aware_summarizer row now says it also holds a span copy for one request's lifetime while a summary waits for that request's body (Summarizer: a detached summary always ends stale_prefix, because it starts before this turn's stash put #722). Data dependence is otherwise unchanged (content, the same stash reads).
  • The test comment "7 required against 5": reworded. 7/5 is the live case; the fixture needs end and stashes end-1.
  • The checkpoint lands one round trip later on a long streamed answer: agreed. It is inherent to waiting for this turn's stash, and it is the trade the fix makes.
  • Observe mode can under-report: agreed, measurement only. With the replaced-deferral dispatch above, a shadow run slower than the turn cadence is now dispatched when the next turn replaces it, instead of being dropped, so this is smaller than before.

One more fix found by the full -race run: TestCacheAwareStalePrefixThroughARealOversizedTurn (proxy) failed once under the full package. The cause is in the test hook, not in production: the host dispatches from its request-end hook, which can run after the client has its response, so WaitForSummaryForTest could see nothing in flight and return early. It now first waits until no deferral is pending for the thread. No production code changed in that commit.

How it was tested (eval box):

Run Result
the 3 new tests, plus the #722 test and every cold, deferral, prefix-ask and stale-prefix test PASS
M1 drop a replaced deferral / M2 warm into the cold registry / M3 no duplicate skip FAIL each
go test -race ./components/... PASS
go test -race ./proxy/... PASS (452 s)
go vet, gofmt -l clean

@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.

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. deferWarm now 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 on Ctx.PrefixAsk (components/component.go:613-617) and on ResolveDeferredCacheAwareSummary (cache_aware_cold.go:268-271). TestAReplacedWarmDeferralIsDispatchedWithoutTheHook drives 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 warmDeferred with maxWarmDeferred = 4096 and their own counters (cache_aware_cold.go:144-172). The cold registry is untouched. TestAWarmCommissionDefersWhenTheColdRegistryIsFull fills the cold registry to its cap, then asserts the warm commission still defers; the primary assertion (takeWarmDeferral must 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 full counter and a 16× bound. (2) A dispatch startAsyncSummary refuses is counted in refused (cache_aware_cold.go:233-235). (3) The duplicate paid call is fixed for the warm path: dispatchDeferred skips a commission whose span a checkpoint already covers (cache_aware_cold.go:230-238). I verified the hash basis: commitAsyncSummary stores CoveredHash: 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's tryReuse would 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 call startAsyncSummary directly, 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 deferWarm holds the mutex for a replacement, the blocked resolveWarmFallback then takes and dispatches the NEW deferral early, counted as fallback. One commission refused by the coverage check, fail-open. The cold path's takeColdDeferral has 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.
  • CacheAwareWarmDeferralStats is 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 — 9a759819 fix(offload): dispatch a replaced warm deferral, and give warm its own bound; 17a844ef test(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), commit 17a844ef (test hook only).
  • The full diff 5bc5938a..17a844ef, and each changed file around the changes: deferWarm/takeWarmDeferral/resolveWarmFallback/dispatchDeferred locking and exclusivity, both deferSummary call sites (cold passes warm: false, prefix-ask passes warm: true), ResolveDeferredCacheAwareSummary now draining both registries.
  • The duplicate-skip hash basis against commitAsyncSummary and the keeper's commit path, and loadCheckpoint'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 (takeWarmDeferral at each test's end stops it).
  • The test-hook change: WaitForSummaryForTest now spins on deferralPending before peeking inFlight, 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 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.

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. deferWarm now 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 on Ctx.PrefixAsk (components/component.go) and on ResolveDeferredCacheAwareSummary. TestAReplacedWarmDeferralIsDispatchedWithoutTheHook drives 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. TestAWarmCommissionDefersWhenTheColdRegistryIsFull fills 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 full counter.
  • My non-blocking 2 (a hook dispatch that startAsyncSummary refuses is invisible): fixed for warm. dispatchDeferred counts a refusal into refused. 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. dispatchDeferred skips a commission whose span a checkpoint already covers, counted as skipped_dup. TestADeferredCommissionSkipsASpanACheckpointAlreadyCovers drives 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. deferWarm stops prev.timer under the lock, but a timer whose goroutine already fired and is blocked on warmDeferredMu proceeds after the swap: resolveWarmFallback takes warmDeferred[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 as fallback. 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 its CoveredHash hashes 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. deferWarm holds warmDeferredMu only around the map operations; both dispatches (full-registry and replaced) run after the unlock, so startAsyncSummary and loadCheckpoint never 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. WaitForSummaryForTest now 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 coldDeferred with 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-by and Assisted-By:, conventional titles, and the author as repo owner.

@amiddavid
amiddavid merged commit 65485b8 into main Oct 26, 2026
8 of 9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 26, 2026
amiddavid added a commit that referenced this pull request Oct 26, 2026
…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]>
amiddavid added a commit that referenced this pull request Oct 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Summarizer: a detached summary always ends stale_prefix, because it starts before this turn's stash put

1 participant