Skip to content

Refactor: pdf parser - #16625

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:refactor/pdf-parser-go
Jul 5, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
xugangqiang:refactor/pdf-parser-go

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

PDF parser refactor

@coderabbitai

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

This PR refactors PDF layout, parser page processing, and table grouping/rendering/post-processing into helper-based flows, and updates the surrounding tests to match the new behavior.

Changes

Layout Refactor

Layer / File(s) Summary
Per-page column assignment
internal/deepdoc/parser/pdf/layout/layout.go
AssignColumn now groups boxes by page, selects a per-page cluster count, and remaps clustered column IDs by centroid order.
Per-page vertical merge
internal/deepdoc/parser/pdf/layout/layout.go
NaiveVerticalMerge groups boxes by page and processes each page with merge eligibility and merge combination helpers.
Layout helper tests
internal/deepdoc/parser/pdf/layout/layout_test.go
Tests cover page grouping, merge eligibility, box merging, and page-box processing edge cases.

Parser Pipeline Restructure

Layer / File(s) Summary
ParseRaw setup and batch helpers
internal/deepdoc/parser/pdf/parser.go
ParseRaw normalizes page ranges, computes batch size, prescans pages, extracts outlines, and merges batch results.
Sync and async page extraction
internal/deepdoc/parser/pdf/parser.go
extractPages now uses per-page result slots, sync and async page processors, concurrency throttling, unified OCR handling, and result collection.
OCR detect and match helpers
internal/deepdoc/parser/pdf/parser_ocr.go
ocrMergeChars delegates detection, box sorting, and character-to-box matching into separate helpers.
Parser helper tests
internal/deepdoc/parser/pdf/parser_test.go
Tests cover batch sizing, page concurrency setup, prescan behavior, batch merging, and OCR-related formatting updates.

Table Grouping, Spans, Rendering, Merge, Post-processing

Layer / File(s) Summary
Box-to-grid grouping
internal/deepdoc/parser/pdf/table/group_boxes.go, internal/deepdoc/parser/pdf/table/group_boxes_test.go
GroupBoxesByRC and GroupBoxesByYX build table grids from text boxes, with helper functions for row and column compression and cell labeling.
Cell span calculation
internal/deepdoc/parser/pdf/table/table_spans.go, internal/deepdoc/parser/pdf/table/table_spans_test.go
CalSpans computes colspan/rowspan coverage, and FlattenGrid flattens grid rows for downstream processing.
Grid-to-HTML rendering
internal/deepdoc/parser/pdf/table/table_html.go, internal/deepdoc/parser/pdf/table/table_html_test.go
Table grid helpers render HTML, convert grids to strings, and detect non-empty text.
Cross-page table merge and cleanup
internal/deepdoc/parser/pdf/table/table_merge.go, internal/deepdoc/parser/pdf/table/table_construct.go, internal/deepdoc/parser/pdf/table/table_construct_test.go, internal/deepdoc/parser/pdf/table/table_merge_test.go
MergeTablesAcrossPages merges adjacent-page tables, and CleanupOrphanColumns is split into helper-driven column removal logic.
Table extraction and figure consolidation
internal/deepdoc/parser/pdf/table/table_post.go, internal/deepdoc/parser/pdf/table/table_post_test.go
Table replacement and figure consolidation are rewritten around remove-set filtering, anchor lookup, and grouped figure merging.

Estimated code review effort: 4 (Complex) | ~75 minutes

Suggested labels: 🧪 test

Suggested reviewers: yingfeng, JinHai-CN, yuzhichang

Poem

A rabbit hopped through pages deep,
Split the boxes, row by row to keep.
Tables now span and HTML glows,
OCR hums while the parser flows.
Hop, hop — the burrow’s tidy, bright,
With columns, captions, merged just right. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is too terse and lacks the background context the template asks for. Expand the Summary with the problem being solved, the refactor goals, and any reviewer context or behavior changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and clearly describes the main change: a PDF parser refactor.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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.

@xugangqiang xugangqiang added the ci Continue Integration label Jul 3, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review July 3, 2026 13:42
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jul 3, 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: 9

Caution

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

⚠️ Outside diff range comments (1)
internal/deepdoc/parser/pdf/parser.go (1)

208-237: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Sync page dispatch loop ignores context cancellation.

Unlike processPageAsync (which checks ctx.Done()), the loop in extractPages never checks ctx.Err() before calling processPageSync for non-garbled pages. A canceled context (e.g., request timeout) won't stop already-reachable synchronous page rendering for the remainder of the batch.

🩹 Proposed fix
 	for i := 0; i < pageCount; i++ {
+		if err := ctx.Err(); err != nil {
+			for ; i < pageCount; i++ {
+				results[i] = pageResult{pg: fromPage + i, err: err}
+			}
+			break
+		}
 		pg := fromPage + i
 		chars := prescanChars[pg]
🤖 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/deepdoc/parser/pdf/parser.go` around lines 208 - 237, The
synchronous dispatch path in extractPages does not honor cancellation before
calling processPageSync for non-garbled pages, unlike the async path that checks
ctx.Done(). Add a ctx.Err() check in the page loop before processing each page
so a canceled context stops further synchronous rendering. Keep the existing
processPageSync/processPageAsync split, but make the loop exit early on
cancellation and preserve the current result collection behavior for
already-finished pages.
🧹 Nitpick comments (10)
internal/deepdoc/parser/pdf/layout/layout.go (1)

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

LGTM! Minor nit: the debug log at Line 351 slices prevText/currText by byte count (prevText[:min(40, len(prevText))]), which can split a multi-byte UTF-8 rune (e.g. Chinese characters) mid-sequence. Purely cosmetic (debug log only, no data corruption), consider slicing by rune count if log fidelity matters.

🤖 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/deepdoc/parser/pdf/layout/layout.go` around lines 341 - 354, The
debug logging in mergeTwoBoxes currently truncates prevText and currText by byte
count, which can split UTF-8 runes in the slog.Debug output. Update the
truncation logic in mergeTwoBoxes to limit by rune count (or otherwise produce
valid UTF-8 substrings) so the debug preview remains readable for multi-byte
text while keeping the rest of the merge behavior unchanged.
internal/deepdoc/parser/pdf/layout/layout_test.go (1)

508-749: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Column-assignment helpers (determineBestKForPage, extractX0Values, applyIndentTolerance, findBestK, assignColIDsForPage, remapLabelsByCentroidOrder) have no direct unit tests.

Only the vertical-merge helpers got new tests this round; the newly extracted AssignColumn pipeline is only covered indirectly through the pre-existing end-to-end test. A focused test on assignColIDsForPage/determineBestKForPage with an indented-line scenario would likely have caught the indent-tolerance inconsistency flagged in layout.go (tolerance applied for k-selection but not for final cluster assignment).

🤖 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/deepdoc/parser/pdf/layout/layout_test.go` around lines 508 - 749,
Add focused unit coverage for the column-assignment path, since the new tests
only exercise vertical merging and miss the indent-tolerance bug in the column
pipeline. Create tests around assignColIDsForPage and determineBestKForPage that
use an indented-line scenario, and verify the same tolerance behavior is applied
during final clustering as during k selection. Include direct coverage for the
helper chain (extractX0Values, applyIndentTolerance, findBestK,
remapLabelsByCentroidOrder) so a mismatch between selection and assignment is
caught.
internal/deepdoc/parser/pdf/table/group_boxes.go (4)

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

Dead btm variable.

btm is computed and updated throughout the loop but never returned or used elsewhere in the function — it has no effect on the output. This appears to be a leftover from an intended (but unfinished) Y-proximity row-merge feature referenced in the file's top-level doc comment.

🤖 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/deepdoc/parser/pdf/table/group_boxes.go` around lines 190 - 208,
compressRowIndices currently computes and updates btm but never uses it, so
remove the dead variable or finish the intended Y-proximity merge logic in
group_boxes.go. If the function is only meant to map original R values to
compressed indices, keep the existing rowMap/compressed flow and delete btm from
the loop; if the doc-commented row-merging behavior is intended, incorporate btm
into the row-comparison logic in compressRowIndices so it affects row
compression.

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

Stale/misleading doc comments vs. actual behavior.

  • Lines 19-20 say GroupBoxesByRC will "merge nearby rows by Y proximity", but compressRowIndices only starts a new row when R strictly changes (Line 197) — there is no Y-proximity merge across differing R values. This is confirmed by TestGroupBoxesByRC_RDiffSplitsRow, which explicitly expects rows with different R at the same Y to stay split.
  • Lines 63-64 label GroupBoxesByYX as "test-only — used by table_parity_test.go", but GroupBoxesByRC itself calls it as a production fallback (Line 34) whenever maxR <= 0, and the ConstructTable fallback (table_construct.go, per supplied snippet) also invokes it outside of tests.

These comments will mislead future maintainers about actual control flow.

🤖 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/deepdoc/parser/pdf/table/group_boxes.go` around lines 18 - 64,
Update the doc comments on GroupBoxesByRC and GroupBoxesByYX to match the actual
control flow and grouping behavior. In GroupBoxesByRC, remove the claim about
merging rows by Y proximity and describe that row grouping is driven by R-based
compression via compressRowIndices after sorting by R/Top/X0. In GroupBoxesByYX,
remove the “test-only” wording and note that it is a general fallback used by
GroupBoxesByRC when maxR <= 0 and by ConstructTable. Keep the comments aligned
with these function names so future readers do not infer behavior that the
implementation and tests do not support.

210-254: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Merged-cell text can gain a stray leading/trailing space.

Line 229 always does v.txt += " " + t when a second box maps to the same (row,col), even if t == "" (which happens for SP/H-annotated boxes kept solely for coordinates, Line 217-221). This can append a trailing space to otherwise-clean cell text.

🤖 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/deepdoc/parser/pdf/table/group_boxes.go` around lines 210 - 254, The
merged-cell text handling in collectBoxesPerRow can append an unwanted space
when a later box for the same row/col has empty trimmed text but is kept for
SP/H coordinates. Update the text merge logic in collectBoxesPerRow (and the rb
accumulation path) so only non-empty text is concatenated, or so whitespace is
inserted conditionally based on both existing and incoming text. Keep the
coordinate-merge behavior for spanning boxes unchanged.

21-45: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Both grouping functions sort the caller's slice in place.

sort.Slice(boxes, ...) reorders the underlying backing array of the caller-supplied boxes slice as a side effect of calling an exported function. Callers (e.g. ConstructTable) that reuse boxes after this call will see reordered elements, which can be surprising for an otherwise "grouping" API. Given the parser pipeline processes pages with sync/async paths described elsewhere in this PR, please confirm boxes slices aren't shared/read concurrently by another goroutine while this sort runs.

Also applies to: 65-76

🤖 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/deepdoc/parser/pdf/table/group_boxes.go` around lines 21 - 45, Both
grouping helpers mutate the caller’s slice in place by sorting it, which is a
side effect an exported grouping API should avoid. Update GroupBoxesByRC and
GroupBoxesByYX to sort a local copy of the boxes slice before grouping so the
original order remains unchanged for callers such as ConstructTable. Also make
sure any call sites do not share the same boxes slice across goroutines while
the sort/grouping runs, since the current in-place sort would be unsafe in that
case.
internal/deepdoc/parser/pdf/table/group_boxes_test.go (1)

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

Non-assertive test — always passes regardless of behavior.

TestGroupBoxesByRC_ColspanMissing never calls t.Error/t.Fatal; it only logs a message. It documents a "known limitation" but provides no regression protection.

🤖 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/deepdoc/parser/pdf/table/group_boxes_test.go` around lines 118 -
134, TestGroupBoxesByRC_ColspanMissing is only logging a limitation and never
fails, so it does not protect against regressions. Update the test in
GroupBoxesByRC to assert the expected colspan behavior for the first row (merged
[0,0] spanning two columns and no separate [0,1] cell) using t.Errorf/t.Fatalf,
and remove the “known limitation” log so the test enforces the contract in
group_boxes_test.go.
internal/deepdoc/parser/pdf/parser.go (2)

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

Local variable cap shadows the builtin cap().

Harmless here but reduces readability/lint hygiene.

♻️ Proposed rename
 func (p *Parser) setupPageConcurrency() (chan struct{}, *sync.WaitGroup) {
-	cap := p.Config.MaxOCRConcurrency
-	if cap <= 0 {
-		cap = 1
+	capacity := p.Config.MaxOCRConcurrency
+	if capacity <= 0 {
+		capacity = 1
 	}
-	return make(chan struct{}, cap), &sync.WaitGroup{}
+	return make(chan struct{}, capacity), &sync.WaitGroup{}
 }
🤖 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/deepdoc/parser/pdf/parser.go` around lines 239 - 246, The local
variable in setupPageConcurrency currently shadows the builtin cap(), which
hurts readability and lint hygiene. Rename that variable in
Parser.setupPageConcurrency to a non-builtin name such as maxConcurrency or
concurrencyLimit, and update the surrounding logic to use the new name while
keeping the channel buffer setup and WaitGroup behavior unchanged.

599-627: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the unused mergePageResults helper
collectPageResults already covers this path, and there are no remaining call sites for mergePageResults. Keeping both copies only increases the risk of drift.

🤖 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/deepdoc/parser/pdf/parser.go` around lines 599 - 627, The
backward-compatibility helper mergePageResults is now unused because
collectPageResults already handles this flow, so remove mergePageResults and any
related dead code. Verify there are no remaining call sites or references to
mergePageResults in the pdf/parser package, and keep collectPageResults as the
single source of truth for merging page OCR results.
internal/deepdoc/parser/pdf/table/table_merge_test.go (1)

10-106: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Good coverage of adjacency/overlap rules — consider adding tests for the gaps found in table_merge.go.

The current tests validate X-overlap and consecutive-page adjacency, but there's no coverage for: a table with empty Positions (currently silently dropped), a candidate with genuinely large Y gap (should reject merge but the current formula likely never triggers rejection), or tables with differing Scale/CropOffX/CropOffY across pages (coordinate corruption risk). Adding these would have caught the issues raised in table_merge.go.

Based on the concerns raised in table_merge.go's MergeTablesAcrossPages, additional regression tests here would help lock in the fix.

🤖 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/deepdoc/parser/pdf/table/table_merge_test.go` around lines 10 - 106,
Add regression tests around MergeTablesAcrossPages to cover the missing
table_merge.go edge cases: verify a TableItem with empty Positions is not
silently dropped or merged, verify tables with a genuinely large Y gap are
rejected by the merge logic, and verify tables with mismatched Scale, CropOffX,
or CropOffY are not merged because their coordinates would be corrupted. Use the
existing MergeTablesAcrossPages test patterns and TableItem/Position/TSRCell
symbols so the new cases exercise the same merge path.
🤖 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/deepdoc/parser/pdf/layout/layout.go`:
- Around line 295-339: The gap-based veto in shouldMergeBoxes is duplicated and
currently unreachable because the earlier gap check already returns false for
curr.Top-prev.Bottom > mh*1.5. Remove the redundant anti condition or move the
large-gap logic into the anti/concatting decision so the merge rules in
shouldMergeBoxes remain consistent and non-overlapping.

In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 248-259: The sync page path in processPageSync is swallowing
RenderPageToImage failures because renderErr is only passed to processPageBoxes
and never propagated to pageResult.err or logged. Update processPageSync so a
render failure is captured on the returned pageResult (and logged if
appropriate), matching the error handling behavior used in the async path and
collectPageResults. Keep the existing pageImages and OCR flow intact, but ensure
the pageResult from processPageSync preserves render errors for later
aggregation.
- Around line 284-330: The OCR synthetic-char path in processPageBoxes is
mutating only the local chars slice, so the OCR-detected text never reaches
pageResult.chars or downstream layout/median calculations. Update
processPageBoxes to return the updated chars slice (or otherwise propagate it),
and update both processPageAsync and processPageSync call sites to assign that
returned value into pageResult.chars. Make sure the async detect+recognize
branch still sets ocrUsed appropriately while preserving the OCR-generated
characters for later consumers like collectPageResults and buildLayout.
- Around line 100-112: The normalizePageRange method in Parser currently bounds
toPage but leaves fromPage unchanged, so a negative config value can flow into
prescanPages and extractPages and reach ExtractChars with an invalid page index.
Update normalizePageRange to clamp fromPage to at least page 0, using the same
style of bounds checking already applied to toPage, while keeping the existing
pageCount handling intact.

In `@internal/deepdoc/parser/pdf/table/group_boxes_test.go`:
- Around line 285-311: The overlap-merge test in
TestCompressColIndices_OverlapMerge is asserting the current buggy cMaxCol value
instead of the corrected compressed-column result. Update the expectation so it
matches the fixed compressColIndices behavior: when two overlapping boxes
collapse into one compressed column, cMaxCol should reflect the single unique
column rather than the original column count. Use the existing cCompressed and
cMaxCol checks in TestCompressColIndices_OverlapMerge to align the test with the
corrected logic.

In `@internal/deepdoc/parser/pdf/table/group_boxes.go`:
- Around line 265-318: Fix the compressed-column merge handling in
compressColIndices and buildGrid: cMaxCol should be based on the number of
unique compressed column values per row, not len(cMap), so the grid width
matches the actual merged columns. In buildGrid, stop relying on map iteration
when multiple original columns collapse to the same compressed index; use a
deterministic merge for collisions on the same cci (combine text and expand
bounds, similar to collectBoxesPerRow) instead of letting the last map entry
win. Use the symbols compressColIndices, cMaxCol, and buildGrid to locate the
affected logic.

In `@internal/deepdoc/parser/pdf/table/table_merge.go`:
- Around line 17-44: Tables without Positions are currently skipped in
tableMerge because only entries added to items are ever considered, so those
tables never reach the returned slice. Update tableMerge to preserve tables with
no Positions by passing them through unchanged (unmerged) while still
sorting/merging the positioned tables via the existing indexed/items path, and
make sure the final result includes both the merged output and any positionless
tables. Add coverage in table_merge_test.go for a table item with empty
Positions to verify it is not dropped.
- Around line 59-61: The Y-gap check in table merging is using the original
fragment instead of the latest merged fragment, which breaks alignment with the
intended cross-page gap logic. Update the logic in the table merge flow around
anchor selection so the gap comparison uses the last merged position from the
anchor’s Positions slice rather than Positions[0], keeping the anchor page and
bottom reference in sync for subsequent merges.

In `@internal/deepdoc/parser/pdf/table/table_post.go`:
- Around line 269-286: Build the replacements after tables are merged so the
captured table indices match the final slice used later. In
ExtractTableAndReplace, move buildReplacements to run after
MergeTablesAcrossPages and keep the MarkNoMergeTables call where needed so
replacement.tableIdx is derived from the merged tables. Add a regression test
around ExtractTableAndReplace with multiple mergeable tables across pages to
verify anchors are preserved and not dropped or misassociated.

---

Outside diff comments:
In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 208-237: The synchronous dispatch path in extractPages does not
honor cancellation before calling processPageSync for non-garbled pages, unlike
the async path that checks ctx.Done(). Add a ctx.Err() check in the page loop
before processing each page so a canceled context stops further synchronous
rendering. Keep the existing processPageSync/processPageAsync split, but make
the loop exit early on cancellation and preserve the current result collection
behavior for already-finished pages.

---

Nitpick comments:
In `@internal/deepdoc/parser/pdf/layout/layout_test.go`:
- Around line 508-749: Add focused unit coverage for the column-assignment path,
since the new tests only exercise vertical merging and miss the indent-tolerance
bug in the column pipeline. Create tests around assignColIDsForPage and
determineBestKForPage that use an indented-line scenario, and verify the same
tolerance behavior is applied during final clustering as during k selection.
Include direct coverage for the helper chain (extractX0Values,
applyIndentTolerance, findBestK, remapLabelsByCentroidOrder) so a mismatch
between selection and assignment is caught.

In `@internal/deepdoc/parser/pdf/layout/layout.go`:
- Around line 341-354: The debug logging in mergeTwoBoxes currently truncates
prevText and currText by byte count, which can split UTF-8 runes in the
slog.Debug output. Update the truncation logic in mergeTwoBoxes to limit by rune
count (or otherwise produce valid UTF-8 substrings) so the debug preview remains
readable for multi-byte text while keeping the rest of the merge behavior
unchanged.

In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 239-246: The local variable in setupPageConcurrency currently
shadows the builtin cap(), which hurts readability and lint hygiene. Rename that
variable in Parser.setupPageConcurrency to a non-builtin name such as
maxConcurrency or concurrencyLimit, and update the surrounding logic to use the
new name while keeping the channel buffer setup and WaitGroup behavior
unchanged.
- Around line 599-627: The backward-compatibility helper mergePageResults is now
unused because collectPageResults already handles this flow, so remove
mergePageResults and any related dead code. Verify there are no remaining call
sites or references to mergePageResults in the pdf/parser package, and keep
collectPageResults as the single source of truth for merging page OCR results.

In `@internal/deepdoc/parser/pdf/table/group_boxes_test.go`:
- Around line 118-134: TestGroupBoxesByRC_ColspanMissing is only logging a
limitation and never fails, so it does not protect against regressions. Update
the test in GroupBoxesByRC to assert the expected colspan behavior for the first
row (merged [0,0] spanning two columns and no separate [0,1] cell) using
t.Errorf/t.Fatalf, and remove the “known limitation” log so the test enforces
the contract in group_boxes_test.go.

In `@internal/deepdoc/parser/pdf/table/group_boxes.go`:
- Around line 190-208: compressRowIndices currently computes and updates btm but
never uses it, so remove the dead variable or finish the intended Y-proximity
merge logic in group_boxes.go. If the function is only meant to map original R
values to compressed indices, keep the existing rowMap/compressed flow and
delete btm from the loop; if the doc-commented row-merging behavior is intended,
incorporate btm into the row-comparison logic in compressRowIndices so it
affects row compression.
- Around line 18-64: Update the doc comments on GroupBoxesByRC and
GroupBoxesByYX to match the actual control flow and grouping behavior. In
GroupBoxesByRC, remove the claim about merging rows by Y proximity and describe
that row grouping is driven by R-based compression via compressRowIndices after
sorting by R/Top/X0. In GroupBoxesByYX, remove the “test-only” wording and note
that it is a general fallback used by GroupBoxesByRC when maxR <= 0 and by
ConstructTable. Keep the comments aligned with these function names so future
readers do not infer behavior that the implementation and tests do not support.
- Around line 210-254: The merged-cell text handling in collectBoxesPerRow can
append an unwanted space when a later box for the same row/col has empty trimmed
text but is kept for SP/H coordinates. Update the text merge logic in
collectBoxesPerRow (and the rb accumulation path) so only non-empty text is
concatenated, or so whitespace is inserted conditionally based on both existing
and incoming text. Keep the coordinate-merge behavior for spanning boxes
unchanged.
- Around line 21-45: Both grouping helpers mutate the caller’s slice in place by
sorting it, which is a side effect an exported grouping API should avoid. Update
GroupBoxesByRC and GroupBoxesByYX to sort a local copy of the boxes slice before
grouping so the original order remains unchanged for callers such as
ConstructTable. Also make sure any call sites do not share the same boxes slice
across goroutines while the sort/grouping runs, since the current in-place sort
would be unsafe in that case.

In `@internal/deepdoc/parser/pdf/table/table_merge_test.go`:
- Around line 10-106: Add regression tests around MergeTablesAcrossPages to
cover the missing table_merge.go edge cases: verify a TableItem with empty
Positions is not silently dropped or merged, verify tables with a genuinely
large Y gap are rejected by the merge logic, and verify tables with mismatched
Scale, CropOffX, or CropOffY are not merged because their coordinates would be
corrupted. Use the existing MergeTablesAcrossPages test patterns and
TableItem/Position/TSRCell symbols so the new cases exercise the same merge
path.
🪄 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: 30b41c72-fd5c-45cb-ad8f-1c8a38fba412

📥 Commits

Reviewing files that changed from the base of the PR and between a0e6563 and b8af774.

📒 Files selected for processing (17)
  • internal/deepdoc/parser/pdf/layout/layout.go
  • internal/deepdoc/parser/pdf/layout/layout_test.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/parser_ocr.go
  • internal/deepdoc/parser/pdf/parser_test.go
  • internal/deepdoc/parser/pdf/table/group_boxes.go
  • internal/deepdoc/parser/pdf/table/group_boxes_test.go
  • internal/deepdoc/parser/pdf/table/table_construct.go
  • internal/deepdoc/parser/pdf/table/table_construct_test.go
  • internal/deepdoc/parser/pdf/table/table_html.go
  • internal/deepdoc/parser/pdf/table/table_html_test.go
  • internal/deepdoc/parser/pdf/table/table_merge.go
  • internal/deepdoc/parser/pdf/table/table_merge_test.go
  • internal/deepdoc/parser/pdf/table/table_post.go
  • internal/deepdoc/parser/pdf/table/table_post_test.go
  • internal/deepdoc/parser/pdf/table/table_spans.go
  • internal/deepdoc/parser/pdf/table/table_spans_test.go

Comment thread internal/deepdoc/parser/pdf/parser.go Resolved
Comment thread internal/deepdoc/parser/pdf/parser.go Resolved
Comment thread internal/deepdoc/parser/pdf/parser.go 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.

🧹 Nitpick comments (1)
internal/deepdoc/parser/pdf/parser.go (1)

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

Remove the unused compatibility helper — mergePageResults no longer has any call sites and only duplicates collectPageResults; delete it to avoid the two paths drifting.

🤖 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/deepdoc/parser/pdf/parser.go` around lines 621 - 648, Remove the
dead compatibility path by deleting mergePageResults from parser.go, since it
has no remaining call sites and duplicates collectPageResults. Ensure any
references to its pageResult handling, OCR box merging, pageImages/pageChars
updates, and error aggregation are cleaned up so only the single active
results-collection flow remains.
🤖 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/deepdoc/parser/pdf/parser.go`:
- Around line 621-648: Remove the dead compatibility path by deleting
mergePageResults from parser.go, since it has no remaining call sites and
duplicates collectPageResults. Ensure any references to its pageResult handling,
OCR box merging, pageImages/pageChars updates, and error aggregation are cleaned
up so only the single active results-collection flow remains.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d38a494f-b70b-4fbb-b6c2-184cd44c862d

📥 Commits

Reviewing files that changed from the base of the PR and between c579b39 and 81462e1.

📒 Files selected for processing (4)
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/table/group_boxes.go
  • internal/deepdoc/parser/pdf/table/group_boxes_test.go
  • internal/deepdoc/parser/pdf/table/table_post.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/deepdoc/parser/pdf/table/table_post.go
  • internal/deepdoc/parser/pdf/table/group_boxes.go
  • internal/deepdoc/parser/pdf/table/group_boxes_test.go

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

Use English in comments.

- Simplify applyIndentTolerance to avoid unnecessary allocation
- Extract mergeColumn helper to reduce duplicate logic
- Add test helpers to reduce repetition in tests
- Merge column merge tests to use table-driven approach
- Fix minor formatting issue
@xugangqiang
xugangqiang force-pushed the refactor/pdf-parser-go branch from 14ee46a to d2cfb4c Compare July 4, 2026 14:07
@yuzhichang
yuzhichang merged commit 1d3c100 into infiniflow:main Jul 5, 2026
3 checks passed
@xugangqiang
xugangqiang deleted the refactor/pdf-parser-go branch August 7, 2026 12:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants