Repository navigation
fix(chunker): decide token merge on running sum, not re-tokenized join - #17948
Conversation
The TokenChunker merge decision used tokenizeStr(joined) — re-tokenizing
the whole joined chunk text — to decide whether to merge the next unit.
Because BPE tokenization (cl100k_base) is non-additive across the "\n"
join separator, this count disagreed with Python's merge decision, which
accumulates a running sum of per-unit token counts (size("\n" + sub_sec) in
rag/nlp/__init__.py:_merge_paragraph_groups and tk_nums += current["tk_nums"]
in rag/flow/chunker/token_chunker.py:_merge_text_chunks_by_token_size).
The disagreement shifted every downstream chunk boundary by a line and,
on a small enough budget, changed the chunk count (e.g. Go emitted 8
chunks where Python emitted 9 for a 29-line text at chunk_token_size=32).
Fix mergeDecision to decide on the running sum of per-unit token counts
(prevTokens + incomingTokens). Both callers now maintain and pass that
running sum (tkns in the text path, prev.TKNums in the JSON path),
matching Python's per-paragraph size() sum.
Add TestTokenChunkerMergeMatchesPython which pins the text-path merge
against a Python oracle (running sum, OVER_CAP) for two budgets, asserting
chunk count and per-chunk text. Update three existing tests that pinned the
old re-tokenized (under-packed) boundaries to their Python-faithful
expectations.
Co-Authored-By: CodeBuddy <[email protected]>
📝 WalkthroughWalkthrough
ChangesToken merge accounting parity
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
- Add TestPythonMergeGroupsOracleSanity: validate the parity oracle itself via tokenizer-independent invariants so it cannot drift in lock-step with the chunker under test. - Add TestMergeDecisionOverCapVsUnderCapBoundary: pin the semantic difference between OVER_CAP (merge-then-close) and UNDER_CAP (start-new-chunk) at the exact running-sum boundary, restoring the strong 'toggle is live' constraint that the weakened integration assertion lost. - Add TestMergeByTokenSizeFromJSON_TKNumsConsistency (overlap 0/30): first coverage of the JSON merge path with overlap > 0, pinning the TKNums accounting (running sum on the merge path, re-tokenized text on the boundary path). - Document the residual JSON OVER_CAP vs Python prev_tk_nums>threshold strategy difference and the mixed TKNums caliber in token.go. Verified: go test ./internal/ingestion/component/chunker/... passes (176 tests, 0 failures).
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/ingestion/component/chunker/token_merge_parity_test.go`:
- Around line 133-167: Update the oracle in the token-merge parity test to match
mergeByTokenSize behavior: exclude empty paragraphs when building the expected
flattened output and comparisons, and require every group containing a paragraph
whose token count exceeds cap to contain exactly one paragraph. Retain the
existing non-empty-group and token-cap validations for all other groups.
In `@internal/ingestion/component/chunker/token_strict_cap_test.go`:
- Around line 385-391: Add a focused assertion beside the existing
schema.MergeOverCap check in the current test, calling mergeDecision with
schema.MergeUnderCap and the same oversized target+5 incoming size, and verify
it returns startNewChunk.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8793e9cf-de4f-43f2-9dfd-091c9c0e8ab2
📒 Files selected for processing (4)
internal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_json_overlap_test.gointernal/ingestion/component/chunker/token_merge_parity_test.gointernal/ingestion/component/chunker/token_strict_cap_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/ingestion/component/chunker/token.go
… tests - Make pythonMergeGroups drop empty/whitespace paragraphs like the Python caller (rag/nlp:1403) and the Go chunker (token.go:703); compare the oracle-sanity test against the non-empty partition and assert oversized paragraphs stand alone. - Assert oversized-unit isolation for MergeUnderCap in the boundary test (previously only MergeOverCap was checked).
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/ingestion/component/chunker/token_merge_parity_test.go`:
- Around line 150-159: Add a whitespace-only paragraph such as " \t " between
retained paragraphs in the sanity input used by the token merge parity test.
Keep the existing strings.TrimSpace filtering in the oracle and verify the
expected output excludes the whitespace-only fragment while preserving the
remaining paragraphs’ order.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f6c8fac7-68d7-4335-8b20-1d0702492aa4
📒 Files selected for processing (2)
internal/ingestion/component/chunker/token_merge_parity_test.gointernal/ingestion/component/chunker/token_strict_cap_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/ingestion/component/chunker/token_strict_cap_test.go
| // Python (rag/nlp:1403) and the Go chunker (token.go:703) drop | ||
| // empty/whitespace-only fragments, so the oracle does too. Compare | ||
| // against the non-empty partition of the input rather than `in`. | ||
| var nonEmpty []string | ||
| for _, p := range in { | ||
| if strings.TrimSpace(p) == "" { | ||
| continue | ||
| } | ||
| nonEmpty = append(nonEmpty, p) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add a whitespace-only paragraph to the sanity inputs.
The test covers "" but does not cover " \t ". Line 155 uses strings.TrimSpace, so add a whitespace-only paragraph between retained paragraphs. Verify that the oracle drops it and preserves the remaining order.
As per coding guidelines, “Preserve valid behavior with focused tests.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ingestion/component/chunker/token_merge_parity_test.go` around lines
150 - 159, Add a whitespace-only paragraph such as " \t " between retained
paragraphs in the sanity input used by the token merge parity test. Keep the
existing strings.TrimSpace filtering in the oracle and verify the expected
output excludes the whitespace-only fragment while preserving the remaining
paragraphs’ order.
Source: Coding guidelines
|
LGTM |
- mergeUnits: add a re-tokenize guard before accepting a merge. joinSep (e.g. "\n" on the JSON path) can add tokens beyond the running sum, so the emitted text of a merge the running sum deems safe could exceed target. The guard re-checks tokenizeStr(candidate) and starts a fresh chunk when the joined text itself exceeds target; the running-sum decision and bookkeeping stay unchanged (Python parity infiniflow#17948), so this only tightens the hard cap. - overlapTailPositions: measure item spans on the TAG-FREE visible text so offsets line up with overlapCut/overlapFitPrefix; a coordinate tag in an earlier item no longer shifts later items' boundaries (overlap no longer pulls head coordinates into the tail highlight). - splitOversizedText: the all-whitespace branch now hard-splits a whitespace-only unit whose token count exceeds the target instead of emitting it as a single over-cap chunk. - goMergeGroupsOracle: document that whitespace exactness is outside the oracle's contract (pinned by token_oversize_split_test.go and token_overlap_test.go). Tests: - TestMergeUnits_JoinSepAddsTokens: running sum fits but joined text (with "\n") exceeds target -> 2 chunks; plus a matching oracle case "joinsep guard fires on actual joined text". - TestOverlapTailPositions_VisibleTextOffsets: tagged item must not pull head coordinates into the overlap tail. - TestExpandOversizedUnits_AllWhitespaceOverCap: whitespace-only unit over cap is hard-split (lossless). - token_pdfpos_test.go: the partial-overlap fixture declared TKNums=1 for 5-rune texts; the guard (which validates actual token counts) correctly exposed the mismatch. Switched to single-token texts with a target of 9 (5 item tokens + 4 joinSep tokens) so the 5-merge/partial-overlap scenario the test pins stays intact.
Summary
The Go
TokenChunkermerge decision usedtokenizeStr(joined)— re-tokenizing the entire joined chunk text — to decide whether to merge the next unit. Because BPE tokenization (cl100k_base) is non-additive across the"\n"join separator, this count disagreed with Python's merge decision, which accumulates a running sum of per-unit token counts:rag/nlp/__init__.py:_merge_paragraph_groups→size("\n" + sub_sec)rag/flow/chunker/token_chunker.py:_merge_text_chunks_by_token_size→tk_nums += current["tk_nums"]The disagreement shifted every downstream chunk boundary by a line and, on a tight budget, changed the chunk count (e.g. Go emitted 8 chunks where Python emitted 9 for a 29-line text at
chunk_token_size=32).Fix
mergeDecisionnow decides on the running sum of per-unit token counts (prevTokens + incomingTokens) instead oftokenizeStr(joined). Both callers maintain and pass that running sum:tknsslice (per-paragraphtokenizeStr("\n" + sub_sec))prev.TKNums(upstreamtk_numsaccumulated via+=)The joined text is still returned as the merged content; only the decision metric changed.
Tests
TestTokenChunkerMergeMatchesPython— pins the text-path merge against a Python oracle (running sum, OVER_CAP) for two budgets (32,128), asserting both chunk count and per-chunk text. Was RED (Go 8 vs Python 9) before the fix, now GREEN.TestMergeByTokenSizeFromJSON_StrictCapNoOvershoot,TestMergeByTokenSize_UnderCapNoOverflow,TestMergeByTokenSizeFromJSON_OverlapStripsTags. Their original intent (strict-cap bound,under_captoggle liveness, overlap tag-stripping) is preserved.Verified the new boundaries against real Python/tiktoken: the running-sum produces Python's exact chunking for all four inputs.
Impact / follow-up
This is the root cause behind the two golden-parity
go_bugrulestoken-over-segmentation-long-inputandtoken-default-delim-content-mismatch. The text path now matches Python exactly. The golden-parity branch (fix/chunker-parity-infra, with itsknown_diffs.jsonratchet) should be re-run; these rules are expected to resolve, and any residual JSON-path boundary shift must be re-ratchet'd there. I could not run that harness in this environment because its fixtures live on a separate branch.Note: the JSON path keeps the
OVER_CAPstrategy (merge-then-close) rather than Python's JSONprev_tk_nums > thresholddecision; that is a pre-existing, separate strategy difference not addressed by this counting fix.