Repository navigation
fix(parser): emit a single structured table item in document order - #18168
Conversation
HTML and Markdown parsers previously emitted every table twice: an inline doc_type_kwd:"text" copy carrying the full <table> markup (mixed into the surrounding prose) plus a structured doc_type_kwd:"table" item that was deferred and appended at the end of the stream. This caused: - duplicate embedding of the same table (split ranking dilution); - raw <table> tag pollution of neighbouring prose chunks; - tables relocated away from their original document position, breaking the table_context_size context window the chunker attaches. Keep exactly ONE structured doc_type_kwd:"table"/ck_type:"table" item, emitted in its original document order, and drop the redundant inline text copy. Restore the per-block ck_type mapping (htmlTagToCkType) that the duplicate path relied on, and remove the now-dead tableItems deferral plumbing. Python side is intentionally unchanged. Closes infiniflow#18157
📝 WalkthroughWalkthroughHTML and Markdown parsers now emit one structured table item in document order. Surrounding prose no longer contains duplicate table markup. Tests cover top-level, nested, multiple-table, and cross-parser alignment behavior. ChangesStructured table emission
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/parser/parser/markdown_parser_test.go (1)
101-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRename the test for the current contract.
TestMarkdownParser_ParseWithResult_RendersTableInlinenow verifies structured table output. Rename it to describe structured table emission.As per coding guidelines, remove stale documentation.
🤖 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 101 - 104, Rename TestMarkdownParser_ParseWithResult_RendersTableInline to describe structured table emission, matching its current contract that tables produce one structured table item. Remove the stale inline documentation that no longer reflects the test’s intended behavior.Sources: Coding guidelines, Learnings
🤖 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/html_parser_align_test.go`:
- Around line 57-70: Require exactly one structured table item in each
single-table test instead of tracking only a boolean or last index. Update the
checks at internal/parser/parser/html_parser_align_test.go:57-70, :136-149, and
:218-228, plus internal/parser/parser/markdown_parser_test.go:360-364, :415-423,
and :529-534, to count items with doc_type_kwd "table" and fail unless the count
is one; preserve the existing table-content and duplicate-inline-text
assertions.
---
Nitpick comments:
In `@internal/parser/parser/markdown_parser_test.go`:
- Around line 101-104: Rename
TestMarkdownParser_ParseWithResult_RendersTableInline to describe structured
table emission, matching its current contract that tables produce one structured
table item. Remove the stale inline documentation that no longer reflects the
test’s intended behavior.
🪄 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: 9c5100ff-afca-4cd9-8a15-cfcddd4a2026
📒 Files selected for processing (5)
internal/parser/parser/align_test.gointernal/parser/parser/html_parser.gointernal/parser/parser/html_parser_align_test.gointernal/parser/parser/markdown_parser.gointernal/parser/parser/markdown_parser_test.go
…rgence drop The alignment golden previously compared the inline <table> text item on both sides, which is what actually guarded against a table being collapsed or a column dropped. filterTableDivergence (introduced to drop the duplicate inline copy) removed that comparison entirely, leaving only an existence check. Restore the equivalence guard: - tableCellSignature / tableSignatures extract per-table cell text (th/td inner text) and compare the DISTINCT table sets between Go and Python. Tolerant of serialization differences (attribute order, <tbody> insertion) yet sensitive to dropped columns/cells. - Harden filterTableDivergence: drop an item only when it is ENTIRELY a <table> block (isStandaloneTable), so a prose item that merely contains a table is never masked. - Add TestHTMLParser_MultipleTablesOrdering, symmetric to the Markdown counterpart, locking multiple top-level tables in document order. Closes infiniflow#18157
…le test Add a tableCount assertion to each single-table HTML/Markdown test so the cardinality of doc_type_kwd:"table" items is locked to exactly one, strengthening the single-item-in-document-order contract beyond the boolean/last-index checks. Co-authored-by: CodeBuddy <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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 390-425: Update tableSignatures and assertTablesEquivalent to
preserve table occurrence counts and document order instead of storing
signatures in a map/set. Normalize known duplicate representations while
retaining one entry per source table, then compare the ordered occurrence lists
so missing or extra identical tables fail the equivalence check and exactly one
structured item is required per table.
- Around line 340-342: Replace the LastIndex-based table detection in the helper
used by filterTableDivergence with nesting-aware boundary tracking. Match the
closing tag for the first top-level table, reject any second top-level table or
non-whitespace content after that boundary, and continue accepting nested tables
within the first element.
In `@internal/parser/parser/html_parser_align_test.go`:
- Around line 255-260: Update the comment above
TestHTMLParser_MultipleTablesOrdering to describe only the current ordering and
table-emission contract; remove the parenthetical reference to the old
deferred-append behavior and migration history.
- Around line 285-322: Strengthen the assertions around the table items in the
test’s result scan: track whether inline table markup appears in any
doc_type_kwd="text" item, reject such markup, and require each collected table
item to have ck_type="table". Preserve the existing count, ordering, and
cell-content checks while validating both table entries completely.
🪄 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: a139ff62-ac7d-4d4a-92f0-9906399d0ba0
📒 Files selected for processing (3)
internal/parser/parser/align_test.gointernal/parser/parser/html_parser_align_test.gointernal/parser/parser/markdown_parser_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/parser/parser/markdown_parser_test.go
| close := strings.ToLower(t) | ||
| idx := strings.LastIndex(close, "</table>") | ||
| return idx >= 0 && strings.TrimSpace(t[idx+len("</table>"):]) == "" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Detect exactly one table element.
strings.LastIndex accepts text such as "<table>...</table> prose <table>...</table>" as a standalone table. filterTableDivergence then removes the prose item, despite Lines 304-310 requiring surrounding prose to remain in the alignment comparison.
Use nesting-aware table-boundary detection. Reject text that contains a second top-level table or non-whitespace content after the matching closing tag.
🤖 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 340 - 342, Replace the
LastIndex-based table detection in the helper used by filterTableDivergence with
nesting-aware boundary tracking. Match the closing tag for the first top-level
table, reject any second top-level table or non-whitespace content after that
boundary, and continue accepting nested tables within the first element.
| func tableSignatures(items []map[string]any) map[string]bool { | ||
| sigs := map[string]bool{} | ||
| for _, it := range items { | ||
| kd, _ := it["doc_type_kwd"].(string) | ||
| text, _ := it["text"].(string) | ||
| if kd != "table" && !isStandaloneTable(text) { | ||
| continue | ||
| } | ||
| if sig := tableCellSignature(text); sig != "" { | ||
| sigs[sig] = true | ||
| } | ||
| } | ||
| return sigs | ||
| } | ||
|
|
||
| // assertTablesEquivalent fails the test if the set of tables (by cell-content | ||
| // signature) differs between the Go output and the Python golden. This restores | ||
| // the Go↔Python table-equivalence guard that filterTableDivergence intentionally | ||
| // removes from the prose comparison: it catches a table being collapsed or a | ||
| // column/cell dropped on either side, while tolerating serialization | ||
| // differences (attribute order, <tbody> insertion). | ||
| func assertTablesEquivalent(t *testing.T, goItems, pyItems []map[string]any) { | ||
| t.Helper() | ||
| goSigs := tableSignatures(goItems) | ||
| pySigs := tableSignatures(pyItems) | ||
| for sig := range goSigs { | ||
| if !pySigs[sig] { | ||
| t.Errorf("Go table not present in Python golden (possible collapse / dropped column):\n%s", sig) | ||
| } | ||
| } | ||
| for sig := range pySigs { | ||
| if !goSigs[sig] { | ||
| t.Errorf("Python golden table not present in Go output (possible collapse / dropped column):\n%s", sig) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Preserve repeated-table cardinality in the equivalence check.
tableSignatures collapses equal signatures into a set. If a document has two identical tables and the Go parser emits only one, both sides produce the same set and assertTablesEquivalent passes. The prose filter has already removed the Python table items.
Normalize known duplicate representations, but retain each source table occurrence and its document order when comparing tables. The PR requires exactly one structured item per table.
🤖 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 390 - 425, Update
tableSignatures and assertTablesEquivalent to preserve table occurrence counts
and document order instead of storing signatures in a map/set. Normalize known
duplicate representations while retaining one entry per source table, then
compare the ordered occurrence lists so missing or extra identical tables fail
the equivalence check and exactly one structured item is required per table.
| // TestHTMLParser_MultipleTablesOrdering is the HTML counterpart of | ||
| // TestMarkdownParser_MultipleTablesOrdering: two top-level tables must each be | ||
| // emitted as a SINGLE structured doc_type_kwd:"table" item, in document order, | ||
| // bracketing the "Middle." paragraph (not relocated to the end of the stream — | ||
| // the old deferred-append behaviour this PR removes). Cell text of both tables | ||
| // must be present and in source order. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Remove migration-history text from the test comment.
Lines 258-260 describe the removed deferred-append implementation. Keep the comment limited to the current ordering contract.
As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history.”
Proposed fix
// TestHTMLParser_MultipleTablesOrdering is the HTML counterpart of
// TestMarkdownParser_MultipleTablesOrdering: two top-level tables must each be
// emitted as a SINGLE structured doc_type_kwd:"table" item, in document order,
-// bracketing the "Middle." paragraph (not relocated to the end of the stream —
-// the old deferred-append behaviour this PR removes). Cell text of both tables
-// must be present and in source order.
+// bracketing the "Middle." paragraph. Cell text of both tables must be present
+// and in source order.📝 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.
| // TestHTMLParser_MultipleTablesOrdering is the HTML counterpart of | |
| // TestMarkdownParser_MultipleTablesOrdering: two top-level tables must each be | |
| // emitted as a SINGLE structured doc_type_kwd:"table" item, in document order, | |
| // bracketing the "Middle." paragraph (not relocated to the end of the stream — | |
| // the old deferred-append behaviour this PR removes). Cell text of both tables | |
| // must be present and in source order. | |
| // TestHTMLParser_MultipleTablesOrdering is the HTML counterpart of | |
| // TestMarkdownParser_MultipleTablesOrdering: two top-level tables must each be | |
| // emitted as a SINGLE structured doc_type_kwd:"table" item, in document order, | |
| // bracketing the "Middle." paragraph. Cell text of both tables must be present | |
| // and in source order. |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/parser/parser/html_parser_align_test.go` around lines 255 - 260,
Update the comment above TestHTMLParser_MultipleTablesOrdering to describe only
the current ordering and table-emission contract; remove the parenthetical
reference to the old deferred-append behavior and migration history.
Source: Coding guidelines
| for i, it := range res.JSON { | ||
| text, _ := it["text"].(string) | ||
| switch it["doc_type_kwd"] { | ||
| case "text": | ||
| switch text { | ||
| case "Title": | ||
| titleIdx = i | ||
| case "Middle.": | ||
| middleIdx = i | ||
| case "End.": | ||
| endIdx = i | ||
| } | ||
| case "table": | ||
| tableItemIdx = append(tableItemIdx, i) | ||
| default: | ||
| t.Fatalf("unexpected doc_type_kwd %q", it["doc_type_kwd"]) | ||
| } | ||
| } | ||
|
|
||
| if titleIdx < 0 || middleIdx < 0 || endIdx < 0 { | ||
| t.Fatalf("missing anchor text item (title=%d middle=%d end=%d)", titleIdx, middleIdx, endIdx) | ||
| } | ||
| if len(tableItemIdx) != 2 { | ||
| t.Fatalf("table items = %d, want 2", len(tableItemIdx)) | ||
| } | ||
| // Both tables appear in document order, bracketing "Middle.": | ||
| // table1 before Middle, table2 between Middle and End. | ||
| if !(titleIdx < tableItemIdx[0] && tableItemIdx[0] < middleIdx && middleIdx < tableItemIdx[1] && tableItemIdx[1] < endIdx) { | ||
| t.Fatalf("table order wrong: tables=%v title=%d middle=%d end=%d", tableItemIdx, titleIdx, middleIdx, endIdx) | ||
| } | ||
| t1, _ := res.JSON[tableItemIdx[0]]["text"].(string) | ||
| t2, _ := res.JSON[tableItemIdx[1]]["text"].(string) | ||
| if !strings.Contains(t1, "x") || !strings.Contains(t1, "y") { | ||
| t.Errorf("first table item missing x/y cells: %q", t1) | ||
| } | ||
| if !strings.Contains(t2, "p") || !strings.Contains(t2, "q") { | ||
| t.Errorf("second table item missing p/q cells: %q", t2) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Verify the complete contract for both table items.
This test checks table count and order, but it passes if either table lacks ck_type:"table" or if table markup is also emitted in a doc_type_kwd:"text" item. Track inline table markup and validate ck_type for each table item.
Proposed fix
var tableItemIdx []int
titleIdx, middleIdx, endIdx := -1, -1, -1
+ inlineTableCount := 0
for i, it := range res.JSON {
text, _ := it["text"].(string)
switch it["doc_type_kwd"] {
case "text":
+ if strings.Contains(text, "<table") {
+ inlineTableCount++
+ }
switch text {
@@
case "table":
+ if got := it["ck_type"]; got != "table" {
+ t.Errorf("table item ck_type = %v, want table", got)
+ }
tableItemIdx = append(tableItemIdx, i)
@@
if len(tableItemIdx) != 2 {
t.Fatalf("table items = %d, want 2", len(tableItemIdx))
}
+ if inlineTableCount != 0 {
+ t.Errorf("found %d text item(s) containing <table> markup", inlineTableCount)
+ }📝 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.
| for i, it := range res.JSON { | |
| text, _ := it["text"].(string) | |
| switch it["doc_type_kwd"] { | |
| case "text": | |
| switch text { | |
| case "Title": | |
| titleIdx = i | |
| case "Middle.": | |
| middleIdx = i | |
| case "End.": | |
| endIdx = i | |
| } | |
| case "table": | |
| tableItemIdx = append(tableItemIdx, i) | |
| default: | |
| t.Fatalf("unexpected doc_type_kwd %q", it["doc_type_kwd"]) | |
| } | |
| } | |
| if titleIdx < 0 || middleIdx < 0 || endIdx < 0 { | |
| t.Fatalf("missing anchor text item (title=%d middle=%d end=%d)", titleIdx, middleIdx, endIdx) | |
| } | |
| if len(tableItemIdx) != 2 { | |
| t.Fatalf("table items = %d, want 2", len(tableItemIdx)) | |
| } | |
| // Both tables appear in document order, bracketing "Middle.": | |
| // table1 before Middle, table2 between Middle and End. | |
| if !(titleIdx < tableItemIdx[0] && tableItemIdx[0] < middleIdx && middleIdx < tableItemIdx[1] && tableItemIdx[1] < endIdx) { | |
| t.Fatalf("table order wrong: tables=%v title=%d middle=%d end=%d", tableItemIdx, titleIdx, middleIdx, endIdx) | |
| } | |
| t1, _ := res.JSON[tableItemIdx[0]]["text"].(string) | |
| t2, _ := res.JSON[tableItemIdx[1]]["text"].(string) | |
| if !strings.Contains(t1, "x") || !strings.Contains(t1, "y") { | |
| t.Errorf("first table item missing x/y cells: %q", t1) | |
| } | |
| if !strings.Contains(t2, "p") || !strings.Contains(t2, "q") { | |
| t.Errorf("second table item missing p/q cells: %q", t2) | |
| } | |
| var tableItemIdx []int | |
| titleIdx, middleIdx, endIdx := -1, -1, -1 | |
| inlineTableCount := 0 | |
| for i, it := range res.JSON { | |
| text, _ := it["text"].(string) | |
| switch it["doc_type_kwd"] { | |
| case "text": | |
| if strings.Contains(text, "<table") { | |
| inlineTableCount++ | |
| } | |
| switch text { | |
| case "Title": | |
| titleIdx = i | |
| case "Middle.": | |
| middleIdx = i | |
| case "End.": | |
| endIdx = i | |
| } | |
| case "table": | |
| if got := it["ck_type"]; got != "table" { | |
| t.Errorf("table item ck_type = %v, want table", got) | |
| } | |
| tableItemIdx = append(tableItemIdx, i) | |
| default: | |
| t.Fatalf("unexpected doc_type_kwd %q", it["doc_type_kwd"]) | |
| } | |
| } | |
| if titleIdx < 0 || middleIdx < 0 || endIdx < 0 { | |
| t.Fatalf("missing anchor text item (title=%d middle=%d end=%d)", titleIdx, middleIdx, endIdx) | |
| } | |
| if len(tableItemIdx) != 2 { | |
| t.Fatalf("table items = %d, want 2", len(tableItemIdx)) | |
| } | |
| if inlineTableCount != 0 { | |
| t.Errorf("found %d text item(s) containing <table> markup", inlineTableCount) | |
| } | |
| // Both tables appear in document order, bracketing "Middle.": | |
| // table1 before Middle, table2 between Middle and End. | |
| if !(titleIdx < tableItemIdx[0] && tableItemIdx[0] < middleIdx && middleIdx < tableItemIdx[1] && tableItemIdx[1] < endIdx) { | |
| t.Fatalf("table order wrong: tables=%v title=%d middle=%d end=%d", tableItemIdx, titleIdx, middleIdx, endIdx) | |
| } | |
| t1, _ := res.JSON[tableItemIdx[0]]["text"].(string) | |
| t2, _ := res.JSON[tableItemIdx[1]]["text"].(string) | |
| if !strings.Contains(t1, "x") || !strings.Contains(t1, "y") { | |
| t.Errorf("first table item missing x/y cells: %q", t1) | |
| } | |
| if !strings.Contains(t2, "p") || !strings.Contains(t2, "q") { | |
| t.Errorf("second table item missing p/q cells: %q", t2) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/parser/parser/html_parser_align_test.go` around lines 285 - 322,
Strengthen the assertions around the table items in the test’s result scan:
track whether inline table markup appears in any doc_type_kwd="text" item,
reject such markup, and require each collected table item to have
ck_type="table". Preserve the existing count, ordering, and cell-content checks
while validating both table entries completely.
Summary
The Go HTML and Markdown parsers emitted every table twice:
doc_type_kwd:"text"item carrying the full<table>…</table>markup, mixed into the surrounding prose; and
doc_type_kwd:"table"/ck_type:"table"item that wasdeferred and appended at the end of the stream.
This produced three downstream problems:
retrieve-time ranking of the real chunk.
<table>markup was injected into theneighbouring prose chunk instead of clean text.
so the table lost its original document position and the
table_context_sizecontext window the chunker attaches was computed against the wrong
neighbourhood.
Fix (Go only — Python untouched)
Keep exactly one structured
doc_type_kwd:"table"/ck_type:"table"itemand emit it in its original document order; drop the redundant inline
doc_type_kwd:"text"copy. Concretely:walkHTMLBlocks(top-level tables) andwalkHTMLLeaf(nested tables indiv/section/…) now append the single structured item inline at thetable's document position instead of deferring a
tableItemsslice to theend.
walkMarkdownBlocksWithImagesemits the table as one structured item indocument order (no separate inlined copy, no end-of-walk append).
ck_typemapping (htmlTagToCkType) that theduplicate path relied on, and removed the now-dead
tableItemsdeferral.The downstream chunker still consumes a single
doc_type_kwd:"table"item tokeep the table whole as a discrete, independently retrievable chunk
(
internal/ingestion/component/chunker/token.go), so its behaviour isunchanged.
Scope
internal/parser/parser/html_parser.gointernal/parser/parser/markdown_parser.goPython side is intentionally not changed.
Test plan
no-inline-copy contract for: top-level table, nested table, nested table
with surrounding prose (
<div><p>before</p><table>…</table><p>after</p></div>),markdown table with surrounding prose, multiple tables ordering, and raw
<table>HTML blocks.TestHTMLParser_AlignmentGolden,TestMarkdownParser_AlignmentGolden) keep comparing non-table prose viafilterTableDivergence, and now additionally assert a table representationis present on both sides (
hasTableRepresentation) so a silently droppedtable cannot pass.
bash build.sh --test ./internal/parser/parser/...✅bash build.sh --test ./internal/ingestion/...✅ (chunker table contractunchanged; no ingestion golden exercises the parser table path, so this is
not a regression surface for the change).
Closes #18157