Skip to content

Fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain + Chunker) - #17349

Merged
yuzhichang merged 5 commits into
infiniflow:mainfrom
xugangqiang:fix/parser-params
Jul 24, 2026
Merged

yuzhichang merged 5 commits into
infiniflow:mainfrom
xugangqiang:fix/parser-params

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Aligns the Go ingestion pipeline with the Python implementation, closing several behavioral gaps found during the Python→Go migration (tracked in docs/migration_python_go_diff.md). Covers parser/media dispatch alignment, the PDF coordinate-chain (preview images, outline→title, chunk coordinate finalization), and the Chunker Token/QA batches below.

Commits are grouped as follows.

1. Fix parser params (c524f45)

Fixes parser/media wiring and several dispatch gaps:

  • docx/pdf vision dispatch: correct parameter handling and VLM invocation.
  • markdown vision (diff 2.5): also enhance items whose doc_type_kwd is table, not only image (parser/utils.py:181).
  • media audio (diff 2.11): when output_format is json, carry the ASR transcription as a JSON item instead of only the Text field (the Invoke switch had no json branch and dropped it).
  • email (diff 2.2): default output_format is json (parser.py:212), not text.
  • tokenizer: handle empty/whitespace-only names; trim before embedding.
  • extractor: tag-matching parameter wiring.
  • split: keyword-split regex now covers CJK/English separators.
  • parser.go: parser-param plumbing.

2. fix parser gap (373537d)

Image dispatch now mirrors rag/app/picture.py:chunk():

  • Always OCR the image (PaddleOCR or local ONNX).
  • When OCR text is short, also call VLM (describe) and combine OCR + VLM text.
  • Emits a structured JSON item carrying the image data-URI and doc_type_kwd:"image", instead of a bare Text string. This fixes the payload being rejected downstream by OneChunker/TokenChunker (JSON=nil).

3. PDF coordinate-chain fixes (55367a8, 727f816)

Closes three items from the migration tracker in the chunker/tokenizer/task layer:

  • (Chunker-1.3) restore_pdf_text_previews — needsCrop now also returns true for text chunks that carry PDF positions (pdfcrop_cgo.go), so text blocks get a rendered preview image uploaded to storage via imageUploadDecorator/ChunkImageUploader, matching Python restore_pdf_text_previews + image2id.

  • (Chunker-1.5) PDF outline → title levels — title.go adds outlineSimilarity (rune-bigram Jaccard, mirroring common.py:_outline_similarity), resolveOutlineLevels (matches text lines to outline entries at similarity > 0.8, with a sparse guard len(outline)/len(records) <= 0.03), and outlineFromInputs (reads file.outline). Wired into newLevelContext in both group.go and hierarchy.go; falls back to the title-shape heuristic when no outline is present.

  • (Tokenizer-(T)1) finalize_pdf_chunk — the coordinate → position_int/page_num_int/top_int conversion is owned by the task layer (processChunkPositions→AddPositions), which runs after the tokenizer and consumes the tokenizer-owned fields. The tokenizer only preserves the raw positions/_pdf_positions (no duplicate conversion), pinned by TestChunkDocsToMaps_PreservesPDFPositions.

4. Integration test made environment-free (internal/ingestion/task/pipeline_real_integration_test.go)

  • Removed the //go:build integration tag so the contract tests run under the default build.sh --test (which does not pass -tags integration).
  • External dependencies replaced with in-memory substitutes so no MySQL/MinIO/ES is required:
    • MySQL → on-disk sqlite (glebarez/sqlite) with the needed tables auto-migrated.
    • MinIO → storage.NewMemoryStorage().
    • Elasticsearch → chunks captured via WithInsertFunc instead of engine.InsertChunks/Search.
  • requireTokenizerPool still skips gracefully when the native tokenizer pool is unavailable; WithLogCreateFunc(noop) avoids depending on the operation-log table.
  • Added taskChunkFieldEqualsStr to tolerate kb_id being a []string/[]any in the raw chunk payload (the search engine flattens it to a string on read).

5. TokenChunker alignment — Batch 1 (internal/ingestion/component/chunker/token.go)

Closes four Chunker items from the migration tracker:

  • (Chunker-2.1) sentence delimiter — the boundary regex now also breaks on ASCII !/?. Extracted to a package-level var sentenceDelimiter and used in mergeByTokenSize, matching Python's full delimiter set.
  • (Chunker-2.2) overlap tag leakage — when a new chunk starts, its overlap prefix is taken from the previous chunk after removeTag, in both the text path (mergeByTokenSize) and the JSON path (mergeByTokenSizeFromJSON). Parser tags (@@…##) no longer leak into the overlap region (mirrors nlp/__init__.py:1181).
  • (Chunker-2.11) empty-text merge — merging a non-empty chunk into an empty previous chunk now assigns the text directly instead of being skipped (mergeByTokenSizeFromJSON), mirroring token_chunker.py:236-239.
  • (Chunker-2.4) overlap token counting — takeFromEnd/takeFromStart now count tokens exactly via tokenizeStr instead of the 4-bytes/token heuristic, fixing over-counting for CJK text.

6. QA Chunker alignment — Batch 2 (internal/ingestion/component/chunker/qa.go + schema)

Closes three Chunker items from the migration tracker:

  • (Chunker-2.13) default language — an empty lang now defaults to Chinese prefixes (问题:/回答:) instead of English, matching qa.py:299.
  • (Chunker-2.12) rmQAPrefix regex — the separator is changed to [\t:: ]+ (one-or-more), matching qa.py:241, so multiple separators (e.g. Q:: answer) are fully stripped.
  • (Chunker-1.8 QA) missing chunk fields — QA chunks now preserve:
    • top_int — the source row/record index, threaded through the tab/csv/markdown extractors (mirrors qa.py beAdoc(..., row_num=i));
    • image + doc_type_kwd:"image";
    • _pdf_positions / positions carried from the upstream JSON item.
      schema.ChunkDoc gains a TopInt []int field (serialized as top_int, registered in UnmarshalJSON). Note: the Tag/Table/Presentation/One chunker field gaps under 1.8 remain pending.

Test plan

  • Added/updated unit tests: pdfcrop_cgo_test.go (TestNeedsCrop, TestRestorePDFTextPreview), title_test.go (TestResolveOutlineLevels, TestResolveOutlineLevels_SparseGuard, TestNewLevelContext_OutlineBranch, TestOutlineFromInputs), tokenizer_unit_test.go (TestChunkDocsToMaps_PreservesPDFPositions), token_pdfpos_test.go.
  • Batch 1 — token_batch1_test.go: TestSentenceDelimiterMatchesBangAndQuestion, TestMergeByTokenSizeFromJSON_OverlapStripsTags, TestMergeByTokenSizeFromJSON_EmptyPrevKeepsChunk, TestTakeFromEndRespectsTokenCount, TestTakeFromStartRespectsTokenCount.
  • Batch 2 — qa_batch2_test.go: TestQAChunker_DefaultLangIsChinese, TestRmQAPrefixStripsMultipleSeparators, TestQAChunker_SetsTopInt, TestQAChunker_CarriesImageAndPositions. Existing qa_test.go expectations were updated to the corrected language default / separator behavior.
  • pipeline_real_integration_test.go (TestPipelineExecutor_Run_RealCanvasDSL_UsesGeneralPipeline, TestPipelineExecutor_Run_RealPDF_ProducesIndexedChunks, TestRunPipeline_RealPipelineOutput_ProducesIndexFields) now runs without any external service.
  • bash build.sh --test ./internal/ingestion/... passes.
  • No files deleted.

@xugangqiang xugangqiang added the ci Continue Integration label Jul 24, 2026
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR standardizes media JSON output, expands vision enrichment, updates parser inputs and method recognition, preserves PDF coordinates and outlines through chunking, carries QA metadata, renders positioned text previews, normalizes text inputs, and isolates pipeline integration tests.

Changes

Media vision output contracts

Layer / File(s) Summary
Media output contracts
internal/ingestion/component/media_dispatch.go, internal/ingestion/component/parser.go, internal/ingestion/pipeline/template/..., internal/ingestion/task/pipeline_executor_defaults_test.go, internal/ingestion/component/media_dispatch_test.go
Image results use JSON items with data URIs, JSON audio results carry transcription items, defaults change for email/audio, and related output contracts are tested.
Vision enrichment paths
internal/ingestion/component/docx_vision_dispatch.go, internal/ingestion/component/docx_vision_dispatch_test.go, internal/ingestion/component/markdown_vision_dispatch.go, internal/ingestion/component/media_dispatch_test.go
DOCX vision enriches JSON image/table items, while Markdown vision also processes table items.

Parser input and method handling

Layer / File(s) Summary
Parser input normalization
internal/ingestion/component/extractor.go, internal/ingestion/component/extractor_test.go, internal/ingestion/component/pdf_vision_dispatch.go, internal/ingestion/component/pdf_vision_dispatch_test.go
Extractor prompts accept bare strings, and PDF named-method recognition uses updated canonical forms without layout suffixes.

Text normalization and embedding inputs

Layer / File(s) Summary
Raw embedding and keyword filtering
internal/ingestion/component/tokenizer.go, internal/ingestion/component/tokenizer_test.go, internal/utility/split.go, internal/utility/split_test.go
Title embeddings receive raw names, and keyword splitting removes whitespace-only segments.

PDF chunk metadata and heading detection

Layer / File(s) Summary
Outline-based heading resolution
internal/ingestion/component/chunker/title.go, internal/ingestion/component/chunker/group.go, internal/ingestion/component/chunker/hierarchy.go, internal/ingestion/component/chunker/title_test.go
Chunk level construction parses PDF outlines and prefers outline-based heading levels before frequency-based detection.
Coordinate metadata through chunking
internal/ingestion/component/chunker/group.go, internal/ingestion/component/chunker/token.go, internal/ingestion/component/chunker/*test.go, internal/ingestion/component/tokenizer_unit_test.go
Chunk grouping and token merging strip position tags, preserve coordinate matrices, deep-copy raw arrays, and retain mapped PDF positions.
Positioned text previews
internal/ingestion/component/chunker/pdfcrop_cgo.go, internal/ingestion/component/chunker/pdfcrop_cgo_test.go
Text chunks with PDF positions now receive rendered image previews.
QA chunk metadata
internal/ingestion/component/chunker/qa.go, internal/ingestion/component/chunker/qa_*test.go, internal/ingestion/component/schema/chunk_types.go
QA chunks carry source row indices, images, positions, language-specific prefixes, and typed top_int metadata.

Isolated pipeline validation

Layer / File(s) Summary
Isolated pipeline execution checks
internal/ingestion/task/pipeline_real_integration_test.go
Canvas and PDF integration tests use temporary SQLite databases, in-memory storage, direct chunk capture, and tolerant field comparisons.

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

Sequence Diagram(s)

sequenceDiagram
  participant ParserComponent
  participant MediaDispatch
  participant DOCXVision
  participant VisionModel
  participant Chunker
  participant TextPreviewRenderer
  ParserComponent->>MediaDispatch: dispatch image or audio
  MediaDispatch-->>ParserComponent: return structured JSON or text output
  ParserComponent->>DOCXVision: provide DOCX JSON items
  DOCXVision->>VisionModel: send eligible image or table data URI
  VisionModel-->>DOCXVision: return description
  DOCXVision-->>ParserComponent: append description to item text
  ParserComponent->>Chunker: provide positioned records
  Chunker->>TextPreviewRenderer: render positioned text preview
  TextPreviewRenderer-->>Chunker: return preview image
Loading

Possibly related PRs

Suggested reviewers: yingfeng, yuzhichang, jinhai-cn

Poem

I’m a rabbit with JSON in my hat,
Enriching each image, table, and chat.
Coordinates hop through every chunk,
Blank words vanish—swiftly sunk.
Outlines guide headings in line,
Hop-hop hooray, the outputs align!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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.
Title check ✅ Passed The title is concise and accurately summarizes the main change: aligning the Go ingestion pipeline with Python.
Description check ✅ Passed The description includes the required Summary section and provides clear migration context plus implementation details.

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.

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

🧹 Nitpick comments (2)
internal/ingestion/component/extractor.go (1)

172-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove migration-history references from Go comments.

These comments repeat Python source paths, migration identifiers, or template-history rationale. Keep each comment concise and limited to the current Go input or dispatch contract.

  • internal/ingestion/component/extractor.go#L172-L178: document that non-empty string-form prompts is accepted.
  • internal/ingestion/component/extractor_test.go#L573-L578: describe the string-form prompt test without Python/source-history details.
  • internal/ingestion/component/extractor_test.go#L595-L598: describe prompt precedence without migration context.
  • internal/ingestion/component/pdf_vision_dispatch_test.go#L20-L30: describe whitelist alignment without “Diff 2.10” or Python-validation history.
  • internal/ingestion/component/pdf_vision_dispatch_test.go#L63-L67: describe layout suffix behavior without migration rationale.

As per coding guidelines, Go comments should describe the current runtime path rather than 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/ingestion/component/extractor.go` around lines 172 - 178, Remove
migration-history and Python/source-path references from comments at
internal/ingestion/component/extractor.go:172-178,
internal/ingestion/component/extractor_test.go:573-578, and
internal/ingestion/component/extractor_test.go:595-598; describe respectively
non-empty string-form prompts, the string-form prompt test, and prompt
precedence using current Go behavior. Update comments at
internal/ingestion/component/pdf_vision_dispatch_test.go:20-30 and :63-67 to
describe whitelist alignment and layout-suffix behavior without migration
rationale, preserving all runtime and test logic.

Source: Coding guidelines

internal/ingestion/component/tokenizer.go (1)

437-440: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove migration-history references from the changed Go comments.

The implementation and tests are correct; the shared issue is that the added comments cite Python files and line numbers instead of documenting the current Go contract.

  • internal/ingestion/component/tokenizer.go#L437-L440: describe blank-name validation and raw title embedding directly in Go terms.
  • internal/ingestion/component/tokenizer_test.go#L594-L598: explain the raw-name expectation without Python source locations.
  • internal/ingestion/component/tokenizer_test.go#L613-L614: state that surrounding whitespace must be preserved without the Python reference.
  • internal/utility/split.go#L30-L34: retain the TrimSpace/nil semantics and remove the task_executor reference.
  • internal/utility/split_test.go#L55-L58: describe whitespace-only filtering locally.

As per coding guidelines, Go comments should remain aligned with the current runtime path rather than 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/ingestion/component/tokenizer.go` around lines 437 - 440, Remove
migration-history references from comments at
internal/ingestion/component/tokenizer.go#L437-L440,
internal/ingestion/component/tokenizer_test.go#L594-L598, and
internal/ingestion/component/tokenizer_test.go#L613-L614; describe blank-name
validation, raw title embedding, and preservation of surrounding whitespace
using current Go behavior. Update comments at internal/utility/split.go#L30-L34
to retain TrimSpace/nil semantics without mentioning task_executor, and at
internal/utility/split_test.go#L55-L58 to describe whitespace-only filtering
locally; do not change implementation or tests.

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/ingestion/component/pdf_vision_dispatch.go`:
- Around line 361-389: Update isNamedPDFParseMethod to recognize only the plain
PDF parser names accepted by ParserComponent.Check(), removing the `@mineru`,
`@paddleocr`, `@somark`, and `@opendataloader` suffix matching. Preserve suffix
handling for layout_recognizer through a separate classifier or caller-specific
logic, and add regression coverage confirming foo@mineru remains a VLM
parse_method while valid plain names remain recognized.

---

Nitpick comments:
In `@internal/ingestion/component/extractor.go`:
- Around line 172-178: Remove migration-history and Python/source-path
references from comments at internal/ingestion/component/extractor.go:172-178,
internal/ingestion/component/extractor_test.go:573-578, and
internal/ingestion/component/extractor_test.go:595-598; describe respectively
non-empty string-form prompts, the string-form prompt test, and prompt
precedence using current Go behavior. Update comments at
internal/ingestion/component/pdf_vision_dispatch_test.go:20-30 and :63-67 to
describe whitelist alignment and layout-suffix behavior without migration
rationale, preserving all runtime and test logic.

In `@internal/ingestion/component/tokenizer.go`:
- Around line 437-440: Remove migration-history references from comments at
internal/ingestion/component/tokenizer.go#L437-L440,
internal/ingestion/component/tokenizer_test.go#L594-L598, and
internal/ingestion/component/tokenizer_test.go#L613-L614; describe blank-name
validation, raw title embedding, and preservation of surrounding whitespace
using current Go behavior. Update comments at internal/utility/split.go#L30-L34
to retain TrimSpace/nil semantics without mentioning task_executor, and at
internal/utility/split_test.go#L55-L58 to describe whitespace-only filtering
locally; do not change implementation or tests.
🪄 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 Plus

Run ID: ec3ab3ab-8b8c-496d-aeaf-83af32b97113

📥 Commits

Reviewing files that changed from the base of the PR and between bdfc3ad and 373537d.

📒 Files selected for processing (15)
  • internal/ingestion/component/docx_vision_dispatch.go
  • internal/ingestion/component/docx_vision_dispatch_test.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/extractor_test.go
  • internal/ingestion/component/markdown_vision_dispatch.go
  • internal/ingestion/component/media_dispatch.go
  • internal/ingestion/component/media_dispatch_test.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/pdf_vision_dispatch.go
  • internal/ingestion/component/pdf_vision_dispatch_test.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/pipeline/template/ingestion_pipeline_picture.json
  • internal/utility/split.go
  • internal/utility/split_test.go

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 24, 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: 4

🧹 Nitpick comments (2)
internal/ingestion/component/chunker/pdfcrop_cgo.go (1)

144-156: 🚀 Performance & Scalability | 🔵 Trivial

Preview rendering now runs per positioned text chunk — consider the throughput impact on large PDFs.

Extending needsCrop to "text" means every text chunk carrying PDF positions now goes through CropSectionPositions (crop + base64 PNG encode) in cropImageChunks, not just image/table chunks. For large documents this can be the majority of chunks (most paragraphs), multiplying per-chunk image encoding work. Page renders are already cached (pageCache), which helps, but the crop+encode step itself still runs once per chunk. Worth keeping an eye on ingestion latency/memory for large PDFs with dense positions, since this is a new cost surface introduced for parity with the Python behavior.

🤖 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/component/chunker/pdfcrop_cgo.go` around lines 144 - 156,
The updated needsCrop function now sends every positioned text chunk through
expensive crop and PNG encoding. Review the cropImageChunks flow and preserve
text preview parity while reducing redundant per-chunk rendering or encoding
work, using the existing pageCache and relevant crop helpers where possible;
ensure image/table cropping behavior remains unchanged.
internal/ingestion/component/chunker/title.go (1)

398-431: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Sentinel matched == 0 conflates "no match" with a legitimate level 0 outline entry that resolves to level+1 == 0.

matched is used as both the "no match found" sentinel and the computed level; if o.level were -1 (not the typical 0-based PDF outline depth, but not impossible for defensively-parsed data), matched = o.level + 1 == 0 would be silently treated as "unmatched" and demoted to bodyLevel instead of the intended level. Consider a matched bool alongside the level, or offsetting the sentinel (e.g. matched := -1).

🛡️ Proposed defensive fix
-		matched := 0
+		matched := -1
 		for _, o := range outline {
 			if outlineSimilarity(o.title, rec.text) > 0.8 {
 				matched = o.level + 1
 				break
 			}
 		}
-		if matched == 0 {
+		if matched < 0 {
 			levels[i] = bodyLevel
 		} else {
 			levels[i] = matched
 		}
🤖 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/component/chunker/title.go` around lines 398 - 431, Update
resolveOutlineLevels so match detection is independent from the computed level:
track whether an outline entry matched separately from matched’s level value, or
use a sentinel that cannot collide with valid levels such as zero. Preserve the
intended resolved level, including when o.level + 1 equals zero, and only assign
bodyLevel when no outline entry matches.
🤖 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/ingestion/component/chunker/title_test.go`:
- Around line 445-469: Update TestOutlineFromInputs so the outline entries use
float64 values for their level fields, matching JSON-decoded map[string]any data
and exercising anyToInt’s float64 branch. Preserve the existing assertions and
missing-input fallback coverage.

In `@internal/ingestion/task/pipeline_real_integration_test.go`:
- Around line 140-142: Update the setup comment for the integration test to
describe the temporary on-disk SQLite database accurately, remove the obsolete
comparison to external MySQL/MinIO/ES services, and retain only the current
runtime details, including the in-memory storage backend and WithInsertFunc
chunk capture.
- Around line 257-259: Update the content_with_weight assertion in the
integration test to require a string value and reject nil, empty, or non-string
values. Preserve the existing per-chunk failure reporting while validating the
field’s type before checking that its string content is non-empty.
- Around line 412-439: Update the test cleanup registered after SQLite setup to
obtain the underlying *sql.DB from db and close the connection pool before
removing the temporary database file. Preserve the existing cleanup removal
behavior and handle any db.DB error consistently with the surrounding setup.

---

Nitpick comments:
In `@internal/ingestion/component/chunker/pdfcrop_cgo.go`:
- Around line 144-156: The updated needsCrop function now sends every positioned
text chunk through expensive crop and PNG encoding. Review the cropImageChunks
flow and preserve text preview parity while reducing redundant per-chunk
rendering or encoding work, using the existing pageCache and relevant crop
helpers where possible; ensure image/table cropping behavior remains unchanged.

In `@internal/ingestion/component/chunker/title.go`:
- Around line 398-431: Update resolveOutlineLevels so match detection is
independent from the computed level: track whether an outline entry matched
separately from matched’s level value, or use a sentinel that cannot collide
with valid levels such as zero. Preserve the intended resolved level, including
when o.level + 1 equals zero, and only assign bodyLevel when no outline entry
matches.
🪄 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 Plus

Run ID: 8849588a-8def-48c6-b687-5d225788f659

📥 Commits

Reviewing files that changed from the base of the PR and between 55367a8 and 727f816.

📒 Files selected for processing (11)
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/group_test.go
  • internal/ingestion/component/chunker/hierarchy.go
  • internal/ingestion/component/chunker/pdfcrop_cgo.go
  • internal/ingestion/component/chunker/pdfcrop_cgo_test.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_pdfpos_test.go
  • internal/ingestion/component/tokenizer_unit_test.go
  • internal/ingestion/task/pipeline_real_integration_test.go

Comment on lines +140 to +142
// Loads service config (server.Init side effect) without requiring any
// external MySQL/MinIO/ES. The pipeline runs against an in-memory sqlite
// DB and an in-memory storage backend; chunks are captured via WithInsertFunc.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the isolated-database comment.

The test uses a temporary on-disk SQLite file, not an in-memory database. Remove the obsolete external-service comparison while correcting the description. As per coding guidelines, keep documentation comments aligned with the current runtime path rather than migration history.

Proposed fix
-	// Loads service config (server.Init side effect) without requiring any
-	// external MySQL/MinIO/ES. The pipeline runs against an in-memory sqlite
-	// DB and an in-memory storage backend; chunks are captured via WithInsertFunc.
+	// Loads service configuration for this isolated pipeline test. The pipeline
+	// uses a temporary on-disk SQLite database and in-memory storage; chunks are
+	// captured via WithInsertFunc.
📝 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
// Loads service config (server.Init side effect) without requiring any
// external MySQL/MinIO/ES. The pipeline runs against an in-memory sqlite
// DB and an in-memory storage backend; chunks are captured via WithInsertFunc.
// Loads service configuration for this isolated pipeline test. The pipeline
// uses a temporary on-disk SQLite database and in-memory storage; chunks are
// captured via WithInsertFunc.
🤖 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/task/pipeline_real_integration_test.go` around lines 140 -
142, Update the setup comment for the integration test to describe the temporary
on-disk SQLite database accurately, remove the obsolete comparison to external
MySQL/MinIO/ES services, and retain only the current runtime details, including
the in-memory storage backend and WithInsertFunc chunk capture.

Source: Coding guidelines

Comment on lines 257 to +259
if got := chunk["content_with_weight"]; got == nil || got == "" {
t.Fatalf("result chunk[%d].content_with_weight = %v, want non-empty", i, got)
t.Fatalf("chunk[%d].content_with_weight = %v, want non-empty", i, got)
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
git ls-files | grep -F 'internal/ingestion/task/pipeline_real_integration_test.go' || true

echo "== relevant test section =="
if [ -f internal/ingestion/task/pipeline_real_integration_test.go ]; then
  sed -n '230,285p' internal/ingestion/task/pipeline_real_integration_test.go | cat -n
fi

echo "== search content_with_weight producers/uses =="
rg -n "content_with_weight" internal/ingestion -C 3 || true

echo "== file size/stat =="
wc -l internal/ingestion/task/pipeline_real_integration_test.go 2>/dev/null || true

Repository: infiniflow/ragflow

Length of output: 40909


Assert the required string type for content_with_weight.

content_with_weight is consumed as a string by downstream chunking/extractor code, so this test should reject non-string non-empty values.

Proposed fix
-		if got := chunk["content_with_weight"]; got == nil || got == "" {
-			t.Fatalf("chunk[%d].content_with_weight = %v, want non-empty", i, got)
+		if got, ok := chunk["content_with_weight"].(string); !ok || got == "" {
+			t.Fatalf("chunk[%d].content_with_weight = %T/%v, want non-empty string", i, chunk["content_with_weight"], chunk["content_with_weight"])
 		}
📝 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
if got := chunk["content_with_weight"]; got == nil || got == "" {
t.Fatalf("result chunk[%d].content_with_weight = %v, want non-empty", i, got)
t.Fatalf("chunk[%d].content_with_weight = %v, want non-empty", i, got)
}
if got, ok := chunk["content_with_weight"].(string); !ok || got == "" {
t.Fatalf("chunk[%d].content_with_weight = %T/%v, want non-empty string", i, chunk["content_with_weight"], chunk["content_with_weight"])
}
🤖 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/task/pipeline_real_integration_test.go` around lines 257 -
259, Update the content_with_weight assertion in the integration test to require
a string value and reject nil, empty, or non-string values. Preserve the
existing per-chunk failure reporting while validating the field’s type before
checking that its string content is non-empty.

Source: Coding guidelines

@xugangqiang xugangqiang changed the title fix(go): align ingestion parser & image dispatch with Python fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain) Jul 24, 2026
@xugangqiang xugangqiang changed the title fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain) WIP fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain) Jul 24, 2026
@xugangqiang xugangqiang changed the title WIP fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain) Fix(go): align ingestion pipeline with Python (parser/media dispatch + PDF coordinate chain + Chunker) Jul 24, 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: 1

Caution

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

⚠️ Outside diff range comments (1)
internal/ingestion/component/pdf_vision_dispatch.go (1)

373-385: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Align PDF method normalization across validation, dispatch, and tests.

ParserComponent.Check() and resolvePDFVisionModelID normalize whitespace differently, so padded canonical methods can take inconsistent paths.

  • internal/ingestion/component/pdf_vision_dispatch.go#L373-L385: use one shared normalization rule or reject surrounding whitespace consistently.
  • internal/ingestion/component/pdf_vision_dispatch_test.go#L31-L61: add padded-value cases covering the selected contract.
🤖 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/component/pdf_vision_dispatch.go` around lines 373 - 385,
The PDF parse-method handling uses inconsistent whitespace normalization between
validation and dispatch. Align isNamedPDFParseMethod and resolvePDFVisionModelID
with ParserComponent.Check by choosing one shared normalization/rejection
contract, then apply it consistently to canonical method values without treating
“@”-suffixed selectors as parse methods. In
internal/ingestion/component/pdf_vision_dispatch_test.go lines 31-61, add
padded-value cases that verify the selected contract across validation and
dispatch.
🧹 Nitpick comments (1)
internal/ingestion/component/chunker/token.go (1)

288-292: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove migration-history commentary from Go source and tests.

Keep concise comments describing current behavior; remove diff, “legacy,” and Python-migration narratives.

  • internal/ingestion/component/chunker/token.go#L288-L292: describe the active sentence-boundary behavior only.
  • internal/ingestion/component/chunker/token_batch1_test.go#L27-L32: describe the tested delimiter behavior only.
  • internal/ingestion/component/chunker/qa.go#L102-L104: describe the explicit language behavior only.
  • internal/ingestion/component/chunker/qa_batch2_test.go#L44-L46: describe the default-output contract only.
  • internal/ingestion/component/chunker/qa_test.go#L215-L216: describe valid space-separated prefixes only.

As per coding guidelines, keep Go documentation aligned with the current runtime path rather than migration history and remove stale documentation.

🤖 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/component/chunker/token.go` around lines 288 - 292, Remove
migration-history, “diff,” legacy, and Python-migration commentary from the
identified comments. In token.go, document only the active sentence-boundary
behavior; in token_batch1_test.go, describe the tested delimiter behavior; in
qa.go, describe the explicit language behavior; in qa_batch2_test.go, describe
the default-output contract; and in qa_test.go, describe valid space-separated
prefixes. Update comments only, preserving runtime code and tests.

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/ingestion/component/pdf_vision_dispatch.go`:
- Around line 373-377: Update the comments around the named-method
classification in internal/ingestion/component/pdf_vision_dispatch.go:373-377 to
state that `@-suffixed` values are excluded from parse_method classification and
that layout_recognizer uses dedicated MinerU handling. In
internal/ingestion/component/pdf_vision_dispatch_test.go:63-68, remove the claim
that all suffixes fall through to generic VLM dispatch; document the
field-specific dispatch behavior instead.

---

Outside diff comments:
In `@internal/ingestion/component/pdf_vision_dispatch.go`:
- Around line 373-385: The PDF parse-method handling uses inconsistent
whitespace normalization between validation and dispatch. Align
isNamedPDFParseMethod and resolvePDFVisionModelID with ParserComponent.Check by
choosing one shared normalization/rejection contract, then apply it consistently
to canonical method values without treating “@”-suffixed selectors as parse
methods. In internal/ingestion/component/pdf_vision_dispatch_test.go lines
31-61, add padded-value cases that verify the selected contract across
validation and dispatch.

---

Nitpick comments:
In `@internal/ingestion/component/chunker/token.go`:
- Around line 288-292: Remove migration-history, “diff,” legacy, and
Python-migration commentary from the identified comments. In token.go, document
only the active sentence-boundary behavior; in token_batch1_test.go, describe
the tested delimiter behavior; in qa.go, describe the explicit language
behavior; in qa_batch2_test.go, describe the default-output contract; and in
qa_test.go, describe valid space-separated prefixes. Update comments only,
preserving runtime code and tests.
🪄 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 Plus

Run ID: 93d7d3bd-7c29-481e-a434-1b1c4e3e1873

📥 Commits

Reviewing files that changed from the base of the PR and between 727f816 and 8caca43.

📒 Files selected for processing (10)
  • internal/ingestion/component/chunker/qa.go
  • internal/ingestion/component/chunker/qa_batch2_test.go
  • internal/ingestion/component/chunker/qa_test.go
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/chunker/token_batch1_test.go
  • internal/ingestion/component/pdf_vision_dispatch.go
  • internal/ingestion/component/pdf_vision_dispatch_test.go
  • internal/ingestion/component/schema/chunk_types.go
  • internal/ingestion/task/pipeline_real_integration_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/ingestion/component/chunker/title_test.go
  • internal/ingestion/task/pipeline_real_integration_test.go

Comment on lines +373 to +377
// Note: "@"-suffixed spellings such as "foo@mineru" are layout_recognizer
// selectors, not parse_method values. Check() rejects them as parse_method,
// and the MinerU layout branch is resolved from the layout_recognizer field
// separately (pdf_vision_dispatch.go:62-68), so they must NOT be recognized
// here.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document @... handling by field and dispatch path.

The comments conflate layout selectors with custom parse_method VLM values and incorrectly imply that @mineru follows generic VLM handling.

  • internal/ingestion/component/pdf_vision_dispatch.go#L373-L377: explain that suffixes are excluded from named-method classification, while layout_recognizer has dedicated MinerU handling.
  • internal/ingestion/component/pdf_vision_dispatch_test.go#L63-L68: remove the claim that every suffix falls through to generic VLM dispatch.
    As per coding guidelines, keep Go documentation comments aligned with the current runtime path.
📍 Affects 2 files
  • internal/ingestion/component/pdf_vision_dispatch.go#L373-L377 (this comment)
  • internal/ingestion/component/pdf_vision_dispatch_test.go#L63-L68
🤖 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/component/pdf_vision_dispatch.go` around lines 373 - 377,
Update the comments around the named-method classification in
internal/ingestion/component/pdf_vision_dispatch.go:373-377 to state that
`@-suffixed` values are excluded from parse_method classification and that
layout_recognizer uses dedicated MinerU handling. In
internal/ingestion/component/pdf_vision_dispatch_test.go:63-68, remove the claim
that all suffixes fall through to generic VLM dispatch; document the
field-specific dispatch behavior instead.

Source: Coding guidelines

@xugangqiang

Copy link
Copy Markdown
Contributor Author

@yingfeng @JinHai-CN @yuzhichang Please help to review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants