Repository navigation
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]> (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
left a comment
There was a problem hiding this comment.
| 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—adoptcounts tokens onoutbefore 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 thechars/4fallback ininternal/tokens/tokens.go:91, the counts become 571 → 569 andadoptwould 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.jsonsets 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:190compares 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.
adoptnow requires a strict token decrease per message, and the guard sumsschema.MessageTextper message — the same stringsadoptcounts. So a searchfold run can no longer grow the total.adoptand 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,foldPathListand 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
FoldSearchOutputreturns the input unchanged — both test assertions hold.
- Re-ran every existing searchfold test expectation through the same harness under the new rule: all 7
TestFoldShapescases match, the sound fold inTestAdoptDeclinesUnsoundFoldis still adopted (16 → 12 tokens),TestRoutesByContentNotByCommandstill folds the hit list (381 → 221 tokens) and not the prose, andTestThePickBetweenSurvivorsJudgesTokensNotBytesstill 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 —TestFoldRoundTripsEveryCaptureandTestMeasureOnRealCaptureshold. - Checked the callers.
adopthas 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.Countfalls back tochars/4, which tracks bytes —adoptthen 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
left a comment
There was a problem hiding this comment.
| 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:
adoptnow 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 sametokens.Countover the sameMessageTextstrings, so searchfold can no longer trip that guard. Fail-open is untouched: a decline returns the input unchanged.- The token count
adoptreturns is the sameschema.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: based08eff8b(#746) already put the token-ranked pick inFoldSearchOutput, 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 theadoptcontract 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). FoldSearchOutputandadoptcallers:adoptis package-private, used only byFoldSearchOutputand the tests. No other Go caller ofFoldSearchOutputexists, so no other component changes behavior.- The guard alignment:
pipeline.tokensOf→schema.MessagesTokens→tokens.Count(MessageText(m)), the same function and stringsadoptcompares, so per-message strict decrease implies whole-request decrease.Rewritable/SetMessageTextkeepMessageText(after) == out, so the counts the pick sees are the counts the guard sees. - The new test data, traced by hand:
foldHitDirfolds the first twosubstrates/blis_plan.py:rows into asubstrates/heading plus tab rows (~8-byte win, matching the comment), the round-trip holds, and the remaining294-context lines pass through and reset the heading state. - Tests updated coherently:
TestAdoptDeclinesUnsoundFoldstill exercises the inverse check behind the new token check;TestThePickBetweenSurvivorsJudgesTokensNotBytesreuses 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,
searchfoldstays "none" indocs/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 needsfoldHitPathto not win on tokens for this capture) are data-dependent on the embedded o200k_base tokenizer; I verified them by reading, not by running.
|
Closing: #746 already fixed this on main. Since #746 (merged as d08eff8), This PR would add the same token check inside |
Summary
Supersedes #336. This PR ports #336 by Osher Elhadad (OsherElhadad) onto current
main, after #746 landed. Written by GLM through Claude Code.
adopt()incomponents/reformat/searchfold.goaccepted a fold that was byte-shorterbut 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
FoldSearchOutputPICKS between surviving folds, by tokens. It didnot change
adopt(). Both changes are needed and now work together.What changed
adopt(), between the byte check and the round-trip verify, cheapest first. Plus theregression test
TestAdoptDeclinesTokenLosingFoldand its real captured inputtestdata/token_regression_capture.txt.cherry-pick,
adopt()counted a candidate's tokens and the pick inFoldSearchOutputcounted the SAME output again.
adopt()now returns the token count it alreadycomputed, 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
origin/main+ #336's test onlygo test ./components/reformat/ -run TestAdoptDeclinesTokenLosingFoldadopted a token-losing fold: 615 -> 616 tokensgo test ./components/reformat/ -run "Searchfold|Adopt|Fold|Measure|Shape|Frozen|Routes|Pick" -vTestThePickBetweenSurvivorsJudgesTokensNotBytes(in the run above)TestMeasureOnRealCaptures(in the run above)gofmt -l components/reformat/;go vet ./components/reformat/go test -race ./components/reformat/...(detached)Data dependence
None changes. The token check estimates the message's own text in memory, the same way
the existing
min_tokensgate 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