Skip to content

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

Closed
amiddavid wants to merge 2 commits into
mainfrom
fix/glm-searchfold-adopt
Closed

amiddavid wants to merge 2 commits into
mainfrom
fix/glm-searchfold-adopt

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

Supersedes #336. This PR ports #336 by Osher Elhadad (OsherElhadad) onto current
main, after #746 landed. Written by GLM through Claude Code.

adopt() in components/reformat/searchfold.go accepted a fold that was byte-shorter
but token-longer. The pipeline's never-worse guard counts tokens, not bytes, so it
reverted the whole searchfold run on such a request. The PR body of #336 ties all 384 of
searchfold's pipeline-level reverts to this mismatch.

#746 changed only how FoldSearchOutput PICKS between surviving folds, by tokens. It did
not change adopt(). Both changes are needed and now work together.

What changed

  • Commit 536a90d is Osher's commit 4af2d52, cherry-picked unchanged: a token check in
    adopt(), between the byte check and the round-trip verify, cheapest first. Plus the
    regression test TestAdoptDeclinesTokenLosingFold and its real captured input
    testdata/token_regression_capture.txt.
  • Commit f7370d2 (mine) resolves the conflict with fix: nine small fixes (#328 #339 #166 #461 #610 #198 #452 #207 #174) #746's token-ranked pick. After the
    cherry-pick, adopt() counted a candidate's tokens and the pick in FoldSearchOutput
    counted the SAME output again. adopt() now returns the token count it already
    computed, and the pick reuses it: one estimate per candidate, not two. The stale pick
    comment ("adopt itself never counts tokens") is gone. No behavior change: the checks
    and their order are exactly what 4af2d52 introduced.

How it was tested

Box run Tree Command Result
Fail-on-main proof clean origin/main + #336's test only go test ./components/reformat/ -run TestAdoptDeclinesTokenLosingFold FAIL: adopted a token-losing fold: 615 -> 616 tokens
Targeted tests this branch go test ./components/reformat/ -run "Searchfold|Adopt|Fold|Measure|Shape|Frozen|Routes|Pick" -v PASS, all
#746's pick test this branch TestThePickBetweenSurvivorsJudgesTokensNotBytes (in the run above) PASS
Measure aggregate this branch TestMeasureOnRealCaptures (in the run above) PASS, 18.7% overall / 31.9% on folded — same as before
gofmt / vet this branch gofmt -l components/reformat/; go vet ./components/reformat/ clean / clean
Full race suite this branch go test -race ./components/reformat/... (detached) PASS, rc=0

Data dependence

None changes. The token check estimates the message's own text in memory, the same way
the existing min_tokens gate does. Nothing new is stored.

Skipped

Nothing. The batch was the single PR port.

Ported from #336 by Osher Elhadad (OsherElhadad). The owner closes #336; this PR only
supersedes it.

🤖 Generated with Claude Code

Osher-Elhadad and others added 2 commits October 27, 2026 13:53
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]>
(cherry picked from commit 4af2d52)
Signed-off-by: DAVID AMID <[email protected]>
Port of #336 met #746's token-ranked pick: adopt() now counts each
candidate's tokens for its never-worse check, and FoldSearchOutput's
pick counted the SAME output again to rank survivors. One candidate,
two estimates.

adopt() now returns the token count it already computed, and the pick
reuses it. The stale pick comment ("adopt itself never counts tokens")
is gone, and TestThePickBetweenSurvivorsJudgesTokensNotBytes reuses the
returned counts instead of re-estimating both survivors.

No behavior change: the checks and their order (bytes, tokens,
round-trip) are exactly what 4af2d52 introduced.

Written by GLM through Claude Code.

Assisted-By: GLM
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 f7370d2319fd approve

Verdict: approve

Findings

None. The change is correct and I could not break it.

Non-blocking

  • components/reformat/searchfold.go:202 — adopt counts tokens on out before the inverse check. A candidate that shrinks bytes but fails the round-trip now pays one BPE encode it did not pay before. I measured this on the captured corpus: 1 extra encode in 128 byte-shrinking candidates. Negligible. Moving the token check after the inverse check would make it zero, with identical semantics.
  • components/reformat/searchfold_test.go:83 — the regression test has a margin of one token (615 → 616). It also depends on the real o200k_base tokenizer being live: under the chars/4 fallback in internal/tokens/tokens.go:91, the counts become 571 → 569 and adopt would accept the fold, so the test fails loudly. That is the right failure direction, and the fallback fires only when tokenizer init fails. Note only.
  • components/reformat/testdata/token_regression_capture.txt — this is real production tool-result content in an open-source repo. testdata/search_output.json sets the same precedent, so I assume it is cleared. Confirm if in doubt.

What I checked

  • Read the full diff (both commits) and all of components/reformat/searchfold.go.
  • Verified the fix's premise. The never-worse guard at components/pipeline.go:190 compares total request tokens and reverts the whole component run, exactly as the new comment claims. So a per-message token-losing fold could previously cost every other message's fold in the same run.
  • Verified the fix closes the hole. adopt now requires a strict token decrease per message, and the guard sums schema.MessageText per message — the same strings adopt counts. So a searchfold run can no longer grow the total. adopt and the guard share one estimator, so they cannot disagree.
  • Verified the new test's numbers independently. Live Go tests are not approved, so I re-implemented foldHitPath, foldHitDir, foldPathList and both inverses in Python and ran them on the capture with the same o200k_base encoding:
    • input: 2281 bytes, 615 tokens;
    • foldHitDir: 2273 bytes, 616 tokens — byte win, token loss, declined on tokens;
    • foldHitPath: token win (608) but the round-trip fails (the === banner line is mis-consumed as a heading), declined;
    • foldPathList: no fold;
    • so FoldSearchOutput returns the input unchanged — both test assertions hold.
  • Re-ran every existing searchfold test expectation through the same harness under the new rule: all 7 TestFoldShapes cases match, the sound fold in TestAdoptDeclinesUnsoundFold is still adopted (16 → 12 tokens), TestRoutesByContentNotByCommand still folds the hit list (381 → 221 tokens) and not the prose, and TestThePickBetweenSurvivorsJudgesTokensNotBytes still has both survivors with the claimed divergence. On the 135-capture corpus: 35,691 → 29,013 tokens, 80 outputs fold, 0 round-trip failures, 0 growth — TestFoldRoundTripsEveryCapture and TestMeasureOnRealCaptures hold.
  • Checked the callers. adopt has exactly two call sites (the pick and the tests); both were updated. Nothing else uses the old signature.
  • Checked the fallback path. If the tokenizer fails to init, tokens.Count falls back to chars/4, which tracks bytes — adopt then behaves like the old byte rule, and the pipeline guard uses the same estimate, so no fail-open break.
  • Checked data dependence. docs/data-dependence.md:182 — searchfold keeps nothing, unchanged by this PR. No doc update needed.
  • Checked cache stability. The token check is a pure function of the message text and the same tokenizer, so the fold stays deterministic per text across turns. The one-time deploy transition (a message that used to fold now may not) is inherent to any fold-rule change, not a defect of this one.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 f7370d2319fd approve

Verdict: approve

Findings

None. The change is sound:

  • adopt now declines a fold that does not shrink tokens (searchfold.go:202). Each folded message strictly loses tokens, and the never-worse guard (components/pipeline.go:191) sums the same tokens.Count over the same MessageText strings, so searchfold can no longer trip that guard. Fail-open is untouched: a decline returns the input unchanged.
  • The token count adopt returns is the same schema.TextTokens(out) value the pick used to recompute (memoized by content hash), so commit 2 is a pure refactor. The pick's byte tie-break stays reachable between two survivors with equal tokens.
  • Order of checks (bytes, tokens, round-trip) keeps losslessness by construction: the inverse verify still runs before any adoption.

Non-blocking

  • searchfold.go:202 — outTokens >= TextTokens(in) also declines token-equal folds, not only token-growing ones. The commit title and the comment say "grows tokens". Before this PR, a fold with equal tokens and fewer bytes was adopted through the pick's tie-break. It saved 0 tokens (tokens are the billed quantity), so nothing real is lost, and the type doc already says "smaller in tokens". But the equal case is the one behavior change versus base, and no test pins it.
  • searchfold.go:186-191 — the comment presents the 384 pipeline-level reverts as something adopt's byte-only acceptance causes on current code. It cannot: base d08eff8b (#746) already put the token-ranked pick in FoldSearchOutput, and that pick declined every token-growing fold. The reverts belong to pre-#746 code (commit 2 itself says "Port of #336 met #746's token-ranked pick"). The adopt-level check is still worth having — it makes the adopt contract itself never-worse for any future caller — but the comment can mislead a reader about main.
  • searchfold.go:198-207 — the token count now runs before the round-trip verify, so a byte-winning candidate that fails the inverse pays a BPE encode it did not pay before. Fresh fold outputs never hit the memo. One encode per such candidate, three candidates at most; negligible next to the fold's own full-string pass.

What I checked

  • Full diff d08eff8b..HEAD, and each commit alone (536a90d adds the check, f7370d2 shares the count; no semantic drift between them).
  • FoldSearchOutput and adopt callers: adopt is package-private, used only by FoldSearchOutput and the tests. No other Go caller of FoldSearchOutput exists, so no other component changes behavior.
  • The guard alignment: pipeline.tokensOf → schema.MessagesTokens → tokens.Count(MessageText(m)), the same function and strings adopt compares, so per-message strict decrease implies whole-request decrease. Rewritable/SetMessageText keep MessageText(after) == out, so the counts the pick sees are the counts the guard sees.
  • The new test data, traced by hand: foldHitDir folds the first two substrates/blis_plan.py: rows into a substrates/ heading plus tab rows (~8-byte win, matching the comment), the round-trip holds, and the remaining 294- context lines pass through and reset the heading state.
  • Tests updated coherently: TestAdoptDeclinesUnsoundFold still exercises the inverse check behind the new token check; TestThePickBetweenSurvivorsJudgesTokensNotBytes reuses the returned counts and its scenario guards still hold; the corpus tests (TestFoldRoundTripsEveryCapture, TestMeasureOnRealCaptures) are unaffected in token terms, because the only newly declined folds (token-equal) contributed 0 to the measured reduction.
  • Data dependence: unchanged, searchfold stays "none" in docs/data-dependence.md; no storage or marker change, so no row update is due.
  • Limitation: live tests were not approved and Go is not on this machine, so I did not execute the test suite. TestAdoptDeclinesTokenLosingFold's numbers (615 -> 616 tokens, 2281 -> 2273 bytes) and its second assertion (which also needs foldHitPath to not win on tokens for this capture) are data-dependent on the embedded o200k_base tokenizer; I verified them by reading, not by running.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Closing: #746 already fixed this on main.

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, and searchfold no longer trips the never-worse guard. GLM reviewer 2 found this in the review of this PR.

This PR would add the same token check inside adopt(). Today FoldSearchOutput is its only caller, so that changes no behavior. The only other effect is to reject token-equal folds, which save 0 tokens.

@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
@amiddavid
amiddavid deleted the fix/glm-searchfold-adopt branch October 27, 2026 12:29
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