Skip to content

fix(chunker): decide token merge on running sum, not re-tokenized join - #17948

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:fix/chunker-merge-running-sum
Aug 7, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:fix/chunker-merge-running-sum

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

The Go TokenChunker merge decision used tokenizeStr(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

mergeDecision now decides on the running sum of per-unit token counts (prevTokens + incomingTokens) instead of tokenizeStr(joined). Both callers maintain and pass that running sum:

  • text path: tkns slice (per-paragraph tokenizeStr("\n" + sub_sec))
  • JSON path: prev.TKNums (upstream tk_nums accumulated via +=)

The joined text is still returned as the merged content; only the decision metric changed.

Tests

  • Add 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.
  • Update three existing tests that pinned the old re-tokenized (under-packed) boundaries to their Python-faithful expectations: TestMergeByTokenSizeFromJSON_StrictCapNoOvershoot, TestMergeByTokenSize_UnderCapNoOverflow, TestMergeByTokenSizeFromJSON_OverlapStripsTags. Their original intent (strict-cap bound, under_cap toggle 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_bug rules token-over-segmentation-long-input and token-default-delim-content-mismatch. The text path now matches Python exactly. The golden-parity branch (fix/chunker-parity-infra, with its known_diffs.json ratchet) 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_CAP strategy (merge-then-close) rather than Python's JSON prev_tk_nums > threshold decision; that is a pre-existing, separate strategy difference not addressed by this counting fix.

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]>
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 6, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

TokenChunker now makes merge decisions from accumulated per-unit token counts. Text and JSON paths maintain these counts. Tests cover Python parity, overlap accounting, and strict-cap behavior.

Changes

Token merge accounting parity

Layer / File(s) Summary
Running token-count merge logic
internal/ingestion/component/chunker/token.go
mergeDecision uses previous and incoming token counts. Text and JSON merge paths accumulate counts instead of retokenizing joined text.
Python merge parity validation
internal/ingestion/component/chunker/token_merge_parity_test.go
A Python-compatible merge oracle compares exact chunk text and chunk counts for token budgets 32 and 128.
Overlap and strict-cap behavior
internal/ingestion/component/chunker/token_batch1_test.go, internal/ingestion/component/chunker/token_json_overlap_test.go, internal/ingestion/component/chunker/token_strict_cap_test.go
Tests cover running-sum budgets, JSON TKNums accounting, overlap propagation, and OVER_CAP versus UNDER_CAP behavior.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

  • infiniflow/ragflow#17202 — The issue concerns token chunk merging with projected or running token counts, overlap, and oversized-unit boundary behavior.

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: yingfeng, yuzhichang, jinhai-cn

Poem

I count each token, one by one,
Python parity now is done.
Caps and overlaps hold their line,
JSON counts stay well-defined.
Hop, hop—clean chunks shine!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: using running token sums for merge decisions.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, fix, tests, impact, and follow-up.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@xugangqiang xugangqiang added the ci Continue Integration label Aug 6, 2026
@xugangqiang
xugangqiang marked this pull request as draft August 6, 2026 10:53
- 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).
@xugangqiang
xugangqiang marked this pull request as ready for review August 6, 2026 12:17
@xugangqiang xugangqiang added ci Continue Integration and removed ci Continue Integration labels Aug 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4fce7dd and b49241d.

📒 Files selected for processing (4)
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_json_overlap_test.go
  • internal/ingestion/component/chunker/token_merge_parity_test.go
  • internal/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).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between b49241d and 728cec5.

📒 Files selected for processing (2)
  • internal/ingestion/component/chunker/token_merge_parity_test.go
  • internal/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

Comment on lines +150 to +159
// 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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 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

@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@yuzhichang
yuzhichang merged commit cdef804 into infiniflow:main Aug 7, 2026
3 checks passed
@xugangqiang
xugangqiang deleted the fix/chunker-merge-running-sum branch August 7, 2026 12:27
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 20, 2026
- 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants