Skip to content

test(parser): add shared golden-doc + alignment helpers - #18098

Merged
yuzhichang merged 4 commits into
mainfrom
fix/parser-align-foundation
Aug 11, 2026
Merged

yuzhichang merged 4 commits into
mainfrom
fix/parser-align-foundation

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Centralize the shared golden-doc + alignment helpers in align_test.go so the
format-specific PRs (text&code, markdown golden, HTML) reuse one implementation
instead of each carrying their own copy of the scaffolding.

Adds (no production behavior change — consts/helpers only):

  • delimiter.go (non-test): DefaultTextCodeDelimiter and
    DefaultMarkdownDelimiter, the single source of truth for the flow parser's
    default delimiter sets. Production parsers and the alignment tests both
    reference these, so there is no duplicated hard-coded copy that could drift.
  • 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, HTMLAlignOptions / StripHTMLHeadingMarker:
    normalizer presets reused by the alignment tests.
  • LoadGolden now tolerates the {meta, items} format.
  • TestParseGolden: unit test locking the two tolerated golden formats (legacy
    array, {meta, items}) and the corrupt-input failure path, so future changes
    to the golden format cannot silently break parsing.

Dependency

The align_test.go framework (CompareAlignment, Normalizer, LoadGolden) comes
from #18014, which is already in main. This PR only layers the shared helpers
and delimiter consts on top. Merge this first; PR-2/3/4 branch from it.

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 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

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: b6ea9cd6-9020-40ae-b3e3-edfb0f16d2da

📥 Commits

Reviewing files that changed from the base of the PR and between 1e39d24 and 13d3933.

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

📝 Walkthrough

Walkthrough

The parser test helpers now load legacy and metadata-bearing golden documents. They expose accepted-divergence and document-type filtering. They also add text/code and HTML alignment presets with delimiter, heading-marker, tag, and whitespace normalization.

Changes

Golden alignment helpers

Layer / File(s) Summary
Golden document loading and filtering
internal/parser/parser/align_test.go
GoldenDoc supports metadata and items. Loading accepts legacy arrays and {meta, items} documents. Helpers extract accepted divergences, filter document types, reject empty documents, and test malformed input.
Text, code, and HTML alignment presets
internal/parser/parser/align_test.go, internal/parser/parser/delimiter.go
Text/code alignment replaces configured delimiters and collapses whitespace. HTML alignment removes heading markers, replaces tags, and collapses whitespace. Shared delimiter constants are defined in the parser package.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: 🧪 test, ☯️ refactor

Suggested reviewers: yuzhichang

Poem

A rabbit loads goldens in a row,
Metadata helps the test flow.
Tags and headings softly align,
Delimiters fall into line.
Whitespace rests, clean and fine.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the addition of shared golden-document and alignment helpers.
Description check ✅ Passed The description includes the required Summary section and clearly explains the purpose, background, and scope of the changes.
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.

@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

🤖 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 200-215: Update gen_markdown_golden.py and
markdown.python.golden.json to generate and consume the {meta, items} document
format, then simplify parseGolden to unmarshal only GoldenDoc and remove its
legacy bare-array fallback. Leave unified_html_cases.json unchanged as a shared
array fixture, and retain array compatibility only if it represents a documented
external contract.
🪄 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: 0d02f56f-ac6a-49b3-b338-2f010f1c4118

📥 Commits

Reviewing files that changed from the base of the PR and between dd52dee and 92dbc2f.

📒 Files selected for processing (1)
  • internal/parser/parser/align_test.go

Comment thread internal/parser/parser/align_test.go Outdated
Comment on lines +200 to +215
// parseGolden unmarshals a golden file that may be either a bare JSON array of
// items (legacy format) or a {meta, items} document (current format). It
// returns the full document either way. Tolerant parsing keeps older
// callers/tests working after the format gained a meta block.
func parseGolden(t *testing.T, data []byte) *GoldenDoc {
t.Helper()
var doc GoldenDoc
if err := json.Unmarshal(data, &doc); err == nil && doc.Items != nil {
return &doc
}
// Legacy flat-array format: treat the whole file as the items list.
var items []map[string]any
if err := json.Unmarshal(data, &items); err != nil {
t.Fatalf("parse golden: %v", err)
}
return &GoldenDoc{Items: items}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find alignment fixtures that still use a top-level JSON array.
fd -e json . internal/parser/parser/testdata | while IFS= read -r file; do
  python3 - "$file" <<'PY'
import json
import sys

path = sys.argv[1]
try:
    with open(path, encoding="utf-8") as f:
        value = json.load(f)
except (OSError, json.JSONDecodeError):
    raise SystemExit(0)

if isinstance(value, list):
    print(path)
PY
done

# Inspect remaining loader call sites before removing compatibility.
rg -n -C 3 --glob '*.go' '\bLoadGolden(Doc)?\s*\(' internal/parser

Repository: infiniflow/ragflow

Length of output: 2123


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json
from pathlib import Path

for path in [
    Path("internal/parser/parser/testdata/markdown.python.golden.json"),
    Path("internal/parser/parser/testdata/unified_html_cases.json"),
]:
    value = json.loads(path.read_text(encoding="utf-8"))
    kind = "array" if isinstance(value, list) else type(value).__name__
    print(f"{path}: {kind}, length/keys={len(value)}")
    if isinstance(value, list) and value:
        print(f"  first item keys: {sorted(value[0])}")
    elif isinstance(value, dict):
        print(f"  keys: {sorted(value)}")
PY

sed -n '180,270p' internal/parser/parser/align_test.go
rg -n -C 4 --glob '*.go' '\b(parseGolden|LoadGolden|LoadGoldenDoc)\s*\(' internal/parser
rg -n -i -C 2 'golden|accepted_divergences|meta.*items|items.*meta' --glob '*.md' --glob '*.go' --glob '*.json' internal/parser README.md 2>/dev/null | head -250

Repository: infiniflow/ragflow

Length of output: 16156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 5 'markdown\.python\.golden\.json|unified_html_cases\.json|json\.(load|dump)|accepted_divergences' \
  internal/parser/parser/testdata internal/parser/parser --glob '*.py' --glob '*.go' --glob '*.md'

sed -n '1,240p' internal/parser/parser/testdata/gen_markdown_golden.py
sed -n '1,80p' internal/parser/parser/testdata/markdown.python.golden.json
sed -n '1,60p' internal/parser/parser/testdata/unified_html_cases.json

Repository: infiniflow/ragflow

Length of output: 16898


Converge the alignment golden format.

markdown.python.golden.json is still generated and consumed as a bare array. Update gen_markdown_golden.py and the fixture to use {meta, items}, then remove the array branch from parseGolden. Keep unified_html_cases.json unchanged because Go and Python share it as an array fixture. Retain bare-array support only for a documented external contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/parser/align_test.go` around lines 200 - 215, Update
gen_markdown_golden.py and markdown.python.golden.json to generate and consume
the {meta, items} document format, then simplify parseGolden to unmarshal only
GoldenDoc and remove its legacy bare-array fallback. Leave
unified_html_cases.json unchanged as a shared array fixture, and retain array
compatibility only if it represents a documented external contract.

Source: Coding guidelines

@xugangqiang
xugangqiang requested a review from yuzhichang August 11, 2026 08:19

@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

🤖 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 429-433: Update the “corrupt” case in the relevant parser test so
it does not invoke parseGolden through a subtest expecting failure. Prefer
exposing or reusing a parsing-core path that returns an error and assert that
error directly; otherwise isolate the t.Fatalf contract in a subprocess while
keeping the parent test successful.
🪄 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: df5f3f64-b345-4f58-bf1a-c95842d88981

📥 Commits

Reviewing files that changed from the base of the PR and between 92dbc2f and 7a2057a.

📒 Files selected for processing (1)
  • internal/parser/parser/align_test.go

Comment thread internal/parser/parser/align_test.go Resolved
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels 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).
DefaultTextCodeDelimiter and DefaultMarkdownDelimiter are shared by both
the production parsers and the alignment tests. They previously lived in
align_test.go (a _test.go file), so production text_parser.go had to keep
a private duplicate that could drift silently. Move them to a non-test
delimiter.go as the single source of truth.
@xugangqiang
xugangqiang force-pushed the fix/parser-align-foundation branch from f2e724d to 1e39d24 Compare August 11, 2026 09:17
parseGolden now returns (*GoldenDoc, error) instead of calling t.Fatalf
internally on a malformed golden. Callers (LoadGolden/LoadGoldenDoc and
TestParseGolden) handle the error. The corrupt subtest asserts err != nil
directly, so the intended loud failure no longer propagates to and fails
TestParseGolden itself.
@yuzhichang

Copy link
Copy Markdown
Member

LGTM

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

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants