Skip to content

Fix: TokenChunker discards TitleChunker chunks when output_format is 'chunks' - #16825

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
devYRPauli:fix/tokenchunker-consume-chunks
Jul 13, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
devYRPauli:fix/tokenchunker-consume-chunks

Conversation

@devYRPauli

Copy link
Copy Markdown
Contributor

Fixes #16812

Problem

In the rag/flow ingestion pipeline, when TitleChunker feeds TokenChunker, the chapter-aware chunks are silently discarded and the parser's raw flat json is re-chunked instead.

TitleChunker emits output_format="chunks" and writes its chapter-aware output to the chunks field (rag/flow/chunker/title_chunker/common.py, set_output("output_format", "chunks")). But TokenChunker._invoke only handles output_format in ["markdown", "text", "html"], then falls through to the # json path which reads from_upstream.json_result. There is no branch for "chunks", so from_upstream.chunks is 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 in title_chunker/common.py:

json_result = (from_upstream.chunks if from_upstream.output_format == "chunks" else from_upstream.json_result) or []

chunks items share the same dict shape as json_result items (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 the json/markdown/text/html paths.

Test

Adds rag/flow/tests/test_token_chunker.py, an isolated unit test that runs the real TokenChunker._invoke (heavy deps stubbed; real pydantic schema used when available) and asserts that with output_format="chunks" the upstream chunks are consumed rather than the raw parser json.

Verified RED -> GREEN: the test fails against the current code (reads the raw json) and passes with the fix.

…'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]>
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

TokenChunker now uses upstream chunks data when the upstream output format is "chunks". A regression test loads the real implementation with isolated stubs and verifies that upstream chunks are preserved over raw JSON input.

Changes

TokenChunker upstream chunk handling

Layer / File(s) Summary
Select upstream chunks for chunk output
rag/flow/chunker/token_chunker.py
_invoke selects from_upstream.chunks for "chunks" output and retains json_result as the fallback source otherwise.
Validate upstream chunk preference
rag/flow/tests/test_token_chunker.py
Adds isolated module loading and verifies that _outputs["chunks"] matches upstream chunks when both chunks and JSON inputs are provided.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

I’m a rabbit with chunks in my tray,
Keeping the chapter paths all the way.
Raw JSON waits, while upstream leads,
Tests hop brightly through stubby reeds.
Thump, thump—structured output succeeds!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main fix: TokenChunker now respects upstream chunks when output_format is "chunks".
Description check ✅ Passed It includes the problem, fix, and test details, though it doesn't follow the template's Summary heading.
Linked Issues check ✅ Passed The code change and test align with #16812 by reading upstream chunks when output_format is "chunks" and leaving other paths unchanged.
Out of Scope Changes check ✅ Passed The changes stay focused on TokenChunker behavior and a targeted regression test; no unrelated code paths were introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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: 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 lift

Preserve chapter boundaries in the token-size merge path. _merge_text_chunks_by_token_size() only looks at ck_type and token size, so when delimiter_pattern is 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 win

Import the real schema directly and drop the fallback stub. rag.flow.chunker.schema already depends on pydantic, so the try/except Exception and hand-rolled TokenChunkerFromUpstream only 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b60870 and 4e48aeb.

📒 Files selected for processing (2)
  • rag/flow/chunker/token_chunker.py
  • rag/flow/tests/test_token_chunker.py

Comment on lines +166 to +187
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"}]

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

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.

@yuzhichang
yuzhichang self-requested a review July 11, 2026 09:47

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 13, 2026
@yuzhichang yuzhichang added the ci Continue Integration label Jul 13, 2026
@codecov

codecov Bot commented Jul 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (eca8e87) to head (4e48aeb).
⚠️ Report is 46 commits behind head on main.

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.
📢 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
yuzhichang merged commit e54e7ec into infiniflow:main Jul 13, 2026
17 of 19 checks passed
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jul 13, 2026
…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]>
yuzhichang added a commit that referenced this pull request Jul 13, 2026
Ports two Python fixes to Go: the variable_ref_patt underscore/colon fix
(#16792) and the TokenChunker upstream-chunks fix (#16825). Keeps Go
behavior aligned with upstream Python.
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 lgtm This PR has been approved by a maintainer size:XS This PR changes 0-9 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: TokenChunker ignores TitleChunker's chunks output and reads the parser's raw json field instead when output_format="chunks"

2 participants