Skip to content

fix: align pipeline delimiter chunking - #17723

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b131
Aug 3, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b131

Conversation

@buua436

@buua436 buua436 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Preserve delimiters in pipeline parser sections when requested.
  • Recombine parser-pre-split text sections before delimiter-mode chunking.
  • Make delimiter_mode="delimiter" ignore chunk_token_size.
  • Remove delimiters from final chunks.
  • Keep ordinary naive parser behavior unchanged.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🌈 python Pull requests that update Python code labels Aug 3, 2026
# Conflicts:
#	deepdoc/parser/txt_parser.py
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Delimiter-aware chunking

Layer / File(s) Summary
Text delimiter preservation
deepdoc/parser/txt_parser.py, rag/flow/parser/parser.py
TxtParser accepts keep_delimiters, appends following delimiters when enabled, changes chunk accumulation, and source-code parsing enables the option.
Text chunk routing
rag/flow/chunker/token_chunker.py
Delimiter splitting removes matched delimiters. Text and HTML-like inputs select delimiter or token-size processing based on configuration.
Structured JSON chunk routing
rag/flow/chunker/token_chunker.py
JSON delimiter mode buffers text around media chunks, preserves boundaries and context, restores PDF previews, and limits token-size merging to token-size mode.

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

Possibly related PRs

Suggested labels: 🐞 bug

Suggested reviewers: wangq8, skbs-eng

Poem

A rabbit keeps each ending mark,
Through text and JSON in the dark.
Chunks split clean, media stays,
PDF previews return to place.
Delimiters hop along—
Thump, thump, the parse is strong!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: aligning pipeline delimiter chunking.
Description check ✅ Passed The description summarizes the main changes and matches the pull request objectives, although it omits background context.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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

🧹 Nitpick comments (1)
deepdoc/parser/txt_parser.py (1)

62-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1478aa4 and a370a4b.

📒 Files selected for processing (3)
  • deepdoc/parser/txt_parser.py
  • rag/flow/chunker/token_chunker.py
  • rag/flow/parser/parser.py

Comment on lines +368 to +377
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()
)

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.

🗄️ 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.

Comment on lines +387 to +391
_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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 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.

Suggested change
_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.

@buua436
buua436 requested a review from wangq8 August 3, 2026 07:18
@buua436 buua436 added the ci Continue Integration label Aug 3, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between a370a4b and 858062b.

📒 Files selected for processing (1)
  • deepdoc/parser/txt_parser.py

Comment thread deepdoc/parser/txt_parser.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.

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 win

Log the delimiter-preservation mode.

Add keep_delimiters to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 858062b and a9e7065.

📒 Files selected for processing (2)
  • deepdoc/parser/txt_parser.py
  • test/unit_test/deepdoc/parser/test_txt_parser.py
💤 Files with no reviewable changes (1)
  • test/unit_test/deepdoc/parser/test_txt_parser.py

Comment on lines +44 to +52
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 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

codecov Bot commented Aug 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (ef9feef) to head (a9e7065).
⚠️ Report is 5 commits behind head on main.

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

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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_num before 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!

@wangq8
wangq8 merged commit 9ccb23e into infiniflow:main Aug 3, 2026
3 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]>
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 10, 2026
…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 <>
yuzhichang pushed a commit that referenced this pull request Aug 12, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 🌈 python Pull requests that update Python code size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants