Skip to content

fix(chunker): eliminate O(n^2) coordinate extension and redundant merge copies - #20132

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
xugangqiang:fix/chunker-merge-alloc
Sep 23, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
xugangqiang:fix/chunker-merge-alloc

Conversation

@xugangqiang

Copy link
Copy Markdown
Collaborator

Summary

The TokenChunker's JSON merge path had two peak-memory / wall-time hot spots on large PDFs:

  • P0 — extendRawJSONArray O(n²) → O(n): the old code re-serialised the entire growing coordinate array on every merge step (json.Unmarshal + json.Marshal), an O(n²) byte + reflection cost that dominated the 3266-page PDF's chunker heap peak. The new compact-array fast path strips the outer brackets and appends the element bytes directly into the accumulator buffer (O(n) total). It also fixes an aliasing bug: the empty-accumulator case previously returned the caller's source bytes directly, so the overlap branch later mutated the original unit coordinate list (_pdf_positions / positions) in place and dropped coordinates from merged chunks. The empty case now returns a fresh COPY, and the append-like mutation contract is documented.
  • P1 — redundant full-document copies in invokeJSONPayload: perItem's [][]ChunkDoc scaffolding was retained after flattening, and the kept chunks were copied into out and then copied again by chunkOutputs. perItem is now dropped after flatten and the keep-filter is fused with materializeMediaContext into one pass, removing one full-document-scale []ChunkDoc allocation. The output contract (output_format=chunks + ChunkDocsToMaps) is unchanged.

Test plan

  • Added token_merge_alloc_test.go:
    • TestExtendRawJSONArray_BehaviorIdenticalToSlow / TestExtendRawJSONArray_NonArrayFallsBackToSlow lock the fast path to byte-identical output versus the old unmarshal/marshal reference across nil/empty/nested/non-array inputs.
    • TestMergeByTokenSizeFromJSON_OverlapPrefixCarriesPrevPositions (pre-existing) guards the overlap-chain coordinate carry that the aliasing bug broke.
    • Benchmarks isolate the O(n²)→O(n) improvement: BenchmarkExtendRawJSONArrayChain_1k drops from ~17s/op to ~1.3ms/op.
  • bash build.sh --test ./internal/ingestion/component/chunker/ passes.

🤖 Generated with CodeBuddy Code

…ge copies

The TokenChunker's JSON merge path had two peak-memory / wall-time
hot spots on large PDFs:

P0 - extendRawJSONArray re-serialised the ENTIRE growing coordinate
array on every merge step (per-step json.Unmarshal + json.Marshal),
an O(n^2) byte + reflection cost that dominated the 3266-page PDF's
chunker heap peak. Replace it with a compact-array fast path that
strips the outer brackets and appends the element bytes directly
into the accumulator buffer (O(n) total).

The fast path also had an aliasing bug: when the accumulator was
empty it returned the caller's source bytes directly, so the
overlap branch later mutated the ORIGINAL unit coordinate list
(_pdf_positions / positions) in place, dropping coordinates from
merged chunks. The empty case now returns a fresh COPY, and the
append-like mutation contract is documented.

P1 - invokeJSONPayload held perItem's [][]ChunkDoc scaffolding after
flattening and built a full []ChunkDoc copy before chunkOutputs
copied it again. Drop perItem after flatten and fuse the
keep-filter with materializeMediaContext into one pass, removing
one full-document-scale slice allocation. Output contract
(output_format=chunks + ChunkDocsToMaps) is unchanged.

Add token_merge_alloc_test.go locking the fast path to byte-identical
output versus the old unmarshal/marshal reference, plus benchmarks
that isolate the O(n^2)->O(n) improvement (chain_1k drops from
~17s/op to ~1.3ms/op).
@xugangqiang xugangqiang added the ci Continue Integration label Sep 23, 2026
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 58dd3416-65f6-4856-80c8-590a57afd58e

📥 Commits

Reviewing files that changed from the base of the PR and between 11c1663 and b621b0f.

📒 Files selected for processing (2)
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_merge_alloc_test.go

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The chunker now materializes kept outputs directly and releases consumed slices. Raw JSON array extension copies non-empty operands when the other is empty and concatenates bracket-delimited arrays directly. Tests check output parity, and benchmarks cover extension and merge paths.

Changes

Chunker allocation and JSON merge

Layer / File(s) Summary
Direct chunk output materialization
internal/ingestion/component/chunker/token.go
invokeJSONPayload appends kept chunks to the materialized output directly and clears slices after use.
Raw JSON array extension and validation
internal/ingestion/component/chunker/token.go, internal/ingestion/component/chunker/token_merge_alloc_test.go
extendRawJSONArray copies non-empty operands when the other is empty and concatenates bracket-delimited arrays. Tests compare its output with a reference implementation. Benchmarks cover array extension and merging.

Priority: ⬇️ Low

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

Change: Bug fix

Suggested reviewers: jay77721

Merge Risk: ⚪ Minimal · up to b621b

The chunker changes are ready to merge after normal checks; no confirmed output regression or workflow failure remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the two main changes: removing O(n²) coordinate extension and redundant merge copies.
Description check ✅ Passed The description includes the required Summary section, explains the problem and solution in detail, and provides relevant test information.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI

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

A rabbit checks the arrays in a row,
Then watches the chunk outputs flow.
Fewer copies hop away,
Benchmarks measure their day,
And tidy brackets stay in tow.

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

✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

@xugangqiang xugangqiang added ci Continue Integration and removed ci Continue Integration labels Sep 23, 2026
@yuzhichang
yuzhichang merged commit e81fb8d into infiniflow:main Sep 23, 2026
10 of 11 checks passed
@xugangqiang
xugangqiang deleted the fix/chunker-merge-alloc branch November 26, 2026 09:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants