Repository navigation
fix(chunker): align Go token merge with Python OVER_CAP and delimiter boundary - #17835
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe chunker now drops custom delimiters for text-like formats, preserves JSON delimiter whitespace, and supports configurable strict-cap or boundary-overflow token merging. Regression tests cover delimiters, overlap, metadata, whitespace, and multiple content formats. ChangesChunker parity updates
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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 |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
internal/ingestion/component/chunker/token_strict_cap_test.go (1)
116-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRename the strict-cap tests for
OVER_CAPbehavior.
TestMergeByTokenSizeFromJSON_StrictCapNoOvershoot,TestMergeByTokenSize_TextPathStrictCap,TestMergeByTokenSize_UnbrokenAtomStrictCap, andTestInvokeTextPayload_StrictCapEndToEndnow permit overflow. Rename them to describeOVER_CAP. Update the preceding comment that still says no chunk may exceed the budget.As per coding guidelines, keep doc comments aligned with the current runtime path and remove stale superseded comments and documentation.
Also applies to: 181-207, 243-246, 258-290
🤖 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_strict_cap_test.go` around lines 116 - 123, Rename the four strict-cap tests—TestMergeByTokenSizeFromJSON_StrictCapNoOvershoot, TestMergeByTokenSize_TextPathStrictCap, TestMergeByTokenSize_UnbrokenAtomStrictCap, and TestInvokeTextPayload_StrictCapEndToEnd—to names describing OVER_CAP behavior. Update the associated preceding comments and documentation, including the comment near the token assertion, to state that chunks may exceed the budget by one incoming unit; remove stale claims that no chunk may exceed the budget.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/custom_delim_test.go`:
- Around line 124-135: Strengthen the Markdown assertions in the chunk test by
requiring exactly three chunks and verifying their text values match the
expected delimiter-split, trimmed results in order. Keep the existing newline
and doc_type_kwd checks, but add exact count and content assertions so a single
unsplit chunk cannot pass.
In `@internal/ingestion/component/chunker/token_batch1_test.go`:
- Around line 62-106: Strengthen the assertions in the overlap test around
mergeByTokenSizeFromJSON by deriving the expected overlap prefix from
merged[0].Text using the configured 30.0 overlap and requiring merged[1].Text to
begin with that prefix. Keep the existing parser-tag and token-budget
assertions, while ensuring the test fails when the second chunk starts only with
c and contains no overlap.
In `@internal/ingestion/component/chunker/token.go`:
- Line 978: Reset prevClosed to false before appending any non-text ChunkDoc in
the chunking flow, including the paths around the non-text handling block near
prevClosed. Preserve the existing mergeThenClose behavior for text chunks while
ensuring the first text chunk after a non-text boundary can merge with the
following text chunk.
- Around line 632-643: Update the explanatory comment near the raw split
fragment handling to remove the stale token.go:587 line reference, while
preserving the explanation that final-output TrimSpace only removes a chunk’s
own leading/trailing whitespace and not the inter-line whitespace preserved
here.
---
Nitpick comments:
In `@internal/ingestion/component/chunker/token_strict_cap_test.go`:
- Around line 116-123: Rename the four strict-cap
tests—TestMergeByTokenSizeFromJSON_StrictCapNoOvershoot,
TestMergeByTokenSize_TextPathStrictCap,
TestMergeByTokenSize_UnbrokenAtomStrictCap, and
TestInvokeTextPayload_StrictCapEndToEnd—to names describing OVER_CAP behavior.
Update the associated preceding comments and documentation, including the
comment near the token assertion, to state that chunks may exceed the budget by
one incoming unit; remove stale claims that no chunk may exceed the budget.
🪄 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: 2e83e3e6-9a2e-42d5-bf90-64d99a123127
📒 Files selected for processing (8)
internal/ingestion/component/chunker/common.gointernal/ingestion/component/chunker/custom_delim_test.gointernal/ingestion/component/chunker/delimiter_case_sensitive_test.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_batch1_test.gointernal/ingestion/component/chunker/token_overlap_test.gointernal/ingestion/component/chunker/token_strict_cap_test.gointernal/ingestion/component/chunker/token_test.go
Text path now drops the delimiter and trims each segment, mirroring Python's _split_text_by_pattern + .strip() (token_chunker.py:316-338). Previously splitKeepingDelim glued the delimiter onto the preceding segment, so a chunk read "first sentence here\n" instead of "first sentence here". JSON path no longer TrimSpace-es each chunk, so the delimiter's trailing newline survives like Python's _build_json_chunks / _finalize_json_chunks (which never strip). Previously that newline was deleted (token.go:659). doc_type_kwd is intentionally retained on the text path: it is a load-bearing Go field (Infinity index column + media dispatch) and is classified go_intentional in known_diffs.json, not a bug to fix here. Updates the three existing unit tests that encoded the old keep-delimiter behaviour, and adds custom_delim_test.go reproducing the four parity cases (text/markdown/html/json backtick newline).
… prefix The text path of TokenChunker split the payload on sentence delimiters and TrimSpaced each fragment before merging. This dropped the trailing whitespace of each line, so the overlap prefix carved from the previous (untrimmed) chunk lost a character and diverged from Python's naive_merge by one character on every following chunk. Mirror naive_merge, which builds each unit from "\n" + sub_sec (sub_sec keeps its trailing space and is never TrimSpaced; the only post-processing is dropping the leading empty placeholder at naive_merge:1370-1375). Skip only genuinely empty fragments instead of TrimSpacing each part. Fixes the token-text-overlap-split parity divergence. Adds a regression test that drives Invoke with empty delimiters so it actually lands on the patched mergeByTokenSize: the text path only reaches that function when there is no active delimiter, so a non-empty delimiter (e.g. ["\n"]) must NOT be used — it would route to the separate mergeByTokenSizeFromJSON path, which this fix does not touch. The test pins the exact chunk texts against the Python reference.
Extract a shared mergeDecision helper (mergeAction + allowBoundaryOverflow) and newChunkText, and rewrite the text (addChunk) and JSON (addTextChunk) merge paths to use it. Go now matches Python's canonical OVER_CAP default (rag/nlp MergeStrategy): greedily accumulate adjacent units, allow one boundary overflow then close the chunk, but never merge a unit that already exceeds the cap (it stands alone, mirroring Python's `if pt > cap` branch). Update the cap/overlap tests to the OVER_CAP contract (a chunk may exceed budget by at most one incoming unit) and restructure the overlap-tag test to exercise the overlap path under OVER_CAP. Part of consolidating infiniflow#17744/infiniflow#17748 into a single Go PR that syncs the chunker with Python PR infiniflow#17808 (OVER_CAP default).
6410b75 to
65491a7
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
… tests - mergeByTokenSizeFromJSON: reset prevClosed in addTextChunk's early-return (first text chunk / first text after a non-text chunk). Previously a stale OVER_CAP boundary-overflow flag leaked across an interleaved non-text chunk, forcing the next text chunk to start a fresh chunk instead of merging with its predecessor (broken chunking for mixed image/table+text documents). - Add TDD regression test TestMergeByTokenSizeFromJSON_NonTextBoundaryResetsPrevClosed (red before the fix, green after). - Harden TestCustomDelimMarkdownDropsDelimiter to assert the exact three trimmed chunks (was only checking 'does not end with newline'). - Assert the overlap prefix is actually prepended in TestMergeByTokenSizeFromJSON_OverlapStripsTags. - Drop stale token.go:587 line reference in a code comment.
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_batch1_test.go`:
- Around line 162-163: In the test around the merged chunk count, first assert
that merged[0].Text equals t1 + "\n" + t2 to verify the overflow-closed T1+T2
chunk, then retain the existing assertions for the non-text chunk and remaining
merged chunk.
🪄 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: 2e69dc29-4755-45c1-91d5-0547e3f2dec2
📒 Files selected for processing (3)
internal/ingestion/component/chunker/custom_delim_test.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_batch1_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/ingestion/component/chunker/token.go
… test Assert merged[0].Text == t1+"\n"+t2 so the regression test for the OVER_CAP prevClosed reset fails if the merge path ever stops setting prevClosed on the T1+T2 overflow-closed chunk (CodeRabbit review on the new test).
Follow-up fixes on this branch (after the original PR commits)Two additional commits address the CodeRabbit review and harden the chunker tests:
All review comments are now addressed; the full chunker unit suite ( |
mergeDecision's allowBoundaryOverflow was always called with true, leaving the UNDER_CAP (RESPECT_CAP) branch as dead, untested code. Make it a usable toggle so Go can follow Python's MergeStrategy.RESPECT_CAP: - Add TokenChunkerParam.RespectCap (default false = OVER_CAP, matching Python's canonical default); parse 'respect_cap' in Update. - Thread !param.RespectCap into mergeByTokenSize and mergeByTokenSizeFromJSON (new allowBoundaryOverflow param). Both production call sites pass through the param; existing tests keep OVER_CAP by passing true. TDD: - TestMergeByTokenSize_RespectCapNoOverflow (text path, via NewTokenChunker respect_cap:true) failed red before wiring (OVER_CAP overflowed), passes green after; an OVER_CAP control asserts the toggle actually changes behavior. - TestMergeByTokenSizeFromJSON_RespectCapNoOverflow asserts a, b, c stay as three separate chunks within budget under allowBoundaryOverflow=false. Default behavior is unchanged (OVER_CAP), so no regression for existing users.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/component/chunker/token_strict_cap_test.go (1)
141-148: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winDo not permit a second boundary overflow in this assertion.
Line 147 accepts
budget + 2*unit. With the 10-token units in this fixture and a budget of 25, a chunk containing four units can pass even though it has two post-cap units. This weakens the one-boundary-overflow regression. Use distinct units and assert that only one unit can be added after the target is exceeded.As per coding guidelines, preserve still-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_strict_cap_test.go` around lines 141 - 148, Update the assertion around tokenizeStr in the token-cap test to reject chunks containing two post-cap units: use distinct fixture unit sizes and enforce a limit of budget plus one additional unit, while preserving valid single-boundary-overflow behavior and the existing overlap handling.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/token_strict_cap_test.go`:
- Around line 230-267: Update the test helper around NewTokenChunker so the
OVER_CAP control constructs configuration without the “respect_cap” key, thereby
verifying the documented default behavior. Keep the existing explicit-false
coverage only if needed to test configuration parsing separately, while
preserving the current assertions that RESPECT_CAP stays within budget and the
default OVER_CAP path overflows.
---
Outside diff comments:
In `@internal/ingestion/component/chunker/token_strict_cap_test.go`:
- Around line 141-148: Update the assertion around tokenizeStr in the token-cap
test to reject chunks containing two post-cap units: use distinct fixture unit
sizes and enforce a limit of budget plus one additional unit, while preserving
valid single-boundary-overflow behavior and the existing overlap handling.
🪄 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: 8567363f-d20a-4c82-a3b1-a702b366fd31
📒 Files selected for processing (5)
internal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_batch1_test.gointernal/ingestion/component/chunker/token_pdfpos_test.gointernal/ingestion/component/chunker/token_strict_cap_test.gointernal/ingestion/component/schema/chunker.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/ingestion/component/chunker/token.go
…sed invariant - Rename the merge-strategy toggle RespectCap/respect_cap/RESPECT_CAP to UnderCap/under_cap/UNDER_CAP to match the codebase's OVER_CAP/UNDER_CAP vocabulary (per review correction). Behavior is unchanged: false = OVER_CAP (Python canonical default), true = UNDER_CAP (no boundary overflow). - In addTextChunk, add a defensive prevClosed=false reset on the prev.Text=="" empty-prev branch so the OVER_CAP boundary-overflow flag can never leak across chunks. The early-return path already clears it for the first-text / after-non-text case; making the invariant explicit here keeps the closure complete against future refactors. Co-authored-by: CodeBuddy <[email protected]>
|
LGTM |
…egy enum (#17851) ## Summary Follow-up to #17835 (merged). The OVER_CAP / UNDER_CAP merge strategy was threaded through `mergeDecision` and `mergeByTokenSizeFromJSON` as an inlined `allowBoundaryOverflow bool` derived from `!c.param.UnderCap` at three call sites. This replaces that with a named `schema.MergeStrategy` enum. ## Why - The `!c.param.UnderCap` inversion was hand-written in three places, so a future strategy addition could silently drift between the JSON path (`invokeTextPayload` / `invokeJSONPayload`) and the text path (`mergeByTokenSize`) — no compile error, and the existing tests don't cover all three sites with both strategies. - The strategy concept was never named; `allowBoundaryOverflow` (true = OVER_CAP) is a double-negation of `UnderCap` and reads opaquely at the 5th positional argument. ## What changed - Add `schema.MergeStrategy` (`MergeOverCap` / `MergeUnderCap`) mirroring Python's `rag/nlp/__init__.py` `MergeStrategy`, so Go and Python stay on the same vocabulary. - Expose `TokenChunkerParam.MergeStrategy()` derived from the wire-facing `UnderCap bool` (existing `"under_cap"` configs keep working — no schema break). - `mergeDecision` and `mergeByTokenSizeFromJSON` now take `schema.MergeStrategy` instead of `allowBoundaryOverflow bool`; the three call sites pass `c.param.MergeStrategy()` (no `!`). - Tests updated to pass the enum; added a guard test for the `UnderCap` -> `MergeStrategy` mapping and an end-to-end test for UNDER_CAP on the JSON path. No behavior change: default remains OVER_CAP, `under_cap=true` still selects UNDER_CAP. ## Test plan `bash build.sh --test ./internal/ingestion/component/chunker/... ./internal/ingestion/component/schema/...` — all green, including `TestMergeByTokenSizeFromJSON_UnderCapNoOverflow`, `TestMergeByTokenSize_UnderCapNoOverflow`, `TestInvokeJSONPayload_UnderCapEndToEnd`, and `TestTokenChunkerParamMergeStrategy`. ## Related issues - Relates to #17835 — wired UNDER_CAP as a tested merge-strategy seam (merged) - Relates to #17799 — contract doc for token-chunker cap/delimiter alignment - Relates to #17808 — related chunker alignment work --------- Co-authored-by: CodeBuddy <[email protected]>
…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.
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.
Summary
Consolidates the Go chunker work that syncs
TokenChunkerwith the Pythonreference (
rag/nlp.naive_merge/rag/flow/chunker/token_chunker.py) into asingle PR:
path now drops the captured delimiter like Python's
_split_text_by_patterninstead of gluing it to the preceding segment; the JSON path stops
TrimSpace-ing chunk text so the delimiter's trailing newline survives,matching Python's
_build_json_chunks.fix(chunker): preserve inter-line trailing space in text-path overlap prefix #17748): the overlap prefix is carved from the untrimmed previous chunk, so a
line's trailing space is no longer dropped (Python emits
"alpha \nbeta",not
"alpha\nbeta").shared
mergeDecisionhelper (mergeAction+allowBoundaryOverflow) andnewChunkText, and rewrite the text (addChunk) and JSON (addTextChunk)merge paths to use it. Go now greedily accumulates adjacent units, allows one
boundary overflow then closes the chunk, and never merges a unit that already
exceeds the cap (it stands alone) — mirroring Python's
MergeStrategy.OVER_CAP.The two paths' overlap guards are unified to the more correct
overlapTokens + incoming <= targetform.Test plan
bash build.sh --test ./internal/ingestion/component/chunker/...— unit tiergreen (cap/overlap tests updated to the OVER_CAP contract: a chunk may exceed
budget by at most one incoming unit).
bash build.sh --test-integration ./internal/ingestion/component/chunker/...— integration tier green.
Notes
This is the Go-side change only; it aligns with Python PR #17808 (OVER_CAP
default). The strict-cap and overlap tests were updated to the OVER_CAP
semantics, and the overlap-tag test was restructured to keep exercising the
overlap path under OVER_CAP.
Closes #17744 and #17748 (superseded by this combined PR).
Related
soft-target merge). This PR's OVER_CAP merge and delimiter-boundary behavior
implement that contract on the Go side.
atom-split (OVER_CAP default). The Go change here mirrors the Python default.