Skip to content

refactor(parser): text&code align + markdown golden meta-driven cleanup - #18022

Closed
xugangqiang wants to merge 6 commits into
infiniflow:mainfrom
xugangqiang:fix/text-code-parser-align
Closed

xugangqiang wants to merge 6 commits into
infiniflow:mainfrom
xugangqiang:fix/text-code-parser-align

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Consolidation

This PR folds in two sibling alignment efforts (each closed as superseded):

Shared align_test.go keeps a backward-compatible LoadGolden and adds LoadGoldenDoc / AcceptedDivergences / FilterOutDocTypes, plus the MarkdownAlignOptions / TextCodeAlignOptions / HTMLAlignOptions presets.


Summary

text&code — Aligns the Go TextParser (the text&code family: .txt/.py/.js/.go/...) with the Python flow _code path (deepdoc.parser.txt_parser.TxtParser).

  • Go previously split only on blank lines (\n\n); now it splits on the flow parser's default delimiter set \n!?;。;!?, mirroring Python's re.split(r"(%s)" % pattern, txt).
  • keep_delimiters=True (the actual _code call) keeps each trailing delimiter attached, so sentence-ending punctuation survives the split.
  • CRLF/CR normalized to LF like Python.
  • The OVER_CAP token merge is intentionally not performed here — chunking ownership stays with the downstream Chunker (PARSER_ALIGNMENT_HANDOFF.md §2.3, decision 1). Item counts therefore differ from Python's merged chunks and are reconciled by the stitch-compare alignment test.
  • The 8192-byte per-item cap is retained: the downstream chunker keeps any single oversized item whole and the embedding step truncates it, so without the cap a minified / no-newline file would collapse to one mega-chunk and lose most of its content.

html — Aligns the Go HTMLParser with the Python RAGFlowHtmlParser. walkHTMLLeaf is now table-aware: a <table> (including one nested inside a container or another table) is rendered to its inline markup, emitted as text, AND appended as a structured doc_type_kwd:"table" item — fixing the nested-table collapse ("NameAge\nAlice30") where a table was flattened into one string. <pre>/<textarea> stay verbatim. No chunker/wiring change.

Test plan

  • Reuses the shared align_test.go framework with MarkdownAlignOptions / TextCodeAlignOptions / HTMLAlignOptions presets.
  • Goldens are {meta, items} documents; regeneration metadata is embedded and no generator script is committed. Tests are meta-driven via LoadGoldenDoc / AcceptedDivergences / FilterOutDocTypes (no hardcoded divergence list).
  • TestTextParser_AlignmentGolden / TestHTMLParser_AlignmentGolden verify Go output is content-equivalent to the Python goldens on shared samples.
  • TestTextParser_ParseWithResult_DefaultDelimiter pins the new split rule (single-newline + sentence-delimiter splitting with the delimiter retained).
  • TestHTMLParser_NestedTableProducesStructuredItems / TestHTMLParser_TableProducesStructuredItems (inline + structured table item) / TestHTMLParser_NestedListItemsPreserved / TestHTMLParser_PrePreservesVerbatim pin the HTML fix.

Dependency

Stacked on #18014 (fix/markdown-parser-align) to reuse the align_test.go framework. This branch is currently based on the #18014 tip, so the diff includes #18014 until it merges; after that, rebase onto main and retarget.

🤖 Generated with CodeBuddy Code

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Aug 9, 2026
@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

TextParser now uses delimiter-based, uncapped segmentation. Golden documents support metadata and legacy arrays. Tests and fixtures validate multilingual text, code parsing, and Go/Python alignment.

Changes

Text parser alignment

Layer / File(s) Summary
Delimiter-based text segmentation
internal/parser/parser/text_parser.go, internal/parser/parser/parse_with_result_test.go, internal/parser/parser/testdata/textcode.sample.txt
TextParser normalizes newlines, splits on configured delimiters, preserves trailing delimiters, skips empty sections, and keeps undelimited items intact without a byte cap.
Golden-document alignment contracts
internal/parser/parser/align_test.go, internal/parser/parser/markdown_parser_test.go, internal/parser/parser/testdata/markdown.python.golden.json, internal/parser/parser/testdata/markdown.sample.md
Golden loading supports metadata-bearing objects and legacy arrays. Metadata now controls accepted divergences and document-type filtering.
Text/code alignment fixtures and validation
internal/parser/parser/parse_with_result_test.go, internal/parser/parser/testdata/textcode.python.golden.json
Fixtures and tests compare normalized Go and Python parser output for multilingual text and Python code.

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

Possibly related issues

Possibly related PRs

Suggested labels: 🐞 bug

Suggested reviewers: yuzhichang

Poem

I split each sentence, neat and bright,

Kept long code lines whole in flight.
Golden words now guide the way,
Metadata helps tests compare.
Hop, hop—parsing works today!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
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 identifies the text-and-code alignment and Markdown golden cleanup, which are real changes in the pull request.
Description check ✅ Passed The description provides a clear summary, background, test plan, dependency context, and details for the main parser and golden-data changes.

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

Caution

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

⚠️ Outside diff range comments (1)
internal/parser/parser/text_parser.go (1)

252-267: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Split the oversized remainder until it meets maxItemBytes.

This branch performs only one split. A 16,385-byte undelimited input produces an 8,192-byte item and an 8,193-byte tail. The tail violates the cap and reaches the downstream Chunker unchanged.

Loop over the remainder until every emitted item meets the cap. For hard byte cuts, move the cut to a UTF-8 rune boundary. Add a test with input larger than 2 * 8192.

🤖 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_parser.go` around lines 252 - 267, The
oversized-text handling around the maxItemBytes branch must repeatedly split the
remainder until every emitted text item is at or below the cap. Update this
logic to loop over the remaining text, prefer the nearest newline within
maxItemBytes, and for hard cuts adjust the boundary to a valid UTF-8 rune
boundary before emitting and trimming the remainder; add coverage for input
larger than 2 * 8192.
🧹 Nitpick comments (3)
internal/parser/parser/markdown_parser.go (1)

162-165: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove handoff-history references from code comments.

Keep comments that describe current parser behavior and test behavior. Remove references to PARSER_ALIGNMENT_HANDOFF.md and plan labels.

  • internal/parser/parser/markdown_parser.go#L162-L165: describe only the blank-line requirement for standalone HTML blocks.
  • internal/parser/parser/markdown_parser_test.go#L526-L536: describe only the current alignment contract and supported golden regeneration process.

As per coding guidelines, “keep package and doc comments 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/parser/parser/markdown_parser.go` around lines 162 - 165, Remove the
handoff-document and plan-label references from the comment near the markdown
parser’s inline table handling in
internal/parser/parser/markdown_parser.go#L162-L165, retaining only the
requirement that standalone HTML blocks are surrounded by blank lines. Update
the related comment in internal/parser/parser/markdown_parser_test.go#L526-L536
to describe only the current alignment contract and supported golden
regeneration process; no runtime code changes are needed.

Source: Coding guidelines

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

42-80: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging to both golden-generator flows.

Both generators only write a final print message. Add module logging for the input fixture, output fixture, and generated item count.

  • internal/parser/parser/testdata/gen_markdown_golden.py#L42-L80: log parser generation and output details.
  • internal/parser/parser/testdata/gen_textcode_golden.py#L41-L54: log parser generation and output details.

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 42 - 80,
Add module logging to main() in
internal/parser/parser/testdata/gen_markdown_golden.py (lines 42-80) and
internal/parser/parser/testdata/gen_textcode_golden.py (lines 41-54): log the
input fixture, output fixture, and generated item count for each
parser-generation flow, while retaining the existing generation behavior and
final output notification.

Source: Coding guidelines

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

31-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the migration-history reference.

“sessions A–E” does not describe Normalizer behavior. Keep this comment limited to the current reusable alignment behavior.

As per coding guidelines, keep package and doc comments 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/parser/parser/align_test.go` around lines 31 - 33, Update the
comment describing Normalizer to remove the “sessions A–E” migration-history
reference, while retaining only its current behavior: transforming one item’s
text and being composed per parser type for shared comparisons.

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/markdown_parser.go`:
- Around line 101-103: Update the fence-detection logic used by
renderMarkdownTablesInlineText so a prospective closing fence is accepted only
when its trailing content contains spaces or tabs; do not treat text such as
“not-a-close” after the delimiter as closing the block. Add a regression test
covering that input and verifying fenced content remains unchanged.

---

Outside diff comments:
In `@internal/parser/parser/text_parser.go`:
- Around line 252-267: The oversized-text handling around the maxItemBytes
branch must repeatedly split the remainder until every emitted text item is at
or below the cap. Update this logic to loop over the remaining text, prefer the
nearest newline within maxItemBytes, and for hard cuts adjust the boundary to a
valid UTF-8 rune boundary before emitting and trimming the remainder; add
coverage for input larger than 2 * 8192.

---

Nitpick comments:
In `@internal/parser/parser/align_test.go`:
- Around line 31-33: Update the comment describing Normalizer to remove the
“sessions A–E” migration-history reference, while retaining only its current
behavior: transforming one item’s text and being composed per parser type for
shared comparisons.

In `@internal/parser/parser/markdown_parser.go`:
- Around line 162-165: Remove the handoff-document and plan-label references
from the comment near the markdown parser’s inline table handling in
internal/parser/parser/markdown_parser.go#L162-L165, retaining only the
requirement that standalone HTML blocks are surrounded by blank lines. Update
the related comment in internal/parser/parser/markdown_parser_test.go#L526-L536
to describe only the current alignment contract and supported golden
regeneration process; no runtime code changes are needed.

In `@internal/parser/parser/testdata/gen_markdown_golden.py`:
- Around line 42-80: Add module logging to main() in
internal/parser/parser/testdata/gen_markdown_golden.py (lines 42-80) and
internal/parser/parser/testdata/gen_textcode_golden.py (lines 41-54): log the
input fixture, output fixture, and generated item count for each
parser-generation flow, while retaining the existing generation behavior and
final output notification.
🪄 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: fb4a0bfc-d0fc-4fb9-a1c8-ab963df2067a

📥 Commits

Reviewing files that changed from the base of the PR and between 99110c2 and 78e8fb1.

📒 Files selected for processing (11)
  • internal/parser/parser/align_test.go
  • internal/parser/parser/markdown_parser.go
  • internal/parser/parser/markdown_parser_test.go
  • internal/parser/parser/parse_with_result_test.go
  • internal/parser/parser/testdata/gen_markdown_golden.py
  • internal/parser/parser/testdata/gen_textcode_golden.py
  • internal/parser/parser/testdata/markdown.python.golden.json
  • internal/parser/parser/testdata/markdown.sample.md
  • internal/parser/parser/testdata/textcode.python.golden.json
  • internal/parser/parser/testdata/textcode.sample.txt
  • internal/parser/parser/text_parser.go

Comment on lines +101 to +103
rendered := renderMarkdownTablesInlineText(rawText)

doc := markdownNew().Parse(data)
doc := markdownNew().Parse([]byte(rendered))

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

Preserve valid fenced-code content.

Line 101 enables table rewriting for every Markdown document. markdownFenceMarker treats a matching fence prefix with trailing non-whitespace text as a closing fence. A line such as `````not-a-close`` inside a fenced block then ends inFence, and later pipe rows can be rewritten into `

` HTML.

Require a prospective closing fence to contain only spaces or tabs after its delimiter. Add a regression test with that input.

🤖 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 101 - 103, Update the
fence-detection logic used by renderMarkdownTablesInlineText so a prospective
closing fence is accepted only when its trailing content contains spaces or
tabs; do not treat text such as “not-a-close” after the delimiter as closing the
block. Add a regression test covering that input and verifying fenced content
remains unchanged.

@xugangqiang

Copy link
Copy Markdown
Contributor Author

Added commit `32b73d2dd` to this PR: dropped the 8192-byte per-item cap from the text&code Parser.

The cap was a Go-only defensive slice with no equivalent in the Python _code path (deepdoc TxtParser.parser_txt does no size slicing). Keeping it made Go diverge from Python for continuous runs longer than the cap (minified / no-newline files). After removal, TextParser is a pure delimiter splitter matching Python's parser_txt exactly; sizing is delegated to the Chunker + embedding truncation (PARSER_ALIGNMENT_HANDOFF.md §2.3, decision 1). TestTextParser_ParseWithResult_LongParagraphSlicing was replaced by TestTextParser_ParseWithResult_NoSizeCap.

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

Caution

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

⚠️ Outside diff range comments (1)
internal/parser/parser/text_parser.go (1)

239-239: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve the captured delimiter in emitted text.

Line 239 removes a trailing newline after Lines 231-233 append it to sec. For input such as "one\ntwo\n", emitted items become "one" and "two" instead of retaining "\n".

Use strings.TrimSpace(para) only to detect an empty item. Emit the original para when it is non-empty.

Proposed fix
-		text := strings.TrimSpace(para)
-		if text == "" {
+		if strings.TrimSpace(para) == "" {
 			continue
 		}
+		text := para
🤖 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_parser.go` at line 239, Update the parsing logic
around the text variable in the relevant parser function: use
strings.TrimSpace(para) only for the empty-item check, and emit the original
para unchanged when it contains content so trailing delimiters such as "\n" are
preserved.
🤖 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.

Outside diff comments:
In `@internal/parser/parser/text_parser.go`:
- Line 239: Update the parsing logic around the text variable in the relevant
parser function: use strings.TrimSpace(para) only for the empty-item check, and
emit the original para unchanged when it contains content so trailing delimiters
such as "\n" are preserved.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f4db7a2-81e7-42e7-9808-8a413f2ac50a

📥 Commits

Reviewing files that changed from the base of the PR and between 78e8fb1 and 32b73d2.

📒 Files selected for processing (2)
  • internal/parser/parser/parse_with_result_test.go
  • internal/parser/parser/text_parser.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/parser/parser/parse_with_result_test.go

@xugangqiang xugangqiang changed the title fix(parser): align text&code Parser to Python delimiter split Fix(parser): align text&code Parser to Python delimiter split Aug 10, 2026
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 11, 2026
…-compatible

- Translate markdown.sample.md and markdown.python.golden.json to English
  (content only; {meta, items} structure unchanged).
- Keep LoadGolden returning []map[string]any and make it tolerant of both the
  legacy flat-array and the new {meta, items} golden format, so other
  alignment PRs (e.g. infiniflow#18022) that call LoadGolden + FilterByDocType keep
  working. Add LoadGoldenDoc (returns the full {meta, items}) for the
  meta-driven test; AcceptedDivergences / FilterOutDocTypes are additive.
- TestMarkdownParser_AlignmentGolden now reads accepted_divergences from the
  golden meta instead of a hardcoded filter.
@xugangqiang xugangqiang added the ci Continue Integration label Aug 11, 2026
The Go TextParser previously split only on blank lines ("\n\n"), so it
diverged from the Python flow _code path (deepdoc TxtParser) which splits
on the default delimiter set "\n!?;。;!?" and keeps the trailing delimiter
attached (keep_delimiters=True).

Align TextParser to the Python split rule:
- split on the flow parser's default delimiter set, capturing delimiters;
- keep each trailing delimiter attached (sentence-ending punctuation survives);
- CRLF/CR normalized to LF like Python;
- the OVER_CAP token merge is intentionally NOT performed here — chunking
  ownership stays with the downstream Chunker per PARSER_ALIGNMENT_HANDOFF.md
  §2.3 (decision 1), so item counts differ from the Python merged chunks and
  are reconciled by the stitch-compare alignment test;
- the 8192-byte per-item cap is retained: the downstream chunker keeps any
  single oversized item whole and the embedding step truncates it, so without
  the cap a minified / no-newline file would collapse to one mega-chunk.

Add the TextCodeAlignOptions preset to the shared align framework and a
Python golden (gen_textcode_golden.py) plus a Go alignment test that verifies
content equivalence against the real Python parser on a shared sample.
The TextParser previously sliced any segment longer than 8192 bytes at
the nearest line boundary, a Go-side defensive cap with no equivalent in
the Python flow _code path (deepdoc TxtParser.parser_txt does no size
slicing). Keeping it made Go diverge from Python for continuous runs
longer than the cap (minified / no-newline files): Go split them while
Python kept one chunk.

Remove the cap so TextParser becomes a pure delimiter splitter, matching
Python's parser_txt exactly. Sizing is delegated to the downstream Chunker
and the embedding truncation step, per PARSER_ALIGNMENT_HANDOFF.md §2.3
(decision 1 — chunking ownership stays with the Chunker). A continuous run
longer than the embedding token budget is now kept as one item and
collapses to one chunk downstream, matching Python rather than diverging.

Replace TestTextParser_ParseWithResult_LongParagraphSlicing (which pinned
the removed slicing) with TestTextParser_ParseWithResult_NoSizeCap, which
pins the new behaviour: a continuous >8192-byte run stays as one item with
its full content preserved.
@xugangqiang
xugangqiang force-pushed the fix/text-code-parser-align branch from 32b73d2 to 0f03d2b Compare August 11, 2026 06:17
@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 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@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 (1)
internal/parser/parser/testdata/gen_textcode_golden.py (1)

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

Use logging for generator progress.

Line 54 reports the new flow with print(...). Add a module logger and use a parameterized logger.info(...) call. Configure logging in the CLI entry point so direct execution still displays the message.

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

Proposed logging change
 import json
+import logging
 import os
 import sys
 
+logger = logging.getLogger(__name__)
...
-    print("wrote %d items to %s" % (len(items), OUT))
+    logger.info("Wrote %d items to %s", len(items), OUT)
 
 if __name__ == "__main__":
+    logging.basicConfig(level=logging.INFO, format="%(message)s")
     sys.exit(main())
🤖 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_textcode_golden.py` at line 54, Replace
the progress print in the generator with a module-level logger and parameterized
logger.info call, preserving the item count and output path. Configure logging
in the CLI entry point so direct execution continues displaying the progress
message.

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/testdata/gen_textcode_golden.py`:
- Around line 36-37: Update gen_textcode_golden.py to derive the repository root
from __file__, then construct SAMPLE and OUT with os.path.join so both fixture
paths resolve independently of the current working directory.

---

Nitpick comments:
In `@internal/parser/parser/testdata/gen_textcode_golden.py`:
- Line 54: Replace the progress print in the generator with a module-level
logger and parameterized logger.info call, preserving the item count and output
path. Configure logging in the CLI entry point so direct execution continues
displaying the progress message.
🪄 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: 16d8a6a0-70e9-45c5-bd3b-e31c63046664

📥 Commits

Reviewing files that changed from the base of the PR and between 61fa96e and 0f03d2b.

📒 Files selected for processing (6)
  • internal/parser/parser/align_test.go
  • internal/parser/parser/parse_with_result_test.go
  • internal/parser/parser/testdata/gen_textcode_golden.py
  • internal/parser/parser/testdata/textcode.python.golden.json
  • internal/parser/parser/testdata/textcode.sample.txt
  • internal/parser/parser/text_parser.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • internal/parser/parser/testdata/textcode.sample.txt
  • internal/parser/parser/testdata/textcode.python.golden.json
  • internal/parser/parser/align_test.go
  • internal/parser/parser/parse_with_result_test.go
  • internal/parser/parser/text_parser.go

Comment on lines +36 to +37
SAMPLE = "internal/parser/parser/testdata/textcode.sample.txt"
OUT = "internal/parser/parser/testdata/textcode.python.golden.json"

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

Resolve fixture paths from __file__.

SAMPLE and OUT are relative to the current working directory, while the import path is based on __file__. The documented command works only from the repository root. Running this standalone script from another directory can fail to read SAMPLE or write OUT to the fixture directory.

Define the repository root once and build both paths with os.path.join.

Proposed path fix
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
+ROOT = os.path.abspath(
+    os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
+)
+sys.path.insert(0, ROOT)

-SAMPLE = "internal/parser/parser/testdata/textcode.sample.txt"
-OUT = "internal/parser/parser/testdata/textcode.python.golden.json"
+SAMPLE = os.path.join(
+    ROOT, "internal", "parser", "parser", "testdata", "textcode.sample.txt"
+)
+OUT = os.path.join(
+    ROOT, "internal", "parser", "parser", "testdata",
+    "textcode.python.golden.json"
+)
📝 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
SAMPLE = "internal/parser/parser/testdata/textcode.sample.txt"
OUT = "internal/parser/parser/testdata/textcode.python.golden.json"
ROOT = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
)
sys.path.insert(0, ROOT)
SAMPLE = os.path.join(
ROOT, "internal", "parser", "parser", "testdata", "textcode.sample.txt"
)
OUT = os.path.join(
ROOT, "internal", "parser", "parser", "testdata",
"textcode.python.golden.json"
)
🤖 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_textcode_golden.py` around lines 36 - 37,
Update gen_textcode_golden.py to derive the repository root from __file__, then
construct SAMPLE and OUT with os.path.join so both fixture paths resolve
independently of the current working directory.

…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.
…-compatible

- Translate markdown.sample.md and markdown.python.golden.json to English
  (content only; {meta, items} structure unchanged).
- Keep LoadGolden returning []map[string]any and make it tolerant of both the
  legacy flat-array and the new {meta, items} golden format, so other
  alignment PRs (e.g. infiniflow#18022) that call LoadGolden + FilterByDocType keep
  working. Add LoadGoldenDoc (returns the full {meta, items}) for the
  meta-driven test; AcceptedDivergences / FilterOutDocTypes are additive.
- TestMarkdownParser_AlignmentGolden now reads accepted_divergences from the
  golden meta instead of a hardcoded filter.
@xugangqiang xugangqiang changed the title Fix(parser): align text&code Parser to Python delimiter split refactor(parser): text&code align + markdown golden meta-driven cleanup 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 (2)
internal/parser/parser/markdown_parser_test.go (1)

534-540: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Commit a deterministic Markdown golden generator.

The fixture and test documentation state that no generator is committed. This makes the Python baseline depend on a manual or AI-created wrapper. Commit the generator used for this fixture and replace the manual regeneration instructions with its command.

  • internal/parser/parser/markdown_parser_test.go#L534-L540: document the committed generator command instead of the manual or AI recreation process.
  • internal/parser/parser/testdata/markdown.python.golden.json#L9-L9: remove the no-generator note and record the committed generator identity.

As per coding guidelines, remove stale documentation and “move later” notes instead of preserving manual recovery instructions.

🤖 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_test.go` around lines 534 - 540,
Commit the deterministic generator used to produce the Markdown Python golden
fixture, then update internal/parser/parser/markdown_parser_test.go lines
534-540 to document its actual regeneration command instead of manual or AI
recreation. Update internal/parser/parser/testdata/markdown.python.golden.json
line 9 to remove the no-generator note and record the committed generator
identity.

Source: Coding guidelines

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

200-231: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use one golden JSON format.

textcode.python.golden.json is still a bare array, while the other fixture uses {meta, items}. Convert the fixture, update parse_with_result_test.go to use LoadGoldenDoc(...).Items, then remove the array fallback and LoadGolden.

🤖 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/align_test.go` around lines 200 - 231, Standardize the
Python golden fixture to the {meta, items} document format, and update
parse_with_result_test.go to load it through LoadGoldenDoc(...).Items. In
parseGolden, remove legacy bare-array parsing and make it require the document
format; then delete the now-unused LoadGolden helper.

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/align_test.go`:
- Around line 200-231: Standardize the Python golden fixture to the {meta,
items} document format, and update parse_with_result_test.go to load it through
LoadGoldenDoc(...).Items. In parseGolden, remove legacy bare-array parsing and
make it require the document format; then delete the now-unused LoadGolden
helper.

In `@internal/parser/parser/markdown_parser_test.go`:
- Around line 534-540: Commit the deterministic generator used to produce the
Markdown Python golden fixture, then update
internal/parser/parser/markdown_parser_test.go lines 534-540 to document its
actual regeneration command instead of manual or AI recreation. Update
internal/parser/parser/testdata/markdown.python.golden.json line 9 to remove the
no-generator note and record the committed generator identity.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 192f54a0-8bf5-41c8-8b6a-095be572b5dc

📥 Commits

Reviewing files that changed from the base of the PR and between 0f03d2b and c9f32b6.

📒 Files selected for processing (5)
  • internal/parser/parser/align_test.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
💤 Files with no reviewable changes (1)
  • internal/parser/parser/testdata/gen_markdown_golden.py

xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Aug 11, 2026
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.
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.
@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 (b762905).
⚠️ Report is 20 commits behind head on main.

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

Copy link
Copy Markdown
Contributor Author

Superseded by the split per-review: this combined PR is broken into 4 focused PRs for cleaner review/bisect:

@xugangqiang
xugangqiang deleted the fix/text-code-parser-align branch August 12, 2026 11:00
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