Repository navigation
fix(chunker): enforce strict chunk_token_num cap on .txt / PDF / email paths - #17203
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:
📝 WalkthroughWalkthroughText parsing and naive merge functions now enforce hard token caps. They split oversized units, account for overlap and position text, preserve image alignment, and add regression coverage for boundary, oversized, empty-input, and fallback splitting cases. ChangesStrict chunk token caps
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches 💡 2⚔️ Resolve merge conflicts 💡
🛠️ Fix failing CI checks 💡
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 (3)
test/unit_test/deepdoc/parser/test_txt_parser.py (1)
110-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo test exercises the single-oversized-atom character-window fallback.
test_atomic_oversized_line_is_sub_split_on_whitespaceonly exercises the whitespace-accumulation path of_split_oversized_text(each "alpha" atom is well under the budget). The character-window fallback (a single non-whitespace run exceedingchunk_token_num) — where the char-count-as-token-count bug lives (seedeepdoc/parser/txt_parser.pylines 23-63) — is never exercised by any test in this file. Consider adding a case with one long unbroken token (e.g. a base64-like blob or CJK run) to pin down correct behavior once the fallback is fixed.🤖 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 `@test/unit_test/deepdoc/parser/test_txt_parser.py` around lines 110 - 118, Add a unit test in test_txt_parser.py for a single unbroken token exceeding the chunk budget, exercising _split_oversized_text’s character-window fallback rather than whitespace splitting. Use a long non-whitespace string and assert every emitted chunk stays within the token limit while the complete input is preserved.deepdoc/parser/txt_parser.py (1)
110-116: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMissing logging for the new oversized-split flow.
rag/nlp/__init__.py's equivalent new flows addedlogging.debug(...)(e.g. at the end ofnaive_merge), but this new per-section splitting path inparser_txthas none. As per coding guidelines,**/*.pychanges should add logging for new flows.♻️ Suggested addition
for piece in _split_oversized_text(sec, chunk_token_num): add_chunk(piece) + logging.debug("parser_txt: %d sections -> %d chunks (chunk_token_num=%d)", len(secs), len(cks), chunk_token_num) return [[c, ""] for c in cks]🤖 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 `@deepdoc/parser/txt_parser.py` around lines 110 - 116, Add debug logging to the oversized-section splitting flow in parser_txt, specifically around the _split_oversized_text loop, consistent with the existing logging style used by naive_merge. Log enough context to indicate that a section was split and processed while preserving the current add_chunk behavior.Source: Coding guidelines
test/unit_test/rag/test_naive_merge.py (1)
249-255: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFallback char-window branch still not exercised with a token-dense atom.
test_strict_cap_single_overlong_section_is_sub_split_on_whitespaceuses"alpha"repeated with spaces — each atom tokenizes to roughly 1 token via the real tokenizer, so the accumulation path handles it and the character-window fallback (_split_oversized_unit'satom[i:i+chunk_token_num]slicing, flagged separately onrag/nlp/__init__.pylines 1157-1218) is never triggered. None of the new "Hard cap" tests use a single unbroken oversized run (no whitespace) to hit that fallback, so the char-count-vs-token-count bug there has no regression coverage.🤖 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 `@test/unit_test/rag/test_naive_merge.py` around lines 249 - 255, The test test_strict_cap_single_overlong_section_is_sub_split_on_whitespace must exercise _split_oversized_unit’s character-window fallback by using one unbroken, token-dense string with no whitespace. Keep the assertions verifying multiple chunks, the strict 50-token cap, and preservation of the complete input content so the char-count-versus-token-count behavior is covered.
🤖 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 `@deepdoc/parser/txt_parser.py`:
- Around line 23-63: Update _split_oversized_text’s oversized-atom fallback to
create windows based on token counts rather than character count, ensuring every
returned piece stays within chunk_token_num even for CJK or emoji runs. Reuse
the project’s tokenization utilities, and add a regression test covering a
single unbroken atom that exceeds the limit.
- Around line 80-92: Update the merge branch in the text chunking logic to
recalculate tk_nums[-1] from the complete merged cks[-1] string after appending
the newline and t, using the existing num_tokens_from_string helper. Preserve
the current chunk-boundary check and append behavior for non-merged text.
In `@rag/nlp/__init__.py`:
- Around line 1237-1274: Update both the first-chunk branch and proactive-merge
branch to recompute the token count after appending pos to t, then assign the
recalculated value to tk_nums[-1]. Keep the existing duplicate-pos checks and
chunk text behavior unchanged.
- Around line 1157-1218: Replace the local _split_oversized_unit implementation
with the shared token-aware helper from
deepdoc/parser/txt_parser.py::_split_oversized_text, or move that helper to a
common reusable location and update both callers to use it. Remove the
duplicated splitter and ensure oversized non-whitespace runs are divided by
token budget rather than character count, including CJK and emoji text.
---
Nitpick comments:
In `@deepdoc/parser/txt_parser.py`:
- Around line 110-116: Add debug logging to the oversized-section splitting flow
in parser_txt, specifically around the _split_oversized_text loop, consistent
with the existing logging style used by naive_merge. Log enough context to
indicate that a section was split and processed while preserving the current
add_chunk behavior.
In `@test/unit_test/deepdoc/parser/test_txt_parser.py`:
- Around line 110-118: Add a unit test in test_txt_parser.py for a single
unbroken token exceeding the chunk budget, exercising _split_oversized_text’s
character-window fallback rather than whitespace splitting. Use a long
non-whitespace string and assert every emitted chunk stays within the token
limit while the complete input is preserved.
In `@test/unit_test/rag/test_naive_merge.py`:
- Around line 249-255: The test
test_strict_cap_single_overlong_section_is_sub_split_on_whitespace must exercise
_split_oversized_unit’s character-window fallback by using one unbroken,
token-dense string with no whitespace. Keep the assertions verifying multiple
chunks, the strict 50-token cap, and preservation of the complete input content
so the char-count-versus-token-count behavior is covered.
🪄 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
Run ID: 4b1f0bd3-7d73-4845-b36c-3d5ac7099655
📒 Files selected for processing (4)
deepdoc/parser/txt_parser.pyrag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/nlp/__init__.py (1)
1267-1304: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winStrict token cap bypassed when appending delimiters or position text.
The
chunk_token_numlimit can still be bypassed during chunk creation and merging. Extra text (\norpos) is appended to the chunk after checking the budget via an optimistic sum (tk_nums[-1] + tnum) that does not account for the extra text's token footprint. To enforce a strict cap, always check the exact merged string's token count before assigning it.
rag/nlp/__init__.py#L1267-L1304: Innaive_merge, verify thatt + posfits before addingposto the first chunk, and check thatcks[-1] + t + pos(or justcks[-1] + t) strictly fits before completing a proactive merge.rag/nlp/__init__.py#L1369-L1409: Apply the same exact merged-size checks forposadditions in the first chunk and proactive merge paths ofnaive_merge_with_images.deepdoc/parser/txt_parser.py#L41-L54: Usenum_tokens_from_string(cks[-1] + "\n" + t) <= chunk_token_numto verify the combined string fits before assigning it.🛠️ Proposed fixes across all three locations
For
rag/nlp/__init__.py(innaive_merge):# First chunk ever — no previous content to overlap with. if cks[-1] == "": - if t.find(pos) < 0: - t += pos - cks[-1] = t + new_t = t + pos if t.find(pos) < 0 else t + cks[-1] = new_t if num_tokens_from_string(new_t) <= chunk_token_num else t tk_nums[-1] = num_tokens_from_string(cks[-1]) return # Proactive merge: append only if the *projected* total still fits. - if tk_nums[-1] + tnum <= chunk_token_num: - if cks[-1].find(pos) < 0: - t += pos - cks[-1] += t - tk_nums[-1] = num_tokens_from_string(cks[-1]) + merged = cks[-1] + t + merged_pos = merged + pos if cks[-1].find(pos) < 0 else merged + if num_tokens_from_string(merged_pos) <= chunk_token_num: + cks[-1] = merged_pos + tk_nums[-1] = num_tokens_from_string(cks[-1]) + return + elif num_tokens_from_string(merged) <= chunk_token_num: + cks[-1] = merged + tk_nums[-1] = num_tokens_from_string(cks[-1]) returnFor
rag/nlp/__init__.py(innaive_merge_with_images):# First chunk ever — no previous content to overlap with. if cks[-1] == "": - if t.find(pos) < 0: - t += pos - cks[-1] = t + new_t = t + pos if t.find(pos) < 0 else t + cks[-1] = new_t if num_tokens_from_string(new_t) <= chunk_token_num else t tk_nums[-1] = num_tokens_from_string(cks[-1]) result_images[-1] = image return # Proactive merge: append only if the *projected* total still fits. - if tk_nums[-1] + tnum <= chunk_token_num: - if cks[-1].find(pos) < 0: - t += pos - cks[-1] += t - tk_nums[-1] = num_tokens_from_string(cks[-1]) + merged = cks[-1] + t + merged_pos = merged + pos if cks[-1].find(pos) < 0 else merged + if num_tokens_from_string(merged_pos) <= chunk_token_num: + cks[-1] = merged_pos + tk_nums[-1] = num_tokens_from_string(cks[-1]) + if result_images[-1] is None: + result_images[-1] = image + else: + result_images[-1] = concat_img(result_images[-1], image) + return + elif num_tokens_from_string(merged) <= chunk_token_num: + cks[-1] = merged + tk_nums[-1] = num_tokens_from_string(cks[-1]) if result_images[-1] is None: result_images[-1] = image else: result_images[-1] = concat_img(result_images[-1], image) returnFor
deepdoc/parser/txt_parser.py:if cks[-1] == "": cks[-1] = t tk_nums[-1] = tnum return - if tk_nums[-1] + tnum <= chunk_token_num: - cks[-1] += "\n" + t - tk_nums[-1] = num_tokens_from_string(cks[-1]) - return + merged = cks[-1] + "\n" + t + merged_tnum = num_tokens_from_string(merged) + if merged_tnum <= chunk_token_num: + cks[-1] = merged + tk_nums[-1] = merged_tnum + return🤖 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 `@rag/nlp/__init__.py` around lines 1267 - 1304, The chunk budget checks use optimistic token sums and can exceed chunk_token_num when adding delimiters or position text. In rag/nlp/__init__.py lines 1267-1304, update naive_merge to compute exact token counts for t + pos and cks[-1] + t + pos (or cks[-1] + t) before assignment; apply the same checks in naive_merge_with_images at lines 1369-1409. In deepdoc/parser/txt_parser.py lines 41-54, only assign the merged chunk when num_tokens_from_string(cks[-1] + "\n" + t) <= chunk_token_num.
🤖 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.
Outside diff comments:
In `@rag/nlp/__init__.py`:
- Around line 1267-1304: The chunk budget checks use optimistic token sums and
can exceed chunk_token_num when adding delimiters or position text. In
rag/nlp/__init__.py lines 1267-1304, update naive_merge to compute exact token
counts for t + pos and cks[-1] + t + pos (or cks[-1] + t) before assignment;
apply the same checks in naive_merge_with_images at lines 1369-1409. In
deepdoc/parser/txt_parser.py lines 41-54, only assign the merged chunk when
num_tokens_from_string(cks[-1] + "\n" + t) <= chunk_token_num.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0e6bd4c3-cfe5-4d5f-93b4-9c6e51f711da
📒 Files selected for processing (4)
deepdoc/parser/txt_parser.pyrag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
🚧 Files skipped from review as they are similar to previous changes (1)
- test/unit_test/rag/test_naive_merge.py
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
rag/nlp/__init__.py (2)
1340-1345: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a debug log when the atom-splitting fallback triggers.
_split_oversized_unitis the new safety-net path for units that survive delimiter splitting but still exceedchunk_token_num. Right now only the end-of-function summary log exists; a one-line debug log at the trigger site (fired once per oversized unit, not per token) would make it easy to spot corpora that are hitting the fallback frequently, without adding hot-path overhead. As per coding guidelines, "Add logging for new flows" for**/*.py.Also applies to: 1464-1469
🤖 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 `@rag/nlp/__init__.py` around lines 1340 - 1345, Add a single debug-level log immediately before each call to _split_oversized_unit in the oversized-unit fallback branches, identifying that the unit exceeded chunk_token_num; ensure it logs once per oversized unit rather than inside token-level splitting and preserves the existing summary logging.Source: Coding guidelines
1260-1305: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
add_chunklogic is duplicated almost verbatim betweennaive_mergeandnaive_merge_with_images.The first-chunk branch, proactive-merge branch, and overlap/pos branch are copy-pasted between the two closures, differing only in
result_imagesbookkeeping. This is exactly why the priortk_numsdesync bug had to be fixed in two places at once (per past review). Extracting a shared helper that returns the merge decision (new/merged text, token count, whether to start a new chunk) would let both closures reuse one code path and only add their own image bookkeeping on top.Also applies to: 1363-1417
🤖 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 `@rag/nlp/__init__.py` around lines 1260 - 1305, Extract the duplicated chunk-merging logic from the add_chunk closures in naive_merge and naive_merge_with_images into one shared helper that handles first-chunk initialization, proactive merging, overlap, delimiter positioning, and token-count updates. Have the helper return the resulting text, token count, and whether a new chunk was created, then let each closure apply only its own result_images bookkeeping while reusing the shared cks/tk_nums decision path.
🤖 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 `@rag/nlp/__init__.py`:
- Around line 1269-1285: The empty-delimiter branches in both naive_merge and
naive_merge_with_images must route oversized sections through
_split_oversized_unit before add_chunk, rather than sending them directly to the
first-chunk fallback. Preserve normal add_chunk behavior for sections within
chunk_token_num and enforce the hard token cap when dels is empty.
---
Nitpick comments:
In `@rag/nlp/__init__.py`:
- Around line 1340-1345: Add a single debug-level log immediately before each
call to _split_oversized_unit in the oversized-unit fallback branches,
identifying that the unit exceeded chunk_token_num; ensure it logs once per
oversized unit rather than inside token-level splitting and preserves the
existing summary logging.
- Around line 1260-1305: Extract the duplicated chunk-merging logic from the
add_chunk closures in naive_merge and naive_merge_with_images into one shared
helper that handles first-chunk initialization, proactive merging, overlap,
delimiter positioning, and token-count updates. Have the helper return the
resulting text, token count, and whether a new chunk was created, then let each
closure apply only its own result_images bookkeeping while reusing the shared
cks/tk_nums decision path.
🪄 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
Run ID: 7337a13f-d8d7-41ef-928c-7c2b155861a4
📒 Files selected for processing (4)
deepdoc/parser/txt_parser.pyrag/nlp/__init__.pytest/unit_test/deepdoc/parser/test_txt_parser.pytest/unit_test/rag/test_naive_merge.py
🚧 Files skipped from review as they are similar to previous changes (3)
- test/unit_test/deepdoc/parser/test_txt_parser.py
- deepdoc/parser/txt_parser.py
- test/unit_test/rag/test_naive_merge.py
can you add the appropriate reviewers to this PR? |
|
@yuzhichang @Lynn-Inf @wangq8 @dcc123456 please review! |
|
@yuzhichang @Lynn-Inf @wangq8 @dcc123456 @JinHai-CN please review! |
|
@skbs-eng We are actively porting from python to golang. Could you implement the go part in this same PR? |
77df5f2 to
6a8111a
Compare
|
@yuzhichang Go port is in this PR now.
Coverage in |
The size check in RAGFlowTxtParser.parser_txt and rag.nlp.naive_merge fired *after* the append, so each chunk could overshoot chunk_token_num by up to the size of one line / section. Make the check proactive (tk_nums[-1] + tnum <= chunk_token_num) and add an atom-level sub-splitter for units that still exceed the budget after the regex split. In naive_merge the overlap prefix is now only applied when overlap_tokens + tnum still fits; otherwise the overlap is dropped at that boundary so the chunk stays within budget. Real-world impact on a 154k-chunk "Plain Text" dataset (chunk_token_num=512, delimiter="\n", overlapped_percent=0.1): before: 56% of chunks over 512 tokens (median 539, max 14,813) after: strictly <= 512 tokens Tighten existing size tolerances from +10 / +2 slack to 0 to guard the regression, and add new strict-cap tests covering the non-overlap, overflow-overlap, atomic-oversize and overlap-fitting branches. Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
…splitting, exact token recount on merge, and logging Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
…ining newline delimiters Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
…en delimiter="" and add debug logging Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
Mirror the Python naive_merge / parser_txt fix in the Go ingestion chunker so oversized .txt / PDF / email paths cannot exceed the budget: - projected-total merge before append (exact hard cap) - overlap applied only when overlap+segment still fits - splitOversizedUnit atom fallback for unbroken oversize units - regression tests for strict cap, overlap drop, and atom split Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
Co-authored-by: kiloconnect[bot] <240665456+kiloconnect[bot]@users.noreply.github.com>
de696cb to
5c99528
Compare
# Conflicts: # deepdoc/parser/txt_parser.py # rag/nlp/__init__.py
… to prevent triggering atom sub-splitter
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17203 +/- ##
==========================================
- Coverage 94.56% 90.65% -3.91%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 650 -28
- Misses 25 39 +14
- Partials 14 28 +14 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
LGTM |
…P default) (#17808) ## Summary Fixes a regression introduced by #17203 (strict-cap atom-split) and a secondary delimiter-handling bug from #17723. **Root cause:** - #17203 added `_split_oversized_unit` / `_compute_chunk_update`, which split oversize units into ≤ token_size pieces. This collapsed `token_size=1` into 1-token chunks and set the cap at 512, mismatching the model-layer truncation boundary (embedding ~8191 / rerank 500/4096/8192/2048). Atom-split is unnecessary: oversize units stay whole and the model layer truncates. - #17723's delimiter handling dropped consecutive delimiters (`A####B` -> `A##B`), glued JSON items with `"".join`, ignored `children_delimiters`, and stripped whitespace delimiters. ## Changes - New pure helper `merge_paragraphs(paragraphs, token_size, strategy)` with a `MergeStrategy` enum (`UNDER_CAP` / `OVER_CAP`); **default `OVER_CAP`**. `UNDER_CAP` is a strict cap (never overflows `token_size`); `OVER_CAP` greedily accumulates adjacent paragraphs while the projected total stays within `token_size`, merging one boundary-overflow paragraph before closing. Oversize paragraphs stand alone. - `naive_merge` / `naive_merge_with_images` / `RAGFlowTxtParser.parser_txt` now use `merge_paragraphs`; atom-split removed. `naive_merge` / `naive_merge_with_images` always split a section on the delimiter whenever one is present (even when the section already fits `token_size`), so delimiter text never leaks into a chunk. Only the empty-delimiter (size-only) mode skips splitting. - `token_chunker`: delimiter text is dropped (not stripped); JSON flush joins buffered items with `"\n"`; `children_delimiters` and `PDF_POSITIONS_KEY` are preserved on the delimiter path. PDF positions are now attributed **per segment** — each split chunk carries only the positions of the item(s) that contributed to it — fixing a leak where page-N coordinates were attached to page-M chunks and all segments shared one preview image. - `test_txt_parser.py` rewritten to assert the new contract (not the old strict cap); `naive_merge` and delimiter-case-sensitive matrices updated. ## Contract (refs #17799) - user specified delimiter = chunk boundary; user specified delimiter text never enters a chunk. - `token_size` = soft target + merge strategy; no atom-split. - Default strategy = `OVER_CAP`; migration can switch to `UNDER_CAP` (strict cap). - `OVER_CAP` has no hard cap; the model layer truncates oversize units. `UNDER_CAP` enforces a strict cap. ## Notes - Closes the wrong-object revert in #17774 (revert #17723 would re-introduce delimiter-in-chunk and the strict cap). - Go-side alignment (`internal/ingestion/component/chunker/token.go`) is a follow-up PR. --------- Co-authored-by: CodeBuddy <[email protected]>
Fixes #17202 (and complements #12109).
Problem
RAGFlowTxtParser.parser_txt(deepdoc/parser/txt_parser.py:36-47) andrag.nlp.naive_merge(rag/nlp/__init__.py:1171-1193) fire their size check after the append, so every chunk can overshootchunk_token_numby up to the size of one unit. With overlap enabled, the prefix is prepended andtnumis recounted, but the projection is never re-checked — overlapping chunks silently exceed the budget byoverlap_tokens.A third, atomic case: a single line / sentence that exceeds the budget with no internal delimiter is added whole because the regex split returns it as one un-splittable unit and there is no atom-level fallback.
RAGFlowHtmlParser.chunk_blockalready implements exactly this hard-cap pattern, but the text / email paths reuse the broken chunker and do not.Measured on a live dataset (336
.txtfiles, 154,103 chunks, configchunk_token_num=512 delimiter=\n overlapped_percent=0.1): 56.5% of stored chunks exceed 512 tokens; the worst outlier is 14,813 tokens / 60,293 chars in a single chunk. Symptom downstream: rerank failures on the >2048-token outliers (ref. #12109) and silent embedding truncation on every oversize chunk.Fix
Mirror the proven pattern in
RAGFlowHtmlParser.chunk_block:Proactive projected-total check in
TxtParser.parser_txtand innaive_merge.add_chunk:The check uses the projected total and runs before the append, so the cap is exact, never approached-then-exceeded.
Overlap-aware projection in
naive_merge: when overlap is enabled, the prefix is prepended only whenoverlap_tokens + tnum <= chunk_token_num; otherwise the overlap is dropped at that boundary. The naive_merge-with-images mirror gets the same treatment. Custom-delimiter behaviour is preserved per the existing test suite.Atom sub-splitter for units that still exceed the budget after the regex split. Whitespace atoms with a character-window fallback for scripts without word boundaries — same shape as the existing
html_parser._split_oversized_block, so behaviour matches for HTML vs.txtvs PDF atomic-oversize.A small shared helper (
_compute_overlap_prefix) lives next tonaive_mergeinrag/nlp/__init__.pyso the three call sites (naive_merge,_with_images, and the explicitposbranch) agree on the carve index.Result on the dataset above
Tests
+10and+2slack) to0— they existed only to document the soft-cap bug.test_strict_cap_no_overlap_packs_to_budget,test_strict_cap_with_overlap_drops_overlap_at_overflow_boundary,test_strict_cap_overlap_chosen_when_it_fits,test_strict_cap_single_overlong_section_is_sub_split_on_whitespacefornaive_merge.test_images_strict_cap_packs_to_budgetfornaive_merge_with_images.test/unit_test/deepdoc/parser/test_txt_parser.pycoversparser_txtstrict cap and atom sub-split. Uses the same path-loading pattern as the existingtest_html_parser.pyto avoid pulling the deep import chain into a test-time-only venv.All 22 unit tests pass on the host venv:
ruff checkandruff format --checkare clean on all four changed files.Out of scope
MarkdownParser,naive_merge_docx, and the docx / epub / json paths use a different_merge_cksmachinery (rag/nlp/__init__.py:1574) that already enforces the budget. They are unchanged.chunk_blockcall sites indeepdoc/parser/html_parser.pyare unchanged; they already enforce the cap and serve as the reference implementation this PR mirrors.Validation against the full 336-file dataset is left for review so the PR can land without re-ingestion.