Skip to content

Refactor: oss parser go refactor - #16391

Merged
JinHai-CN merged 47 commits into
infiniflow:mainfrom
xugangqiang:feat/oss-parser-go-refactor
Jun 29, 2026
Merged

JinHai-CN merged 47 commits into
infiniflow:mainfrom
xugangqiang:feat/oss-parser-go-refactor

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Package refactor and PDF post process.

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Jun 26, 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

The PR splits PDF parsing into inference, layout, table, and post subpackages, migrates parser and test code to shared pdf.* types, adds PDFium outline extraction and VLM image description, and rewires OCR, table extraction, and post-processing flows to the new APIs.

Changes

PDF Parser Decomposition

Layer / File(s) Summary
Inference client and PDFium outlines
internal/deepdoc/parser/pdf/{inference,pdfium,pdfoxide}/*, internal/deepdoc/parser/pdf/dla_*_test.go, internal/deepdoc/parser/pdf/ocr_merge_test.go, internal/deepdoc/parser/pdf/ocr_recognize_batch_test.go, internal/deepdoc/parser/pdf/mock_doc_analyzer_test.go, internal/deepdoc/parser/pdf/pdfium_integration_test.go
InferenceClient replaces DeepDocClient, prediction methods return pdf.* types, and PDFium/pdfoxide expose outline traversal via pdf.Outline and pdf.PDFEngine.
Layout text and section transforms
internal/deepdoc/parser/pdf/layout/*, internal/deepdoc/parser/pdf/rotate_test.go, internal/deepdoc/parser/pdf/snapshot_test.go, internal/deepdoc/parser/pdf/pipeline_parity_test.go
Character grouping, section conversion, and text-box merge helpers now operate on shared pdf.TextChar and pdf.TextBox types.
Table grid and annotation primitives
internal/deepdoc/parser/pdf/table/table_{cells,layout,coords,annotate,orient,builder}*, internal/deepdoc/parser/pdf/table_parity_issues_test.go
TSR cell grouping, table-box matching, coordinate transforms, annotation, and orientation helpers use pdf.* geometry and updated overlap checks.
Table construction and HTML replacement
internal/deepdoc/parser/pdf/table/table_construct*, internal/deepdoc/parser/pdf/table/merge_captions*, internal/deepdoc/parser/pdf/table/table_post.go, internal/deepdoc/parser/pdf/table_parity_test.go, internal/deepdoc/parser/pdf/table_parity_issues_test.go
Table construction, caption merging, and cross-page replacement build HTML tables and merge figures from table cells and sections.
Table extraction and parser table integration
internal/deepdoc/parser/pdf/table_extract.go, internal/deepdoc/parser/pdf/table_section_test.go, internal/deepdoc/parser/pdf/table_parity_issues_test.go, internal/deepdoc/parser/pdf/inference_client_integration_test.go, internal/deepdoc/parser/pdf/scan_all_pdfs_test.go, internal/deepdoc/parser/pdf/parser_test.go
Table extraction orchestration and parser/table integration tests now drive DeepDocTableBuilder, ExtractTableAndReplace, and pdf.DefaultParserConfig().
Parser OCR and runtime wiring
internal/deepdoc/parser/pdf/parser.go, internal/deepdoc/parser/pdf/parser_ocr.go, internal/deepdoc/parser/pdf/renderer*.go, internal/deepdoc/parser/pdf/parser_mock_test.go, internal/deepdoc/parser/pdf/parser_ocr_test.go, internal/deepdoc/parser/pdf/parser_test.go, internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go, internal/deepdoc/parser/pdf/parser_pipeline_manual_test.go, internal/deepdoc/parser/pdf/batch_smoke_test.go, internal/deepdoc/parser/pdf/page_batch_test.go, internal/deepdoc/parser/pdf/crop_integration_test.go, internal/deepdoc/parser/pdf/ocr_merge_test.go
Parser OCR, rendering, batch processing, and parser integration tests now use shared pdf.* types and the new table-builder wiring.
Post-process pipeline
internal/deepdoc/parser/pdf/post/*, internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
PostProcess and image-description helpers normalize sections, filter outlines and headers/footers, assign doc types, and run optional VLM descriptions.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • infiniflow/ragflow#15976: Both PRs modify build.sh CGO setup and native library linking, including setup_cgo_env() behavior around shared PDF/oxide dependencies.

Suggested labels

ci, ☯️ refactor, size:XXL

Suggested reviewers

  • yingfeng
  • yuzhichang

Poem

🐰 Hop-hop! The pages sorted neat,
Inference carrots make the tables sweet.
Outlines dance, and captions tuck in place,
Post-process twinkles across the trace.
I nibble a byte, then wiggle my nose—
This PDF garden now softly glows.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description misses the required Summary section and gives only a minimal, vague problem statement. Add the template's ### Summary section with a brief purpose statement and context; expand the problem description beyond "package refactor and PDF post process."
Docstring Coverage ⚠️ Warning Docstring coverage is 55.60% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title mentions the parser refactor, but it is generic and does not clearly summarize the main change. Rename it to a specific one-line summary of the parser/PDF refactor, such as the main subsystem or feature changed.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

Revert files outside the target packages to match upstream/main,
removing unintended changes from the merge.

Co-Authored-By: Claude <[email protected]>

@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: 3

🤖 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 `@build.sh`:
- Around line 298-299: Preserve existing caller-provided linker flags in the
build.sh CGO setup: the CGO_LDFLAGS export currently overwrites any preexisting
values, unlike the CGO_CFLAGS line. Update the CGO_LDFLAGS assignment in the
same block that sets OFFICE_OXIDE_PREFIX so it appends the office_oxide library
paths and rpath while retaining any prior CGO_LDFLAGS content, using the same
pattern already used for CGO_CFLAGS.
- Around line 192-193: The job count passed to make in the build script is
Linux-specific and unquoted, which breaks portability on macOS and triggers
ShellCheck warnings. Update the build step around the rag_tokenizer_c_api target
to use a portable way to determine the parallel job count in build_cpp, and make
sure the substitution is quoted so the shell expands it safely on both Darwin
and Linux.
- Around line 303-327: The setup_cgo_env logic currently hardcodes
Linux-specific pdfium and pdf_oxide library names/paths, so adjust the pdfium
and pdf_oxide lookup blocks to resolve per OS and architecture like office_oxide
does. Use the existing setup_cgo_env/pdfium/pdf_oxide symbols to branch on
platform, select the correct native library filename and directory for each
target, and only then export CGO_LDFLAGS and LD_LIBRARY_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: ec3e1524-9305-4560-8cfc-5999ab441d83

📥 Commits

Reviewing files that changed from the base of the PR and between 1137f67 and d6974ea.

📒 Files selected for processing (18)
  • build.sh
  • 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/pdfium/pdfium.go
  • internal/deepdoc/parser/pdf/table/table_annotate.go
  • internal/deepdoc/parser/pdf/table/table_cell_spatial_test.go
  • internal/deepdoc/parser/pdf/table/table_cells.go
  • internal/deepdoc/parser/pdf/table/table_construct.go
  • internal/deepdoc/parser/pdf/table/table_layout.go
  • internal/deepdoc/parser/pdf/table/table_layout_test.go
  • internal/deepdoc/parser/pdf/table/table_parity_issues_test.go
  • internal/deepdoc/parser/pdf/type/types.go
  • internal/deepdoc/parser/pdf/type/types_test.go
  • internal/deepdoc/parser/pdf/util/garbled.go
  • internal/deepdoc/parser/pdf/util/garbled_test.go
  • internal/deepdoc/parser/pdf/util/geometry.go
  • internal/deepdoc/parser/pdf/util/geometry_test.go
💤 Files with no reviewable changes (2)
  • internal/deepdoc/parser/pdf/layout/layout.go
  • internal/deepdoc/parser/pdf/parser.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • internal/deepdoc/parser/pdf/pdfium/pdfium.go
  • internal/deepdoc/parser/pdf/table/table_layout.go
  • internal/deepdoc/parser/pdf/table/table_annotate.go
  • internal/deepdoc/parser/pdf/layout/layout_test.go
  • internal/deepdoc/parser/pdf/table/table_construct.go
  • internal/deepdoc/parser/pdf/table/table_layout_test.go
  • internal/deepdoc/parser/pdf/table/table_parity_issues_test.go

Comment thread build.sh Resolved
Comment thread build.sh Resolved
Comment thread build.sh 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: 3

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

40-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the stale failure note.

Parse() now calls engine.Outlines() and assigns result.Outlines, so this comment documents the opposite of the current implementation and will mislead the next person debugging this test.

🤖 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/outline_extraction_test.go` around lines 40 - 42,
Remove the stale failure note from the outline extraction test comment because
it no longer matches the current behavior. Update the test documentation in
outline_extraction_test.go so it reflects that Parse() now invokes
engine.Outlines() and populates result.Outlines, rather than describing the old
failure mode. Keep the comment aligned with the current Parse and ParseResult
behavior so future debugging is not misled.
🤖 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 `@build.sh`:
- Around line 259-263: The native library bootstrap helpers are only printing
“install failed” and letting setup continue, so missing pdfium/pdf_oxide
dependencies surface later as CGO failures. Update the pdfium and pdf_oxide
install checks in the bootstrap flow, including the helper used by
setup_cgo_env(), to return a non-zero status or exit immediately when the
library file is not present. Make sure the failure path is propagated to the
caller instead of continuing after the failed install, so the setup stops at the
first missing prerequisite.
- Around line 233-236: In the build.sh logic that sets so_path for
pypdfium2_raw, the current pip show -f lookup uses a relative libpdfium.so path
that can fail the file check even when the package is installed. Update the
so_path resolution to join the pip show file entry with the package Location, or
rely on the absolute path derived from pypdfium2_raw.__file__, so the subsequent
[ -f ] check and copy step use a real filesystem path.

In `@internal/deepdoc/parser/pdf/parser_test.go`:
- Around line 565-570: The concurrent Parse() test is discarding errors inside
the worker goroutines, so failures won’t fail the test. Update the goroutine in
the parser test around p.Parse and mockEngine to capture both the returned error
and nil/invalid result cases, report them with t.Errorf(...) from inside the
worker, and return early for that worker when a failure is detected. Keep using
wg to coordinate completion, but do not ignore Parse() outcomes.

---

Nitpick comments:
In `@internal/deepdoc/parser/pdf/outline_extraction_test.go`:
- Around line 40-42: Remove the stale failure note from the outline extraction
test comment because it no longer matches the current behavior. Update the test
documentation in outline_extraction_test.go so it reflects that Parse() now
invokes engine.Outlines() and populates result.Outlines, rather than describing
the old failure mode. Keep the comment aligned with the current Parse and
ParseResult behavior so future debugging is not misled.
🪄 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: 5679b2bb-6c8a-403a-8f73-7b9fa2ef5fb3

📥 Commits

Reviewing files that changed from the base of the PR and between d6974ea and 4f775a0.

📒 Files selected for processing (8)
  • build.sh
  • internal/deepdoc/parser/pdf/outline_extraction_test.go
  • internal/deepdoc/parser/pdf/parser.go
  • internal/deepdoc/parser/pdf/parser_test.go
  • internal/deepdoc/parser/pdf/post/outline_postprocess_test.go
  • internal/deepdoc/parser/pdf/post/post_steps.go
  • internal/deepdoc/parser/pdf/post/post_steps_test.go
  • internal/deepdoc/parser/pdf/type/types.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/deepdoc/parser/pdf/post/post_steps.go
  • internal/deepdoc/parser/pdf/post/post_steps_test.go
  • internal/deepdoc/parser/pdf/parser.go

Comment thread build.sh Resolved
Comment thread build.sh Resolved
Comment on lines +565 to +570
go func() {
defer wg.Done()
for range 5 {
eng := &mockEngine{pageCount: 2}
_, _ = p.Parse(context.Background(), eng)
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Don't drop parse failures inside the worker goroutines.

Right now this only helps -race; it still passes if concurrent Parse() calls start returning errors or nil results. Record failures with t.Errorf(...) inside the goroutine and stop that worker early when one occurs. Based on learnings, failures from non-test goroutines should use t.Errorf(...) rather than t.Fatalf(...).

Proposed fix
         go func() {
             defer wg.Done()
             for range 5 {
                 eng := &mockEngine{pageCount: 2}
-                _, _ = p.Parse(context.Background(), eng)
+                result, err := p.Parse(context.Background(), eng)
+                if err != nil || result == nil {
+                    t.Errorf("Parse failed during concurrent run: result=%v err=%v", result, err)
+                    return
+                }
             }
         }()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
go func() {
defer wg.Done()
for range 5 {
eng := &mockEngine{pageCount: 2}
_, _ = p.Parse(context.Background(), eng)
}
go func() {
defer wg.Done()
for range 5 {
eng := &mockEngine{pageCount: 2}
result, err := p.Parse(context.Background(), eng)
if err != nil || result == nil {
t.Errorf("Parse failed during concurrent run: result=%v err=%v", result, err)
return
}
}
🤖 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_test.go` around lines 565 - 570, The
concurrent Parse() test is discarding errors inside the worker goroutines, so
failures won’t fail the test. Update the goroutine in the parser test around
p.Parse and mockEngine to capture both the returned error and nil/invalid result
cases, report them with t.Errorf(...) from inside the worker, and return early
for that worker when a failure is detected. Keep using wg to coordinate
completion, but do not ignore Parse() outcomes.

Source: Learnings

xugangqiang and others added 5 commits June 29, 2026 13:00
check_pdfium_deps now checks .venv first (uv sync provides
pypdfium2_raw on CI), then ~/.pdfium/ cache, then PyPI wheel
download via curl+python3 zipfile.  Zero pip dependency avoids
PEP 668 externally-managed-environment failures on modern Linux.

Co-Authored-By: Claude <[email protected]>
The check_pdfium_deps function in build.sh needs .venv to find
pypdfium2_raw (which provides libpdfium.so for pdfium CGO linking).
Previously uv sync ran AFTER build.sh --test, so .venv did not exist
when Go tests tried to link ee/deepdoc/parser/pdf/table, causing
'cannot find -lpdfium' linker errors.

Move Prepare Python test environment step to before Run Go unit tests
in both ragflow_tests_infinity jobs.

Co-Authored-By: Claude <[email protected]>
Files that reference git-untracked testdata PDFs are now marked
cgo && manual so they are skipped by normal go test but still
runnable with -tags='cgo && manual' on developer machines.

Remove CI grep -v exclusions for pdf packages — manual build
tags now handle this cleanly.

Co-Authored-By: Claude <[email protected]>
@codecov

codecov Bot commented Jun 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (bf1eabe) to head (ffc2190).
⚠️ Report is 48 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16391   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

xugangqiang and others added 5 commits June 29, 2026 15:00
check_pdfium_deps and check_pdf_oxide_deps now return non-zero
on install failure.  setup_cgo_env propagates the error via
'|| return 1', turning a missing-library condition into a clear
setup error instead of a confusing CGO linker failure later.

Co-Authored-By: Claude <[email protected]>
Replace nproc (Linux-only) with a fallback chain:
  nproc || sysctl -n hw.ncpu || 1
Also quotes the value to address ShellCheck SC2046.

Co-Authored-By: Claude <[email protected]>
DefaultDLALabels duplicates (indices 4/7/9) are intentional — they
mirror the 10-class taxonomy in deepdoc/vision/dla_cli.py:10-21.
DefaultTSRLabels matches TSR_CLASS_MAP in tsr_adapter.py:21-26.

Co-Authored-By: Claude <[email protected]>
check_pdfium_deps needs .venv from uv sync to find pypdfium2_raw.
Previously uv sync ran after build.sh --go, causing the fail-fast
to abort the build with 'pdfium -> install failed'.

Insert uv sync between docker C++ build and Go binary build in
both ragflow_tests_infinity jobs.

Co-Authored-By: Claude <[email protected]>
@JinHai-CN
JinHai-CN merged commit 98323e7 into infiniflow:main Jun 29, 2026
3 checks passed
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Jun 30, 2026
- Remove uv sync from Build ragflow go server step
- Remove duplicate Prepare Python test environment step after Build step
- Restore grep -v exclusions for pdfium/pdfoxide/pdf Go packages
- Move Prepare Python test environment back before Prepare function test environment

These changes were introduced in PR infiniflow#16391 (oss parser go refactor)
and are no longer needed since the pdf Go packages must be excluded
from unit tests that lack required CGo build dependencies.
Co-Authored-By: Claude <[email protected]>
yingfeng pushed a commit that referenced this pull request Jun 30, 2026
## Summary

Two changes to make Go build \& run independent of native libraries
(office_oxide, pdfium, pdf_oxide).

## 1. Make native libraries optional (build.sh + Go source)

## 2. Roll back tests.yml CI changes from PR #16391
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…niflow#16505)

## Summary

Two changes to make Go build \& run independent of native libraries
(office_oxide, pdfium, pdf_oxide).

## 1. Make native libraries optional (build.sh + Go source)

## 2. Roll back tests.yml CI changes from PR infiniflow#16391
This was referenced Jul 1, 2026
@xugangqiang
xugangqiang deleted the feat/oss-parser-go-refactor branch August 7, 2026 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 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