Skip to content

Fix(parser): don't collapse markdown doc into one item when a table is present - #18014

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
xugangqiang:fix/markdown-parser-align
Aug 11, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
xugangqiang:fix/markdown-parser-align

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Go's MarkdownParser.ParseWithResult (internal/parser/parser/markdown_parser.go) short-circuited to a single item whenever the document contained any GFM/HTML table: renderMarkdownTablesInline returned changed=true and the whole document was rewritten into one {"text": rendered, "doc_type_kwd":"text"} item. Python's _markdown (rag/flow/parser/parser.py, separate_tables=False) only inlines the table as an HTML block but still emits one section per top-level block. The same input therefore produced 1 giant item (Go) vs N items (Python) — the most severe divergence in the Go↔Python Parser alignment (see PARSER_ALIGNMENT_HANDOFF.md §3.1).

This change aligns Go to Python's per-block shape.

Changes

  • Remove the whole-document short-circuit. Tables are rendered inline as HTML blocks via renderMarkdownTablesInlineText, then parsed normally; walkMarkdownBlocksWithImages emits one item per top-level block. A new ast.HTMLBlock case (ck_type "table") captures the re-parsed cell text.
  • Fix image association: resolve the image per-block from the AST (findBlockImage) instead of scanning the whole document. The old resolveMarkdownImage(txt, rawText) scan wrongly tagged every block as doc_type_kwd:"image" whenever any image was present, emptying the text item set. This latent bug was exposed by the golden test.
  • Capture CodeBlock/HTMLBlock leaf text in walkLeaf (content lives in Literal/Content, not child text nodes) — previously silently dropped.

Alignment decisions (confirmed; see PARSER_ALIGNMENT_HANDOFF.md §2.3 / §3.1)

  • ck_type is kept as a Go extra field (accepted shape difference; Python _markdown does not emit it).
  • Delimiter splitting is treated as an accepted difference, normalized at compare time rather than replicating Python's splitting inside Go.

Test plan

  • Added a reusable, format-agnostic alignment helper internal/parser/parser/align_test.go (NormalizeConcat / CompareAlignment / LoadGolden / FilterByDocType + composable Normalizers + a MarkdownAlignOptions preset). Designed to be shared across all format-alignment sessions (A–E).
  • TestMarkdownParser_TableNotCollapsed — regression guard: heading + table cells + trailing note present across multiple items; no raw | ... | leaked.
  • TestMarkdownParser_ParseWithResult_RendersTableInline — asserts len(res.JSON) >= 2.
  • TestMarkdownParser_AlignmentGolden — runs the real Go parser and compares concatenated, normalized text against a golden baseline (testdata/markdown.python.golden.json). The golden is a {meta, items} document whose meta block records how it was produced (generator: rag/flow/parser/parser.py:_markdown, sample, delimiter, accepted_divergences). No generator script is committed — to regenerate, call _markdown on the sample and dump {meta, items}; the baseline is reproducible from the metadata alone (an AI or human can recreate the thin wrapper on demand).

All tests pass: ok ragflow/internal/parser/parser. Unit-tier only (no external services).

Risk

Low. Table-free input is byte-identical to before (the inline renderer returns the input unchanged when no table is present). Image tagging is now strictly narrower (per-block). No production import surface changed.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 7, 2026
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

新增 Go/Python Parser 对齐交接文档和通用比较工具。Markdown Parser 现在保留独立表格块,按 AST block 关联图片,并保留代码与 HTML 内容。新增 Python golden 生成脚本、样本、基线和回归测试。

Changes

Parser alignment

Layer / File(s) Summary
对齐契约与决策
PARSER_ALIGNMENT_HANDOFF.md
记录 Go/Python Parser 的输出契约、类型映射、文件类型差异、验收流程、对齐决策和关键实现索引。
Parser 输出比较工具
internal/parser/parser/align_test.go
新增可组合的文本归一化、类型过滤、拼接比较、差异报告、golden 加载和 Markdown 对齐配置。
Markdown 表格、图片与叶节点解析
internal/parser/parser/markdown_parser.go
在 AST 解析前渲染表格,保留独立表格块;按 AST block 关联图片;支持 data URI 和 HTTP(S) 图片解析;保留代码和 HTML 内容。
Markdown fixtures 与回归验证
internal/parser/parser/markdown_parser_test.go, internal/parser/parser/testdata/*
新增表格、图片和非表格 HTML 测试,增加 Go/Python golden 对齐测试、生成脚本、Markdown 样本和预期输出。

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

Sequence Diagram(s)

sequenceDiagram
  participant MarkdownInput
  participant GoMarkdownParser
  participant PythonGoldenGenerator
  participant AlignmentTest
  MarkdownInput->>GoMarkdownParser: Parse Markdown
  GoMarkdownParser->>GoMarkdownParser: Render tables and walk AST
  GoMarkdownParser-->>AlignmentTest: Go parser items
  MarkdownInput->>PythonGoldenGenerator: Read sample
  PythonGoldenGenerator-->>AlignmentTest: Python golden items
  AlignmentTest->>AlignmentTest: Normalize and compare text
Loading

Possibly related PRs

Suggested labels: 🐞 bug, 🧪 test

Suggested reviewers: yuzhichang

Poem

我是小兔,守着对齐表,
Go 和 Python,文本排得好。
表格分成清晰块,
图片跟随 AST 跑。
Golden 灯亮,测试跳。

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the main parser change: preserving multiple Markdown items when a table is present.
Description check ✅ Passed The description includes a clear summary, background, detailed changes, alignment decisions, tests, and risk assessment.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/markdown-parser-align

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 7, 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: 7

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

352-365: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the legacy raw-text image resolver.

resolveMarkdownImage is only referenced by three tests in internal/parser/parser/markdown_parser_test.go, while production parsing uses findBlockImage + resolveImageURL. Move those tests into block-scoped image tests or split coverage across findBlockImage/resolveImageURL, then delete the unneeded helper.

🤖 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/markdown_parser.go` around lines 352 - 365, Remove the
legacy resolveMarkdownImage helper and its raw-text scanning logic. Update the
three tests in markdown_parser_test.go to cover block-scoped image resolution
through findBlockImage and URL resolution through resolveImageURL, preserving
their existing behavioral coverage without retaining references to
resolveMarkdownImage.

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/parser/parser/align_test.go`:
- Around line 70-73: Update StripHTMLTags to replace matched HTML tags with a
single space instead of an empty string, preserving separation between adjacent
text; rely on CollapseWhitespace to normalize the resulting whitespace.
- Around line 203-228: Update MarkdownAlignOptions so
WithDelimiterStrip(delimiter) runs before CollapseWhitespace(), making
CollapseWhitespace the final normalizer and reducing spaces introduced by
delimiter replacement to a single space. Preserve StripMarkdownSyntax and
StripHTMLTags ordering.

In `@internal/parser/parser/markdown_parser.go`:
- Around line 274-283: Update the *ast.HTMLBlock handling to assign ckType =
"table" and docTypeKwd = "text" only when the block contains an outer <table>
element; preserve the existing leafText extraction for table blocks and avoid
table metadata for markup such as <div>. Add a regression test covering a
non-table HTML block and verify it is not classified as a table chunk.

In `@internal/parser/parser/testdata/gen_markdown_golden.py`:
- Around line 77-79: Replace the completion print in the golden-generation flow
with the project’s established logging mechanism, preserving the generated item
count and output path in the log message. Update the code around the json.dump
call and final completion reporting without changing file generation behavior.
- Around line 72-75: Make the table-item contract consistent in the loop over
tables: either add the rendered HTML payload to each appended table item’s text
field, or, if omission is intentional, update the function docstring and nearby
comment to document that behavior. Remove stale documentation or comments rather
than preserving contradictory guidance.

In `@PARSER_ALIGNMENT_HANDOFF.md`:
- Line 69: Update the tables in PARSER_ALIGNMENT_HANDOFF.md, including the table
containing the OutputFormat header and the second table, by inserting one blank
line before and after each table to satisfy markdownlint MD058.
- Line 137: Remove the FIXME-preservation instruction from the relevant sections
of PARSER_ALIGNMENT_HANDOFF.md, including the note about
deepdoc/parser/html_parser.py:236 and rag_tokenizer.tokenize; do not replace it
with unverified behavior, and remove any duplicate occurrence rather than
instructing future readers to retain the investigation.

---

Nitpick comments:
In `@internal/parser/parser/markdown_parser.go`:
- Around line 352-365: Remove the legacy resolveMarkdownImage helper and its
raw-text scanning logic. Update the three tests in markdown_parser_test.go to
cover block-scoped image resolution through findBlockImage and URL resolution
through resolveImageURL, preserving their existing behavioral coverage without
retaining references to resolveMarkdownImage.
🪄 Autofix

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: 256cec2e-8f69-4161-bf72-15a66ae3271d

📥 Commits

Reviewing files that changed from the base of the PR and between 8e37f55 and 1de8d21.

📒 Files selected for processing (7)
  • PARSER_ALIGNMENT_HANDOFF.md
  • internal/parser/parser/align_test.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/testdata/gen_markdown_golden.py
  • internal/parser/parser/testdata/markdown.python.golden.json
  • internal/parser/parser/testdata/markdown.sample.md

Comment thread internal/parser/parser/align_test.go Resolved
Comment thread internal/parser/parser/align_test.go Resolved
Comment on lines +77 to +79
with open(OUT, "w", encoding="utf-8") as f:
json.dump(items, f, ensure_ascii=False, indent=2)
print("wrote %d items to %s" % (len(items), OUT))

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

Add logging for golden generation.

This new flow reports completion with print only. Use the project logging mechanism to record the generated item count and output path.

As per coding guidelines, “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_markdown_golden.py` around lines 77 - 79,
Replace the completion print in the golden-generation flow with the project’s
established logging mechanism, preserving the generated item count and output
path in the log message. Update the code around the json.dump call and final
completion reporting without changing file generation behavior.

Source: Coding guidelines

Comment thread PARSER_ALIGNMENT_HANDOFF.md Outdated
- 下游 dispatch(`internal/ingestion/component/parser_dispatch.go`):`OutputFormat=="json"` → 每个 item 一个 page(`jsonItemsToPages`);`markdown/text/html` → 整段作 1 个 page;未知 → 按 `\f` 切页。所以「item 数」对比**只对 json 输出格式有意义**。

### item 数量(因格式与输入而异,无固定值)
| 格式 | OutputFormat | item 数量 |

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

Add blank lines around both tables.

Add a blank line before and after each table. This resolves markdownlint MD058.

Also applies to: 116-116

🧰 Tools
🪛 markdownlint-cli2 (0.23.2)

[warning] 69-69: Tables should be surrounded by blank lines

(MD058, blanks-around-tables)

🤖 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 `@PARSER_ALIGNMENT_HANDOFF.md` at line 69, Update the tables in
PARSER_ALIGNMENT_HANDOFF.md, including the table containing the OutputFormat
header and the second table, by inserting one blank line before and after each
table to satisfy markdownlint MD058.

Source: Linters/SAST tools

Comment thread PARSER_ALIGNMENT_HANDOFF.md Outdated
1. **切块所有权:保留现状**。不做 pipeline 重构——Go Parser 仍不切块、Python flow Parser 仍内嵌 token 切块(html/epub 等)。不在「把切块挪到 Chunker 统一」上做改动。
2. **对比方法:采用拼接对比(stitch-compare)**。以「拼接后内容等价」作为一级闸门(见 §5),item 数 / 字段比对作为二级。验收重点是「两端 Parser 提取出相同内容」,而非 item 边界一致。
3. **块抽取粒度基准:以 Python 为准**。逐块边界(段落 / 块 / 表 / 列表续行等)的对齐目标是让 **Go 收敛到 Python 的块边界**;Python 现状视为事实基准。
4. **FIXME 保留不动**。`deepdoc/parser/html_parser.py:236` 处 `rag_tokenizer.tokenize` 身份未确认,暂不调查。

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

Remove the retained FIXME guidance.

Do not instruct future readers to retain the unresolved rag_tokenizer.tokenize investigation. Replace it with verified current behavior, or remove the note.

As per coding guidelines, “Remove dead tests, commented-out code, stale documentation, and ‘move later’ notes instead of preserving them.”

Also applies to: 157-157

🤖 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 `@PARSER_ALIGNMENT_HANDOFF.md` at line 137, Remove the FIXME-preservation
instruction from the relevant sections of PARSER_ALIGNMENT_HANDOFF.md, including
the note about deepdoc/parser/html_parser.py:236 and rag_tokenizer.tokenize; do
not replace it with unverified behavior, and remove any duplicate occurrence
rather than instructing future readers to retain the investigation.

Source: Coding guidelines

@codecov

codecov Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #18014   +/-   ##
=======================================
  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.

@xugangqiang
xugangqiang force-pushed the fix/markdown-parser-align branch from 1de8d21 to 3c9e171 Compare August 7, 2026 16:31
@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 Aug 7, 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 (1)
internal/parser/parser/markdown_parser.go (1)

106-106: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Propagate the parse context through image resolution.

ParseWithResult receives ctx, but walkMarkdownBlocksWithImages, resolveImageURL, fetchImageAsBase64, and resolveAndValidateHost do not accept it. Remote image fetches and DNS lookups create contexts from context.Background(), so a canceled parse can continue DNS resolution and an HTTP fetch independently. Pass ctx through the image resolution path and derive request timing from it.

🤖 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/markdown_parser.go` at line 106, Update
ParseWithResult’s image-resolution path to pass its ctx through
walkMarkdownBlocksWithImages, resolveImageURL, fetchImageAsBase64, and
resolveAndValidateHost. Replace context.Background-based DNS and HTTP contexts
with contexts derived from the propagated parse context, preserving the existing
request timeout while allowing cancellation to stop image resolution.
🤖 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/markdown_parser.go`:
- Line 106: Update ParseWithResult’s image-resolution path to pass its ctx
through walkMarkdownBlocksWithImages, resolveImageURL, fetchImageAsBase64, and
resolveAndValidateHost. Replace context.Background-based DNS and HTTP contexts
with contexts derived from the propagated parse context, preserving the existing
request timeout while allowing cancellation to stop image resolution.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d00f50d-2bfb-465e-91b5-774c136216a7

📥 Commits

Reviewing files that changed from the base of the PR and between 1de8d21 and 3c9e171.

📒 Files selected for processing (6)
  • PARSER_ALIGNMENT_HANDOFF.md
  • internal/parser/parser/align_test.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/testdata/gen_markdown_golden.py
  • internal/parser/parser/testdata/markdown.python.golden.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/parser/parser/testdata/markdown.python.golden.json
  • internal/parser/parser/align_test.go

@xugangqiang
xugangqiang force-pushed the fix/markdown-parser-align branch from 3c9e171 to a00131a Compare August 7, 2026 16:45
…table shape fix)

Go's MarkdownParser.ParseWithResult short-circuited to a single item whenever any
GFM/HTML table existed, while Python's _markdown (separate_tables=False) still
emits one section per block plus a dedicated doc_type_kwd:"table" item per table.
Align Go to Python's per-block shape (Plan Y).

- Render tables inline as <table> HTML blocks wrapped in blank lines (MD058) so
  gomarkdown keeps each table as a single *ast.HTMLBlock (raw <table> markup)
  instead of re-parsing it into scattered cell text.
- For each table HTML block, emit two items (mirrors Python _markdown):
  1. an inlined <table> copy as a doc_type_kwd:"text" item in original order;
  2. a separate doc_type_kwd:"table", ck_type:"table" item with the raw table text.
- Only real tables (<table prefix via isTableHTML) get ck_type:"table"; non-table
  HTML blocks (<div>/<style> etc.) are emitted as plain text with no ck_type.
- Fix image association: resolve image per-block from the AST (findBlockImage)
  instead of scanning the whole document, which wrongly tagged every block as an
  image and emptied the text set.
- Capture CodeBlock/HTMLBlock leaf text in walkLeaf (was silently dropped).
- Remove dead resolveMarkdownImage and the unused mdImagePattern/regexp import.

ck_type is kept as a Go extra field; the chunker actually consumes doc_type_kwd, so
table handling relies on doc_type_kwd:"table" (verified against chunker/common.go
and chunker/token.go). Delimiter splitting is an accepted diff, normalized in the
shared alignment tool.

Add a reusable, format-agnostic alignment helper (align_test.go) with a
MarkdownAlignOptions preset and a golden-file test (TestMarkdownParser_AlignmentGolden)
driven by a golden produced from the real Python flow parser
(testdata/markdown.python.golden.json, regenerated via testdata/gen_markdown_golden.py).
@xugangqiang
xugangqiang force-pushed the fix/markdown-parser-align branch from a00131a to 1c364eb Compare August 7, 2026 16:59
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Aug 7, 2026
@xugangqiang xugangqiang changed the title fix(parser): don't collapse markdown doc into one item when a table is present Fix(parser): don't collapse markdown doc into one item when a table is present Aug 10, 2026
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Aug 11, 2026
@yuzhichang yuzhichang added ci Continue Integration and removed ci Continue Integration labels Aug 11, 2026
@yuzhichang
yuzhichang merged commit d6f6b62 into infiniflow:main Aug 11, 2026
16 checks passed
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 11, 2026
… 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.
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 11, 2026
…es from meta

Follow-up to the merged infiniflow#18014.

- Remove the committed Python golden generator script
  (testdata/gen_markdown_golden.py). The golden baseline
  (markdown.python.golden.json) is now a {meta, items} document whose meta
  block records how it was produced (generator, sample, delimiter,
  accepted_divergences). It stays reproducible without the script — an AI or
  human can recreate the thin wrapper on demand from the metadata.
- Make TestMarkdownParser_AlignmentGolden meta-driven: the doc types to ignore
  are read from meta.accepted_divergences (LoadGolden now returns *GoldenDoc;
  new AcceptedDivergences / FilterOutDocTypes helpers) instead of a hardcoded
  text-only filter. The golden JSON is the single source of truth for what
  counts as an accepted divergence.
xugangqiang added a commit that referenced this pull request Aug 11, 2026
Extract the alignment scaffolding so the format-specific PRs (text&code,
markdown golden, HTML) don't conflict on align_test.go.

Adds (test-only, no production behavior change):
- GoldenDoc{Meta,Items} and parseGolden: tolerant of both the legacy bare
  array and the new {meta, items} golden format.
- LoadGoldenDoc, AcceptedDivergences(meta), FilterOutDocTypes(items, drop):
  meta-driven divergence handling, no hardcoded divergence lists.
- TextCodeAlignOptions / DefaultTextCodeDelimiter, HTMLAlignOptions /
  StripHTMLHeadingMarker: normalizer presets reused by the alignment tests.
- LoadGolden now tolerates the {meta, items} format.

Stacks on #18014 (the align_test.go framework is already in main).
xugangqiang added a commit that referenced this pull request Aug 11, 2026
Make Go TextParser match Python deepdoc TxtParser._code:
- Split on the flow default delimiter set "\n!?;。;!?" (was blank-line only).
- keep_delimiters=True: each trailing delimiter is retained on its segment.
- Normalize CRLF/CR -> LF like Python.
- Do NOT perform the OVER_CAP token merge; chunking stays with the downstream
  Chunker (PARSER_ALIGNMENT_HANDOFF.md §2.3).
- The 8192-byte per-item cap is dropped: the parser is a pure delimiter
  splitter, matching Python's parser_txt (no size slicing). Sizing is delegated
  to the Chunker + embedding truncation per contract #17799.

Tests:
- TestTextParser_ParseWithResult_DefaultDelimiter pins the new split rule
  (single-newline + sentence-delimiter splitting with delimiter retained).
- TestTextParser_ParseWithResult_NoSizeCap pins no per-item byte slicing.
- TestTextParser_AlignmentGolden verifies content-equivalence vs the Python
  golden on a shared sample.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/text_parser.go
  internal/parser/parser/parse_with_result_test.go
  internal/parser/parser/testdata/textcode.sample.txt (new)
  internal/parser/parser/testdata/textcode.python.golden.json (new)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…ript

Move the markdown golden baseline to the {meta, items} format and drive
accepted divergences from meta.accepted_divergences instead of hardcoded lists.
No production parser code changes.

- markdown.python.golden.json is now {meta, items}; meta records how it was
  produced so it is reproducible without a committed script.
- TestMarkdownParser_AlignmentGolden uses LoadGoldenDoc / AcceptedDivergences /
  FilterOutDocTypes (from the foundation helpers PR).
- Deletes testdata/gen_markdown_golden.py.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/markdown_parser_test.go
  internal/parser/parser/testdata/markdown.python.golden.json
  internal/parser/parser/testdata/markdown.sample.md
  internal/parser/parser/testdata/gen_markdown_golden.py (deleted)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…d item)

Stop flattening <table> into a single text blob. A <table> now emits:
1. an inlined doc_type_kwd:"text" item keeping the <table>...</table> markup
   (row/column structure survives for embedding/retrieval/LLM rendering), and
2. a structured doc_type_kwd:"table" / ck_type:"table" item appended after
   the walk, consumed by the downstream chunker.

Covers both top-level tables (walkHTMLBlocks) and tables nested in
div/section/article (via walkHTMLLeaf). Mirrors markdown_parser.go table
handling and Python's RAGFlowHtmlParser.

Tests:
- TestHTMLParser_TableProducesStructuredItems
- TestHTMLParser_NestedTableProducesStructuredItems
- TestHTMLParser_NestedListItemsPreserved
- TestHTMLParser_PrePreservesVerbatim
- TestHTMLParser_AlignmentGolden (compares vs html.python.golden.json, ignores
  "table" via meta.accepted_divergences)

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/html_parser.go
  internal/parser/parser/html_parser_align_test.go (new)
  internal/parser/parser/testdata/html.python.golden.json (new)
  internal/parser/parser/testdata/html.sample.html (new)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
Make Go TextParser match Python deepdoc TxtParser._code:
- Split on the flow default delimiter set "\n!?;。;!?" (was blank-line only).
- keep_delimiters=True: each trailing delimiter is retained on its segment.
- Normalize CRLF/CR -> LF like Python.
- Do NOT perform the OVER_CAP token merge; chunking stays with the downstream
  Chunker (PARSER_ALIGNMENT_HANDOFF.md §2.3).
- The 8192-byte per-item cap is dropped: the parser is a pure delimiter
  splitter, matching Python's parser_txt (no size slicing). Sizing is delegated
  to the Chunker + embedding truncation per contract #17799.

Tests:
- TestTextParser_ParseWithResult_DefaultDelimiter pins the new split rule
  (single-newline + sentence-delimiter splitting with delimiter retained).
- TestTextParser_ParseWithResult_NoSizeCap pins no per-item byte slicing.
- TestTextParser_AlignmentGolden verifies content-equivalence vs the Python
  golden on a shared sample.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/text_parser.go
  internal/parser/parser/parse_with_result_test.go
  internal/parser/parser/testdata/textcode.sample.txt (new)
  internal/parser/parser/testdata/textcode.python.golden.json (new)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…ript

Move the markdown golden baseline to the {meta, items} format and drive
accepted divergences from meta.accepted_divergences instead of hardcoded lists.
No production parser code changes.

- markdown.python.golden.json is now {meta, items}; meta records how it was
  produced so it is reproducible without a committed script.
- TestMarkdownParser_AlignmentGolden uses LoadGoldenDoc / AcceptedDivergences /
  FilterOutDocTypes (from the foundation helpers PR).
- Deletes testdata/gen_markdown_golden.py.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/markdown_parser_test.go
  internal/parser/parser/testdata/markdown.python.golden.json
  internal/parser/parser/testdata/markdown.sample.md
  internal/parser/parser/testdata/gen_markdown_golden.py (deleted)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…d item)

Stop flattening <table> into a single text blob. A <table> now emits:
1. an inlined doc_type_kwd:"text" item keeping the <table>...</table> markup
   (row/column structure survives for embedding/retrieval/LLM rendering), and
2. a structured doc_type_kwd:"table" / ck_type:"table" item appended after
   the walk, consumed by the downstream chunker.

Covers both top-level tables (walkHTMLBlocks) and tables nested in
div/section/article (via walkHTMLLeaf). Mirrors markdown_parser.go table
handling and Python's RAGFlowHtmlParser.

Tests:
- TestHTMLParser_TableProducesStructuredItems
- TestHTMLParser_NestedTableProducesStructuredItems
- TestHTMLParser_NestedListItemsPreserved
- TestHTMLParser_PrePreservesVerbatim
- TestHTMLParser_AlignmentGolden (compares vs html.python.golden.json, ignores
  "table" via meta.accepted_divergences)

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/html_parser.go
  internal/parser/parser/html_parser_align_test.go (new)
  internal/parser/parser/testdata/html.python.golden.json (new)
  internal/parser/parser/testdata/html.sample.html (new)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
Extract the alignment scaffolding so the format-specific PRs (text&code,
markdown golden, HTML) don't conflict on align_test.go.

Adds (test-only, no production behavior change):
- GoldenDoc{Meta,Items} and parseGolden: tolerant of both the legacy bare
  array and the new {meta, items} golden format.
- LoadGoldenDoc, AcceptedDivergences(meta), FilterOutDocTypes(items, drop):
  meta-driven divergence handling, no hardcoded divergence lists.
- TextCodeAlignOptions / DefaultTextCodeDelimiter, HTMLAlignOptions /
  StripHTMLHeadingMarker: normalizer presets reused by the alignment tests.
- LoadGolden now tolerates the {meta, items} format.

Stacks on #18014 (the align_test.go framework is already in main).
xugangqiang added a commit that referenced this pull request Aug 11, 2026
Make Go TextParser match Python deepdoc TxtParser._code:
- Split on the flow default delimiter set "\n!?;。;!?" (was blank-line only).
- keep_delimiters=True: each trailing delimiter is retained on its segment.
- Normalize CRLF/CR -> LF like Python.
- Do NOT perform the OVER_CAP token merge; chunking stays with the downstream
  Chunker (PARSER_ALIGNMENT_HANDOFF.md §2.3).
- The 8192-byte per-item cap is dropped: the parser is a pure delimiter
  splitter, matching Python's parser_txt (no size slicing). Sizing is delegated
  to the Chunker + embedding truncation per contract #17799.

Tests:
- TestTextParser_ParseWithResult_DefaultDelimiter pins the new split rule
  (single-newline + sentence-delimiter splitting with delimiter retained).
- TestTextParser_ParseWithResult_NoSizeCap pins no per-item byte slicing.
- TestTextParser_AlignmentGolden verifies content-equivalence vs the Python
  golden on a shared sample.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/text_parser.go
  internal/parser/parser/parse_with_result_test.go
  internal/parser/parser/testdata/textcode.sample.txt (new)
  internal/parser/parser/testdata/textcode.python.golden.json (new)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…ript

Move the markdown golden baseline to the {meta, items} format and drive
accepted divergences from meta.accepted_divergences instead of hardcoded lists.
No production parser code changes.

- markdown.python.golden.json is now {meta, items}; meta records how it was
  produced so it is reproducible without a committed script.
- TestMarkdownParser_AlignmentGolden uses LoadGoldenDoc / AcceptedDivergences /
  FilterOutDocTypes (from the foundation helpers PR).
- Deletes testdata/gen_markdown_golden.py.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/markdown_parser_test.go
  internal/parser/parser/testdata/markdown.python.golden.json
  internal/parser/parser/testdata/markdown.sample.md
  internal/parser/parser/testdata/gen_markdown_golden.py (deleted)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…d item)

Stop flattening <table> into a single text blob. A <table> now emits:
1. an inlined doc_type_kwd:"text" item keeping the <table>...</table> markup
   (row/column structure survives for embedding/retrieval/LLM rendering), and
2. a structured doc_type_kwd:"table" / ck_type:"table" item appended after
   the walk, consumed by the downstream chunker.

Covers both top-level tables (walkHTMLBlocks) and tables nested in
div/section/article (via walkHTMLLeaf). Mirrors markdown_parser.go table
handling and Python's RAGFlowHtmlParser.

Tests:
- TestHTMLParser_TableProducesStructuredItems
- TestHTMLParser_NestedTableProducesStructuredItems
- TestHTMLParser_NestedListItemsPreserved
- TestHTMLParser_PrePreservesVerbatim
- TestHTMLParser_AlignmentGolden (compares vs html.python.golden.json, ignores
  "table" via meta.accepted_divergences)

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/html_parser.go
  internal/parser/parser/html_parser_align_test.go (new)
  internal/parser/parser/testdata/html.python.golden.json (new)
  internal/parser/parser/testdata/html.sample.html (new)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…ript

Move the markdown golden baseline to the {meta, items} format and drive
accepted divergences from meta.accepted_divergences instead of hardcoded lists.
No production parser code changes.

- markdown.python.golden.json is now {meta, items}; meta records how it was
  produced so it is reproducible without a committed script.
- TestMarkdownParser_AlignmentGolden uses LoadGoldenDoc / AcceptedDivergences /
  FilterOutDocTypes (from the foundation helpers PR).
- Deletes testdata/gen_markdown_golden.py.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/markdown_parser_test.go
  internal/parser/parser/testdata/markdown.python.golden.json
  internal/parser/parser/testdata/markdown.sample.md
  internal/parser/parser/testdata/gen_markdown_golden.py (deleted)
xugangqiang added a commit that referenced this pull request Aug 11, 2026
…ript

Move the markdown golden baseline to the {meta, items} format and drive
accepted divergences from meta.accepted_divergences instead of hardcoded lists.
No production parser code changes.

- markdown.python.golden.json is now {meta, items}; meta records how it was
  produced so it is reproducible without a committed script.
- TestMarkdownParser_AlignmentGolden uses LoadGoldenDoc / AcceptedDivergences /
  FilterOutDocTypes (from the foundation helpers PR).
- Deletes testdata/gen_markdown_golden.py.

Depends on #18014 and the foundation helpers PR (align_test.go).

Files:
  internal/parser/parser/markdown_parser_test.go
  internal/parser/parser/testdata/markdown.python.golden.json
  internal/parser/parser/testdata/markdown.sample.md
  internal/parser/parser/testdata/gen_markdown_golden.py (deleted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants