Skip to content

fix(offload,proxy): the stale-prefix guard ignored a moving cache marker and the pipeline order - #431

Merged
amiddavid merged 4 commits into
mainfrom
feat/prefix-hash-followup
Oct 11, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/prefix-hash-followup

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

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

  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 this made every commission decline as stale_prefix.
  2. extract_llm_sweep reads the same host stash through the same PrefixAsker construction, with
    no coverage check of its own.
  3. feat(config): switch the xhigh preset to cache_aware_summarizer #414's review found that a pipeline component downstream of cache_aware_summarizer
    (textclean, format, ...) rewrites a message before the request is forwarded. The guard
    compared 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 5
    commissions declined, 0 summaries.

What changed

  • components.SpanHash strips cache_control before hashing, on both sides of every comparison.
  • extract_llm_sweep gained the same stale-prefix guard cache_aware_summarizer already 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.
  • proxy's sentStash now keeps two bodies per session: the one actually forwarded (what Ask
    appends 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:

go build ./...
go vet ./...
gofmt -l .
go test ./components/offload/... ./proxy/...
go test -race ./components/offload/... ./proxy/...

All pass.

New tests through the real serve() path, each confirmed to fail without its matching fix and
pass with it:

  • TestCacheAwareClaudeCodeStyleMovingCacheControlIsNotStale — the marker moves to the last
    message every turn, keep_last_turns: 2. Fails without the SpanHash fix (0 ask calls).
  • TestCacheAwareRealContentChangeInsideSpanStillDeclines — same shape, but a real text change
    inside the span. Still declines either way.
  • TestCacheAwarePipelineOrderMinimalTextCleanCase and TestCacheAwarePipelineOrderXHighEquivalent
    — [cache_aware_summarizer, textclean] and the full pipeline feat(config): switch the xhigh preset to cache_aware_summarizer #414 switches xhigh to (spelled
    out 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.Input at its own pipeline position,
while CoversSpan compares against the stashed PRE-pipeline body — so any component ahead of the
sweep in the pipeline (textclean, format, ... — the sweep runs 9th in housellm/xhigh) made
the 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_summarizer has the identical failure whenever it is
not first.

Fixed by giving apply a pre-pipeline snapshot of the normalized messages (components.Ctx. RawInput), which both guards now hash instead of req.Input/msgs at their own position. A Ctx
built directly (nil RawInput, most unit tests) falls back to the old behavior; a RawInput whose
length disagrees with req.Input's (an earlier component changed the message count) declines
rather 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 CoversSpan call was comparing against the plain session while the Ask call
beside 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.

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

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 real sentStash and prefixAsker.

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):

  1. 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.
  2. Run the sweep's check on the raw request. apply could put the pre-pipeline messages on Ctx, and the sweep could hash RawInput[:requiredCount] instead of req.Input. This is the smallest change, because MaxCachedIdx is already in the raw coordinates. It also fixes the summarizer-not-first case if the summarizer hashes the same field.
  3. 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_summarizer is first when PrefixAsk is 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

  • SpanHash strips cache_control on a copy, so the forwarded request keeps its breakpoints. Both sides of every comparison use SpanHash.
  • put drops the entry when either body is too large, so CoversSpan cannot report "covered" for a missing preBody.
  • preBody is assigned on every path through the pipeline closure. The panic path forwards orig with the pre-pipeline preBody, and that is consistent.
  • Strategy naming with attemptedPrefixAsk is 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]>
@amiddavid
amiddavid force-pushed the feat/prefix-hash-followup branch from e84d068 to 33986a9 Compare October 11, 2026 10:03
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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Fixed. The guard now hashes components.Ctx.RawInput, a pre-pipeline snapshot apply takes
before Pipeline.Run starts, instead of req.Input/msgs at the guarded component's own
position — so it hashes the same span CoversSpan compares against (the host's stashed
PRE-pipeline body) regardless of where the sweep or the summarizer sits in the configured
pipeline.

A Ctx built directly, as most component unit tests still do, leaves RawInput nil and falls
back to the old behavior (unchanged test suite). A non-nil RawInput whose length disagrees with
req.Input's at the guarded component's own position means an earlier component changed the
message count; the guard declines rather than compare the wrong span.

Tests, through the real serve() path, each confirmed to fail without the fix and pass with it:

  • TestSweepGuardUsesRawCoordinatesNotPipelinePosition — [textclean, extract_llm_sweep], an
    ANSI tool output textclean rewrites every turn. One prefix ask, no sweep_stale_prefix.
  • TestSummarizerNotFirstStillAsksOnce — [textclean, cache_aware_summarizer]. Exactly one ask,
    matching the existing first-in-pipeline case.
  • TestSweepGuardDeclinesWhenRawCoverageTrulyFalls — a genuinely changed cached span (not merely
    rewritten by an earlier component) still declines, so the fix does not make the guard vacuously
    pass.

While rebasing onto origin/main (#423/#426, the per-thread prefix-ask stash) I found a second
instance of the same coordinate mistake: the sweep's 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) both use thread.Key(c.Session, c.Thread). For any thread but the
first, that mismatch let the guard's missing-key convention report "covered" and it never fired.
Fixed to use the same key as Ask.

That merge also broke a stated assumption in a pre-existing test
(TestCacheAwareRealContentChangeInsideSpanStillDeclines): a genuine content edit inside the
cached span now 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 and still asks nothing — the safety property holds — just via ErrNoPrefix instead of
ErrStalePrefix. Updated the test to check that either counter moved, with a comment explaining
why.

On the eval box, CGO_ENABLED=1: go build ./..., go vet ./..., gofmt -l . report nothing;
go test ./components/... ./apply/... ./proxy/... and
go test -race ./components/offload/... ./proxy/... both pass. CI (build-test, DCO, purego,
trivy) is green on the pushed commit.

Also added the "Eval boxes" section to CLAUDE.md, which the repo's own CLAUDE.md referred sessions
to but did not have.

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

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.BodyOpts on each route and records len(c.RawInput).

Round-1 finding: fixed on Messages

  • rawSpanForHash is the one place that computes the guarded span for both guards. Good.
  • The PR's TestSummarizerNotFirstStillAsksOnce goes through the real serve() → apply.BodyOpts path. It shows that RawInput gets to the summarizer on the Messages route.
  • The sweep's CoversSpan now uses thread.Key(c.Session, c.Thread), which matches Ask and 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 high and xhigh, summarize runs first and can change the message count. After that, the length check makes the sweep decline on each turn and count it as sweep_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 example sweep_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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 2: fixed in 73d5177

Result: the Responses route now sets Ctx.RawInput, the same way the Messages route does. This is the only change.

What changed

  1. apply/responses.go: bodyResponsesOpts copies norm into a separate slice and sets RawInput on the Ctx.
  2. components/component.go: the RawInput comment now agrees with rawSpanForHash. 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.
  3. New test TestResponsesSetsRawInputBeforeThePipelineRewrites (apply/responses_test.go): a component before the probe rewrites the tool output. RawInput still holds the original text and has the same message count as the normalized input.

How it was tested (eval box, CGO_ENABLED=1)

  • go build ./..., go vet, gofmt -l: clean.
  • The new test fails without the fix: with RawInput: nil on the Responses route, it reports RawInput has 0 messages, want 3.
  • go test ./apply/... ./components/...: pass.
  • go test -race ./apply/... ./components/offload/... ./proxy/...: pass.

Non-blocking note

The message-count shift is now tracked in #454 (count it apart from a stale stash).

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round-2 condition check (head 73d5177) — not a new review round

The round-2 fix is approved. It changes only what round 2 asked for.

  • apply/responses.go now sets Ctx.RawInput. My round-2 probe gives len(RawInput)=3 on Responses (it was 0) and 3 on Messages.
  • TestResponsesSetsRawInputBeforeThePipelineRewrites passes. It checks a positive control: the earlier component did run, and RawInput still holds the original text.
  • The Ctx.RawInput comment now agrees with rawSpanForHash.
  • Eval box: go vet is clean, and go test ./apply/ ./components/... passes. CI build-test was still running when I checked.

One scope note: commit b743110 ("docs: add the eval-box procedure to CLAUDE.md") has nothing to do with this PR. I did not review it as part of #431. Please move it to its own PR, or get the repo owner to accept it here, before merge.

The non-blocking gate-name point from round 2 is now #452.

🤖 Generated with Claude Code

@amiddavid
amiddavid merged commit 76f2cbc into main Oct 11, 2026
4 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 11, 2026
@amiddavid
amiddavid deleted the feat/prefix-hash-followup branch October 11, 2026 11:14
amiddavid added a commit that referenced this pull request Oct 11, 2026
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]>
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.

1 participant