Skip to content

fix(deepdoc): keep pipe tables inside markdown code fences - #17201

Merged
xugangqiang merged 3 commits into
infiniflow:mainfrom
Yurii214:fix/markdown-table-in-code-fence
Jul 23, 2026
Merged

xugangqiang merged 3 commits into
infiniflow:mainfrom
Yurii214:fix/markdown-table-in-code-fence

Conversation

@Yurii214

Copy link
Copy Markdown
Contributor

Summary

RAGFlowMarkdownParser.extract_tables_and_remainder matches pipe tables anywhere in the document, with no notion of fenced code. A table inside a fenced code block is therefore appended to tables and deleted from the remainder.

For any doc that documents markdown syntax (or LLM-generated docs containing a ```markdown block), the example is destroyed. Given this input:

# Guide

Write a table like this:

```markdown
| Name | Value |
| --- | --- |
| A | 1 |
```

Done.

extract_tables_and_remainder(doc, separate_tables=True) currently returns:

remainder: '# Guide\n\nWrite a table like this:\n\n```markdown\n\n```\n\nDone.\n'
tables:    ['\n| Name | Value |\n| --- | --- |\n| A | 1 |\n']

The fence is left hollow and the example resurfaces as a bogus standalone table chunk (via rag/app/naive.py, which feeds the remainder to MarkdownElementExtractor and renders each extracted table separately).

MarkdownElementExtractor in this same module already shields fenced code (_fenced_code_ranges / _protected_ranges) so delimiters never split inside a fence — table extraction simply missed the same case. This skips matches that start inside a fence; genuine tables outside fences are extracted exactly as before.

Tests

Two regression tests added to TestMarkdownTableDedup: one asserting a fenced example survives, one asserting a real table alongside a fenced example is still extracted. Both fail without the change and pass with it; the existing 12 markdown tests are unaffected.

extract_tables_and_remainder matched pipe tables anywhere in the
document, with no notion of fenced code. a doc that documents markdown
syntax lost its example: the table was appended to `tables` and deleted
from the remainder, leaving a hollow fence behind and re-emitting the
example as a bogus standalone table chunk.

skip matches that start inside a fence, mirroring the shielding
MarkdownElementExtractor already does in this module
(_fenced_code_ranges / _protected_ranges). genuine tables outside fences
are still extracted. adds regression tests for both cases.
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 🧪 test Pull requests that update test cases. labels Jul 21, 2026
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Markdown table extraction now detects fenced code blocks and leaves table-like content inside them unchanged. New tests verify fenced examples remain in the remainder while genuine tables outside fences are still extracted.

Changes

Markdown table fence protection

Layer / File(s) Summary
Fence-aware table extraction and validation
deepdoc/parser/markdown_parser.py, test/unit_test/deepdoc/parser/test_markdown_parser.py
Fenced spans are excluded from Markdown table replacement, HTML-tag simplification, and HTML-table extraction. Tests verify fenced examples remain intact while genuine tables outside fences are extracted.

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

Suggested reviewers: xugangqiang

Poem

I’m a rabbit with a parsing pen,
I guard fenced tables in their den.
Real tables hop out clean and bright,
While code stays safe from needless flight.
Thump, thump—Markdown reads just right!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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 is concise and matches the main fix, though it mentions only pipe tables while the PR also covers fenced HTML handling.
Description check ✅ Passed The description matches the required Summary section and provides sufficient context, behavior details, and regression test notes.

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.

🧹 Nitpick comments (1)
deepdoc/parser/markdown_parser.py (1)

32-50: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Extend code fence protection to HTML tag replacement and HTML table extraction.

The current changes successfully protect Markdown pipe tables inside fenced code blocks. However, the exact same issue applies to HTML table extraction and HTML tag attribute stripping (lines 89-136). Without similar protection, HTML examples inside code fences will still be modified (e.g., <table border="1"> stripped to <table>) or extracted, hollowing out the code block.

Consider applying this newly introduced fence protection logic consistently to the HTML passes.

♻️ Proposed refactor to protect HTML tables and tags

Update the tag replacement pass (around line 93):

         # Replace any TAGS e.g. <table ...> to <table>
         TAGS = ["table", "td", "tr", "th", "tbody", "thead", "div"]
         table_with_attributes_pattern = re.compile(rf"<(?:{'|'.join(TAGS)})[^>]*>", re.IGNORECASE)
 
+        fenced_spans_tags = [(m.start(), m.end()) for m in fence_pattern.finditer(working_text)]
         def replace_tag(m):
+            if any(start <= m.start() < end for start, end in fenced_spans_tags):
+                return m.group()
             tag_name = re.match(r"<(\w+)", m.group()).group(1)
             return "<{}>".format(tag_name)
 
         working_text = re.sub(table_with_attributes_pattern, replace_tag, working_text)

Update the HTML table extraction pass (around line 121):

             def replace_html_tables():
                 nonlocal working_text
                 new_text = ""
                 last_end = 0
+                fenced_spans_html = [(m.start(), m.end()) for m in fence_pattern.finditer(working_text)]
                 for match in html_table_pattern.finditer(working_text):
+                    if any(start <= match.start() < end for start, end in fenced_spans_html):
+                        continue
                     raw_table = match.group()
                     tables.append(raw_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 `@deepdoc/parser/markdown_parser.py` around lines 32 - 50, Extend the
fence-aware filtering in replace_tables_with_rendered_html to the HTML tag
attribute replacement and HTML table extraction passes around the existing HTML
processing logic. Reuse the existing fence_pattern and fenced_spans computed
from working_text, skip matches whose start lies within a fenced span, and
preserve their original text so HTML examples remain unchanged inside code
fences.
🤖 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 `@deepdoc/parser/markdown_parser.py`:
- Around line 32-50: Extend the fence-aware filtering in
replace_tables_with_rendered_html to the HTML tag attribute replacement and HTML
table extraction passes around the existing HTML processing logic. Reuse the
existing fence_pattern and fenced_spans computed from working_text, skip matches
whose start lies within a fenced span, and preserve their original text so HTML
examples remain unchanged inside code fences.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a8c2cc1d-20f7-4757-bbef-478f77d1f9c6

📥 Commits

Reviewing files that changed from the base of the PR and between 6a85d1c and 7dcda19.

📒 Files selected for processing (2)
  • deepdoc/parser/markdown_parser.py
  • test/unit_test/deepdoc/parser/test_markdown_parser.py

review follow-up: the tag-stripping and html-table passes had the same
blind spot as the pipe-table pass. an html example inside a fence had its
attributes stripped (<table border="1"> -> <table>) and the table pulled
out into `tables`, leaving a hollow fence behind.

shield both passes with the same fence spans. html tables outside fences
are still normalised and extracted exactly as before. adds a regression
test.
@Yurii214

Copy link
Copy Markdown
Contributor Author

Good catch — that was a real gap, applied in d173d21.

Confirmed the same failure on the HTML passes before fixing: for a html fence containing `<table border="1">…`, the tag pass stripped the attribute and the html-table pass extracted the table, leaving the fence hollow (html + two blank lines). Both passes now use the same fence spans.

HTML tables outside fences are unchanged — still normalised to <table> and extracted — and there's a regression test covering the fenced case.

@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)
deepdoc/parser/markdown_parser.py (1)

37-40: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Match the fence character, not the exact opener length.

\\1 requires the closing fence to have exactly the same length as the opener. Markdown allows a closing fence to be longer, so an opener of ``` followed by ```` is treated as unclosed; the \Z fallback then shields all subsequent content from extraction.

Proposed fix
-            r"^[ \t]{0,3}(`{3,}|~{3,})[^\n]*\n.*?(?:^[ \t]{0,3}\1[ \t]*$|\Z)",
+            r"^[ \t]{0,3}(?P<fence_char>`|~)(?P=fence_char){2,}[^\n]*\n"
+            r".*?(?:^[ \t]{0,3}(?P=fence_char){3,}[ \t]*$|\Z)",

Add a regression test with a longer closing fence followed by a genuine 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 `@deepdoc/parser/markdown_parser.py` around lines 37 - 40, Update the
fence_pattern in the markdown parser so the closing fence matches the opener’s
character while allowing a closing run longer than the opener, rather than
requiring identical length. Preserve support for both backtick and tilde fences
and ensure subsequent table content remains extractable; add a regression test
covering a longer closing fence followed by a genuine table.
🧹 Nitpick comments (2)
test/unit_test/deepdoc/parser/test_markdown_parser.py (1)

209-220: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise the HTML-table extraction branch in this regression test.

With <table border="1">, tag preservation prevents the "<table>" fast-path from running, so this test only validates tag stripping. Add a second fenced fixture containing a bare <table> to verify replace_html_tables also skips it.

[details]

+        bare_table = "```html\n<table>\n<tr><td>A</td></tr>\n</table>\n```"
+        remainder, tables = parser.extract_tables_and_remainder(
+            bare_table, separate_tables=True
+        )
+        assert tables == []
+        assert "<table>" in remainder
+        assert "</table>" in remainder
🤖 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 `@test/unit_test/deepdoc/parser/test_markdown_parser.py` around lines 209 -
220, Extend test_html_table_inside_code_fence_is_left_intact with a second
fenced Markdown fixture containing a bare <table> element, then call
extract_tables_and_remainder with separate_tables=True and assert no tables are
extracted while both table tags remain in the remainder, exercising
replace_html_tables’ fenced-code branch.
deepdoc/parser/markdown_parser.py (1)

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

Add debug logging for the new fence-skipping flows.

These branches silently skip Markdown tables, HTML tags, and HTML tables. Add low-volume debug logs identifying the processing pass and match position, without logging document content. As per coding guidelines, new Python flows should add logging.

Also applies to: 96-98, 130-133

🤖 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 `@deepdoc/parser/markdown_parser.py` around lines 47 - 50, Add low-volume debug
logging to the fence-skipping branches in the Markdown parser, including the
flows around the shown check and the corresponding Markdown-table, HTML-tag, and
HTML-table branches. Log the processing pass and match position without
including document content, using the module’s existing logger conventions.

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.

Outside diff comments:
In `@deepdoc/parser/markdown_parser.py`:
- Around line 37-40: Update the fence_pattern in the markdown parser so the
closing fence matches the opener’s character while allowing a closing run longer
than the opener, rather than requiring identical length. Preserve support for
both backtick and tilde fences and ensure subsequent table content remains
extractable; add a regression test covering a longer closing fence followed by a
genuine table.

---

Nitpick comments:
In `@deepdoc/parser/markdown_parser.py`:
- Around line 47-50: Add low-volume debug logging to the fence-skipping branches
in the Markdown parser, including the flows around the shown check and the
corresponding Markdown-table, HTML-tag, and HTML-table branches. Log the
processing pass and match position without including document content, using the
module’s existing logger conventions.

In `@test/unit_test/deepdoc/parser/test_markdown_parser.py`:
- Around line 209-220: Extend test_html_table_inside_code_fence_is_left_intact
with a second fenced Markdown fixture containing a bare <table> element, then
call extract_tables_and_remainder with separate_tables=True and assert no tables
are extracted while both table tags remain in the remainder, exercising
replace_html_tables’ fenced-code branch.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6b66909d-5245-4668-90e1-8cd299854f38

📥 Commits

Reviewing files that changed from the base of the PR and between 7dcda19 and d173d21.

📒 Files selected for processing (2)
  • deepdoc/parser/markdown_parser.py
  • test/unit_test/deepdoc/parser/test_markdown_parser.py

@yingfeng
yingfeng requested a review from xugangqiang July 22, 2026 06:26
@yingfeng yingfeng added the ci Continue Integration label Jul 22, 2026
review follow-up:
- the existing html-fence test used <table border="1">, which the
  "<table>" fast-path guard skips, so the html-table extraction pass
  (and its new fence check) was never exercised. add a bare-<table>
  fenced fixture that drives that pass.
- add low-volume debug logs to the three fence-skip branches (markdown
  table, html tag, html table), position only, no document content.
@Yurii214

Copy link
Copy Markdown
Contributor Author

Both applied in 6e87376.

  • Good catch on the test: <table border="1"> never reaches replace_html_tables because the "<table>" in working_text fast-path guard doesn't match a tag with attributes, so that pass (and its fence check) was untested. Added test_bare_html_table_inside_code_fence_is_not_extracted with a bare <table> — I confirmed it fails if the html-table fence skip is removed.
  • Added low-volume debug logs to the three fence-skip branches (markdown-table, html-tag, html-table), logging only the pass name and match offset, no document content.

@Yurii214

Copy link
Copy Markdown
Contributor Author

Heads-up: the red ragflow_preflight here is an environment-setup flake, not this change. It fails in "Prepare Python test environment" while uv sync clones a dependency:

Failed to download and build graspologic @ git+https://gitee.com/infiniflow/graspologic.git
fatal: could not read Username for 'https://gitee.com': terminal prompts disabled

So the gitee clone couldn't authenticate/reach the host — the test code never ran. The same preflight passed on my other PRs (#17062, #17064), so it looks transient. A re-run should clear it. This PR only touches deepdoc/parser/markdown_parser.py (+ its unit test); locally test_markdown_parser.py is green and ruff check passes.

@xugangqiang
xugangqiang marked this pull request as draft July 23, 2026 05:00
@xugangqiang
xugangqiang marked this pull request as ready for review July 23, 2026 05:00
@xugangqiang xugangqiang self-assigned this Jul 23, 2026
@codecov

codecov Bot commented Jul 23, 2026

Copy link
Copy Markdown

Codecov Report

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

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

☔ 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 merged commit 64be858 into infiniflow:main Jul 23, 2026
7 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants