Skip to content

fix(chunker): JSON path merges globally and keeps over-budget items whole - #17739

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
xugangqiang:fix/chunker-json-global-merge
Aug 3, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
xugangqiang:fix/chunker-json-global-merge

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Fixes two TokenChunker json-path over-segmentation bugs that diverge from Python's rag/app chunkers (tracked as go_bug known-diffs).

1. token-json-per-item-merge

Python's _merge_text_chunks_by_token_size merges adjacent text chunks across JSON items into one global token budget. Go merged within each item separately, emitting one chunk per item (2 items that jointly fit the budget → 2 chunks instead of 1). invokeJSONPayload now flattens the per-item structure into a single sequence before mergeByTokenSizeFromJSON, so a multi-item document is merged globally like Python.

2. token-json-single-item-oversize

Python's json path keeps a single item that exceeds chunk_token_size whole; Go sub-split it via splitOversizedUnit. mergeByTokenSizeFromJSON gains a subSplitOversize flag — the json path passes false (no sub-split), the text path passes true (keeps matching Python's _split_oversized_unit).

Changes

  • token.go: flatten-then-global-merge in invokeJSONPayload; subSplitOversize flag on mergeByTokenSizeFromJSON.
  • Test call sites updated for the new signature (true for text-path simulations).

Test plan

bash build.sh --test ./internal/ingestion/component/chunker/... — green, including the two new self-contained tests TestJSONGlobalMergeMatchesPython and TestJSONSingleItemNotSubSplitMatchesPython (drive NewTokenChunker directly, no .venv, default unit tier).

Note

Follow-up: the known_diffs.json rules token-json-per-item-merge and token-json-single-item-oversize (in the parity-infra PR #17735) should be removed once this lands. This PR is independent of #17729 / #17735; based on upstream/main.

…hole

Two TokenChunker json-path over-segmentation bugs, both diverging from
Python's rag/app chunkers:

1. token-json-per-item-merge (known_diff): Python's
   _merge_text_chunks_by_token_size merges adjacent text chunks across JSON
   items into one global token budget, but Go merged within each item
   separately (one chunk per item). invokeJSONPayload now flattens the
   per-item structure into a single sequence before mergeByTokenSizeFromJSON,
   so a multi-item document is merged globally like Python (e.g. two items
   that jointly fit the budget collapse to one chunk instead of two).

2. token-json-single-item-oversize (known_diff): Python's json path keeps a
   single item that exceeds chunk_token_size whole, while Go sub-split it via
   splitOversizedUnit. mergeByTokenSizeFromJSON gains a subSplitOversize flag;
   the json path passes false (no sub-split) and the text path passes true
   (matching Python's _split_oversized_unit).

Tests are self-contained (drive NewTokenChunker directly, no .venv) so they
run in the default unit tier. known_diffs.json rules token-json-per-item-merge
and token-json-single-item-oversize should be removed once this lands (they
live in the parity-infra PR infiniflow#17735).

Co-Authored-By: CodeBuddy <[email protected]>
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The chunker now globally merges adjacent JSON text items within the token budget and preserves oversized JSON items as whole chunks. Text paths still split oversized units. Tests cover the new behavior and updated helper signature.

Changes

JSON token merging

Layer / File(s) Summary
JSON merge behavior
internal/ingestion/component/chunker/token.go
mergeByTokenSizeFromJSON now receives a splitting flag. JSON text items share a global token budget, while oversized JSON items remain whole when splitting is disabled.
Merge contract validation
internal/ingestion/component/chunker/json_global_merge_test.go, internal/ingestion/component/chunker/token_*_test.go
Tests cover cross-item JSON merging, oversized-item preservation, and updated merge calls across overlap, position, clamp, empty-chunk, and strict-cap cases.

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

Possibly related issues

Possibly related PRs

Suggested labels: ci

Suggested reviewers: euvre, yuzhichang

Poem

I’m a rabbit guarding tokens tight,
JSON carrots merge just right.
Big roots stay whole in the queue,
Text still splits when limits do.
Tests hop onward—clean and bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main JSON chunking fixes: global merging and preserving over-budget items.
Description check ✅ Passed The description follows the template and clearly explains the objectives, implementation changes, tests, and follow-up actions.
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 3, 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: 1

🧹 Nitpick comments (1)
internal/ingestion/component/chunker/json_global_merge_test.go (1)

28-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove migration-history details from the test comment.

Keep the comment focused on the current behavior that TestJSONGlobalMergeMatchesPython verifies. Remove references to historical Go behavior and prior test harnesses.

As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history” and remove “stale documentation … migration notes.”

🤖 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/json_global_merge_test.go` around lines
28 - 38, Update the comment above TestJSONGlobalMergeMatchesPython to describe
only the current JSON cross-item token merging behavior and the Python parity it
verifies; remove references to historical Go behavior, migration history,
virtual environments, golden harnesses, and test-tier details.

Source: Coding guidelines

🤖 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/json_global_merge_test.go`:
- Around line 80-82: Update the assertions in the first JSON merge test to
verify the expected item order, not just substring membership, by checking
ordered substrings in the first chunk’s text. In the second test assertions
around the chunk-count check, also verify that the second chunk’s text exactly
equals strings.TrimSpace(long), confirming preservation of the oversized item.

---

Nitpick comments:
In `@internal/ingestion/component/chunker/json_global_merge_test.go`:
- Around line 28-38: Update the comment above TestJSONGlobalMergeMatchesPython
to describe only the current JSON cross-item token merging behavior and the
Python parity it verifies; remove references to historical Go behavior,
migration history, virtual environments, golden harnesses, and test-tier
details.
🪄 Autofix (Beta)

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: 83ae6d84-09c0-42f2-afc1-0c1372daf1de

📥 Commits

Reviewing files that changed from the base of the PR and between f9fd764 and aacdb2f.

📒 Files selected for processing (5)
  • internal/ingestion/component/chunker/json_global_merge_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_batch1_test.go
  • internal/ingestion/component/chunker/token_pdfpos_test.go
  • internal/ingestion/component/chunker/token_strict_cap_test.go

Comment on lines +80 to +82
text, _ := chunks[0]["text"].(string)
if !strings.Contains(text, "alpha beta gamma") || !strings.Contains(text, "another long item") {
t.Errorf("merged chunk does not contain both items:\n%q", text)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert ordered and complete JSON text output.

The first assertion proves membership but not item order. The second assertion proves chunk count but not preservation of the oversized item. Assert ordered substrings in the first test. Assert that the second chunk text equals strings.TrimSpace(long).

Proposed test assertions
- if !strings.Contains(text, "alpha beta gamma") || !strings.Contains(text, "another long item") {
+ first := strings.Index(text, "alpha beta gamma")
+ second := strings.Index(text, "another long item")
+ if first < 0 || second < 0 || first > second {
    t.Errorf("merged chunk does not contain both items:\n%q", text)
  }

+ text, _ := chunks[0]["text"].(string)
+ if text != strings.TrimSpace(long) {
+   t.Errorf("oversized JSON item changed: got %q", text)
+ }

Also applies to: 117-120

🤖 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/json_global_merge_test.go` around lines
80 - 82, Update the assertions in the first JSON merge test to verify the
expected item order, not just substring membership, by checking ordered
substrings in the first chunk’s text. In the second test assertions around the
chunk-count check, also verify that the second chunk’s text exactly equals
strings.TrimSpace(long), confirming preservation of the oversized item.

…tion comments

- Assert the two JSON items appear in source order within the single merged
  chunk, not just as substring membership.
- Assert the over-budget single item is kept whole verbatim (exact text
  match) instead of only checking the chunk count.
- Remove migration-history details from the test doc comments so they
  describe current behavior only.

Co-Authored-By: CodeBuddy <[email protected]>

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Aug 3, 2026
@yuzhichang yuzhichang added ci Continue Integration and removed ci Continue Integration labels Aug 3, 2026
@yuzhichang
yuzhichang merged commit 3fd4ead into infiniflow:main Aug 3, 2026
6 of 9 checks passed
yuzhichang pushed a commit that referenced this pull request Aug 5, 2026
…ent) (#17854)

The Go `TokenChunker` text/markdown path (`mergeByTokenSize`)
unconditionally
called `splitOversizedUnit` on any unit that exceeded
`chunk_token_size`,
emitting Go-only sub-chunks. Python's `naive_merge`
(`_merge_paragraph_groups`,
`rag/nlp/__init__.py`) never atom-splits an oversize unit under either
`OVER_CAP` or `UNDER_CAP`: a paragraph larger than the budget becomes
its own
standalone chunk and the model layer truncates it later.

This aligns the text/markdown path with the **structured JSON path**
(`invokeJSONPayload` → `mergeByTokenSizeFromJSON(...,
subSplitOversize=false)`,
#17739). It completes the OVER_CAP alignment started in #17835.
@xugangqiang
xugangqiang deleted the fix/chunker-json-global-merge branch August 7, 2026 12:27
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 10, 2026
After rebasing onto upstream/main (which merged infiniflow#17739/infiniflow#17835/infiniflow#17854/infiniflow#17868):
- Remove 4 go_bug rules now resolved by merged fixes:
  token-json-per-item-merge, token-json-custom-delim-drops-newline,
  token-json-single-item-oversize, token-text-overlap-split.
- Delete their go_snapshot files; also drop 4 orphaned tokenizer
  go_snapshot files that the harness never reads (strict-compare path).
- Refresh the 3 remaining ratcheted snapshots for
  token-custom-delim-newline-and-field (html/markdown/text_backtick), whose
  Go output shifted under the merged delimiter/children-split fixes but the
  divergence itself persists.

The 4 tokenizer-count cases (text/html/markdown_default_delim,
text_token_liveness) now match the Python golden strict-compare with no
rule, i.e. the tokenizer count mismatch is resolved. Harness is green under
both plain and -update runs.
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 lgtm This PR has been approved by a maintainer size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants