Skip to content

fix(searchfold): reject a fold that shrinks bytes but grows tokens - #336

Closed
OsherElhadad wants to merge 1 commit into
mainfrom
night0928/fixcomp-work
Closed

OsherElhadad wants to merge 1 commit into
mainfrom
night0928/fixcomp-work

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

searchfold's own accept/decline check (adopt(), components/reformat/searchfold.go) only
verified that a fold was byte-shorter and losslessly invertible — never that it was token-shorter.
The pipeline's never-worse guard (components/pipeline.go) compares real BPE token counts, not
bytes, and the two do not move together: replacing a repeated inline path prefix with a heading
line plus tab-indented rows removes bytes but breaks a BPE merge the inline text had. This costs
the most on a heading with only one or two rows under it, where there's nothing to amortize the
heading against.

This is the root cause of searchfold's 384 pipeline-level reverts (0.31% of its 125,427
mutations, the only component in the corpus with any reverts): each is err="" — no panic, no
error — the only remaining path for a Reformat component is the token-based never-worse guard.
adopt() had already accepted a token-losing fold as a byte-shaped win, and the guard had to
reject the whole component run to keep the never-worse contract.

Measured against the production snapshot: of 258,701 message-slots where searchfold was the sole
component to touch that slot, 3,690 (1.43%) came out of the old adopt() with more tokens than
they went in with. The 384 full-request reverts are the tail of this same distribution.

Fix

Add a token check in adopt(), between the (cheap) byte check and the (more expensive)
round-trip-verify, cheapest-first:

if schema.TextTokens(out) >= schema.TextTokens(in) {
    return in, false
}

schema.TextTokens is memoized by content hash, so the added calls are cache hits after the first.
Nothing lost on a revert either way — confirmed, but scoped correctly (an earlier draft of this PR
overclaimed this, caught in review by REV): requests.tokens_before == tokens_after does not
hold on all 384 reverted rows as a blanket check (280/384 match). The 104 mismatches are fully
explained and unrelated to searchfold's own revert — on those rows another component
(textclean, extract, cmdfilter, extract_llm, cachesplit) also mutated the same request, so
the request-level tokens reflect that component's surviving change, not searchfold's reverted
one. Isolating to the 108 of 384 where searchfold was the sole component to touch the request:
tokens_before == tokens_after holds on all 108, zero exceptions. pipeline.go's revert()
restores the pipeline's own pre-searchfold snapshot exactly, which is exactly why the two can
legitimately differ when another component also acted.

Test plan

  • New regression test TestAdoptDeclinesTokenLosingFold, built from a real captured
    tool-result message (testdata/token_regression_capture.txt, generic source code, no
    tenant identity or secrets) where the fold saves 8 bytes but costs 1 token on the real
    o200k_base encoder.
  • All pre-existing searchfold tests pass unchanged; TestMeasureOnRealCaptures's logged
    aggregate (135 real captures: 18.7% overall, 31.9% on the 80 that fold) is identical before
    and after the fix.
  • go test ./components/... — all packages pass.
  • go test -race ./components/... — all packages pass.
  • gofmt -l and go vet ./components/reformat/... — clean.
$ go test ./components/reformat/ -run 'Searchfold|Adopt|Fold|Measure|Shape|Frozen|Routes' -v
--- PASS: TestFoldRoundTripsEveryCapture (0.10s)
--- PASS: TestAdoptDeclinesUnsoundFold (0.00s)
--- PASS: TestAdoptDeclinesTokenLosingFold (0.00s)
--- PASS: TestFoldShapes (0.00s)
--- PASS: TestFrozenPrefixIsByteStable (0.03s)
--- PASS: TestRoutesByContentNotByCommand (0.00s)
--- PASS: TestMeasureOnRealCaptures (0.03s)
--- PASS: TestShapeGateAdmitsEveryFoldableCapture (0.00s)
--- PASS: TestShapeGateRejectsProseAndBuildLogs (0.00s)
--- PASS: TestInPlaceFoldReportsTheSameSavingOnEveryTurn (0.00s)
PASS
ok  	github.com/rossoctl/context-guru/components/reformat	0.194s

$ go test ./components/... 2>&1 | tail -6
ok  	github.com/rossoctl/context-guru/components	0.089s
ok  	github.com/rossoctl/context-guru/components/all	0.171s
ok  	github.com/rossoctl/context-guru/components/dsl	0.007s
ok  	github.com/rossoctl/context-guru/components/offload	14.464s
ok  	github.com/rossoctl/context-guru/components/reformat	10.932s

$ go test -race ./components/... 2>&1 | tail -6
ok  	github.com/rossoctl/context-guru/components	1.460s
ok  	github.com/rossoctl/context-guru/components/all	2.066s
ok  	github.com/rossoctl/context-guru/components/dsl	1.036s
ok  	github.com/rossoctl/context-guru/components/offload	164.887s
ok  	github.com/rossoctl/context-guru/components/reformat	95.780s

Full investigation, including the two other assigned items (format's near-no-op — not a defect,
a denominator artifact from one tenant's un-compactable content — and issue #329's root cause — a
resolved 3-day bootstrap incident, not a live ~4% gap) is at
/home/vpcuser/cg-night-0928/reports2/FIX-comp.md.

adopt() only checked byte length and round-trip losslessness, but the
pipeline's never-worse guard compares real BPE token counts
(components/pipeline.go). The two do not move together: replacing a
repeated inline path prefix with a heading line plus tab-indented rows
removes bytes but breaks a BPE merge the inline text had, and it costs
most on a heading with only one or two rows under it. Byte-only
adoption let 3,690 of 258,701 real fold attempts land a net token
increase, and every one of searchfold's 384 pipeline-level reverts
(err="", the only path left for a Reformat) is this same mismatch
surfacing one level up as a whole-run rollback.

Add a token check between the byte check and the round-trip verify,
cheapest first; schema.TextTokens is memoized by content hash so the
added calls are cache hits after the first. Covered by a new
regression test built from a real captured tool-result message
(testdata/token_regression_capture.txt) where the fold saves 8 bytes
but costs 1 token on the real o200k_base encoder.

Signed-off-by: Osher-Elhadad <[email protected]>

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

Independent review (REV) — PR #336 (fix(searchfold): reject a fold that shrinks bytes but grows tokens)

Reproduced everything below myself: own worktree, own SQL against the read-only snapshot, own
constructed test case beyond the author's fixture. No spend, no writes to the snapshot.

The load-bearing claim — verified exactly

You asked specifically to check "all 384 reverts have err=''" since that's what rules out every
other revert path. Direct query against the snapshot:

SELECT COUNT(*), SUM(err=''), SUM(err!='') FROM request_components
WHERE component='searchfold' AND reverted=1;
-- 384 | 384 | 0

All 384, zero exceptions. Also confirmed searchfold is the only component in the corpus with
any reverted=1 rows at all — matches the PROGRESS.md framing. This fully supports the diagnosis:
no panic, no error, the only remaining path for a Reformat is the pipeline's own token-based
never-worse guard.

The slot-level claim — independently reproduced, exact match, via a different method

Not re-running the fold algorithm — straight SQL against the already-recorded before_tokens/
after_tokens columns (which I confirmed in the #332 review are computed on the full, uncapped
string, unlike before_gz's capped preview — so this is a sound source for this comparison):

SELECT COUNT(*), SUM(after_tokens>before_tokens), MAX(after_tokens-before_tokens)
FROM request_content WHERE components='searchfold';
-- 258701 | 3690 | 35

258,701 sole-toucher slots, 3,690 net token increases, max +35 tokens — matches the PR's
"3,690 of 258,701 (1.43%)... up to +35 tokens" exactly, three-for-three.

Test suite — ran myself, matches claimed output exactly

go test ./components/reformat/... -run 'Searchfold|Adopt|Fold|Measure|...' -v: all pass,
including the logged aggregate (18.7% overall / 31.9% on the 80 that fold) identical to what's
quoted in the PR. go test -race ./components/...: all 5 packages pass (offload 167.6s, reformat
98.7s).

One thing I went looking for and found reachable, but benign in the case I could construct

FoldSearchOutput still picks among its 3 candidate folds by byte length
(len(out) < len(best)), even after this fix. Each individual candidate that clears the new
adopt() is guaranteed token-improving, but if two candidates both clear it for the same input,
the byte-shortest of the two isn't guaranteed to also be the token-shortest. I checked whether this
is reachable: for most shapes only one candidate's shape-gate fires, but a multiple hits in one
file
input ("pkg/a.go:12:foo\npkg/a.go:31:foo\npkg/b.go:7:foo\n") has both HitPath and
HitDir survive adopt() simultaneously. In that specific case the byte-shortest survivor
(HitPath, 38 bytes/20 tokens) was also the token-shortest (HitDir: 43 bytes/23 tokens), so no
actual regression there — but this is a real, reachable multi-candidate case, not a purely
theoretical one, and I didn't exhaustively search for a case where the two diverge. Not
blocking
— every survivor is still strictly better than the original in both bytes and tokens, so
the never-worse contract holds regardless of which survivor wins; this is at most a "could pick a
slightly-less-optimal-but-still-good candidate" residual, several notches lower severity than the
bug this PR fixes. Worth a one-line note in a future pass (compare tokens, not bytes, when more
than one candidate survives) but I wouldn't hold this PR for it.

Not independently re-verified (time-scoped, flagging rather than silently skipping)

Spot-checked the report's other two assigned items (format's near-no-op characterization, #329's
root cause) for internal consistency — they read soundly and the format-slot numbers quoted
(4,809 slots / 15.7M→15.5M tokens / 1.33%) look like a plausible, specific measurement rather than
a hand-waved estimate — but I did not re-derive either from the snapshot myself. Neither is part of
this PR's code diff (both are investigative findings in the report, not searchfold.go), so I
scoped my verification budget to the actual code change and its two headline claims (both now
independently confirmed above). Happy to go deeper on either if wanted.

Verdict

Passes. Root-caused correctly (the never-worse guard was working as designed; the defect was
one level down, in adopt()'s own byte-only accept condition), minimal fix, ordered cheapest-first
as claimed, both headline numbers (384/err="" and 3,690/258,701) independently reproduced exactly
via methods that don't reuse any of the author's own scripts, full test suite and -race clean.

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

Follow-up: the "tokens_before == tokens_after on all 384" claim is imprecisely worded (the

underlying fact is true, verified below) — plus a benchmark for the latency question

The orchestrator specifically flagged two things worth double-checking on the actual revert
mechanism, so I did both.

"Nothing lost on revert" — true, but not literally at the whole-request level as worded

Checking requests.tokens_before == tokens_after across all 384 reverted rows directly:

SELECT COUNT(*), SUM(tokens_before=tokens_after), SUM(tokens_before!=tokens_after)
FROM request_components rc JOIN requests r ON r.id=rc.request_id
WHERE rc.component='searchfold' AND rc.reverted=1;
-- 384 | 280 | 104

104 of 384 do NOT match this literal check. Before flagging this as a real defect, I checked
why: for every one of those 104, at least one other component (textclean, extract,
cmdfilter, extract_llm, cachesplit) also mutated/acted on the same request —
independent, legitimate token reductions unrelated to searchfold's reverted attempt. Isolating to
requests where searchfold was the sole actor (no other component touched anything):

-- 108 of the 384 reverts had searchfold as the sole actor on their request
-- of those 108: tokens_before == tokens_after on ALL 108, zero exceptions

So the underlying claim is correct once properly scoped — searchfold's own revert loses nothing —
but "confirmed... on all 384 affected rows" is not literally true and would fail exactly the check
I ran first, which is the check any reader would naturally try. Recommend rewording to something
like "on the 108 of 384 where searchfold was the sole actor (the only clean way to isolate its
effect at the request level, since a reverted component leaves no request_content row of its
own — confirmed: 0 rows anywhere in the corpus name searchfold among the components of a
message on one of these 384 requests)."

Separately, I read components/pipeline.go's runOne directly rather than trusting the "restores
the snapshot exactly" claim: revert := func() { req.Input = before; *snap = schema.CloneMessages(before) } — before is the deep-cloned pre-component snapshot taken at
entry. This is an exact, unconditional restore, independent of the token-count question above.
That half of the claim holds cleanly at the code level.

Latency on the hot path — benchmarked, not assumed

BenchmarkAdoptFoldHitDir-16                                37,631 ns/op   (full adopt() call)
BenchmarkTextTokensColdVsWarm/cold_each_iter-16              3,461 ns/op   (uncached BPE encode)
BenchmarkTextTokensColdVsWarm/warm_same_content-16             379 ns/op   (memoized cache hit)

Worst case (both TextTokens(in) and TextTokens(out) cold on the very first candidate) adds
~6.9µs to a ~37.6µs adopt() call — real but small (≈18%), and FoldSearchOutput reuses the same
in across up to 3 candidates plus repeated turns on the same content, so it's a cache hit for
every call after the first in practice (confirmed the memoization is real: warm calls are ~9x
faster than cold). Nowhere near a latency concern next to the actual network/LLM-call cost this
sits inside.

Neither of these changes my verdict — still passes — but the wording nit is worth fixing before
merge since it's the kind of claim that looks alarming on a literal re-check (as it did to me for
about five minutes) until you find the actual explanation.

@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Fixed the overclaim REV caught: the PR description and reports2/FIX-comp.md now say the
tokens_before==tokens_after check holds on the 108 of 384 rows where searchfold was the sole
mutating component (verified: 108/108, zero exceptions), not on all 384 blanket. The 104 mismatches
among the other rows are other components (textclean, extract, cmdfilter, extract_llm, cachesplit)
also mutating the same request — unrelated to searchfold's own revert correctness, exactly as REV
found. Re-verified both counts (280/104 split, 108-of-384 sole-actor subset, 108/108 clean) directly
against the snapshot before editing. The diagnosis, fix, and test plan are unchanged.

@amiddavid

Copy link
Copy Markdown
Collaborator

Closing: #746 already fixed this on main. Thank you for finding the root cause of searchfold's reverts.

Since #746 (merged as d08eff8), FoldSearchOutput starts from the input's own token count. A fold wins only when it has fewer tokens than the input, or equal tokens and fewer bytes. So a fold that shrinks bytes but grows tokens is never adopted, which is the case this PR found. #750 ported this PR onto main, and its review showed that the check in adopt() would change no behavior. Both PRs are now closed.

@amiddavid amiddavid closed this Oct 27, 2026
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 27, 2026
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.

2 participants