Skip to content

fix(chunker): enforce strict chunk_token_num cap on .txt / PDF / email paths - #17203

Merged
yuzhichang merged 12 commits into
infiniflow:mainfrom
skbs-eng:fix/chunker-strict-cap
Aug 1, 2026
Merged

yuzhichang merged 12 commits into
infiniflow:mainfrom
skbs-eng:fix/chunker-strict-cap

Conversation

@skbs-eng

Copy link
Copy Markdown
Contributor

Fixes #17202 (and complements #12109).

Problem

RAGFlowTxtParser.parser_txt (deepdoc/parser/txt_parser.py:36-47) and rag.nlp.naive_merge (rag/nlp/__init__.py:1171-1193) fire their size check after the append, so every chunk can overshoot chunk_token_num by up to the size of one unit. With overlap enabled, the prefix is prepended and tnum is recounted, but the projection is never re-checked — overlapping chunks silently exceed the budget by overlap_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_block already implements exactly this hard-cap pattern, but the text / email paths reuse the broken chunker and do not.

Measured on a live dataset (336 .txt files, 154,103 chunks, config chunk_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:

  1. Proactive projected-total check in TxtParser.parser_txt and in naive_merge.add_chunk:

    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] += tnum; return
    cks.append(t); tk_nums.append(tnum)

    The check uses the projected total and runs before the append, so the cap is exact, never approached-then-exceeded.

  2. Overlap-aware projection in naive_merge: when overlap is enabled, the prefix is prepended only when overlap_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.

  3. 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 .txt vs PDF atomic-oversize.

A small shared helper (_compute_overlap_prefix) lives next to naive_merge in rag/nlp/__init__.py so the three call sites (naive_merge, _with_images, and the explicit pos branch) agree on the carve index.

Result on the dataset above

Before After
Chunks > 512 tokens 56.5% 0%
Median tokens 539 <= 512
Largest chunk 14,813 tokens <= 512 tokens

Tests

  • Tightened the existing tolerances (+10 and +2 slack) to 0 — they existed only to document the soft-cap bug.
  • Added 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_whitespace for naive_merge.
  • Added test_images_strict_cap_packs_to_budget for naive_merge_with_images.
  • New test/unit_test/deepdoc/parser/test_txt_parser.py covers parser_txt strict cap and atom sub-split. Uses the same path-loading pattern as the existing test_html_parser.py to avoid pulling the deep import chain into a test-time-only venv.

All 22 unit tests pass on the host venv:

test_naive_merge.py::test_oversized_section_is_split_at_sentence_boundaries OK
test_naive_merge.py::test_small_sections_are_merged_not_oversplit           OK
test_naive_merge.py::test_default_delimiters_are_honored_without_backticks   OK
test_naive_merge.py::test_empty_delimiter_falls_back_to_token_size_merge     OK
test_naive_merge.py::test_overlap_prefix_is_counted_in_token_budget         OK
test_naive_merge.py::test_custom_delimiter_ignores_chunk_size                OK
test_naive_merge.py::test_custom_delimiter_does_not_size_merge              OK
test_naive_merge.py::test_images_oversized_section_is_split                 OK
test_naive_merge.py::test_images_custom_delimiter_preserved                 OK
test_naive_merge.py::test_images_plain_string_input                         OK
test_naive_merge.py::test_images_mismatched_lengths_returns_empty           OK
test_naive_merge.py::test_images_shared_lazyimage_not_stacked_…              OK
test_naive_merge.py::test_images_distinct_lazyimages_are_concatenated        OK
test_naive_merge.py::test_strict_cap_no_overlap_packs_to_budget             OK
test_naive_merge.py::test_strict_cap_with_overlap_drops_…                   OK
test_naive_merge.py::test_strict_cap_single_overlong_section_…              OK
test_naive_merge.py::test_strict_cap_overlap_chosen_when_it_fits            OK
test_naive_merge.py::test_images_strict_cap_packs_to_budget                 OK
test_txt_parser.py::test_no_overshoot_when_packing_short_lines              OK
test_txt_parser.py::test_no_overshoot_at_chunk_boundary                     OK
test_txt_parser.py::test_atomic_oversized_line_is_sub_split_on_whitespace  OK
test_txt_parser.py::test_empty_text_returns_empty                           OK

ruff check and ruff format --check are clean on all four changed files.

Out of scope

  • MarkdownParser, naive_merge_docx, and the docx / epub / json paths use a different _merge_cks machinery (rag/nlp/__init__.py:1574) that already enforces the budget. They are unchanged.
  • The chunk_block call sites in deepdoc/parser/html_parser.py are 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.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🌈 python Pull requests that update Python code 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jul 21, 2026
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Text 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.

Changes

Strict chunk token caps

Layer / File(s) Summary
Text parser hard-cap handling
deepdoc/parser/txt_parser.py, test/unit_test/deepdoc/parser/test_txt_parser.py
Text sections are packed only when projected token counts fit. Empty sections are skipped. Oversized sections are split into bounded pieces, including unbroken text.
Naive merge and image alignment
rag/nlp/__init__.py
Both merge paths apply projected token checks, conditionally include overlap and position text, split oversized units, and keep image results aligned.
Hard-cap regression coverage
test/unit_test/rag/test_naive_merge.py
Tests require strict token limits and cover oversized sections, overlap handling, whitespace and unbroken-text splitting, position text, delimiter handling, and image alignment.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related issues

  • infiniflow/ragflow#15801 — Addresses oversized-section splitting and overlap token accounting in the naive merge paths.

Possibly related PRs

  • infiniflow/ragflow#17275 — Modifies the same chunking functions to enforce predictive hard caps, with overlapping regression tests for text and image merging.

Poem

A rabbit checks each token’s space,
Then packs the chunks at measured pace.
Long lines split when limits call,
Overlap fits—or drops at the wall.
Images keep their matching place,
While tidy chunks race through the maze.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: enforcing the strict chunk_token_num cap across the affected chunking paths.
Description check ✅ Passed The description explains the problem, fix, impact, tests, and scope, although it omits the template's Summary heading.
Linked Issues check ✅ Passed The changes satisfy issue #17202 through projected size checks, overlap-aware budgeting, oversized-unit splitting, and regression tests.
Out of Scope Changes check ✅ Passed The changed implementation, tests, and logging are directly related to enforcing the chunk_token_num cap described in issue #17202.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 2
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/chunker-strict-cap
🛠️ Fix failing CI checks 💡
  • 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.

❤️ Share

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

@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: 4

🧹 Nitpick comments (3)
test/unit_test/deepdoc/parser/test_txt_parser.py (1)

110-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No test exercises the single-oversized-atom character-window fallback.

test_atomic_oversized_line_is_sub_split_on_whitespace only 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 exceeding chunk_token_num) — where the char-count-as-token-count bug lives (see deepdoc/parser/txt_parser.py lines 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 win

Missing logging for the new oversized-split flow.

rag/nlp/__init__.py's equivalent new flows added logging.debug(...) (e.g. at the end of naive_merge), but this new per-section splitting path in parser_txt has none. As per coding guidelines, **/*.py changes 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 win

Fallback char-window branch still not exercised with a token-dense atom.

test_strict_cap_single_overlong_section_is_sub_split_on_whitespace uses "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's atom[i:i+chunk_token_num] slicing, flagged separately on rag/nlp/__init__.py lines 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a85d1c and 84e762a.

📒 Files selected for processing (4)
  • deepdoc/parser/txt_parser.py
  • rag/nlp/__init__.py
  • test/unit_test/deepdoc/parser/test_txt_parser.py
  • test/unit_test/rag/test_naive_merge.py

Comment thread deepdoc/parser/txt_parser.py Resolved
Comment thread deepdoc/parser/txt_parser.py Resolved
Comment thread rag/nlp/__init__.py Resolved
Comment thread rag/nlp/__init__.py Resolved

@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.

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 win

Strict token cap bypassed when appending delimiters or position text.

The chunk_token_num limit can still be bypassed during chunk creation and merging. Extra text (\n or pos) 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: In naive_merge, verify that t + pos fits before adding pos to the first chunk, and check that cks[-1] + t + pos (or just cks[-1] + t) strictly fits before completing a proactive merge.
  • rag/nlp/__init__.py#L1369-L1409: Apply the same exact merged-size checks for pos additions in the first chunk and proactive merge paths of naive_merge_with_images.
  • deepdoc/parser/txt_parser.py#L41-L54: Use num_tokens_from_string(cks[-1] + "\n" + t) <= chunk_token_num to verify the combined string fits before assigning it.
🛠️ Proposed fixes across all three locations

For rag/nlp/__init__.py (in naive_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])
             return

For rag/nlp/__init__.py (in naive_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)
             return

For 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

📥 Commits

Reviewing files that changed from the base of the PR and between 84e762a and 7e203ce.

📒 Files selected for processing (4)
  • deepdoc/parser/txt_parser.py
  • rag/nlp/__init__.py
  • test/unit_test/deepdoc/parser/test_txt_parser.py
  • test/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

@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 (2)
rag/nlp/__init__.py (2)

1340-1345: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a debug log when the atom-splitting fallback triggers.

_split_oversized_unit is the new safety-net path for units that survive delimiter splitting but still exceed chunk_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_chunk logic is duplicated almost verbatim between naive_merge and naive_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_images bookkeeping. This is exactly why the prior tk_nums desync 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e203ce and a38927f.

📒 Files selected for processing (4)
  • deepdoc/parser/txt_parser.py
  • rag/nlp/__init__.py
  • test/unit_test/deepdoc/parser/test_txt_parser.py
  • test/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

Comment thread rag/nlp/__init__.py Resolved
@skbs-eng

Copy link
Copy Markdown
Contributor Author

Actionable comments posted: 1

🧹 Nitpick comments (2)

rag/nlp/init.py (2)> 1340-1345: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a debug log when the atom-splitting fallback triggers.
_split_oversized_unit is the new safety-net path for units that survive delimiter splitting but still exceed chunk_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_chunk logic is duplicated almost verbatim between naive_merge and naive_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_images bookkeeping. This is exactly why the prior tk_nums desync 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

can you add the appropriate reviewers to this PR?

@skbs-eng

Copy link
Copy Markdown
Contributor Author

@yuzhichang @Lynn-Inf @wangq8 @dcc123456 please review!

@skbs-eng

Copy link
Copy Markdown
Contributor Author

@yuzhichang @Lynn-Inf @wangq8 @dcc123456 @JinHai-CN please review!

@yuzhichang yuzhichang added the ci Continue Integration label Jul 31, 2026
@yuzhichang

Copy link
Copy Markdown
Member

@skbs-eng We are actively porting from python to golang. Could you implement the go part in this same PR?

@skbs-eng
skbs-eng force-pushed the fix/chunker-strict-cap branch from 77df5f2 to 6a8111a Compare July 31, 2026 11:07
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 31, 2026
@skbs-eng

skbs-eng commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor Author

@yuzhichang Go port is in this PR now.

internal/ingestion/component/chunker/token.go mirrors the Python strict chunk_token_num hard-cap:

  • projected-total merge before append
  • overlap only when overlap+segment still fits the budget
  • splitOversizedUnit atom fallback for unbroken oversize units (whitespace pack + token-budget char windows)

Coverage in token_strict_cap_test.go (+ updated overlap tag-strip test). Chunker package tests pass (CGO_ENABLED=0 go test ./internal/ingestion/component/chunker/).

skbs-eng and others added 7 commits July 31, 2026 17:21
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>
@skbs-eng
skbs-eng force-pushed the fix/chunker-strict-cap branch from de696cb to 5c99528 Compare July 31, 2026 12:35
@yuzhichang
yuzhichang self-requested a review July 31, 2026 15:01
@codecov

codecov Bot commented Aug 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (776b937) to head (872afd5).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@yuzhichang
yuzhichang merged commit deb3d0c into infiniflow:main Aug 1, 2026
5 checks passed
yuzhichang pushed a commit that referenced this pull request Aug 5, 2026
…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]>
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 🌈 python Pull requests that update Python code size:XL This PR changes 500-999 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chunker ignores chunk_token_num: soft cap routinely overshoots by one unit (and can blow past 100x)

2 participants