Repository navigation
Fix: TokenChunker discards TitleChunker chunks when output_format is 'chunks' - #16825
Conversation
…'chunks' When an upstream chunker (e.g. TitleChunker) emits output_format='chunks' and populates the chunks field, TokenChunker._invoke had no branch for 'chunks' and fell through to the json path, reading the parser's raw json_result instead. The chapter-aware chunks were silently dropped and the flat parser json was re-chunked, degrading PageIndex/TOC extraction and retrieval quality. Read from_upstream.chunks when output_format == 'chunks', mirroring the existing selection in title_chunker/common.py. Chunk items share the json_result item shape, so the existing token-sizing path handles them unchanged. Adds an isolated unit test that runs the real TokenChunker._invoke and asserts the upstream chunks are consumed rather than the raw parser json. Signed-off-by: Yash Raj Pandey <[email protected]>
📝 WalkthroughWalkthroughTokenChunker now uses upstream ChangesTokenChunker upstream chunk handling
Estimated code review effort: 2 (Simple) | ~10 minutes 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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/flow/chunker/token_chunker.py (1)
362-365: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftPreserve chapter boundaries in the token-size merge path.
_merge_text_chunks_by_token_size()only looks atck_typeand token size, so whendelimiter_patternis empty it can still merge adjacent structured chunks across section breaks. Carry a boundary marker through the upstream chunks and stop merging when it changes.🤖 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 362 - 365, Preserve section boundaries when merging chunks: update the upstream chunk construction (including _build_json_chunks and related chunk metadata) to attach a boundary marker, then update _merge_text_chunks_by_token_size to compare that marker and refuse merges when it changes. Ensure the marker survives context attachment and is retained on merged chunks, while preserving existing token-size and ck_type behavior.
🧹 Nitpick comments (1)
rag/flow/tests/test_token_chunker.py (1)
84-146: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winImport the real schema directly and drop the fallback stub.
rag.flow.chunker.schemaalready depends on pydantic, so thetry/except Exceptionand hand-rolledTokenChunkerFromUpstreamonly add a second path and hide real import failures.🤖 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/tests/test_token_chunker.py` around lines 84 - 146, In the schema setup block, remove the broad try/except and the hand-rolled TokenChunkerFromUpstream fallback; directly import and load rag.flow.chunker.schema, preserving the existing loader validation and module installation. Allow genuine import or execution failures to propagate instead of masking them with a stub.Sources: Coding guidelines, Linters/SAST tools
🤖 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/tests/test_token_chunker.py`:
- Around line 166-187: The regression test only exercises TokenChunker’s
delimiter_mode="one" early return and not the chunk-processing pipeline. Add a
second test alongside
test_token_chunker_prefers_upstream_chunks_for_json_output_format_chunks using a
non-"one" delimiter_mode and upstream chunks containing structural metadata such
as docnm_kwd, top_int, and chapter markers; assert _invoke preserves chapter
boundaries and metadata after _build_json_chunks,
_merge_text_chunks_by_token_size, and _finalize_json_chunks.
---
Outside diff comments:
In `@rag/flow/chunker/token_chunker.py`:
- Around line 362-365: Preserve section boundaries when merging chunks: update
the upstream chunk construction (including _build_json_chunks and related chunk
metadata) to attach a boundary marker, then update
_merge_text_chunks_by_token_size to compare that marker and refuse merges when
it changes. Ensure the marker survives context attachment and is retained on
merged chunks, while preserving existing token-size and ck_type behavior.
---
Nitpick comments:
In `@rag/flow/tests/test_token_chunker.py`:
- Around line 84-146: In the schema setup block, remove the broad try/except and
the hand-rolled TokenChunkerFromUpstream fallback; directly import and load
rag.flow.chunker.schema, preserving the existing loader validation and module
installation. Allow genuine import or execution failures to propagate instead of
masking them with a stub.
🪄 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: a646f82a-a42d-4a3a-892d-39699081e16a
📒 Files selected for processing (2)
rag/flow/chunker/token_chunker.pyrag/flow/tests/test_token_chunker.py
| def test_token_chunker_prefers_upstream_chunks_for_json_output_format_chunks(): | ||
| # Regression for #16812: when the upstream (e.g. TitleChunker) emits | ||
| # output_format="chunks", TokenChunker must consume from_upstream.chunks and | ||
| # not fall through to the raw parser json_result. Heavy deps are stubbed so | ||
| # the real TokenChunker._invoke runs against the real schema when pydantic is | ||
| # available (see title_chunker/common.py for the same chunks-vs-json branch). | ||
| with _load_token_chunker_with_stubs() as token_chunker_module: | ||
| token_chunker = token_chunker_module.TokenChunker | ||
| param = token_chunker_module.TokenChunkerParam() | ||
| param.delimiter_mode = "one" | ||
| chunker = token_chunker(None, "token_chunker", param) | ||
|
|
||
| kwargs = { | ||
| "name": "token_chunker", | ||
| "output_format": "chunks", | ||
| "chunks": [{"text": "CHAPTER-AWARE"}], | ||
| "json": [{"text": "RAW-PARSER-JSON"}], | ||
| } | ||
|
|
||
| asyncio.run(chunker._invoke(**kwargs)) | ||
|
|
||
| assert chunker._outputs["chunks"] == [{"text": "CHAPTER-AWARE"}] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Test only covers the delimiter_mode == "one" early-return path.
The test sets param.delimiter_mode = "one" (line 175), which triggers the early return at lines 348–359 of token_chunker.py. This verifies data source selection but doesn't exercise the non-"one" path (lines 362–372) where _build_json_chunks, _merge_text_chunks_by_token_size, and _finalize_json_chunks process the chunks. The PR objective requires "process them without merging across chapter boundaries" and "preserve structural metadata for downstream PageIndex, retrieval, and extractor nodes" — neither is verified by this test.
Consider adding a second test case with delimiter_mode != "one" and upstream chunks carrying structural metadata (e.g., docnm_kwd, top_int, chapter markers) to verify that chapter boundaries and metadata survive the merge/finalize pipeline.
🤖 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/tests/test_token_chunker.py` around lines 166 - 187, The regression
test only exercises TokenChunker’s delimiter_mode="one" early return and not the
chunk-processing pipeline. Add a second test alongside
test_token_chunker_prefers_upstream_chunks_for_json_output_format_chunks using a
non-"one" delimiter_mode and upstream chunks containing structural metadata such
as docnm_kwd, top_int, and chapter markers; assert _invoke preserves chapter
boundaries and metadata after _build_json_chunks,
_merge_text_chunks_by_token_size, and _finalize_json_chunks.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16825 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…6825) Port of token_chunker.py:347 to the Go TokenChunker. When the upstream emitted chunks (output_format == "chunks", e.g. a TitleChunker feeding into this TokenChunker), consume those chunks rather than the raw parser json_result. Otherwise fall back to the structured json_result. This fixes infiniflow#16812 where a TitleChunker -> TokenChunker chain silently discarded the chapter-level chunks and re-chunked the raw parser output. Co-authored-by: yuzhichang <[email protected]>
Fixes #16812
Problem
In the
rag/flowingestion pipeline, whenTitleChunkerfeedsTokenChunker, the chapter-aware chunks are silently discarded and the parser's raw flat json is re-chunked instead.TitleChunkeremitsoutput_format="chunks"and writes its chapter-aware output to thechunksfield (rag/flow/chunker/title_chunker/common.py,set_output("output_format", "chunks")). ButTokenChunker._invokeonly handlesoutput_formatin["markdown", "text", "html"], then falls through to the# jsonpath which readsfrom_upstream.json_result. There is no branch for"chunks", sofrom_upstream.chunksis never read.Downstream effects reported in #16812: PageIndex/TOC extraction receives flat line-level text instead of structured chapter blocks (incorrect/duplicate/missing chapters), and retrieval quality degrades because chunks are no longer aligned to document structure.
Fix
Select the source list based on
output_format, mirroring the exact pattern already used intitle_chunker/common.py:chunksitems share the same dict shape asjson_resultitems (both consumed via.get("text"),.get("doc_type_kwd"), etc.), so they flow through the existing token-sizing path unchanged. One-line change, no behavior change for thejson/markdown/text/htmlpaths.Test
Adds
rag/flow/tests/test_token_chunker.py, an isolated unit test that runs the realTokenChunker._invoke(heavy deps stubbed; real pydantic schema used when available) and asserts that withoutput_format="chunks"the upstreamchunksare consumed rather than the raw parserjson.Verified RED -> GREEN: the test fails against the current code (reads the raw json) and passes with the fix.