Repository navigation
fix(chunker): eliminate O(n^2) coordinate extension and redundant merge copies - #20132
Conversation
…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).
|
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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughThe 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. ChangesChunker allocation and JSON merge
Priority: ⬇️ Low Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix Suggested reviewers: Merge Risk: ⚪ Minimal · up to 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)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. A rabbit checks the arrays in a row, Comment ✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
|
Summary
The
TokenChunker's JSON merge path had two peak-memory / wall-time hot spots on large PDFs:extendRawJSONArrayO(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.invokeJSONPayload:perItem's[][]ChunkDocscaffolding was retained after flattening, and the kept chunks were copied intooutand then copied again bychunkOutputs.perItemis now dropped after flatten and the keep-filter is fused withmaterializeMediaContextinto one pass, removing one full-document-scale[]ChunkDocallocation. The output contract (output_format=chunks+ChunkDocsToMaps) is unchanged.Test plan
token_merge_alloc_test.go:TestExtendRawJSONArray_BehaviorIdenticalToSlow/TestExtendRawJSONArray_NonArrayFallsBackToSlowlock 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.BenchmarkExtendRawJSONArrayChain_1kdrops from ~17s/op to ~1.3ms/op.bash build.sh --test ./internal/ingestion/component/chunker/passes.🤖 Generated with CodeBuddy Code