Repository navigation
fix(paper): bound title-pivot merge by chunk_token_num (#12109) - #16959
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthrough
ChangesChunk token enforcement
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
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Title checkExplanation 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 checkExplanation 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. 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 (2)
rag/app/book.py (2)
1-1: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick winRemove 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#12109and 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#12109and 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#12109and the oversized chunk history.internal/ingestion/component/chunker/group_test.go#L234-236: Remove the reference to#12109and 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 winAdd 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: Addlogging.infoorlogging.debugindicating whethernaive_mergeorhierarchical_mergeis selected based on thechunk_token_numsetting.rag/app/paper.py#L223-231: Addlogging.infoorlogging.debugdetailing the activechunk_token_numbudget 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 valueUse
strict=Trueforzip().Since
sorted_sectionsandsec_idsare verified to be the same length (via theassert len(sorted_sections) == len(levels)earlier), consider addingstrict=Trueto thezip()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
📒 Files selected for processing (8)
internal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/schema/chunker.gorag/app/book.pyrag/app/paper.pytest/unit_test/rag/test_book_positions.pytest/unit_test/rag/test_paper_chunk_size.py
| @@ -0,0 +1,139 @@ | |||
| # | |||
There was a problem hiding this comment.
📐 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_splitand its dedicated testtest_old_split_drops_position_tag(lines 82-90).test/unit_test/rag/test_paper_chunk_size.py#L38-49: Remove_group_oldand its dedicated testtest_old_grouping_makes_one_oversized_chunk(lines 70-74). Additionally, refactortest_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
20a4d01 to
7ea8e31
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
rag/app/book.py (1)
185-186: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueEnsure the logged chunk limit matches the runtime fallback.
When
chunk_token_numis absent fromparser_config, the log statement will outputchunk_token_num=None, butnaive_mergewill actually use the fallback value of256. 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
📒 Files selected for processing (8)
internal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/schema/chunker.gorag/app/book.pyrag/app/paper.pytest/unit_test/rag/test_book_positions.pytest/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
7ea8e31 to
a68bcda
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
internal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/schema/chunker.gorag/app/book.pyrag/app/paper.pytest/unit_test/rag/test_book_positions.pytest/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
a68bcda to
219fdb6
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@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
📒 Files selected for processing (8)
internal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/schema/chunker.gorag/app/book.pyrag/app/paper.pytest/unit_test/rag/test_book_positions.pytest/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
|
Addressed both:
|
219fdb6 to
638f2ef
Compare
|
On the
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 |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
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 winApply
RootChunkAsHeadingprior to capping to prevent logic errors and budget violations.By flattening the split pieces into the
chunksarray before evaluatingRootChunkAsHeading, this logic introduces a few critical issues:
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.- If there is only one group but it gets split into multiple pieces,
len(chunks) > 1becomes true. This incorrectly drops the first piece and prepends it to the remaining pieces.- Prepending the heading text after
capChunkTextguarantees that the resulting chunks will exceed the configuredchunk_token_numbudget.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
maxTokdynamically by subtracting the heading's token count before callingcapChunkText, 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 valueRemove the redundant list comprehension.
random_choicesalready 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
📒 Files selected for processing (8)
internal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/schema/chunker.gorag/app/book.pyrag/app/paper.pytest/unit_test/rag/test_book_positions.pytest/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
ac245bb to
57547fd
Compare
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/ingestion/component/chunker/group_test.go (1)
287-296: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename variable to avoid shadowing the built-in
capfunction.The variable name
capshadows the Go built-in functioncap(). Consider renaming it tomaxTok(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
📒 Files selected for processing (8)
internal/ingestion/component/chunker/group.gointernal/ingestion/component/chunker/group_test.gointernal/ingestion/component/chunker/title.gointernal/ingestion/component/schema/chunker.gorag/app/book.pyrag/app/paper.pytest/unit_test/rag/test_book_positions.pytest/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
|
@yingfeng could you please have a look? |
57547fd to
d48e195
Compare
|
@xugangqiang ping |
|
@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:
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. |
4340e79 to
ddecfe9
Compare
|
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. |
|
@xugangqiang confirmed: happy to merge as-is; I have resolved the conflict and cleaned up the comments in this PR (no follow-up needed).
|
79ed77a to
adddc88
Compare
|
@xugangqiang ping :-) |
|
Reviewed against current 1. Does it actually fix the reported problem?Partially — the most common user path isn't covered.
The Go half is dead config. 2. Blocking regression: PDF positions are dropped
piece := map[string]any{"text": text}
if v, ok := ch["doc_type_kwd"]; ok { ... }
if v, ok := ch["img_id"]; ok { ... }
Worth flagging given the PR title says "keep page positions". 3. Other regressions
O(n²) tokenisation. 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 Minor: 4. On the approachUsing the presence of Two cleaner options:
Same on the Go side: 5. Suggested changes before mergeMust fix:
Nice to have:
To be clear about what's good here: the |
2494fe5 to
4fd4bf4
Compare
|
pls fix ci error |
4fd4bf4 to
be4d5c5
Compare
|
Rebased on current main. Most of what this PR originally did is now covered by #18455 - the Go 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. Scoped down to |
|
LGTM @yuzhichang pls have a second eye. |
|
@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]>
be4d5c5 to
f5a860e
Compare
|
green! |
|
LGTM |
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.
Paper's title-pivot merge emitted a whole pivot as one unbounded chunk - the loop quoted in #12109.
_merge_sections_by_pivotbounds it bychunk_token_num;@@...##position tags are stripped before counting so they don't eat the budget, and stay in the chunk forcrop().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 + achunk()-level guard that's red against the unbounded loop).