Skip to content

fix: honor parser params and image VLM system_prompt in Go ingestion - #17334

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
xugangqiang:feat/parser-pdf-params
Jul 24, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
xugangqiang:feat/parser-pdf-params

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Fix the Go ingestion pipeline so that several parser setup switches and the
image VLM prompt are actually honored end-to-end (previously the DSL fields
existed but the Go code never read them).

  • DOCX (docx_parser.go, docx_postprocess.go): read remove_toc and
    remove_header_footer; apply to both JSON and markdown output paths
    (outline-based TOC removal with a text-heuristic fallback, plus
    header/footer section filtering).
  • HTML (html_parser.go, html_postprocess.go, text_toc.go): read
    remove_header_footer (pre-parse strip of <header>/<footer> and ARIA
    banner/contentinfo) and remove_toc (post-parse remove_contents_table
    heuristic).
  • Markdown (markdown_parser.go): read flatten_media_to_text and force
    media blocks to text when enabled.
  • Image VLM (media_dispatch.go): read system_prompt instead of prompt
    so the user-configured image VLM prompt is no longer silently dropped
    (prompt remains the video family key).

All flags are wired through ConfigureFromSetup, which the dispatch layer
already invokes for every family, so the behavior is live rather than dead code.

Test plan

  • New unit tests: docx_postprocess_test.go, html_parser_test.go,
    text_toc_test.go, markdown_parser_test.go, media_dispatch_test.go.
  • bash build.sh --test ./internal/parser/parser/... ./internal/ingestion/component/...

Notes

  • The File component is excluded from this migration scope.
  • Relates to the Python→Go parity diff (Parser 1.8–1.11, 1.15).

@xugangqiang xugangqiang added the ci Continue Integration label Jul 24, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds configurable HTML and DOCX removal of headers, footers, and TOC content, Markdown image flattening, DOCX IR processing, shared TOC utilities, and image VLM prompt selection using the image-family system_prompt key.

Changes

Image prompt dispatch

Layer / File(s) Summary
Image system prompt dispatch
internal/ingestion/component/media_dispatch.go, internal/ingestion/component/media_dispatch_test.go
Image dispatch now reads system_prompt, with a capture-driver test verifying the generated VLM message.

Parser content controls

Layer / File(s) Summary
Shared TOC filtering
internal/parser/parser/text_toc.go, internal/parser/parser/text_toc_test.go
Adds multilingual TOC heading detection, prefix-based entry removal, and table-driven tests.
HTML content controls
internal/parser/parser/html_parser.go, internal/parser/parser/html_postprocess.go, internal/parser/parser/html_parser_test.go
Adds setup flags for removing header/footer nodes and TOC items, including role-based HTML elements and tests.
DOCX IR conversion
internal/parser/parser/docx_ir.go, internal/parser/parser/docx_ir_test.go
Converts office_oxide IR into sections and extracted figures with image data and surrounding text context.
DOCX content controls
internal/parser/parser/docx_parser.go, internal/parser/parser/docx_postprocess.go, internal/parser/parser/docx_postprocess_test.go
Adds DOCX outline and header/footer extraction, conditional JSON/Markdown filtering, and helper tests.
Markdown media flattening
internal/parser/parser/markdown_parser.go, internal/parser/parser/markdown_parser_test.go
Adds flatten_media_to_text handling so resolved images retain image data while optionally remaining text-typed.
Parser test support
internal/ingestion/task/pipeline_real_integration_test.go, internal/parser/parser/docx_parser_test.go
Skips the real PDF integration test when its fixture cannot be read and removes a duplicate DOCX test helper.

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

Suggested labels: 🐞 bug

Suggested reviewers: yingfeng, yuzhichang, jinhai-cn

Poem

A rabbit hops through parsed pages bright,
Trimming headers by day, TOCs by night.
Images keep their data tucked away,
System prompts guide the VLM’s way.
“Hop tested!” cries the bun, with delight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.11% 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
Title check ✅ Passed The title clearly summarizes the main change: honoring parser params and the image VLM system_prompt in Go ingestion.
Description check ✅ Passed The description matches the template’s Summary section and includes relevant context, test plan, and notes.
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.

@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 (3)
internal/ingestion/component/media_dispatch_test.go (3)

64-67: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the test documentation focused on the current contract.

The “Before the fix” explanation preserves migration history. Document only that image dispatch uses system_prompt for the VLM user text, per the Go review guidelines.

Proposed wording
-// `system_prompt` setup key (Python/DSL contract), not `prompt`. Before the fix
-// the branch read setup["prompt"] which is empty for image, so the VLM received
-// the hardcoded default instead of the user-configured value.
+// Verifies that image dispatch uses the `system_prompt` setup key for VLM 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/ingestion/component/media_dispatch_test.go` around lines 64 - 67,
Update the comment for TestMaybeDispatchImage_UsesSystemPrompt to describe only
the current contract: image dispatch reads system_prompt for the VLM user text.
Remove the “Before the fix” migration-history explanation and retain the
Python/DSL contract context.

Source: Coding guidelines


46-61: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Search for the first text content part.

firstUserText claims to find the first "text" part but only inspects parts[0]. Iterate over all parts and check the "type" discriminator so the test remains valid if image content is reordered.

Proposed fix
-	part, ok := parts[0].(map[string]any)
-	if !ok {
-		return "", false
-	}
-	txt, ok := part["text"].(string)
-	return txt, ok
+	for _, raw := range parts {
+		part, ok := raw.(map[string]any)
+		if !ok || part["type"] != "text" {
+			continue
+		}
+		txt, ok := part["text"].(string)
+		if ok {
+			return txt, true
+		}
+	}
+	return "", false
🤖 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/media_dispatch_test.go` around lines 46 - 61,
Update firstUserText to iterate through every content part, selecting the first
map whose "type" discriminator identifies it as text and whose "text" value is a
string; skip image or malformed parts and return false only when no valid text
part exists.

77-80: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test precedence when both prompt keys are present.

The test currently proves that system_prompt is accepted, but not that it wins when a legacy prompt value is also configured. Add a conflicting sentinel value to catch regressions that select the wrong key.

Proposed test improvement
 	setups := defaultSetups()
+	setups["image"]["prompt"] = "legacy prompt"
 	setups["image"]["system_prompt"] = "自定义视觉提示"
🤖 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/media_dispatch_test.go` around lines 77 - 80,
Add a conflicting legacy prompt sentinel to the setup in the relevant media
dispatch test, alongside the existing image system_prompt value, and assert the
dispatched result uses system_prompt rather than prompt. Keep the current
system_prompt acceptance coverage while explicitly validating precedence when
both keys are configured.
🤖 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/ingestion/component/media_dispatch_test.go`:
- Around line 64-67: Update the comment for
TestMaybeDispatchImage_UsesSystemPrompt to describe only the current contract:
image dispatch reads system_prompt for the VLM user text. Remove the “Before the
fix” migration-history explanation and retain the Python/DSL contract context.
- Around line 46-61: Update firstUserText to iterate through every content part,
selecting the first map whose "type" discriminator identifies it as text and
whose "text" value is a string; skip image or malformed parts and return false
only when no valid text part exists.
- Around line 77-80: Add a conflicting legacy prompt sentinel to the setup in
the relevant media dispatch test, alongside the existing image system_prompt
value, and assert the dispatched result uses system_prompt rather than prompt.
Keep the current system_prompt acceptance coverage while explicitly validating
precedence when both keys are configured.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5e562c6c-5a57-40ab-85c3-158a160c0c19

📥 Commits

Reviewing files that changed from the base of the PR and between 74218bd and 60ecacf.

📒 Files selected for processing (12)
  • internal/ingestion/component/media_dispatch.go
  • internal/ingestion/component/media_dispatch_test.go
  • internal/parser/parser/docx_parser.go
  • internal/parser/parser/docx_postprocess.go
  • internal/parser/parser/docx_postprocess_test.go
  • internal/parser/parser/html_parser.go
  • internal/parser/parser/html_parser_test.go
  • internal/parser/parser/html_postprocess.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/text_toc.go
  • internal/parser/parser/text_toc_test.go

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 24, 2026
@xugangqiang

Copy link
Copy Markdown
Contributor Author

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

@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 `@internal/parser/parser/docx_ir.go`:
- Around line 270-280: Update the flattening loop used by the image-context
builder to extract plain text through the shared extractor for every supported
element type, rather than calling joinDOCXIRRuns on el.contentRuns(). Preserve
the existing image handling, and ensure tables, lists, text boxes, and other
elements supported by buildDOCXJSONSections contribute their text to flatBlock.
- Around line 326-344: Update collectDOCXPrevText in
internal/parser/parser/docx_ir.go lines 326-344 to account for the newline
separator when adding each previous text block, reserving one character before
accepting another block so the joined result stays within maxLen; apply the same
separator accounting in the following-block collector at
internal/parser/parser/docx_ir.go lines 346-364. Preserve image boundaries,
block ordering, and existing rune-based truncation.
- Around line 115-128: Update extractTextFromListItem to process each item’s
Nested list before returning, decoding nested entries as docxIRListItem values
and recursively extracting their text. Preserve the existing paragraph/heading
extraction and flatten nested content consistently into the returned text.
🪄 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: 5b6378a7-5bcf-4e3b-a5a7-79de40f1dcd6

📥 Commits

Reviewing files that changed from the base of the PR and between 60ecacf and 79cf387.

📒 Files selected for processing (4)
  • internal/parser/parser/docx_ir.go
  • internal/parser/parser/docx_ir_test.go
  • internal/parser/parser/docx_parser.go
  • internal/parser/parser/docx_postprocess.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/parser/parser/docx_postprocess.go
  • internal/parser/parser/docx_parser.go

Comment thread internal/parser/parser/docx_ir.go Resolved
Comment thread internal/parser/parser/docx_ir.go Resolved
Comment on lines +326 to +344
func collectDOCXPrevText(flat []flatBlock, idx, maxLen int) string {
var parts []string
remaining := maxLen
for i := idx - 1; i >= 0 && remaining > 0; i-- {
if flat[i].image != "" {
break // stop at previous image
}
if flat[i].text == "" {
continue
}
r := []rune(flat[i].text)
if len(r) > remaining {
r = r[len(r)-remaining:]
}
parts = append([]string{string(r)}, parts...)
remaining -= len(r)
}
return strings.Join(parts, "\n")
}

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

Keep figure context within maxLen after joining blocks.

Both collectors decrement remaining only for runes, then append newline separators. For example, 512 one-rune blocks produce 1,023 characters, violating the documented bounded context window.

  • internal/parser/parser/docx_ir.go#L326-L344: reserve one character for each inserted separator before accepting another previous block.
  • internal/parser/parser/docx_ir.go#L346-L364: apply the same separator accounting when collecting following blocks.
📍 Affects 1 file
  • internal/parser/parser/docx_ir.go#L326-L344 (this comment)
  • internal/parser/parser/docx_ir.go#L346-L364
🤖 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/docx_ir.go` around lines 326 - 344, Update
collectDOCXPrevText in internal/parser/parser/docx_ir.go lines 326-344 to
account for the newline separator when adding each previous text block,
reserving one character before accepting another block so the joined result
stays within maxLen; apply the same separator accounting in the following-block
collector at internal/parser/parser/docx_ir.go lines 346-364. Preserve image
boundaries, block ordering, and existing rune-based truncation.

@yuzhichang

Copy link
Copy Markdown
Member

LGTM

@xugangqiang
xugangqiang force-pushed the feat/parser-pdf-params branch from 79cf387 to ec654b6 Compare July 24, 2026 06:25

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

🧹 Nitpick comments (1)
internal/parser/parser/docx_ir_test.go (1)

113-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove migration-history commentary from test documentation.

Keep comments focused on the behavior currently protected by each test.

  • internal/parser/parser/docx_ir_test.go#L113-L118: remove the “Previously” implementation-history explanation.
  • internal/parser/parser/docx_ir_test.go#L140-L144: remove the historical 1023-character regression explanation.
🤖 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/docx_ir_test.go` around lines 113 - 118, Remove the
implementation-history wording from the comments in
internal/parser/parser/docx_ir_test.go at lines 113-118 and 140-144, including
the “Previously” explanation and the historical 1023-character regression
details. Keep each test comment focused only on the current behavior it
verifies; no other code changes are needed.

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/task/pipeline_real_integration_test.go`:
- Around line 207-208: Update the PDF fixture error handling in the integration
test to fail the test instead of calling t.Skipf when the fixture cannot be
read. Preserve the existing diagnostic message with pdfPath and err, and remove
the unreachable return after the failure call.

In `@internal/parser/parser/text_toc.go`:
- Around line 12-16: Update the shared heading normalization used by the TOC
matching flow, including removeTOCWord, to collapse whitespace to a single space
and trim surrounding whitespace so the table of contents pattern remains
reachable; add coverage for that phrase. Tighten the algorithm comment to state
that the gap before the first matching entry is removed rather than claiming
matching entries are deleted.

---

Nitpick comments:
In `@internal/parser/parser/docx_ir_test.go`:
- Around line 113-118: Remove the implementation-history wording from the
comments in internal/parser/parser/docx_ir_test.go at lines 113-118 and 140-144,
including the “Previously” explanation and the historical 1023-character
regression details. Keep each test comment focused only on the current behavior
it verifies; no other code changes are needed.
🪄 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: 8ad96c0a-a00d-401f-b331-92f6ca445c7b

📥 Commits

Reviewing files that changed from the base of the PR and between 79cf387 and ec654b6.

📒 Files selected for processing (16)
  • internal/ingestion/component/media_dispatch.go
  • internal/ingestion/component/media_dispatch_test.go
  • internal/ingestion/task/pipeline_real_integration_test.go
  • internal/parser/parser/docx_ir.go
  • internal/parser/parser/docx_ir_test.go
  • internal/parser/parser/docx_parser.go
  • internal/parser/parser/docx_parser_test.go
  • internal/parser/parser/docx_postprocess.go
  • internal/parser/parser/docx_postprocess_test.go
  • internal/parser/parser/html_parser.go
  • internal/parser/parser/html_parser_test.go
  • internal/parser/parser/html_postprocess.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/text_toc.go
  • internal/parser/parser/text_toc_test.go
💤 Files with no reviewable changes (1)
  • internal/parser/parser/docx_parser_test.go
🚧 Files skipped from review as they are similar to previous changes (12)
  • internal/ingestion/component/media_dispatch.go
  • internal/parser/parser/text_toc_test.go
  • internal/parser/parser/html_postprocess.go
  • internal/parser/parser/html_parser_test.go
  • internal/ingestion/component/media_dispatch_test.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/html_parser.go
  • internal/parser/parser/docx_parser.go
  • internal/parser/parser/docx_postprocess_test.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/docx_postprocess.go
  • internal/parser/parser/docx_ir.go

Comment on lines +207 to +208
t.Skipf("read pdf fixture %s: %v", pdfPath, err)
return

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

Fail when the required PDF fixture is unavailable.

Skipping here can silently remove real-PDF coverage when the fixture path breaks or the asset is absent.

Proposed fix
-		t.Skipf("read pdf fixture %s: %v", pdfPath, err)
-		return
+		t.Fatalf("read pdf fixture %s: %v", pdfPath, err)
📝 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
t.Skipf("read pdf fixture %s: %v", pdfPath, err)
return
t.Fatalf("read pdf fixture %s: %v", pdfPath, err)
🤖 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 207 -
208, Update the PDF fixture error handling in the integration test to fail the
test instead of calling t.Skipf when the fixture cannot be read. Preserve the
existing diagnostic message with pdfPath and err, and remove the unreachable
return after the failure call.

Comment on lines +12 to +16
var tocHeadingPattern = regexp.MustCompile(`(?i)^(contents|目录|目次|table of contents|致谢|acknowledge)$`)

// whitespacePattern matches ASCII spaces and fullwidth space (U+3000)
// for normalization before heading match.
var whitespacePattern = regexp.MustCompile("[ \t\u3000]+")

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 | 🟠 Major | ⚡ Quick win

"table of contents" alternative is unreachable due to whitespace normalization.

whitespacePattern.ReplaceAllString(..., "") at line 44 strips ALL whitespace from the candidate text before matching against tocHeadingPattern. Since normalized text can never contain a space, the table of contents alternative in the regex (line 12) — which requires literal spaces between words — can never match. A heading literally titled "Table of Contents" (a very common English TOC heading) will normalize to "TableofContents" and silently fail to be recognized, breaking TOC removal for that case. None of the existing test cases exercise this multi-word phrase, so the bug is untested.

The same normalization line is duplicated verbatim in docx_postprocess.go's removeTOCWord (per the referenced downstream snippet), so fixing only here still leaves the identical latent bug at that call site. As per coding guidelines, internal/parser/**/*.go should "collapse duplicate paths and do not preserve transitional wrappers or deprecated APIs" — consider extracting this normalization into a shared helper in this file and having docx_postprocess.go call it, so the fix applies once.

Separately, the algorithm doc (lines 36-37) says step 4 "drop[s] up to 128 following entries that start with the prefix," but the implementation only deletes the gap before the first matching entry within that window (keeping the match) — worth tightening the comment while touching this function.

🐛 Proposed fix: normalize whitespace to a single space, then trim
 	for i < len(items) {
 		text := itemText(items[i])
 		// Strip @@ suffix and whitespace before matching.
-		normalized := whitespacePattern.ReplaceAllString(strings.SplitN(text, "@@", 2)[0], "")
+		normalized := strings.TrimSpace(whitespacePattern.ReplaceAllString(strings.SplitN(text, "@@", 2)[0], " "))
 		if !tocHeadingPattern.MatchString(normalized) {

This preserves all currently-passing single-token cases ("目录", "Contents") since they have no internal whitespace to begin with, while making the table of contents alternative reachable.

Also applies to: 39-50

🤖 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/text_toc.go` around lines 12 - 16, Update the shared
heading normalization used by the TOC matching flow, including removeTOCWord, to
collapse whitespace to a single space and trim surrounding whitespace so the
table of contents pattern remains reachable; add coverage for that phrase.
Tighten the algorithm comment to state that the gap before the first matching
entry is removed rather than claiming matching entries are deleted.

Source: Coding guidelines

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