Repository navigation
fix(searchfold): reject a fold that shrinks bytes but grows tokens - #336
OsherElhadad wants to merge 1 commit into
Conversation
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
left a comment
There was a problem hiding this comment.
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 | 0All 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 | 35258,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
left a comment
There was a problem hiding this comment.
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 | 104104 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 exceptionsSo 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.
|
Fixed the overclaim REV caught: the PR description and reports2/FIX-comp.md now say the |
|
Closing: #746 already fixed this on main. Thank you for finding the root cause of searchfold's reverts. Since #746 (merged as d08eff8), |
Summary
searchfold's own accept/decline check (adopt(),components/reformat/searchfold.go) onlyverified 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, notbytes, 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,427mutations, the only component in the corpus with any reverts): each is
err=""— no panic, noerror — the only remaining path for a
Reformatcomponent is the token-based never-worse guard.adopt()had already accepted a token-losing fold as a byte-shaped win, and the guard had toreject the whole component run to keep the never-worse contract.
Measured against the production snapshot: of 258,701 message-slots where
searchfoldwas the solecomponent to touch that slot, 3,690 (1.43%) came out of the old
adopt()with more tokens thanthey 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:
schema.TextTokensis 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_afterdoes nothold 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, sothe request-level tokens reflect that component's surviving change, not
searchfold's revertedone. Isolating to the 108 of 384 where
searchfoldwas the sole component to touch the request:tokens_before == tokens_afterholds on all 108, zero exceptions.pipeline.go'srevert()restores the pipeline's own pre-
searchfoldsnapshot exactly, which is exactly why the two canlegitimately differ when another component also acted.
Test plan
TestAdoptDeclinesTokenLosingFold, built from a real capturedtool-result message (
testdata/token_regression_capture.txt, generic source code, notenant identity or secrets) where the fold saves 8 bytes but costs 1 token on the real
o200k_base encoder.
searchfoldtests pass unchanged;TestMeasureOnRealCaptures's loggedaggregate (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 -landgo vet ./components/reformat/...— clean.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.