Skip to content

fix(paper): bound title-pivot merge by chunk_token_num (#12109) - #16959

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
deadtrickster:pr2-chunk-token-num
Sep 8, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
deadtrickster:pr2-chunk-token-num

Conversation

@deadtrickster

@deadtrickster deadtrickster commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Paper's title-pivot merge emitted a whole pivot as one unbounded chunk - the loop quoted in #12109. _merge_sections_by_pivot bounds it by chunk_token_num; @@...## position tags are stripped before counting so they don't eat the budget, and stay in the chunk for crop().

Originally this PR also covered the book chunker and the Go path; #18455 landed those, so it's now scoped to the paper gap only. rag/app/paper.py + unit tests (helper contract + a chunk()-level guard that's red against the unbounded loop).

@coderabbitai

coderabbitai Bot commented Jul 15, 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

chunk_token_num is parsed and enforced across Go ingestion, book parsing, and paper section grouping. Split chunks preserve structured metadata and DeepDoc position tags, with regression tests covering token caps, routing, grouping, and content preservation.

Changes

Chunk token enforcement

Layer / File(s) Summary
Chunk contract and ingestion splitting
internal/ingestion/component/schema/chunker.go, internal/ingestion/component/chunker/title.go, internal/ingestion/component/chunker/group.go, internal/ingestion/component/chunker/group_test.go
Adds optional chunk_token_num configuration and splits grouped text on newline boundaries while duplicating structured metadata across emitted pieces.
Book routing and position preservation
rag/app/book.py, test/unit_test/rag/test_book_positions.py
Routes capped book chunks through naive_merge and preserves @@...## DeepDoc position tags.
Paper section grouping limits
rag/app/paper.py, test/unit_test/rag/test_paper_chunk_size.py
Bounds merges of consecutive sections sharing a sec_id, while non-positive limits retain unlimited grouping behavior.

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

Sequence Diagram(s)

sequenceDiagram
  participant ParserConfig
  participant Chunkers
  participant TokenCounter
  participant ChunkOutput
  ParserConfig->>Chunkers: provide chunk_token_num
  Chunkers->>TokenCounter: count candidate section tokens
  TokenCounter-->>Chunkers: return token count
  Chunkers->>ChunkOutput: emit bounded chunks with metadata and position tags
Loading

Suggested reviewers: qinling0210

Poem

A bunny counts tokens, one, two, three,
Splits long pages neatly as can be.
Tags hop along, metadata too,
No oversized chunks escape the queue.
“Capped and tagged!” the rabbit sings.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.10% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address #12109 by enforcing chunk_token_num in book, paper, and Go title chunkers while preserving content and tags.
Out of Scope Changes check ✅ Passed No clearly unrelated code changes are present; the added Go logic and tests still align with fixing chunk_token_num handling.
Title check ✅ Passed The title accurately identifies the paper title-pivot merge fix and the chunk_token_num limit. It is concise and relevant, although it does not mention the additional book and Go changes summarized in…
Description check ✅ Passed The description clearly explains the problem, the paper-specific fix, position-tag handling, tests, and current scope. It does not use the template's "### Summary" heading, but it provides the require…
Full details: Title check

Explanation

The title accurately identifies the paper title-pivot merge fix and the chunk_token_num limit. It is concise and relevant, although it does not mention the additional book and Go changes summarized in the full changeset.

Full details: Description check

Explanation

The description clearly explains the problem, the paper-specific fix, position-tag handling, tests, and current scope. It does not use the template's "### Summary" heading, but it provides the required summary information and is mostly complete.


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.

@deadtrickster
deadtrickster marked this pull request as ready for review July 15, 2026 21:15
@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 15, 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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
rag/app/book.py (2)

1-1: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove migration history and references to obsolete behavior from comments.

As per coding guidelines, keep package and documentation comments aligned with the current runtime path and remove migration history (including upstream patches and past issue numbers).

  • rag/app/book.py#L161-177: Remove the extensive "Oracle local patch" block comment detailing upstream bugs and token counts.
  • rag/app/book.py#L182-189: Remove the comment discussing the "SECOND BUG" and the old @ splitting behavior.
  • rag/app/paper.py#L218-222: Reword the comment to remove references to issue #12109 and the old oversized chunk behavior.
  • test/unit_test/rag/test_book_positions.py#L17-38: Update the module docstring to describe the current tests, removing the narrative about "Two bugs" and patch history.
  • test/unit_test/rag/test_paper_chunk_size.py#L17-29: Update the module docstring to remove the narrative about issue #12109 and previous buggy symptoms.
  • internal/ingestion/component/schema/chunker.go#L266-271: Remove the explanation of how old chunkers produced oversized chunks and the reference to #12109.
  • internal/ingestion/component/chunker/group.go#L269-271: Remove the comment referencing #12109 and the oversized chunk history.
  • internal/ingestion/component/chunker/group_test.go#L234-236: Remove the reference to #12109 and how sections "became one oversized chunk".
🤖 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/app/book.py` at line 1, Remove migration and bug-history narratives from
the specified comments and module docstrings, including Oracle patch details,
“SECOND BUG” behavior, issue `#12109` references, token counts, and
oversized-chunk explanations. Reword the paper comment and test module
docstrings to describe only the current runtime behavior and test purpose, while
leaving executable code unchanged.

Source: Coding guidelines


1-1: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Add observability logging for new flows.

As per coding guidelines for Python files (**/*.py), ensure logging is added for new operational flows to aid observability.

  • rag/app/book.py#L179-181: Add logging.info or logging.debug indicating whether naive_merge or hierarchical_merge is selected based on the chunk_token_num setting.
  • rag/app/paper.py#L223-231: Add logging.info or logging.debug detailing the active chunk_token_num budget applied during section accumulation.
🤖 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/app/book.py` at line 1, ​​Add observability logs to the new
merge-selection flow, recording whether naive_merge or hierarchical_merge is
chosen based on chunk_token_num. Also log the active chunk_token_num budget
during section accumulation in the paper processing flow, using logging.info or
logging.debug.

Source: Coding guidelines

🧹 Nitpick comments (1)
rag/app/paper.py (1)

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

Use strict=True for zip().

Since sorted_sections and sec_ids are verified to be the same length (via the assert len(sorted_sections) == len(levels) earlier), consider adding strict=True to the zip() call to align with Python 3.10+ best practices and prevent silent truncation if the lengths ever differ.

♻️ Proposed refactor
-    for (txt, _), sec_id in zip(sorted_sections, sec_ids):
+    for (txt, _), sec_id in zip(sorted_sections, sec_ids, strict=True):
🤖 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/app/paper.py` at line 226, Update the zip call in the section-processing
loop to use strict=True, ensuring mismatched sorted_sections and sec_ids lengths
raise an error instead of being silently truncated while preserving the existing
iteration behavior.

Source: 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 `@test/unit_test/rag/test_book_positions.py`:
- Line 1: Remove the obsolete dummy helpers and their dedicated tests: delete
_old_split and test_old_split_drops_position_tag from test_book_positions.py,
and delete _group_old and test_old_grouping_makes_one_oversized_chunk from
test_paper_chunk_size.py. Update test_zero_budget_preserves_old_behaviour to
assert the expected single-chunk result directly with a hardcoded expectation,
without calling _group_old.

---

Outside diff comments:
In `@rag/app/book.py`:
- Line 1: Remove migration and bug-history narratives from the specified
comments and module docstrings, including Oracle patch details, “SECOND BUG”
behavior, issue `#12109` references, token counts, and oversized-chunk
explanations. Reword the paper comment and test module docstrings to describe
only the current runtime behavior and test purpose, while leaving executable
code unchanged.
- Line 1: ​​Add observability logs to the new merge-selection flow, recording
whether naive_merge or hierarchical_merge is chosen based on chunk_token_num.
Also log the active chunk_token_num budget during section accumulation in the
paper processing flow, using logging.info or logging.debug.

---

Nitpick comments:
In `@rag/app/paper.py`:
- Line 226: Update the zip call in the section-processing loop to use
strict=True, ensuring mismatched sorted_sections and sec_ids lengths raise an
error instead of being silently truncated while preserving the existing
iteration 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

Run ID: fea54f8f-c2ad-41ab-93c1-7e6ea4351663

📥 Commits

Reviewing files that changed from the base of the PR and between df5c8e7 and 20a4d01.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/schema/chunker.go
  • rag/app/book.py
  • rag/app/paper.py
  • test/unit_test/rag/test_book_positions.py
  • test/unit_test/rag/test_paper_chunk_size.py

@@ -0,0 +1,139 @@
#

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.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Remove tests that protect or reproduce obsolete behavior.

As per coding guidelines, remove tests and dummy implementations that solely exist to reproduce or protect obsolete behavior. Testing local dummy functions that intentionally recreate old bugs clutters the test suite and does not cover the actual application code.

  • test/unit_test/rag/test_book_positions.py#L65-68: Remove _old_split and its dedicated test test_old_split_drops_position_tag (lines 82-90).
  • test/unit_test/rag/test_paper_chunk_size.py#L38-49: Remove _group_old and its dedicated test test_old_grouping_makes_one_oversized_chunk (lines 70-74). Additionally, refactor test_zero_budget_preserves_old_behaviour (lines 88-90) to assert against a hardcoded single-chunk expectation instead of relying on _group_old.
🤖 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_book_positions.py` at line 1, Remove the obsolete
dummy helpers and their dedicated tests: delete _old_split and
test_old_split_drops_position_tag from test_book_positions.py, and delete
_group_old and test_old_grouping_makes_one_oversized_chunk from
test_paper_chunk_size.py. Update test_zero_budget_preserves_old_behaviour to
assert the expected single-chunk result directly with a hardcoded expectation,
without calling _group_old.

Source: Coding guidelines

@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 (1)
rag/app/book.py (1)

185-186: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Ensure the logged chunk limit matches the runtime fallback.

When chunk_token_num is absent from parser_config, the log statement will output chunk_token_num=None, but naive_merge will actually use the fallback value of 256. Assigning the resolved value to a local variable ensures the log accurately reflects the runtime behavior.

♻️ Proposed refactor
-        logging.debug("book chunk policy: naive_merge (chunk_token_num=%s)", parser_config.get("chunk_token_num"))
-        chunks = naive_merge(_sections_with_positions(sections), parser_config.get("chunk_token_num", 256), parser_config.get("delimiter", "\n。;!?"))
+        chunk_token_num = parser_config.get("chunk_token_num", 256)
+        logging.debug("book chunk policy: naive_merge (chunk_token_num=%s)", chunk_token_num)
+        chunks = naive_merge(_sections_with_positions(sections), chunk_token_num, parser_config.get("delimiter", "\n。;!?"))
🤖 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/app/book.py` around lines 185 - 186, Update the chunking logic around
naive_merge to resolve parser_config’s chunk_token_num once into a local value
with the 256 fallback, then use that same value in both the logging.debug call
and naive_merge invocation so the logged limit matches runtime behavior.
🤖 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/app/book.py`:
- Around line 71-73: Update the section-processing loop to use rsplit("@@", 1)
when extracting position tags, and detach the suffix only when it is a valid
DeepDoc tag terminating with ##. Preserve any natural @@ occurrences in the
section text as content, and otherwise return an empty tag so naive_merge cannot
duplicate unvalidated text.

---

Nitpick comments:
In `@rag/app/book.py`:
- Around line 185-186: Update the chunking logic around naive_merge to resolve
parser_config’s chunk_token_num once into a local value with the 256 fallback,
then use that same value in both the logging.debug call and naive_merge
invocation so the logged limit matches runtime 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

Run ID: 4a4984e2-436e-4980-94c1-4bc985d67d51

📥 Commits

Reviewing files that changed from the base of the PR and between 20a4d01 and 7ea8e31.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/schema/chunker.go
  • rag/app/book.py
  • rag/app/paper.py
  • test/unit_test/rag/test_book_positions.py
  • test/unit_test/rag/test_paper_chunk_size.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/ingestion/component/schema/chunker.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/group_test.go
  • rag/app/paper.py
  • internal/ingestion/component/chunker/group.go

Comment thread rag/app/book.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: 2

🤖 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/app/book.py`:
- Around line 189-191: Update the chunk_token_num assignment used by naive_merge
in the book chunking flow to fall back to 256 when the configured value is 0 or
otherwise falsy, while preserving explicitly configured positive limits. Keep
the existing logging and naive_merge invocation unchanged.

In `@test/unit_test/rag/test_book_positions.py`:
- Around line 48-53: Lengthen the passage string in
test_position_tag_is_preserved_through_merge to contain at least 8 words, while
preserving the existing POS setup and assertions. Do not change naive_merge or
the test’s expected 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

Run ID: 1f8191bd-e544-4d8b-83e3-6f23c4ca87f4

📥 Commits

Reviewing files that changed from the base of the PR and between 7ea8e31 and a68bcda.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/schema/chunker.go
  • rag/app/book.py
  • rag/app/paper.py
  • test/unit_test/rag/test_book_positions.py
  • test/unit_test/rag/test_paper_chunk_size.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/group.go

Comment thread rag/app/book.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

🤖 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 `@internal/ingestion/component/schema/chunker.go`:
- Around line 266-269: Update the grouped-title chunking flow in group.go to
enforce ChunkTokenNum for every emitted chunk, including individual lines larger
than the configured cap. Split oversized lines at token boundaries and preserve
the existing grouping behavior for lines within the limit, ensuring no emitted
chunk exceeds ChunkTokenNum.
🪄 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: 1eaf38e7-0f6e-4ceb-8dfa-d11908981239

📥 Commits

Reviewing files that changed from the base of the PR and between a68bcda and 219fdb6.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/schema/chunker.go
  • rag/app/book.py
  • rag/app/paper.py
  • test/unit_test/rag/test_book_positions.py
  • test/unit_test/rag/test_paper_chunk_size.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/group_test.go
  • rag/app/paper.py
  • internal/ingestion/component/chunker/group.go
  • test/unit_test/rag/test_paper_chunk_size.py

@deadtrickster

Copy link
Copy Markdown
Contributor Author

Addressed both:

  1. book.py: chunk_token_num now falls back to 256 when the configured value is falsy (e.g. an explicit 0), so naive_merge never gets a degenerate limit; positive values pass through unchanged.
  2. test_book_positions.py: lengthened the passage to 10 words (POS setup and assertions unchanged).

@deadtrickster

Copy link
Copy Markdown
Contributor Author

On the ChunkTokenNum hard-cap comment: I took the second option you suggested (document the exception) rather than splitting mid-line.

capChunkText intentionally mirrors python naive_merge: it splits at line boundaries and never cuts a boundary-less unit mid-token. Python behaves the same way (it splits at delimiter boundaries \n。;!?; a section with no delimiter that exceeds the cap is emitted whole). Hard-splitting a single oversized line at arbitrary token boundaries would cut sentences mid-way and diverge from the python path this PR is matching, for the uncommon case of a single record over the cap.

So I corrected the field doc to describe the actual contract (split at line boundaries; a single line over the cap is emitted whole), and the existing TestCapChunkText "single oversized line is not split mid-line" case documents it.

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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)
internal/ingestion/component/chunker/group.go (1)

257-288: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Apply RootChunkAsHeading prior to capping to prevent logic errors and budget violations.

By flattening the split pieces into the chunks array before evaluating RootChunkAsHeading, this logic introduces a few critical issues:

  1. chunks[0] may only be a fraction of the root group if the heading was split, resulting in an incomplete heading being prepended to other chunks.
  2. If there is only one group but it gets split into multiple pieces, len(chunks) > 1 becomes true. This incorrectly drops the first piece and prepends it to the remaining pieces.
  3. Prepending the heading text after capChunkText guarantees that the resulting chunks will exceed the configured chunk_token_num budget.

To resolve this, assemble the groups and apply the heading logic before splitting the text.

(Note: If the intent is to preserve the heading on every split piece of a section rather than just the first, you will need to adjust maxTok dynamically by subtracting the heading's token count before calling capChunkText, and then prepend the heading to each resulting piece.)

🛠️ Proposed fix (applying heading to the group before splitting)
-	chunks := make([]map[string]any, 0, len(groups))
-	for _, g := range groups {
-		if len(g) == 0 {
-			continue
-		}
-		var docType string
-		var imgID *string
-		if !plain {
-			first := g[0]
-			docType = first.docType
-			imgID = first.imgID
-		}
-		// Split a group larger than chunk_token_num (when set) so no chunk
-		// exceeds the budget; metadata is duplicated across the pieces.
-		for _, text := range capChunkText(joinGroupText(g), maxTok) {
-			chunk := map[string]any{"text": text}
-			if docType != "" {
-				chunk["doc_type_kwd"] = docType
-			}
-			if imgID != nil {
-				chunk["img_id"] = *imgID
-			}
-			chunks = append(chunks, chunk)
-		}
-	}
-	if p.RootChunkAsHeading && len(chunks) > 1 {
-		rootText := toString(chunks[0]["text"])
-		for i := 1; i < len(chunks); i++ {
-			chunks[i]["text"] = rootText + "\n" + toString(chunks[i]["text"])
-		}
-		chunks = chunks[1:]
-	}
+	type groupData struct {
+		text    string
+		docType string
+		imgID   *string
+	}
+	var groupList []groupData
+	for _, g := range groups {
+		if len(g) > 0 {
+			gd := groupData{text: joinGroupText(g)}
+			if !plain {
+				gd.docType = g[0].docType
+				gd.imgID = g[0].imgID
+			}
+			groupList = append(groupList, gd)
+		}
+	}
+
+	if p.RootChunkAsHeading && len(groupList) > 1 {
+		rootText := strings.TrimSuffix(groupList[0].text, "\n")
+		for i := 1; i < len(groupList); i++ {
+			groupList[i].text = rootText + "\n" + groupList[i].text
+		}
+		groupList = groupList[1:]
+	}
+
+	chunks := make([]map[string]any, 0, len(groupList))
+	for _, gd := range groupList {
+		for _, text := range capChunkText(gd.text, maxTok) {
+			chunk := map[string]any{"text": text}
+			if gd.docType != "" {
+				chunk["doc_type_kwd"] = gd.docType
+			}
+			if gd.imgID != nil {
+				chunk["img_id"] = *gd.imgID
+			}
+			chunks = append(chunks, chunk)
+		}
+	}
🤖 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 `@internal/ingestion/component/chunker/group.go` around lines 257 - 288,
Restructure the chunk assembly around RootChunkAsHeading so heading promotion is
determined by the number of non-empty groups before any text is capped. Build
each group’s complete text and metadata first, prepend the complete root group
text to subsequent group texts when enabled, remove the root group, then call
capChunkText on the resulting group texts so every emitted chunk remains within
maxTok and split pieces cannot be mistaken for separate groups.
🧹 Nitpick comments (1)
rag/app/book.py (1)

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

Remove the redundant list comprehension.

random_choices already returns a list, so wrapping the call in a list comprehension is unnecessary and creates a redundant copy.

♻️ Proposed refactor
-    bull = bullets_category([t for t in random_choices([t for t, _ in sections], k=100)])
+    bull = bullets_category(random_choices([t for t, _ in sections], k=100))
🤖 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/app/book.py` at line 184, Remove the redundant outer list comprehension
in the bullets_category call, passing the list returned by random_choices
directly while preserving its existing input and k=100 behavior.
🤖 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 `@internal/ingestion/component/chunker/group.go`:
- Around line 257-288: Restructure the chunk assembly around RootChunkAsHeading
so heading promotion is determined by the number of non-empty groups before any
text is capped. Build each group’s complete text and metadata first, prepend the
complete root group text to subsequent group texts when enabled, remove the root
group, then call capChunkText on the resulting group texts so every emitted
chunk remains within maxTok and split pieces cannot be mistaken for separate
groups.

---

Nitpick comments:
In `@rag/app/book.py`:
- Line 184: Remove the redundant outer list comprehension in the
bullets_category call, passing the list returned by random_choices directly
while preserving its existing input and k=100 behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: eb56e9e6-ef02-4059-8ee2-82559f49d2be

📥 Commits

Reviewing files that changed from the base of the PR and between 219fdb6 and 638f2ef.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/schema/chunker.go
  • rag/app/book.py
  • rag/app/paper.py
  • test/unit_test/rag/test_book_positions.py
  • test/unit_test/rag/test_paper_chunk_size.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/ingestion/component/chunker/title.go
  • rag/app/paper.py
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/schema/chunker.go
  • test/unit_test/rag/test_paper_chunk_size.py

@deadtrickster
deadtrickster force-pushed the pr2-chunk-token-num branch 2 times, most recently from ac245bb to 57547fd Compare July 19, 2026 15:23
@deadtrickster

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (1)
internal/ingestion/component/chunker/group_test.go (1)

287-296: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename variable to avoid shadowing the built-in cap function.

The variable name cap shadows the Go built-in function cap(). Consider renaming it to maxTok (matching the function's parameter name) to improve readability and avoid shadowing.

♻️ Proposed refactor
-		cap := 10
-		got := capChunkText(text, cap)
+		maxTok := 10
+		got := capChunkText(text, maxTok)
 		if len(got) < 2 {
 			t.Fatalf("over cap -> %d chunks, want >= 2", len(got))
 		}
 		for i, piece := range got {
-			if tokenizeStr(piece) > cap && strings.Count(piece, "\n") > 0 {
-				t.Errorf("piece %d has %d tokens > cap %d (and is multi-line)", i, tokenizeStr(piece), cap)
+			if tokenizeStr(piece) > maxTok && strings.Count(piece, "\n") > 0 {
+				t.Errorf("piece %d has %d tokens > maxTok %d (and is multi-line)", i, tokenizeStr(piece), maxTok)
 			}
 		}
🤖 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 `@internal/ingestion/component/chunker/group_test.go` around lines 287 - 296,
Rename the local variable cap in the capChunkText test to maxTok, and update the
call, comparisons, and failure message to use maxTok consistently without
changing test behavior.
🤖 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.

Nitpick comments:
In `@internal/ingestion/component/chunker/group_test.go`:
- Around line 287-296: Rename the local variable cap in the capChunkText test to
maxTok, and update the call, comparisons, and failure message to use maxTok
consistently without changing test behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 825cec9c-22ba-41cd-a301-03c9a17af031

📥 Commits

Reviewing files that changed from the base of the PR and between 638f2ef and 57547fd.

📒 Files selected for processing (8)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/schema/chunker.go
  • rag/app/book.py
  • rag/app/paper.py
  • test/unit_test/rag/test_book_positions.py
  • test/unit_test/rag/test_paper_chunk_size.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/ingestion/component/chunker/title.go
  • rag/app/paper.py
  • internal/ingestion/component/schema/chunker.go
  • test/unit_test/rag/test_paper_chunk_size.py
  • internal/ingestion/component/chunker/group.go

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@yingfeng could you please have a look?

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@xugangqiang ping

@xugangqiang

Copy link
Copy Markdown
Contributor

@deadtrickster Do you want to merge firstly and then rasie another PR to deal with below suggestion? Or add another commit and fix within one PR?

Suggestion: swap capChunkText and RootChunkAsHeading ordering in buildChunksFromRecordGroups

The current PR applies capChunkText after RootChunkAsHeading:

build chunks → RootChunkAsHeading (prepend root text, drop root) → capChunkText (split oversized)

This has a subtle issue: when RootChunkAsHeading prepends the root text to a chunk that was already near the token budget, the combined chunk may now exceed maxTok. capChunkText then splits it — but only the first split piece retains the root heading; subsequent pieces from the same original chunk lose that context.

Consider swapping the order:

build chunks → capChunkText (split oversized first) → RootChunkAsHeading (then prepend root text)

This way:

  1. Every chunk is first ensured to fit within maxTok (split at line boundaries).
  2. The root heading is then prepended to all resulting chunks, so every piece carries the heading context.

The root text is typically a short heading/title — prepending it to an already-budget-compliant chunk produces a negligible overshoot, which is an acceptable trade-off vs. dropping heading context from split fragments.

If the root chunk itself gets split by capChunkText (extreme edge case), only its first piece would be used as the root text, and the remaining pieces would appear as normal chunks that also receive that root prefix — still reasonable behavior.

@xugangqiang

Copy link
Copy Markdown
Contributor

@deadtrickster

To confirm: you're OK with merging this PR as-is and handling the comment/docstring cleanups in a follow-up, correct?

If so, please resolve conflict. Thank you.

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@xugangqiang confirmed: happy to merge as-is; I have resolved the conflict and cleaned up the comments in this PR (no follow-up needed).

  • Rebased onto current main. The rebase surfaced two API changes on main that I adapted: numericFromAny moved to schema.NumericFromAny, and Chunker.Invoke gained the *gorm.DB argument.
  • Adopted main's removeTag(...) on the grouped chunk text.
  • Dropped the porting-reference comment.

bash build.sh --test ./internal/ingestion/component/chunker/... passes locally. Ready when you are.

@deadtrickster

Copy link
Copy Markdown
Contributor Author

@xugangqiang ping :-)

@xugangqiang

Copy link
Copy Markdown
Contributor

Reviewed against current main. The direction is right and two of the bugs here are real, but I don't think this is mergeable as-is: there is a silent data-loss regression on the Go side, and both of the size fixes are unreachable through the product as shipped.


1. Does it actually fix the reported problem?

Partially — the most common user path isn't covered.

Change Effect
paper.py pivot cap ✅ works (default 512), matches the loop quoted in #12109
book.py position tag ✅ genuine bug; rpartition("@@") is correct — the old split("@") also mangled any @ in the body text (e.g. e-mail addresses)
book.py size routing ⚠️ never triggers for UI users
Go title chunker ❌ unreachable config

book.py routing doesn't fire for UI users. The chunk-token field is only rendered for naive and knowledge_graph (web/src/components/chunk-method-dialog/index.tsx:219), and the default parser_config for book is nil in both api/utils/api_utils.py:328 and internal/common/parser_config.go:200. So not parser_config.get("chunk_token_num") is always true and hierarchical_merge still runs. The "median 47 chars" case in the description is only fixed for people who inject chunk_token_num into a book dataset over the HTTP API.

The Go half is dead config. chunk_token_num is absent from the TitleChunker params in internal/ingestion/pipeline/template/ingestion_pipeline_book.json and from initialTitleChunkerValues in web/src/pages/agent/constant/pipeline.tsx:339. CleanComponentParams (internal/ingestion/pipeline/pipeline_params.go:18) drops any param that isn't in the DSL schema, with a warning. Unless someone hand-edits the DSL JSON, capChunkText never runs.

2. Blocking regression: PDF positions are dropped

buildChunksFromRecordGroups attaches positions and _pdf_positions at internal/ingestion/component/chunker/group.go:294-308, but the new split loop rebuilds each piece from scratch and only carries two keys over:

piece := map[string]any{"text": text}
if v, ok := ch["doc_type_kwd"]; ok { ... }
if v, ok := ch["img_id"]; ok { ... }

positions / _pdf_positions are lost. The guard is maxTok > 0 || rootText != "", so this fires whenever a user enables root_chunk_as_heading in the UI (pipeline.tsx:347) — no chunk_token_num needed at all. hierarchy.go:243 calls the same function, so the built-in Book pipeline (method: "hierarchy") is affected, and PDF chunk highlighting silently breaks. The existing coverage at group_test.go:239 only exercises the plain path, so nothing catches it.

Worth flagging given the PR title says "keep page positions".

3. Other regressions

chunk_token_num = 0 semantics are broken. book.py:129-130 explicitly sets chunk_token_num = 0 for tcadp/docling/mineru/paddleocr, meaning "the parser already chunked, don't re-merge". The old .get("chunk_token_num", 256) returned 0; the new parser_config.get("chunk_token_num") or 256 turns it into 256, changing behaviour for those four parsers on the bull < 0 path. Suggest keeping .get(..., 256).

paper.py counts position tags as content. sorted_sections text is b["text"] + self._line_tag(b, zoomin) (paper.py:130), so every entry carries @@3\t72.0\t523.0\t88.0\t101.0##. num_tokens_from_string(chunks[-1] + "\n" + txt) counts those tags. The rest of the codebase does the opposite: hierarchical_merge strips them before counting (rag/nlp/__init__.py:1143) and naive_merge keeps pos out of the token count entirely. Net effect: with DeepDoc PDFs the real body budget is well under the configured 512, and the error grows with the number of boxes. Strip via pdf_parser.remove_tag before counting.

O(n²) tokenisation. _merge_sections_by_pivot re-tokenises the entire accumulated chunk for every section. A running token count would avoid that.

Silent default change for paper. Defaulting to 512 changes chunk sizes for every existing paper dataset, and since the UI doesn't expose the field there's no way back other than passing 0 via the API. Reasonable as a default, but it deserves a release note; no docs are touched here.

Minor: zip(..., strict=True) converts a previously silent truncation into an exception. The assert at paper.py:217 guards it, but asserts are stripped under python -O. Also, strings.Count(...) > N in two of the new assertions relaxes them exactly in the single-oversized-line case that is most likely to be wrong.

4. On the approach

Using the presence of chunk_token_num as a policy switch reads oddly: setting a size completely disables hierarchical merging, which is the one thing that distinguishes the Book method from naive. And hierarchical_merge has exactly one live caller (book.py:171; the laws.py:275 call is commented out), so after this change it becomes half-dead code behind a condition that is almost never false in practice.

Two cleaner options:

  1. Fix the cause. The hardcoded 218 at rag/nlp/__init__.py:1144 / :1152 is what produces the tiny chunks. Parameterise it with chunk_token_num and split over-budget groups. Hierarchy is preserved and the size is honoured.
  2. Drop the branch. Route Book through naive_merge unconditionally. That's the de-facto outcome of this PR anyway — better to state it than to leave a dormant branch.

Same on the Go side: group.go:60-61 already has minGroupTokens = 32 / maxGroupTokens = 1024. Deriving those from chunk_token_num sits closer to the abstraction that owns the behaviour than a post-hoc splitting pass at the end.

5. Suggested changes before merge

Must fix:

  1. Carry positions / _pdf_positions (and any other keys) onto split pieces in buildChunksFromRecordGroups, plus a test covering root_chunk_as_heading + chunk_token_num with positions.
  2. Add chunk_token_num to the TitleChunker params in the pipeline templates and to the frontend form, otherwise the Go change can't be reached.
  3. Restore .get("chunk_token_num", 256) so an explicit 0 survives.
  4. Strip @@...## before counting tokens in _merge_sections_by_pivot.

Nice to have:

  1. Prefer passing the budget into hierarchical_merge (or removing the branch) over switching policy on config presence.
  2. If Book/Paper users are meant to configure this, showMaxTokenNumber at chunk-method-dialog/index.tsx:219 needs to include them.

To be clear about what's good here: the split("@") → rpartition("@@") fix is a real bug fix with tests, the paper cap lands exactly on the code quoted in #12109, capChunkText itself is correct (including counting the joining newline and not splitting mid-line), and the test coverage is solid. It's items 1–4 that hold it back.

@xugangqiang

Copy link
Copy Markdown
Contributor

pls fix ci error

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Aug 29, 2026
@deadtrickster

Copy link
Copy Markdown
Contributor Author

Rebased on current main. Most of what this PR originally did is now covered by #18455 - the Go chunk_token_cap and the book chunker rework - so I dropped those parts rather than ship a second competing path.

What's left is the paper chunker. Its title-pivot merge still emits a whole pivot as one unbounded chunk, the exact loop quoted in #12109. _merge_sections_by_pivot in rag/app/paper.py bounds that by chunk_token_num. The @@...## position tags are stripped before counting so they don't eat the budget, and stay in the chunk text for crop().

Scoped down to rag/app/paper.py plus a unit test. CI should be green now.

@deadtrickster deadtrickster changed the title fix: honour chunk_token_num in the book/paper title chunkers (closes #12109); keep page positions fix(paper): bound title-pivot merge by chunk_token_num (#12109) Aug 29, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM @yuzhichang pls have a second eye.

@JinHai-CN

JinHai-CN commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

@deadtrickster would you please resolve the conflicts and rebase the main branch?

)

paper.py concatenated a whole title pivot into one chunk regardless of
chunk_token_num - the loop quoted in infiniflow#12109. _merge_sections_by_pivot caps it;
position tags stripped before counting so they don't eat the budget. The book
and Go side of infiniflow#12109 is covered by infiniflow#18455; this is the remaining paper gap.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@deadtrickster

Copy link
Copy Markdown
Contributor Author

green!

@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

@yuzhichang
yuzhichang merged commit 0f34246 into infiniflow:main Sep 8, 2026
5 checks passed
shoemoney added a commit to shoemoney/ragflow that referenced this pull request Sep 29, 2026
tree_merge (used by the laws chunk_method) never threaded chunk_token_num
through to Node.build_tree/_dfs, so a heading with a long, sub-heading-free
body came out as a single unbounded chunk. hierarchical_merge (book/paper)
has the same fix in infiniflow#16959; tree_merge was left out of that PR.

chunk_token_num defaults to 0 (off), so any caller that does not pass it
keeps today's behaviour exactly; laws.py now reads chunk_token_num from
parser_config the same way book.py/paper.py do and passes it through.
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:M This PR changes 30-99 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants