Skip to content

fix(parser): align HTML Parser to Python (nested-table fix; alignment golden) - #18084

Closed
xugangqiang wants to merge 2 commits into
infiniflow:mainfrom
xugangqiang:fix/html-epub-parser-align
Closed

xugangqiang wants to merge 2 commits into
infiniflow:mainfrom
xugangqiang:fix/html-epub-parser-align

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Aligns the Go HTML parser (internal/parser/parser/html_parser.go) with the Python RAGFlowHtmlParser and adds a reusable alignment test harness so the two engines can be diffed content-wise, not just line-wise.

This fixes a real divergence — nested-table 塌方 — where a <table> nested inside other block content (or containing another table) was collapsed into a single concatenated string on the Go side while Python kept each cell/tag on its own line.

Root cause

walkHTMLLeaf recursed into <table> children as plain leaf text and concatenated every cell ("NameAge\nAlice30…"). Python keeps each cell/tag on its own line, so the engines diverged whenever a table appeared inside a list, blockquote, or another table.

Fix (surgical; preserves per-block granularity)

  • htmlLeafText / walkHTMLLeaf now take a *[]map[string]any sink for structured table items.
  • walkHTMLLeaf gained a table-aware branch: a <table> is rendered to its inline markup, written as text, and appended as a structured doc_type_kwd:"table" item — mirroring the existing top-level (non-leaf) table path.
  • renderTableHTML returns "" on render error instead of recursing through the leaf extractor (avoids a render loop).

Tests (TDD: RED before fix, GREEN after)

  • TestHTMLParser_NestedTableProducesStructuredItems — the original 塌方 case.
  • TestHTMLParser_NestedListItemsPreserved — nested <ul>/<ol> items stay separate, in document order; top-level list tagged ck_type:"list".
  • TestHTMLParser_PrePreservesVerbatim — <pre>/<textarea> keep indentation and internal newlines verbatim (one leading newline dropped per spec).
  • TestHTMLParser_AlignmentGolden — content-equivalence against the Python RAGFlowHtmlParser baseline via the shared align_test.go tool.

Alignment tooling (mirrors the merged markdown convention, PR #18014)

  • align_test.go: StripHTMLHeadingMarker + HTMLAlignOptions preset.
  • testdata/html.python.golden.json: Python baseline as a plain JSON list of {"text", "doc_type_kwd"} records, regenerated by testdata/gen_html_golden.py.
  • testdata/html.sample.html: shared input sample.
  • testdata/gen_html_golden.py: drives the real Python RAGFlowHtmlParser.

No chunker/wiring change was needed: the HTML parser already emits OutputFormat:"json", and the chunker's table path preserves ck_type, so the structured table item flows through unchanged.

Test plan

  • bash build.sh --test ./internal/parser/parser/... → ok (full package, ~10s), including the four new tests.

Base / stacking

Based on infiniflow:main. The align_test.go framework it reuses (HTMLAlignOptions, LoadGolden list contract) was introduced by #18014, which is already merged into main, so this PR builds directly on main.

Follow-up

The branch name includes epub; EPUB parser alignment is a separate follow-up and is intentionally not part of this PR.

… golden)

Root cause: walkHTMLLeaf recursed into <table> children as plain leaf text
and concatenated every cell into one string ("NameAge\nAlice30…"), i.e. the
nested-table 塌方. The Python RAGFlowHtmlParser keeps each cell/tag on its
own line, so the two engines diverged on any table containing a nested table
or a table inside other block content.

Fix (surgical, preserves per-block granularity):
- htmlLeafText / walkHTMLLeaf now take a *[]map[string]any tableItems sink.
- walkHTMLLeaf gained a table-aware branch: a <table> is rendered to its
  inline markup, written as text, and appended as a structured
  doc_type_kwd:"table" item — mirroring the top-level (non-leaf) table path.
- renderTableHTML returns "" on render error instead of recursing through the
  leaf extractor (avoids a render loop).

Tests (TDD: RED before fix, GREEN after):
- TestHTMLParser_NestedTableProducesStructuredItems: the original 塌方 case.
- TestHTMLParser_NestedListItemsPreserved: nested <ul>/<ol> items stay
  separate, in document order; top-level list tagged ck_type:"list".
- TestHTMLParser_PrePreservesVerbatim: <pre>/<textarea> keep indentation and
  internal newlines verbatim (one leading newline dropped per spec).
- TestHTMLParser_AlignmentGolden: content-equivalence against the Python
  RAGFlowHtmlParser baseline via the shared align_test.go tool.

Align tooling (mirrors the merged markdown convention, PR infiniflow#18014):
- align_test.go: add StripHTMLHeadingMarker + HTMLAlignOptions preset.
- testdata/html.python.golden.json: Python baseline as a plain JSON list of
  {"text", "doc_type_kwd"} records, regenerated by testdata/gen_html_golden.py.
- testdata/html.sample.html: shared input sample.
- testdata/gen_html_golden.py: drives the real Python RAGFlowHtmlParser.

No chunker/wiring change was needed: the HTML parser already emits
OutputFormat:"json", and the chunker's table path preserves ck_type, so the
structured table item flows through unchanged.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3c0df302-1021-4f2b-be6a-027b1e99a9d4

📥 Commits

Reviewing files that changed from the base of the PR and between 2ada5c2 and 6280174.

📒 Files selected for processing (3)
  • internal/parser/parser/html_parser_align_test.go
  • internal/parser/parser/testdata/html.python.golden.json
  • internal/parser/parser/testdata/html.sample.html
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/parser/parser/testdata/html.python.golden.json
  • internal/parser/parser/html_parser_align_test.go

📝 Walkthrough

Walkthrough

HTML parsing now preserves rendered tables in text output and emits structured table items after traversal. New alignment helpers normalize HTML output. Tests and golden fixtures cover tables, nested content, verbatim text, ordering, and Python-parser alignment.

Changes

HTML parser alignment

Layer / File(s) Summary
HTML table preservation
internal/parser/parser/html_parser.go
HTML tables retain rendered markup in text items and produce deferred structured table items. Nested tables use the same handling, with child-text fallback when rendering fails.
HTML alignment options
internal/parser/parser/align_test.go
HTML alignment removes heading markers, strips tags, collapses whitespace, and compares text fields without delimiter splitting.
Parser behavior validation
internal/parser/parser/html_parser_align_test.go
Tests cover tables, nested tables, nested lists, verbatim content, output ordering, parser errors, and Python golden alignment.
Golden fixture generation
internal/parser/parser/testdata/*
A sample HTML document, generator script, and five-record JSON baseline support alignment testing.

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

Sequence Diagram(s)

sequenceDiagram
  participant RAGFlowHtmlParser
  participant walkHTMLLeaf
  participant renderTableHTML
  participant AlignmentTest
  RAGFlowHtmlParser->>walkHTMLLeaf: Traverse HTML leaves
  walkHTMLLeaf->>renderTableHTML: Render table markup
  renderTableHTML-->>walkHTMLLeaf: Return rendered HTML or empty output
  walkHTMLLeaf-->>RAGFlowHtmlParser: Emit inline text and deferred structured table item
  AlignmentTest->>RAGFlowHtmlParser: Parse sample HTML
  AlignmentTest->>AlignmentTest: Normalize text and compare golden output
Loading

Possibly related PRs

Suggested labels: 🐞 bug, 🧪 test

Suggested reviewers: yuzhichang, jinhai-cn, yingfeng

Poem

A rabbit checks each table row,
Keeps HTML in its proper flow.
Headings lose their hashes bright,
Golden records match just right.
Tests hop onward through the night.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the HTML parser alignment fix and the nested-table and golden-test changes.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, fix, tests, alignment tooling, and scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@xugangqiang xugangqiang added the ci Continue Integration label Aug 11, 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.

🧹 Nitpick comments (3)
internal/parser/parser/html_parser_align_test.go (1)

21-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove migration-history text from test comments.

Lines 21-23 and 92-100 describe the previous implementation. Keep the current required behavior and failure condition. Delete the historical path details.

As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history.”

Also applies to: 92-100

🤖 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/html_parser_align_test.go` around lines 21 - 23,
Remove migration-history wording from comments in the HTML parser alignment
test, including the comments near the existing table behavior and
failure-condition assertions. Retain only the current required behavior and the
condition that causes the test to fail, without describing the previous
implementation or its output.

Source: Coding guidelines

internal/parser/parser/testdata/gen_html_golden.py (1)

75-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging for golden-file generation.

Initialize a logger for this script. Log the generated item count and output path when generation succeeds. Keep command-line output only if it is also required for manual use.

As per coding guidelines, “**/*.py: Add logging for new flows.”

🤖 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/testdata/gen_html_golden.py` around lines 75 - 77,
Initialize and configure a logger in the golden-file generation script, then
replace the success print after json.dump with a log message containing the
generated item count and OUT path. Remove the command-line print unless it is
explicitly needed for manual use.

Source: Coding guidelines

internal/parser/parser/html_parser.go (1)

150-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Create one helper for structured table items.

Both paths construct the same table payload. Use one helper that appends the "text", "doc_type_kwd": "table", and "ck_type": "table" fields.

  • internal/parser/parser/html_parser.go#L150-L155: Replace the direct structured-table map construction with the helper.
  • internal/parser/parser/html_parser.go#L335-L339: Replace the direct structured-table map construction with the same helper.

As per coding guidelines, “In actively refactored Go ingestion, parser, and DeepDOC code, collapse duplicate paths rather than preserving transitional wrappers.”

🤖 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/html_parser.go` around lines 150 - 155, Create a
single helper in html_parser.go for appending structured table items with the
text, doc_type_kwd, and ck_type fields, then use it in both
internal/parser/parser/html_parser.go sites at lines 150-155 and 335-339.
Replace each direct map construction with the shared helper and do not retain
duplicate construction paths.

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.

Nitpick comments:
In `@internal/parser/parser/html_parser_align_test.go`:
- Around line 21-23: Remove migration-history wording from comments in the HTML
parser alignment test, including the comments near the existing table behavior
and failure-condition assertions. Retain only the current required behavior and
the condition that causes the test to fail, without describing the previous
implementation or its output.

In `@internal/parser/parser/html_parser.go`:
- Around line 150-155: Create a single helper in html_parser.go for appending
structured table items with the text, doc_type_kwd, and ck_type fields, then use
it in both internal/parser/parser/html_parser.go sites at lines 150-155 and
335-339. Replace each direct map construction with the shared helper and do not
retain duplicate construction paths.

In `@internal/parser/parser/testdata/gen_html_golden.py`:
- Around line 75-77: Initialize and configure a logger in the golden-file
generation script, then replace the success print after json.dump with a log
message containing the generated item count and OUT path. Remove the
command-line print unless it is explicitly needed for manual use.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ef857d44-aac2-4ad9-a48c-f14a38f72dec

📥 Commits

Reviewing files that changed from the base of the PR and between 64533e5 and 2ada5c2.

📒 Files selected for processing (6)
  • internal/parser/parser/align_test.go
  • internal/parser/parser/html_parser.go
  • internal/parser/parser/html_parser_align_test.go
  • internal/parser/parser/testdata/gen_html_golden.py
  • internal/parser/parser/testdata/html.python.golden.json
  • internal/parser/parser/testdata/html.sample.html

@codecov

codecov Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (d6f6b62) to head (6280174).
⚠️ Report is 20 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #18084   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

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

Replace the Chinese content in the HTML alignment fixtures with English so
the test data matches the other parser-alignment suites (markdown/text&code
are English after infiniflow#18022). The sample structure is unchanged, so every test
path (heading marker, paragraph, inline table, nested table, list, pre) is
still exercised. The golden is regenerated from the English sample.
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 11, 2026
Brings the HTML parser alignment work (previously infiniflow#18084) into this
consolidation PR so the whole Go↔Python parser-alignment series lands as
one unit, reusing the shared align_test.go framework.

Fix (surgical, preserves per-block granularity):
- walkHTMLLeaf is now table-aware: a <table> is rendered to its inline markup,
  written as text, AND appended as a structured doc_type_kwd:"table" item,
  mirroring the top-level table path. This fixes the nested-table collapse
  ("NameAge\nAlice30") where a table inside a container or another table was
  flattened into one string.
- renderTableHTML returns "" on render error instead of recursing through the
  leaf extractor.

Tests (TDD: RED before fix, GREEN after):
- TestHTMLParser_NestedTableProducesStructuredItems (the original collapse).
- TestHTMLParser_TableProducesStructuredItems (inline + structured table item).
- TestHTMLParser_NestedListItemsPreserved (items stay separate, in order).
- TestHTMLParser_PrePreservesVerbatim (<pre>/<textarea> verbatim indent/newlines).
- TestHTMLParser_AlignmentGolden (content-equivalence vs Python golden).

Align tooling (matches this PR's meta-driven convention):
- align_test.go: HTMLAlignOptions + StripHTMLHeadingMarker preset.
- testdata/html.python.golden.json: {meta, items} document with
  meta.accepted_divergences:["table"]; no committed generator script (same as
  the markdown golden here).
- testdata/html.sample.html: English shared sample.
- TestHTMLParser_AlignmentGolden uses LoadGoldenDoc + AcceptedDivergences +
  FilterOutDocTypes, so the "table" divergence is driven by meta, not hardcoded.

No chunker/wiring change: the HTML parser already emits OutputFormat:"json"
and the chunker's table path preserves ck_type.
@xugangqiang

Copy link
Copy Markdown
Contributor Author

Superseded: the HTML alignment work (nested-table fix + alignment tests + English {meta,items} golden) is now folded into #18022 (the parser-alignment consolidation PR), which already contains it on top of the text&code + markdown cleanup.

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

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant