Repository navigation
fix(offload,proxy): the stale-prefix guard ignored a moving cache marker and the pipeline order - #431
Conversation
amiddavid
left a comment
There was a problem hiding this comment.
Review round 1 of 2 (head e84d068)
Verdict: 1 blocking finding. The moving-marker fix and the pre/post stash split are correct for cache_aware_summarizer when it is first in the pipeline. The new sweep guard is in the wrong coordinate, so it misfires in every preset that runs the sweep.
What I ran
On the eval box (CGO_ENABLED=1):
go build ./...,go vet ./...,gofmt -l .: pass, no files.go test ./components/offload/... ./proxy/...: pass.go test -race ./components/offload/... ./proxy/...: pass.- A review-only reproduction test (below). Turn 1 goes through the real
serve(). Turn 2 runs through the same pipeline, with the realsentStashandprefixAsker.
No live provider calls. The finding is in the guard's hash input, and a mock upstream shows it fully.
Blocking: the sweep guard declines whenever an earlier component rewrote a cached message
What happens. extract_llm_sweep hashes req.Input[:requiredCount] at its own position in the pipeline (extract_sweep.go:1401). CoversSpan hashes the stashed pre-pipeline body. In housellm and xhigh the sweep runs 9th, after format, dedup, toon, cmdfilter, searchfold, textclean, extract_llm. These components rewrite tool outputs on every turn, prefix included (textclean.go:58 loops over all of req.Input). The two hashes then disagree, and the guard reports sweep_stale_prefix although the stash is the correct one.
Result: the sweep never uses the prefix ask on a real transcript. It falls back to the full-price call, or does nothing when block_fallback is set (and debug logging turns block_fallback on by default).
Measured (12 tool outputs, so the inventory floor of 10 is met; 1 output has an ANSI color code; MaxCachedIdx = turn 1's last index; pre-expiry window):
| Pipeline | Tool output | Prefix asks | Sweep gates |
|---|---|---|---|
[textclean, extract_llm_sweep] |
ANSI | 0 | sweep_stale_prefix, sweep_fallback_no_model |
[textclean, extract_llm_sweep] |
plain (control) | 1 | sweep_kept_everything |
[extract_llm_sweep] |
ANSI (control) | 1 | sweep_kept_everything |
On main the sweep has no guard, so this PR adds the decline.
Same cause, second case. cache_aware_summarizer has the same problem when any component runs before it. I used the PR's own pipelineOrderFixture with pipeline: [textclean, cache_aware_summarizer]: 0 ask calls. With the summarizer first, the same fixture gives 1. Nothing in config makes the summarizer go first, so a user pipeline can reach this.
Why it happens. preBody is right only for a component that sees req.Input before any other component runs. In general, the hash must use the same data that the checking component saw on the previous turn, and the stash keeps only the pipeline's first and last snapshots.
Possible fixes (your choice):
- Stash each component's own pre-component span hash, or its pre-component message snapshot, keyed by component name. Each guard then compares against its own data from the previous turn. This is the most correct fix.
- Run the sweep's check on the raw request.
applycould put the pre-pipeline messages onCtx, and the sweep could hashRawInput[:requiredCount]instead ofreq.Input. This is the smallest change, becauseMaxCachedIdxis already in the raw coordinates. It also fixes the summarizer-not-first case if the summarizer hashes the same field. - If neither is wanted now, take the sweep guard out of this PR and keep the two summarizer fixes. Also add a config check that
cache_aware_summarizeris first whenPrefixAskis used.
For whichever fix you choose, please add a regression test like the one below, with a component before the guarded one. The PR's current tests put every rewriting component after the guarded one, so they cannot catch this.
Checked, no issue found
SpanHashstripscache_controlon a copy, so the forwarded request keeps its breakpoints. Both sides of every comparison useSpanHash.putdrops the entry when either body is too large, soCoversSpancannot report "covered" for a missingpreBody.preBodyis assigned on every path through the pipeline closure. The panic path forwardsorigwith the pre-pipelinepreBody, and that is consistent.Strategynaming withattemptedPrefixAskis correct for all three routes.
Reproduction test (review-only, proxy/zz_review431_sweep_guard_test.go)
package proxy
// Review-only reproduction for PR #431 (not for merge). Question: does extract_llm_sweep's new
// stale-prefix guard misfire when a component that runs BEFORE it (textclean here) rewrites a
// message inside the cached prefix? The guard hashes req.Input at the sweep's own pipeline
// position; CoversSpan hashes the stashed PRE-pipeline body.
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
bschemas "github.com/maximhq/bifrost/core/schemas"
"github.com/rossoctl/context-guru/apply"
"github.com/rossoctl/context-guru/components"
"github.com/rossoctl/context-guru/config"
"github.com/rossoctl/context-guru/internal/cheapmodel"
"github.com/rossoctl/context-guru/metrics"
"github.com/rossoctl/context-guru/store"
)
func review431Run(t *testing.T, pipelineYAML string, toolOut string) (gates map[string]int, asks int64) {
t.Helper()
var upstreamCalls atomic.Int64
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
upstreamCalls.Add(1)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"id":"m","type":"message","role":"assistant","model":"claude-sonnet-5",` +
`"content":[{"type":"text","text":"[]"}],"stop_reason":"end_turn",` +
`"usage":{"input_tokens":5,"output_tokens":2,"cache_read_input_tokens":100,"cache_creation_input_tokens":0}}`))
}))
defer upstream.Close()
cfg, err := config.LoadBytes([]byte(pipelineYAML))
if err != nil {
t.Fatal(err)
}
agg := metrics.NewAggregator()
pipe, err := cfg.Build(agg)
if err != nil {
t.Fatal(err)
}
h := New(pipe, store.NewMemory(store.Options{}), agg, Options{AnthropicUpstream: upstream.URL})
t.Cleanup(h.Close)
srv := httptest.NewServer(h.Mux())
defer srv.Close()
session := "review431-" + t.Name()
msgs1 := []any{map[string]any{"role": "user", "content": "fix the tests"}}
for i := 0; i < 12; i++ {
id := "tu_" + string(rune('a'+i))
out := strings.Repeat("plain record "+id+" of the audit log\n", 200)
if i == 0 {
out = toolOut
}
msgs1 = append(msgs1,
map[string]any{"role": "assistant", "content": []any{map[string]any{
"type": "tool_use", "id": id, "name": "Bash", "input": map[string]any{"command": "go test " + id}}}},
map[string]any{"role": "user", "content": []any{map[string]any{
"type": "tool_result", "tool_use_id": id, "content": out}}})
}
msgs1 = append(msgs1, map[string]any{"role": "assistant", "content": "looked at it"},
map[string]any{"role": "user", "content": "continue"})
post := func(msgs []any) []byte {
body, _ := json.Marshal(map[string]any{"model": "claude-sonnet-5", "max_tokens": 64,
"system": "you are claude code", "messages": msgs})
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/anthropic/v1/messages", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-context-guru-session", session)
req.Header.Set("x-api-key", "sk-test")
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("proxy %d", resp.StatusCode)
}
return body
}
post(msgs1) // turn 1 through the real serve(): stashes preBody + forwarded
// The stash must be keyed under the scoped session id serve() used. Find it.
h.sent.mu.Lock()
var scoped string
for k := range h.sent.m {
scoped = k
}
h.sent.mu.Unlock()
if scoped == "" {
t.Fatal("PRECONDITION: turn 1 stashed nothing")
}
// Turn 2, built as the pipeline would receive it, run through the SAME pipeline with a
// pre-expiry ctx whose cached boundary is turn 1's last message.
msgs2 := append(append([]any{}, msgs1...),
map[string]any{"role": "assistant", "content": "ok"},
map[string]any{"role": "user", "content": "and now?"})
body2, _ := json.Marshal(map[string]any{"model": "claude-sonnet-5", "max_tokens": 64,
"system": "you are claude code", "messages": msgs2})
norm := apply.NormalizeMessages(bschemas.Anthropic, body2)
req := &bschemas.BifrostChatRequest{Input: norm}
ctx := &components.Ctx{
Ctx: context.Background(), Session: scoped, Store: store.NewMemory(store.Options{}),
CtxWindow: 1_000_000, ModelName: "claude-sonnet-5",
CacheAware: true, MaxCachedIdx: len(apply.NormalizeMessages(bschemas.Anthropic, review431JSON(msgs1))) - 1,
IdleMs: 4 * 60 * 1000, CacheTTLMs: 5 * 60 * 1000,
PrefixAsk: prefixAsker{stash: h.sent, cli: cheapmodel.Anthropic{BaseURL: upstream.URL, Model: "claude-sonnet-5", APIKey: "k"}},
}
before := upstreamCalls.Load()
rr := pipe.Run(req, ctx)
gates = map[string]int{}
for _, rep := range rr.Components {
for k, v := range rep.Gates {
gates[rep.Component+"/"+k] += v
}
}
return gates, upstreamCalls.Load() - before
}
func review431JSON(msgs []any) []byte {
b, _ := json.Marshal(map[string]any{"model": "claude-sonnet-5", "messages": msgs})
return b
}
const review431YAML = "pipeline: [%s]\ncomponents:\n extract_llm_sweep:\n min_tokens: 50\n"
func TestReview431SweepGuard(t *testing.T) {
ansi := "\x1b[31mFAIL\x1b[0m " + strings.Repeat("filler output line\n", 200)
plain := "FAIL " + strings.Repeat("filler output line\n", 200)
for _, tc := range []struct{ name, pipe, out string }{
{"textclean+ANSI", "textclean, extract_llm_sweep", ansi},
{"textclean+plain(control)", "textclean, extract_llm_sweep", plain},
{"sweep-only+ANSI(control)", "extract_llm_sweep", ansi},
} {
t.Run(tc.name, func(t *testing.T) {
gates, asks := review431Run(t, strings.Replace(review431YAML, "%s", tc.pipe, 1), tc.out)
t.Logf("RESULT %s: upstream_calls=%d gates=%v", tc.name, asks, gates)
})
}
}
func TestReview431SummarizerNotFirst(t *testing.T) {
asked := pipelineOrderFixture(t, "pipeline: [textclean, cache_aware_summarizer]\n"+
"components:\n cache_aware_summarizer:\n keep_last_turns: 2\n min_tokens: 1\n"+
" trigger:\n min_messages: 7\n min_request_tokens: 1\n min_request_frac: 0\n")
t.Logf("RESULT summarizer-after-textclean: ask_calls=%d (summarizer-first gets 1)", len(asked))
}🤖 Generated with Claude Code
…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]>
extract_llm_sweep and cache_aware_summarizer each guard a prefix ask against a stale cached prefix. Both guards hashed req.Input at their own position in the pipeline. CoversSpan, on the host side, hashes the stashed body from BEFORE the pipeline ran. The two spans match only when the guarded component is first in the pipeline. In housellm and xhigh the sweep runs ninth, after format, dedup, toon, cmdfilter, searchfold, textclean and extract_llm. Any of those components may rewrite a cached tool output on every turn (textclean strips terminal noise, for example). That rewrite makes the two hashes disagree even though the stash holds the correct bytes, so the sweep declines every ask as sweep_stale_prefix on real traffic. The summarizer has the identical failure whenever a component runs ahead of it, which no config check currently prevents. Fix: apply now takes a shallow copy of the normalized messages before Pipeline.Run starts and carries it on components.Ctx as RawInput. Both guards hash RawInput instead of req.Input. A Ctx built without going through apply (most component unit tests) leaves RawInput nil, and both guards fall back to req.Input, so their existing behaviour is unchanged. When RawInput is set but its length disagrees with req.Input's length at the guarded component's own position, an earlier component changed the message count and the two slices no longer share index coordinates; the guards decline rather than compare the wrong span. Added proxy/pr431_stale_prefix_coord_test.go: - extract_llm_sweep behind textclean no longer reports sweep_stale_prefix and still asks through the stash. - cache_aware_summarizer behind textclean asks exactly once, matching the existing first-in-pipeline case. - a genuinely changed cached span (not merely rewritten by an earlier component) still declines as stale, so the fix does not make the guard vacuously pass. On the eval box: go build, go vet and gofmt report nothing; go test ./components/... ./apply/... ./proxy/... and go test -race ./components/offload/... ./proxy/... both pass. Assisted-By: Claude Opus 5.5 <[email protected]> Rebased onto origin/main (#423/#426, the per-thread prefix-ask stash). That merge surfaced a second coordinate bug in the same guard: the sweep's new CoversSpan call compared against the plain session, while the Ask call three lines below it (already thread-aware on main) and the host's stash itself (keyed by thread.Key(session, thread)) both use the per-thread key. For any thread but the first, that mismatch made CoversSpan's missing-key convention report "covered" and the guard never fired. Fixed to use thread.Key(c.Session, c.Thread), same as the Ask call. The rebase also exposed a now-outdated assumption in an existing test, TestCacheAwareRealContentChangeInsideSpanStillDeclines: a genuine content edit inside the cached span breaks thread-prefix continuity, so #423's thread detector classifies the next turn as a new, unstashed thread before the stale-prefix hash check ever runs. The commission still declines (ErrNoPrefix instead of ErrStalePrefix) and still asks nothing, so the safety property holds; only which counter moves changed. Updated the test to check that either counter moved, with a comment on why. Signed-off-by: DAVID AMID <[email protected]>
e84d068 to
33986a9
Compare
This repo's CLAUDE.md told sessions to read an "Eval boxes" section for the full build/test procedure on the shared Go box, but the section did not exist. Every session had to improvise or ask, and the two copies of this knowledge (the global memory file and whatever a session worked out on its own) could drift. Add the section: run remote builds and tests in the foreground, never start a detached remote run and end the turn to wait on it, commit a WIP before a long run, where the go binary and cgo flag live, sync with tar rather than rsync, the box's shared-user rules, and the two tests that fail on the box itself rather than on a real change. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Fixed. The guard now hashes A Tests, through the real
While rebasing onto That merge also broke a stated assumption in a pre-existing test On the eval box, Also added the "Eval boxes" section to CLAUDE.md, which the repo's own CLAUDE.md referred sessions |
amiddavid
left a comment
There was a problem hiding this comment.
Review round 2 of 2 (head 33986a9) — final round
Verdict: approve after one small fix. I will not do a third round. The round-1 finding is fixed on the Anthropic Messages route. The fix is missing on the OpenAI Responses route. That route still has the round-1 bug.
What I ran
On the eval box (CGO_ENABLED=1), at 33986a9:
go build ./...,go vet ./...,gofmt -l .: pass, no files.go test ./components/... ./apply/... ./proxy/...: pass.go test -race ./components/offload/... ./apply/...: pass.go test -race ./proxy/: pass in 574s. The first try stopped at Go's default 10-minute timeout, because the shared box had a load average of ~49. It was not a test failure.- CI: all 4 checks pass.
- A review-only probe test (below). It runs a pipeline component through
apply.BodyOptson each route and recordslen(c.RawInput).
Round-1 finding: fixed on Messages
rawSpanForHashis the one place that computes the guarded span for both guards. Good.- The PR's
TestSummarizerNotFirstStillAsksOncegoes through the realserve()→apply.BodyOptspath. It shows thatRawInputgets to the summarizer on the Messages route. - The sweep's
CoversSpannow usesthread.Key(c.Session, c.Thread), which matchesAskand the stash. The summarizer already did this. Good catch from the rebase. - When an earlier component changes the message count, the guard declines. That is safe.
Blocking: RawInput is not set on the Responses route
What happens. apply/responses.go:560 builds its own components.Ctx and does not set RawInput. That route still gives components PrefixAsk, CacheAware and MaxCachedIdx, and responsesPrefixAsker implements CoversSpan (prefixask.go:235). So rawSpanForHash falls back to req.Input at the component's position. This is the round-1 bug: a guarded component that runs after textclean/format/… declines on a correct stash.
Measured (probe component through apply.BodyOpts, 3-message body):
| Route | len(c.RawInput) |
|---|---|
| Anthropic Messages | 3 |
OpenAI Responses (API: "responses") |
0 (nil) |
Fix. In bodyResponsesOpts, take the same shallow copy of norm before the pipeline runs, and set RawInput on the Ctx. Please also add a test for the Responses route, like the probe below or a sweep-behind-textclean case.
Related doc conflict. The Ctx.RawInput comment (component.go) says a nil RawInput must decline and must "never fall back to req.Input". rawSpanForHash does fall back to it. Because of this fallback, the Responses gap does not show as a decline. Please make the comment and the code agree. Keeping the fallback for unit tests is OK if the comment says so, and if every production Ctx sets the field.
If the fix is only this (set RawInput on Responses, plus a test, plus the comment), take this review as approval. No round 3.
Non-blocking (no change needed for this PR)
- In
highandxhigh,summarizeruns first and can change the message count. After that, the length check makes the sweep decline on each turn and count it assweep_stale_prefix, although the stash is not stale. The result is safe (the sweep makes the full-price call). The gate name will make dashboards show stale stashes that did not happen. A separate gate name (for examplesweep_coords_shifted) would fix that. A follow-up issue is enough.
Probe test (review-only, apply/zz_review431_rawinput_test.go)
package apply
// Review-only probe for PR #431 round 2 (not for merge): does every BodyOpts route hand the
// pipeline a non-nil Ctx.RawInput?
import (
"context"
"testing"
"github.com/maximhq/bifrost/core/schemas"
"github.com/rossoctl/context-guru/components"
"github.com/rossoctl/context-guru/store"
)
type rawProbe struct{ sawRaw *int }
func (rawProbe) Name() string { return "raw_probe" }
func (rawProbe) Enabled(*components.Ctx) bool { return true }
func (p rawProbe) Reformat(_ *schemas.BifrostChatRequest, _ *components.Report, c *components.Ctx) error {
*p.sawRaw = len(c.RawInput)
return nil
}
func TestReview431RawInputOnEveryRoute(t *testing.T) {
for _, tc := range []struct {
name, api string
prov schemas.ModelProvider
body string
}{
{"anthropic messages", "", schemas.Anthropic,
`{"model":"claude-sonnet-5","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`},
{"openai responses", "responses", schemas.OpenAI,
`{"model":"gpt-5.6","input":[{"role":"user","content":"hi"},{"role":"assistant","content":"yo"},{"role":"user","content":"more"}]}`},
} {
saw := -1
pipe := components.NewPipeline([]components.Component{rawProbe{&saw}}, nil)
BodyOpts(context.Background(), pipe, store.NewMemory(store.Options{}), Opts{
Provider: tc.prov, API: tc.api, Body: []byte(tc.body), Session: "s-" + tc.name,
})
t.Logf("RESULT %s: probe ran=%v len(RawInput)=%d", tc.name, saw >= 0, saw)
}
}🤖 Generated with Claude Code
The Messages route sets Ctx.RawInput before the pipeline runs. The Responses route did not. So on Responses, the stale-prefix guards fell back to req.Input at their own pipeline position, which an earlier component may have rewritten (PR #431 review, round 2). - apply/responses.go: copy norm into a separate slice and set RawInput. - components/component.go: the RawInput comment now says what rawSpanForHash does. A nil RawInput falls back to req.Input, which is correct only when no component runs before the guarded one. So every host path that builds a Ctx for a real request must set the field. - New test: a component before the probe rewrites the tool output, and RawInput still has the original text. The test fails without the fix (RawInput has 0 messages, want 3). Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Round 2: fixed in
|
Round-2 condition check (head 73d5177) — not a new review roundThe round-2 fix is approved. It changes only what round 2 asked for.
One scope note: commit The non-blocking gate-name point from round 2 is now #452. 🤖 Generated with Claude Code |
The xhigh test from #431 spelled out the pipeline by hand, because #414 was not merged then. It now loads `preset: xhigh` by name. Only the summarizer's trigger is lowered, so a three-turn fixture reaches it. - With this PR, the test passes: 1 summary call, covering turn 2. - With main's xhigh (summarize), it fails: 0 calls. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Summary
Follow-up to #402. Its own re-review and a review of #414 found two more ways the stale-prefix
guard's hash could disagree with the stash for reasons that are not actual staleness.
What we found
cache_controlmarker. A client that moves a singlecache 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_turns2 or less this made every commission decline asstale_prefix.extract_llm_sweepreads the same host stash through the samePrefixAskerconstruction, withno coverage check of its own.
cache_aware_summarizer(
textclean,format, ...) rewrites a message before the request is forwarded. The guardcompared the summarizer's own span — computed from what the pipeline first received — against
the FORWARDED body, which a later component may have already rewritten. Live
xhigh: 5 of 5commissions declined, 0 summaries.
What changed
components.SpanHashstripscache_controlbefore hashing, on both sides of every comparison.extract_llm_sweepgained the same stale-prefix guardcache_aware_summarizeralready had,scoped to candidates already inside the cached boundary — a candidate in the turn's own new tail
is a separate, already-tracked gap (extract_llm_sweep: the prefix ask reads a transcript that excludes every candidate it judges #122), not this guard's job.
sentStashnow keeps two bodies per session: the one actually forwarded (whatAskappends to) and the one the pipeline received before any component ran. The guard, on both
callers, now checks coverage against the PRE-pipeline body.
How it was tested
Eval box,
CGO_ENABLED=1:All pass.
New tests through the real
serve()path, each confirmed to fail without its matching fix andpass with it:
TestCacheAwareClaudeCodeStyleMovingCacheControlIsNotStale— the marker moves to the lastmessage every turn,
keep_last_turns: 2. Fails without theSpanHashfix (0 ask calls).TestCacheAwareRealContentChangeInsideSpanStillDeclines— same shape, but a real text changeinside the span. Still declines either way.
TestCacheAwarePipelineOrderMinimalTextCleanCaseandTestCacheAwarePipelineOrderXHighEquivalent—
[cache_aware_summarizer, textclean]and the full pipeline feat(config): switch the xhigh preset to cache_aware_summarizer #414 switchesxhighto (spelledout in the test; feat(config): switch the xhigh preset to cache_aware_summarizer #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.
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
unblocks it).
Round 1 review follow-up
The round 1 review found the sweep's new guard hashed
req.Inputat its own pipeline position,while
CoversSpancompares against the stashed PRE-pipeline body — so any component ahead of thesweep in the pipeline (
textclean,format, ... — the sweep runs 9th inhousellm/xhigh) madethe two hashes disagree even though the stash held the right bytes, and the sweep never got to use
the prefix ask on real traffic.
cache_aware_summarizerhas the identical failure whenever it isnot first.
Fixed by giving
applya pre-pipeline snapshot of the normalized messages (components.Ctx. RawInput), which both guards now hash instead ofreq.Input/msgsat their own position. ACtxbuilt directly (nil
RawInput, most unit tests) falls back to the old behavior; aRawInputwhoselength disagrees with
req.Input's (an earlier component changed the message count) declinesrather than compare the wrong span.
Also rebased onto
origin/main(#423/#426, the per-thread prefix-ask stash) and, while doing so,found the sweep's
CoversSpancall was comparing against the plain session while theAskcallbeside it already used the per-thread key — fixed to use the same key. One pre-existing test's
assumption no longer held after that merge (a genuine content edit inside the cached span now gets
caught by thread-prefix-continuity detection instead of the stale-prefix hash, via a different but
equally safe decline) and was updated to check either decline path.
New regression tests:
TestSweepGuardUsesRawCoordinatesNotPipelinePosition,TestSweepGuardDeclinesWhenRawCoverageTrulyFalls,TestSummarizerNotFirstStillAsksOnce.Also adds the "Eval boxes" section CLAUDE.md referred to but did not have.