Repository navigation
fix: align pipeline delimiter chunking - #17723
Conversation
# Conflicts: # deepdoc/parser/txt_parser.py
📝 WalkthroughWalkthroughThe PR adds optional delimiter preservation to text parsing. It updates chunk routing for delimiter and token-size modes across text, HTML-like, and structured JSON inputs. Source-code parsing enables delimiter preservation. ChangesDelimiter-aware chunking
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 2
🧹 Nitpick comments (1)
deepdoc/parser/txt_parser.py (1)
62-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd logging for the new delimiter flows.
deepdoc/parser/txt_parser.py#L62-L66: log delimiter-preservation activation and section count without document content.rag/flow/chunker/token_chunker.py#L316-L326: log selected delimiter mode, input format, and emitted chunk count without payloads.As per coding guidelines:
**/*.py: Add logging for new flows.🤖 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 62 - 66, Add non-content logging for the delimiter-preservation flow in the relevant text parser method, recording whether preservation is enabled and the section count. Also update the chunking flow in rag/flow/chunker/token_chunker.py around the selected delimiter handling to log delimiter mode, input format, and emitted chunk count; do not include document or chunk payloads.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 `@rag/flow/chunker/token_chunker.py`:
- Around line 368-377: Update the chunk construction in the token chunking flow
to retain PDF positions for each buffered split text chunk by mapping the source
chunk’s PDF_POSITIONS_KEY to the corresponding split text. Ensure every
replacement chunk carries the mapped positions before restore_pdf_text_previews
runs, while preserving the existing filtering of blank text.
- Around line 387-391: Before the early return in the media-only branch of the
chunking flow, apply the same child-delimiter splitting logic used around the
later JSON chunk finalization path. Ensure chunks configured with delimiter mode
honor children_delimiters before _finalize_json_chunks(chunks), while preserving
the existing context attachment, preview restoration, callback, and return
behavior.
---
Nitpick comments:
In `@deepdoc/parser/txt_parser.py`:
- Around line 62-66: Add non-content logging for the delimiter-preservation flow
in the relevant text parser method, recording whether preservation is enabled
and the section count. Also update the chunking flow in
rag/flow/chunker/token_chunker.py around the selected delimiter handling to log
delimiter mode, input format, and emitted chunk count; do not include document
or chunk payloads.
🪄 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: 3e0ea22e-99bb-4159-ab90-cdc21a03755d
📒 Files selected for processing (3)
deepdoc/parser/txt_parser.pyrag/flow/chunker/token_chunker.pyrag/flow/parser/parser.py
| chunks.extend( | ||
| { | ||
| "text": text, | ||
| "doc_type_kwd": "text", | ||
| "ck_type": "text", | ||
| "tk_nums": num_tokens_from_string(text), | ||
| } | ||
| for text in split_texts | ||
| if text.strip() | ||
| ) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Preserve PDF positions for buffered text chunks.
These replacement chunks omit PDF_POSITIONS_KEY. Therefore, restore_pdf_text_previews at Line 388 cannot identify PDF text chunks to restore. Retain and map source positions to each split text chunk before calling restore_pdf_text_previews.
🤖 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/flow/chunker/token_chunker.py` around lines 368 - 377, Update the chunk
construction in the token chunking flow to retain PDF positions for each
buffered split text chunk by mapping the source chunk’s PDF_POSITIONS_KEY to the
corresponding split text. Ensure every replacement chunk carries the mapped
positions before restore_pdf_text_previews runs, while preserving the existing
filtering of blank text.
| _attach_context_to_media_chunks(chunks, self._param.table_context_size, self._param.image_context_size) | ||
| await restore_pdf_text_previews(chunks, from_upstream, self._canvas) | ||
| self.set_output("chunks", _finalize_json_chunks(chunks)) | ||
| self.callback(1, "Done.") | ||
| return |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Apply child-delimiter splitting before the early return.
This branch returns before Lines 400-401. Therefore, JSON chunks in delimiter mode ignore children_delimiters, unlike the other chunking path.
Proposed fix
_attach_context_to_media_chunks(chunks, self._param.table_context_size, self._param.image_context_size)
+ if custom_pattern:
+ chunks = _split_chunk_docs_by_children(chunks, custom_pattern)
await restore_pdf_text_previews(chunks, from_upstream, self._canvas)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| _attach_context_to_media_chunks(chunks, self._param.table_context_size, self._param.image_context_size) | |
| await restore_pdf_text_previews(chunks, from_upstream, self._canvas) | |
| self.set_output("chunks", _finalize_json_chunks(chunks)) | |
| self.callback(1, "Done.") | |
| return | |
| _attach_context_to_media_chunks(chunks, self._param.table_context_size, self._param.image_context_size) | |
| if custom_pattern: | |
| chunks = _split_chunk_docs_by_children(chunks, custom_pattern) | |
| await restore_pdf_text_previews(chunks, from_upstream, self._canvas) | |
| self.set_output("chunks", _finalize_json_chunks(chunks)) | |
| self.callback(1, "Done.") | |
| 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/flow/chunker/token_chunker.py` around lines 387 - 391, Before the early
return in the media-only branch of the chunking flow, apply the same
child-delimiter splitting logic used around the later JSON chunk finalization
path. Ensure chunks configured with delimiter mode honor children_delimiters
before _finalize_json_chunks(chunks), while preserving the existing context
attachment, preview restoration, callback, and return behavior.
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 `@deepdoc/parser/txt_parser.py`:
- Around line 70-76: Update the section-processing loop around the delimiter
handling to buffer complete delimiter runs and emit every delimiter with an
adjacent text section, preserving leading and repeated delimiters; when the
input contains only delimiters, emit them as a delimiter-only section. Extend
coverage for leading, repeated, and delimiter-only inputs while keeping
non-delimiter parsing unchanged.
🪄 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: 026c064f-c568-4d0e-bc74-1494fa2145fc
📒 Files selected for processing (1)
deepdoc/parser/txt_parser.py
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)
deepdoc/parser/txt_parser.py (1)
30-35: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winLog the delimiter-preservation mode.
Add
keep_delimitersto the parser debug record. The current logs cannot distinguish delimiter-preserving output from ordinary output.As per coding guidelines, "
**/*.py: Add logging for new flows."🤖 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 30 - 35, Update the parser debug logging in the flow centered on TextParser.__call__ and parser_txt to include the keep_delimiters mode, so records distinguish delimiter-preserving output from ordinary output. Reuse the existing parser logging mechanism and log the boolean value without changing parsing behavior.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 `@deepdoc/parser/txt_parser.py`:
- Around line 44-52: Update the chunking logic around the token-limit check to
compare tk_nums[-1] + tnum against chunk_token_num before appending t, so
ordinary parser calls never create bounded chunks that exceed the configured
limit. Preserve the existing handling for oversized individual sections, and
keep any unlimited delimiter-mode behavior in its separate routing layer rather
than this method.
---
Outside diff comments:
In `@deepdoc/parser/txt_parser.py`:
- Around line 30-35: Update the parser debug logging in the flow centered on
TextParser.__call__ and parser_txt to include the keep_delimiters mode, so
records distinguish delimiter-preserving output from ordinary output. Reuse the
existing parser logging mechanism and log the boolean value without changing
parsing behavior.
🪄 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: 96e503cb-6a7a-4326-898f-c6ce81d45809
📒 Files selected for processing (2)
deepdoc/parser/txt_parser.pytest/unit_test/deepdoc/parser/test_txt_parser.py
💤 Files with no reviewable changes (1)
- test/unit_test/deepdoc/parser/test_txt_parser.py
| if tk_nums[-1] > chunk_token_num: | ||
| cks.append(t) | ||
| tk_nums.append(tnum) | ||
| else: | ||
| if cks[-1]: | ||
| cks[-1] += "\n" + t | ||
| else: | ||
| cks[-1] += t | ||
| tk_nums[-1] += tnum |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Restore the token limit for ordinary parser calls.
Line 44 checks the previous chunk size before it appends t. If the current chunk has 100 tokens, chunk_token_num is 128, and t has 100 tokens, this code creates a 200-token chunk. It starts a new chunk only on the following section.
This method has no delimiter_mode parameter, so the changed behavior also affects ordinary parsing. Check the prospective size before appending. Keep any intentional unlimited delimiter-mode behavior in the delimiter-mode routing layer. Restore bounded handling for one oversized section where the ordinary parser contract requires it.
🤖 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 44 - 52, Update the chunking logic
around the token-limit check to compare tk_nums[-1] + tnum against
chunk_token_num before appending t, so ordinary parser calls never create
bounded chunks that exceed the configured limit. Preserve the existing handling
for oversized individual sections, and keep any unlimited delimiter-mode
behavior in its separate routing layer rather than this method.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17723 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
wangq8
left a comment
There was a problem hiding this comment.
Thanks for the PR! The goal of aligning delimiter-mode chunking in the pipeline makes sense. However, I have several concerns that need to be addressed:
1. Chunk size cap removed for ALL txt-parser callers
The add_chunk rewrite in deepdoc/parser/txt_parser.py changes behavior for all callers — not just the new delimiter-mode path:
- Old: checked
merged_tnum <= chunk_token_numbefore appending — prevented overshoot. - New: only checks if the current chunk is already over budget (
tk_nums[-1] > chunk_token_num). A chunk that starts at 80 tokens can absorb a 100-token section and end up at 180 tokens, well past the cap.
Combined with removing the _split_oversized_unit call, chunk_token_num is no longer enforced by the txt parser. This contradicts the PR summary claim: "Keep ordinary naive parser behavior unchanged."
Suggestion: If delimiter-mode intentionally ignores chunk_token_num, that logic belongs in the chunker layer (where delimiter_mode is checked), not in the txt parser which is a shared utility. Restore the original add_chunk and keep _split_oversized_unit.
2. _split_text_by_pattern behavior change affects all callers
The function now discards delimiters instead of keeping them attached to each chunk. This is a breaking change for any caller that relied on delimiters being preserved. The comment update to "discard delimiters" confirms this is intentional, but it is not scoped to delimiter_mode="delimiter" — it affects all paths.
Suggestion: Either keep the old behavior for non-delimiter-mode callers, or add a keep_delimiters parameter to _split_text_by_pattern so the new discard behavior is opt-in.
3. Unit tests deleted without replacement
test/unit_test/deepdoc/parser/test_txt_parser.py (178 lines) is deleted entirely. These tests validated the strict-cap invariant — no chunk exceeding chunk_token_num. If the new behavior intentionally loosens that invariant, new tests should be added to document the expected behavior and prevent regressions.
4. "".join(text_buffer) in the delimiter-mode flush — paragraph boundaries lost
In the new flush_text_buffer:
combined_text = "".join(text_buffer)Consecutive text chunks from structured JSON are concatenated without any separator. If the original document had paragraph gaps represented as separate text chunks, those boundaries are silently erased before re-splitting by delimiter pattern.
Suggestion: Use "\n".join(text_buffer) or the original separator between text chunks.
5. Redundant branch in non-JSON path
For the text/markdown/html path:
if self._param.delimiter_mode == "delimiter":
cks = _split_text_by_pattern(payload, delimiter_pattern)
elif delimiter_pattern:
cks = _split_text_by_pattern(payload, delimiter_pattern)Both branches do the same thing. The delimiter_mode == "delimiter" check has no effect for non-JSON input.
Please address items 1–3 before merging — they affect correctness for all naive-parser callers, not just the new delimiter pipeline. Items 4–5 are nice-to-fix.
Happy to re-review after updates!
…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]>
…finiflow#17723/infiniflow#17808) Python reference changed via infiniflow#17723 (custom-delimiter rewrite) and infiniflow#17808 (OVER_CAP default + delimiter boundary). Re-capture all golden fixtures so the parity oracle reflects current Python before the Go-side alignment work. Co-authored-by: xugangqiang <>
…17723) (#18182) Go's `TokenChunker` previously ignored **bare (non-backtick) delimiters** such as `::`, `.`, or `;`. `compileDelimPattern` compiled them with `keepBare=false`, so a bare delimiter produced a `nil` pattern and the payload was routed to the single-section merge that never split on it — diverging from Python's `naive_merge`, which splits on bare delimiters and then merges by token size.
Summary
delimiter_mode="delimiter"ignorechunk_token_size.