Repository navigation
feat(agent): Go ingestion pipeline progress mirroring and DeepDOC parser hardening - #16795
Conversation
…ser hardening
Squashed agent-go-port work, grouped by area:
feat(ingestion): mirror Go pipeline progress into the document table; harden resume guards
- pipeline: bind the owning document via WithDocumentID; after each TrackProgress event
aggregate ingestion_task_log progress and mirror progress/run/progress_msg back into
the document table, so GET /api/v1/datasets/{dataset_id}/documents reflects live Go
pipeline progress without a bespoke endpoint.
- canvas: extend the S3 resume guard to reject legacy no-op nodes (e.g. ExitLoop) so
component_total equals the count of progress-reporting components and the aggregate
percent can reach 100%.
- runtime/canvas: route progress through TrackProgress; add interrupt test coverage
(r3_interrupt_test.go).
- dao/entity: add IngestionTask.DocumentID column and AggregateProgress support used by
the mirror; IngestionTaskLog keeps a Checkpoint column alongside the progress fields.
feat(deepdoc): cache DocAnalyzer inference results in Redis (1h TTL)
- Redis-backed DocAnalyzerCache decorator over inference.Client; cache key =
"ddoc:cache:<method>:" + sha256 of the JPEG-encoded image bytes (deterministic).
- TTL = 1h; hits skip the inner HTTP call and return cached JSON; inner errors are not
cached.
refactor(deepdoc): align figure cropping with Python cropout + bounded page caches
- CropSectionByDLA mirrors Python cropout: best-overlap DLA figure/equation region,
fallback to section bbox per page, vertical concat on gray background.
- sliding-window page-image cache bounds peak memory to the recent window instead of
the whole PDF.
- rename DLADebug -> DLARegions across parser/chunker/tests.
refactor(parser): drop lib_type selector; align NewXxxParser with NewPDFParser
- remove config["lib_type"] lookup and the libType param/field/switch from all nine
constructors; surface the CGO-required error at ParseWithResult time instead of
construction time; drop resolveLibType, its test, and the four lib_type constants.
feat(utility): add a reusable workerpool for bounded concurrent execution
- internal/utility/workerpool.go (+ tests).
refactor: translate Chinese prose comments to English in non-harness Go files.
chore: upgrade github.com/cloudwego/eino from v0.9.9 to v0.9.12.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughThis pull request adds resumable canvas execution, structured progress logging, concurrent PDF parsing, shared native PDF synchronization, analyzer caching, multi-page cropping, fixed parser routing, and a generic worker pool, with corresponding API and test updates. ChangesExecution and progress
PDF processing
Parser integration
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/parser/parser/pdf_parser_common.go (1)
650-673: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winNative PDF engine leaks on unsupported
outputFormat.When
opts.outputFormatis neither"json"nor"markdown", thedefaultbranch returns an error without callingparsed.Close(). At that pointparseFnhas already succeeded, soparsed.Engineholds a live native PDF backend (file descriptors, memory) that is never released. The JSON and Markdown branches both close the engine viaprocessed.Close(), but the error path does not.🔧 Proposed fix: close engine before returning error
default: + parsed.Close() return ParseResult{Err: fmt.Errorf("parser: unsupported PDF output_format %q", opts.outputFormat)} }🤖 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/parser/parser/pdf_parser_common.go` around lines 650 - 673, Ensure parsePDFWithDeepDocOptions releases the successfully parsed native engine when outputFormat is unsupported: in the default branch, close parsed (or its engine) before returning the error, matching the cleanup performed by the JSON and Markdown processing paths.
🧹 Nitpick comments (4)
internal/deepdoc/parser/pdf/inference/cache.go (1)
156-171: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winCompute cache key once to avoid double JPEG encoding on cache miss.
cacheKeyOrEmptyis called twice per method invocation — once before the lookup and once before the store. Each call encodes the image to JPEG and hashes it. On a cache miss this doubles the encoding cost for every page image. Compute the key once and reuse it for both paths.The same pattern repeats in
TSR(174–189),OCRDetect(192–207), andOCRRecognize(210–225).♻️ Proposed refactor for DLA (apply same pattern to TSR/OCRDetect/OCRRecognize)
func (c *DocAnalyzerCache) DLA(ctx context.Context, img image.Image) ([]doctype.DLARegion, error) { - if key := cacheKeyOrEmpty("dla", img); key != "" && c.store.Enabled() { + key := cacheKeyOrEmpty("dla", img) + if key != "" && c.store.Enabled() { var cached []doctype.DLARegion if c.store.GetObj(key, &cached) { return cached, nil } } out, err := c.inner.DLA(ctx, img) if err != nil || img == nil { return out, err } - if key := cacheKeyOrEmpty("dla", img); key != "" && c.store.Enabled() { + if key != "" && c.store.Enabled() { c.store.SetObj(key, out, c.ttl) } return out, nil }🤖 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/inference/cache.go` around lines 156 - 171, Compute the cache key once at the start of each method—DLA, TSR, OCRDetect, and OCRRecognize—when caching is enabled, store it in a local variable, and reuse it for both cache lookup and result storage. Remove the repeated cacheKeyOrEmpty calls so each invocation encodes and hashes the image at most once.internal/ingestion/pipeline/pipeline.go (1)
509-509: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift
deriveDocumentProgressqueries the DB on every progress event — O(N²) log reads.
taskLogProgressCallbackcallsderiveDocumentProgresson every component start/done/fail event. Each call invokeslogDAO.AggregateProgresswhich reads allingestion_task_logrows for the task. For a pipeline with N components, this results in ~2N events × O(N) rows per query = O(N²) total log reads on the hot path.Consider maintaining incremental counters (
doneCount,runningCount,failedCount) in the closure and computingprogress/runwithout a DB round-trip. On resume, re-initialize the counters from a singleAggregateProgresscall.Also applies to: 521-539
🤖 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/pipeline/pipeline.go` at line 509, Refactor taskLogProgressCallback and deriveDocumentProgress to avoid querying AggregateProgress on every progress event: initialize doneCount, runningCount, and failedCount once from a single AggregateProgress call when resuming, then update these counters as components start, complete, or fail and compute progress/run from them. Remove the per-event logDAO.AggregateProgress call while preserving existing progress semantics.internal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.go (1)
325-375: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider moving pixel processing outside the PDFium mutex.
renderPageFromDoc(lines 356–375) performs the nativeRenderPageRawcall followed by a pure-Go pixel alpha-premultiplication loop. Both the standaloneRenderPage(line 334) andDocument.RenderPage(line 349) invoke it insidepdfsync.With, so the pixel loop holdspdfsync.Mufor the entire render+process duration. Since the loop is pure Go and touches no PDFium state, it doesn't need the lock. Moving it outside would let the next concurrent render acquire the mutex while the previous pixel processing runs, improving pipeline throughput for multi-page parsing.♻️ Proposed refactor: split native render from pixel processing
func RenderPage(pdfData []byte, pageIdx int, dpi float64) (*RenderResult, error) { if len(pdfData) == 0 { return nil, fmt.Errorf("pdfplumber: empty PDF data for rendering") } var res *RenderResult var rerr error + var pixmap *pdfoxide.Pixmap pdfsync.With(func() { doc, e := pdfoxide.OpenFromBytes(pdfData) if e != nil { rerr = fmt.Errorf("pdfplumber: open for render: %w", e) return } - defer doc.Close() - res, rerr = renderPageFromDoc(doc, pageIdx, dpi) + pixmap, rerr = doc.RenderPageRaw(pageIdx, int(math.Round(dpi))) + doc.Close() }) + if rerr != nil { + return nil, fmt.Errorf("pdfplumber: render page %d: %w", pageIdx, rerr) + } + res = processPixmap(pixmap) return res, rerr }Extract the pixel loop into a standalone
processPixmap(pixmap *pdfoxide.Pixmap) *RenderResultfunction and call it outsidepdfsync.Within bothRenderPageandDocument.RenderPage.🤖 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/pdfoxide/pdf_oxide_adapter.go` around lines 325 - 375, Move pixel processing out of the pdfsync.With critical sections: update RenderPage and Document.RenderPage to call only RenderPageRaw under the mutex, retain error wrapping, then pass the resulting pixmap to a new standalone processPixmap function outside the lock. Move the premultiplied-alpha conversion and RenderResult construction from renderPageFromDoc into processPixmap, and adjust or replace renderPageFromDoc accordingly.internal/deepdoc/parser/pdf/parser_ocr.go (1)
248-252: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDoc comment no longer matches the code path.
The comment states the fallback runs "a direct
doc.OCRRecognizecall," but line 292 now routes throughp.inferOCRRecognize(the limiter-wrapped primitive). Update the wording to reflect the current path.As per coding guidelines: "Keep Go package comments and doc comments aligned with the current runtime path, not with migration history."
🤖 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_ocr.go` around lines 248 - 252, Update the comment for buildTextBoxes to remove the claim that fallback uses a direct doc.OCRRecognize call and accurately state that empty regions are recognized through p.inferOCRRecognize, the limiter-wrapped OCR primitive.Source: Coding guidelines
🤖 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/parser_parallel_integration_test.go`:
- Around line 28-42: Close each ParseResult after its comparisons complete to
release the native PDF engine resources. In the per-fixture test using runParse,
ensure both baseline and parallel are deferred or explicitly closed, handling
any Close errors consistently with the test’s failure reporting.
In `@internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go`:
- Around line 596-613: TestIntegration_MultiChunk leaks native PDF resources
because the ParseResult is not closed. Add a deferred result.Close() immediately
after the successful Parse call, before accessing result.Sections or
result.Tables, matching the cleanup pattern used in the parallel integration
test.
In `@internal/deepdoc/parser/pdf/parser.go`:
- Around line 499-507: Propagate cancellation errors returned by runPageWorkers
instead of continuing with nil pageResults. In the processPages flow, after
calling runPageWorkers, return the error when it is context.Canceled or
context.DeadlineExceeded (or otherwise preserve and return the worker error as
appropriate) before invoking assembleDocument, while retaining logging for
non-fatal page failures.
- Around line 127-131: Restore a per-page upper bound for the zoom retry in the
PDF page-processing logic: before multiplying Config.Zoom by DlaScale, ensure
the retry is only performed when the configured zoom is below 9 and clamp the
resulting retryZoom to the intended maximum. Update the retry render/OCR path
near the per-page retry condition so unusually large zoom settings cannot
produce unsafe DPI or excessive memory usage.
In `@internal/deepdoc/parser/pdf/table_extract.go`:
- Around line 42-50: Prevent nil dereferences before calling Health in
enrichOnePageWithDeepDoc: detect both a nil DocAnalyzer interface and typed-nil
implementations, returning pageBoxes, nil, nil immediately; alternatively make
DocAnalyzerCache.Health nil-safe while preserving this guard for direct
Parse/ParseRaw inputs.
In `@internal/utility/workerpool.go`:
- Around line 116-148: Handle panics from p.handler within WorkerPool.worker by
recovering around the handler invocation, converting the recovered value into an
error, and ensuring activeWorkers is decremented even when a panic occurs.
Continue the normal result-processing path so j.out receives a result containing
the error and markDone is always called, allowing StopWait and Submit().Wait to
complete.
---
Outside diff comments:
In `@internal/parser/parser/pdf_parser_common.go`:
- Around line 650-673: Ensure parsePDFWithDeepDocOptions releases the
successfully parsed native engine when outputFormat is unsupported: in the
default branch, close parsed (or its engine) before returning the error,
matching the cleanup performed by the JSON and Markdown processing paths.
---
Nitpick comments:
In `@internal/deepdoc/parser/pdf/inference/cache.go`:
- Around line 156-171: Compute the cache key once at the start of each
method—DLA, TSR, OCRDetect, and OCRRecognize—when caching is enabled, store it
in a local variable, and reuse it for both cache lookup and result storage.
Remove the repeated cacheKeyOrEmpty calls so each invocation encodes and hashes
the image at most once.
In `@internal/deepdoc/parser/pdf/parser_ocr.go`:
- Around line 248-252: Update the comment for buildTextBoxes to remove the claim
that fallback uses a direct doc.OCRRecognize call and accurately state that
empty regions are recognized through p.inferOCRRecognize, the limiter-wrapped
OCR primitive.
In `@internal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.go`:
- Around line 325-375: Move pixel processing out of the pdfsync.With critical
sections: update RenderPage and Document.RenderPage to call only RenderPageRaw
under the mutex, retain error wrapping, then pass the resulting pixmap to a new
standalone processPixmap function outside the lock. Move the premultiplied-alpha
conversion and RenderResult construction from renderPageFromDoc into
processPixmap, and adjust or replace renderPageFromDoc accordingly.
In `@internal/ingestion/pipeline/pipeline.go`:
- Line 509: Refactor taskLogProgressCallback and deriveDocumentProgress to avoid
querying AggregateProgress on every progress event: initialize doneCount,
runningCount, and failedCount once from a single AggregateProgress call when
resuming, then update these counters as components start, complete, or fail and
compute progress/run from them. Remove the per-event logDAO.AggregateProgress
call while preserving existing progress semantics.
🪄 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: 242880d8-e466-411e-8c6e-76dfe4626a93
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (97)
go.modinternal/agent/canvas/compile.gointernal/agent/canvas/compile_test.gointernal/agent/canvas/node_body.gointernal/agent/canvas/run_tracker.gointernal/agent/runtime/helpers.gointernal/agent/runtime/helpers_test.gointernal/agent/tool/code_exec.gointernal/agent/tool/qweather.gointernal/agent/tool/retrieval.gointernal/agent/workflowx/r3_interrupt_test.gointernal/cli/user_command.gointernal/dao/ingestion.gointernal/deepdoc/parser/pdf/batch_smoke_test.gointernal/deepdoc/parser/pdf/inference/cache.gointernal/deepdoc/parser/pdf/inference/cache_test.gointernal/deepdoc/parser/pdf/inference/client.gointernal/deepdoc/parser/pdf/layout/boxes_sections.gointernal/deepdoc/parser/pdf/layout/layout.gointernal/deepdoc/parser/pdf/layout/layout_test.gointernal/deepdoc/parser/pdf/mock_doc_analyzer.gointernal/deepdoc/parser/pdf/mock_engine.gointernal/deepdoc/parser/pdf/ocr_merge_test.gointernal/deepdoc/parser/pdf/ocr_recognize_batch_test.gointernal/deepdoc/parser/pdf/page_batch_test.gointernal/deepdoc/parser/pdf/parse_cgo.gointernal/deepdoc/parser/pdf/parser.gointernal/deepdoc/parser/pdf/parser_concurrency.gointernal/deepdoc/parser/pdf/parser_mock_test.gointernal/deepdoc/parser/pdf/parser_ocr.gointernal/deepdoc/parser/pdf/parser_ocr_test.gointernal/deepdoc/parser/pdf/parser_parallel_integration_test.gointernal/deepdoc/parser/pdf/parser_parallel_test.gointernal/deepdoc/parser/pdf/parser_pipeline_integration_test.gointernal/deepdoc/parser/pdf/parser_test.gointernal/deepdoc/parser/pdf/pdfium/pdfium.gointernal/deepdoc/parser/pdf/pdfium/pdfium_test.gointernal/deepdoc/parser/pdf/pdfium_integration_test.gointernal/deepdoc/parser/pdf/pdfoxide/pdf_oxide_adapter.gointernal/deepdoc/parser/pdf/pdfsync/pdfsync.gointernal/deepdoc/parser/pdf/pdfsync_shared_mutex_test.gointernal/deepdoc/parser/pdf/pipeline_parity_test.gointernal/deepdoc/parser/pdf/snapshot_test.gointernal/deepdoc/parser/pdf/table/table_annotate.gointernal/deepdoc/parser/pdf/table/table_annotate_test.gointernal/deepdoc/parser/pdf/table/table_cells_group_test.gointernal/deepdoc/parser/pdf/table/table_construct_test.gointernal/deepdoc/parser/pdf/table/table_orient_test.gointernal/deepdoc/parser/pdf/table/table_post_test.gointernal/deepdoc/parser/pdf/table_extract.gointernal/deepdoc/parser/pdf/table_rotate_integration_test.gointernal/deepdoc/parser/pdf/table_section_test.gointernal/deepdoc/parser/pdf/type/types.gointernal/deepdoc/parser/pdf/util/crop.gointernal/deepdoc/parser/pdf/util/crop_matrix_test.gointernal/deepdoc/parser/pdf/util/crop_test.gointernal/deepdoc/parser/pdf/util/eng_detect.gointernal/deepdoc/parser/type/types.gointernal/entity/ingestion_task.gointernal/ingestion/component/chunker/pdfcrop_cgo.gointernal/ingestion/component/chunker/pdfcrop_cgo_test.gointernal/ingestion/component/chunker/pdfcrop_nocgo.gointernal/ingestion/component/chunker/token.gointernal/ingestion/component/document_storage.gointernal/ingestion/component/extractor.gointernal/ingestion/component/extractor_test.gointernal/ingestion/component/parser.gointernal/ingestion/component/parser_dispatch.gointernal/ingestion/component/parser_dispatch_test.gointernal/ingestion/component/parser_test.gointernal/ingestion/component/schema/chunker.gointernal/ingestion/pipeline/PROGRESS_LOG_RESUME_PLAN.mdinternal/ingestion/pipeline/pipeline.gointernal/ingestion/pipeline/pipeline_test.gointernal/parser/parser/doc_parser.gointernal/parser/parser/docx_parser.gointernal/parser/parser/docx_parser_cgo_test.gointernal/parser/parser/html_parser.gointernal/parser/parser/markdown_parser.gointernal/parser/parser/office_parsers_cgo_shared.gointernal/parser/parser/office_parsers_no_cgo.gointernal/parser/parser/office_routes_cgo_test.gointernal/parser/parser/parse_result_test.gointernal/parser/parser/parse_with_result_test.gointernal/parser/parser/parser_type.gointernal/parser/parser/pdf_parser_common.gointernal/parser/parser/pdf_parser_mineru.gointernal/parser/parser/pdf_postprocess.gointernal/parser/parser/pdf_postprocess_test.gointernal/parser/parser/ppt_parser.gointernal/parser/parser/pptx_parser.gointernal/parser/parser/text_parser.gointernal/parser/parser/xls_parser.gointernal/parser/parser/xlsx_parser.gointernal/service/file.gointernal/utility/workerpool.gointernal/utility/workerpool_test.go
💤 Files with no reviewable changes (11)
- internal/deepdoc/parser/pdf/layout/boxes_sections.go
- internal/deepdoc/parser/pdf/table/table_orient_test.go
- internal/ingestion/component/extractor_test.go
- internal/deepdoc/parser/pdf/type/types.go
- internal/deepdoc/parser/pdf/table_rotate_integration_test.go
- internal/parser/parser/office_parsers_cgo_shared.go
- internal/deepdoc/parser/pdf/ocr_recognize_batch_test.go
- internal/deepdoc/parser/pdf/inference/client.go
- internal/deepdoc/parser/pdf/mock_doc_analyzer.go
- internal/ingestion/component/parser_dispatch_test.go
- internal/deepdoc/parser/pdf/page_batch_test.go
- Close leaked ParseResult native resources in integration tests (parser_parallel and parser_pipeline MultiChunk 52-page fixture). - Cap per-page retry zoom (math.Min(Zoom*DlaScale, 9.0)) to avoid unsafe DPI / memory spikes on large pages. - Preserve runPageWorkers cancellation/error instead of letting assembleDocument's empty result swallow it. - Guard nil docAnalyzer before Health() call; make DocAnalyzerCache.Health nil-safe. - Recover from handler panics in workerpool so results are delivered and StopWait/Submit().Wait do not hang.
feat(ingestion): mirror Go pipeline progress into the document table; harden resume guards
feat(deepdoc): cache DocAnalyzer inference results in Redis (1h TTL)
refactor(deepdoc): align figure cropping with Python cropout + bounded page caches
refactor(parser): drop lib_type selector; align NewXxxParser with NewPDFParser
feat(utility): add a reusable workerpool for bounded concurrent execution
refactor: translate Chinese prose comments to English in non-harness Go files.
chore: upgrade github.com/cloudwego/eino from v0.9.9 to v0.9.12.