Skip to content

Fix layout table flattening in pure mode - #71

Merged
letmutex merged 2 commits into
mainfrom
fix-table-flatten-layout
Mar 21, 2026
Merged

letmutex merged 2 commits into
mainfrom
fix-table-flatten-layout

Conversation

@letmutex

@letmutex letmutex commented Mar 21, 2026 •

Copy link
Copy Markdown
Owner

Fix nested tables

Summary by CodeRabbit

  • Bug Fixes

    • Improved table-to-Markdown conversion for tables without explicit headers; headerless tables now render as plain cell content and tables nested inside cells are treated correctly.
    • Prevented header markers from being mistakenly inherited from nested tables, ensuring accurate outer-table rendering.
  • Tests

    • Added comprehensive table conversion tests (including nested combinations and a real-world example) to validate output formatting and whitespace bounds.

@coderabbitai

coderabbitai Bot commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6afd2087-a538-4d02-a7f5-ed053ef32d3a

📥 Commits

Reviewing files that changed from the base of the PR and between e6e9513 and b84c70d.

📒 Files selected for processing (2)
  • src/element_handler/table.rs
  • tests/table_tests.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/element_handler/table.rs
  • tests/table_tests.rs

📝 Walkthrough

Walkthrough

Table handling in TranslationMode::Pure now short-circuits to the fallback when a table subtree lacks explicit header markers (th/thead) or when the current node is inside a table cell. New helpers detect explicit headers (skipping nested tables) and ancestor table-cell context; imports updated accordingly. Tests for headerless and nested tables were added.

Changes

Cohort / File(s) Summary
Table handler
src/element_handler/table.rs
Altered table_handler control flow for TranslationMode::Pure to call handlers.fallback(element) when no explicit headers are found or when inside a td/th. Added helpers has_explicit_headers() (recursive descendant scan that skips nested <table>s) and is_inside_table_cell() (ancestor walk via get_parent_node). Updated imports to include get_parent_node.
Tests
tests/table_tests.rs
Added longest_space_run() helper and extended tests: headerless-table conversion, <thead> rows with <td>, multiple nested-table combinations (outer/inner headered vs headerless), and a Hacker News example that checks visible text presence, multiline output, and bounded whitespace padding.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through rows and cells with care,

Checked headers, ancestors, and nested lair,
When no header's found I take a bow,
Tests applaud — I fixed it now! 🎉

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: fixing layout table flattening behavior in pure mode, which is the primary focus of the PR objectives and code changes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-table-flatten-layout

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 and usage tips.

Tip

You can disable poems in the walkthrough.

Disable the reviews.poem setting to disable the poems in the walkthrough.

@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 (6)
tests/table_tests.rs (4)

279-283: Inconsistent assertion pattern with existing tests.

Existing tests in this file trim the converted output before comparison (e.g., line 54: let result = markdown.trim()), but this test compares directly without trimming. This inconsistency could lead to flaky behavior if the implementation's whitespace handling changes.

♻️ Suggested fix for consistency
     let expected = "Alpha\n\nBeta\n\nGamma\n\nDelta";
     let markdown = htmd::HtmlToMarkdown::new().convert(html).unwrap();
 
-    assert_eq!(expected, markdown);
+    assert_eq!(expected, markdown.trim());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/table_tests.rs` around lines 279 - 283, The test compares the converted
markdown directly but other tests trim whitespace before asserting; update this
test to trim the conversion result for consistency by applying .trim() to the
value returned from htmd::HtmlToMarkdown::new().convert(html).unwrap() (the
variable named markdown) and use that trimmed string in the assert_eq! against
expected so the assertion matches the existing pattern.

319-322: Apply consistent trimming to the assertion.

Same pattern as before - expected is trimmed via .trim() on line 318, but markdown is compared directly without trimming.

♻️ Suggested fix
     let markdown = htmd::HtmlToMarkdown::new().convert(html).unwrap();
 
-    assert_eq!(expected, markdown);
+    assert_eq!(expected, markdown.trim());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/table_tests.rs` around lines 319 - 322, The test compares a trimmed
`expected` but not the produced `markdown`, causing inconsistent whitespace
handling; update the assertion in tests/table_tests.rs to trim `markdown` as
well (e.g., compare `expected.trim()` to `markdown.trim()`) so both sides use
the same normalization after calling
`htmd::HtmlToMarkdown::new().convert(html).unwrap()`; adjust the `assert_eq!`
that currently references `expected` and `markdown` to use the trimmed
`markdown` value.

358-361: Apply consistent trimming.

Same recommendation as previous tests.

♻️ Suggested fix
     let markdown = htmd::HtmlToMarkdown::new().convert(html).unwrap();
 
-    assert_eq!(expected, markdown);
+    assert_eq!(expected, markdown.trim());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/table_tests.rs` around lines 358 - 361, The test currently compares
expected to the raw markdown produced by
HtmlToMarkdown::new().convert(html).unwrap() which can fail on incidental
surrounding whitespace; update the assertion to perform consistent trimming
(e.g., call .trim() on the produced markdown or both sides) before assert_eq! so
the comparison ignores leading/trailing whitespace differences—locate the
markdown variable produced by HtmlToMarkdown::new().convert(...) and the
expected variable and apply .trim() consistently prior to the assert_eq!.

403-406: Apply consistent trimming.

Same recommendation. Consider standardizing all new tests to follow the existing pattern of trimming results before comparison.

♻️ Suggested fix
     let markdown = htmd::HtmlToMarkdown::new().convert(html).unwrap();
 
-    assert_eq!(expected, markdown);
+    assert_eq!(expected, markdown.trim());
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/table_tests.rs` around lines 403 - 406, The test compares the converted
Markdown in variable markdown to expected without trimming; update the assertion
to normalize whitespace by trimming both sides before comparison (e.g., call
.trim() on markdown and expected in the assert_eq!), locating the conversion
call HtmlToMarkdown::new().convert(...) and the assert_eq!(expected, markdown)
and change that assertion to compare expected.trim() and markdown.trim() so the
test follows the project's existing trimming pattern.
src/element_handler/table.rs (2)

187-209: Consider adding a doc comment for clarity.

The function's purpose and the is_root semantics (why nested tables are skipped) may not be immediately obvious to future readers.

📝 Suggested documentation
+/// Returns `true` if the table subtree contains any `<th>` elements,
+/// excluding those inside nested `<table>` elements.
 fn has_explicit_headers(node: &Rc<markup5ever_rcdom::Node>) -> bool {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/element_handler/table.rs` around lines 187 - 209, Add a doc comment above
has_explicit_headers explaining its purpose (to detect whether a table subtree
contains any explicit header cells <th>), and document the inner visit helper's
is_root flag semantics: that is_root==true allows searching the current table
only while nested tables found during traversal are skipped (is_root prevents
descending into nested table elements) to avoid false positives from nested
table headers; mention that the function returns true if any <th> is found in
the target table subtree. Reference the functions has_explicit_headers and its
inner visit to locate where to place the comment.

211-222: Consider adding a doc comment for consistency.

Similar to has_explicit_headers, a brief doc comment would clarify the function's role in detecting nested tables.

📝 Suggested documentation
+/// Returns `true` if the node is nested inside a `<td>` or `<th>` element.
 fn is_inside_table_cell(node: &Rc<markup5ever_rcdom::Node>) -> bool {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/element_handler/table.rs` around lines 211 - 222, Add a short doc comment
above the is_inside_table_cell function explaining its purpose (e.g., "Returns
true if the given node is inside a table cell (td or th) by walking parent
nodes"), mirroring the style and tone used for has_explicit_headers; mention
that it walks up parent nodes and checks for "td" or "th" to clarify intent for
future readers and maintain consistency.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/element_handler/table.rs`:
- Around line 187-209: Add a doc comment above has_explicit_headers explaining
its purpose (to detect whether a table subtree contains any explicit header
cells <th>), and document the inner visit helper's is_root flag semantics: that
is_root==true allows searching the current table only while nested tables found
during traversal are skipped (is_root prevents descending into nested table
elements) to avoid false positives from nested table headers; mention that the
function returns true if any <th> is found in the target table subtree.
Reference the functions has_explicit_headers and its inner visit to locate where
to place the comment.
- Around line 211-222: Add a short doc comment above the is_inside_table_cell
function explaining its purpose (e.g., "Returns true if the given node is inside
a table cell (td or th) by walking parent nodes"), mirroring the style and tone
used for has_explicit_headers; mention that it walks up parent nodes and checks
for "td" or "th" to clarify intent for future readers and maintain consistency.

In `@tests/table_tests.rs`:
- Around line 279-283: The test compares the converted markdown directly but
other tests trim whitespace before asserting; update this test to trim the
conversion result for consistency by applying .trim() to the value returned from
htmd::HtmlToMarkdown::new().convert(html).unwrap() (the variable named markdown)
and use that trimmed string in the assert_eq! against expected so the assertion
matches the existing pattern.
- Around line 319-322: The test compares a trimmed `expected` but not the
produced `markdown`, causing inconsistent whitespace handling; update the
assertion in tests/table_tests.rs to trim `markdown` as well (e.g., compare
`expected.trim()` to `markdown.trim()`) so both sides use the same normalization
after calling `htmd::HtmlToMarkdown::new().convert(html).unwrap()`; adjust the
`assert_eq!` that currently references `expected` and `markdown` to use the
trimmed `markdown` value.
- Around line 358-361: The test currently compares expected to the raw markdown
produced by HtmlToMarkdown::new().convert(html).unwrap() which can fail on
incidental surrounding whitespace; update the assertion to perform consistent
trimming (e.g., call .trim() on the produced markdown or both sides) before
assert_eq! so the comparison ignores leading/trailing whitespace
differences—locate the markdown variable produced by
HtmlToMarkdown::new().convert(...) and the expected variable and apply .trim()
consistently prior to the assert_eq!.
- Around line 403-406: The test compares the converted Markdown in variable
markdown to expected without trimming; update the assertion to normalize
whitespace by trimming both sides before comparison (e.g., call .trim() on
markdown and expected in the assert_eq!), locating the conversion call
HtmlToMarkdown::new().convert(...) and the assert_eq!(expected, markdown) and
change that assertion to compare expected.trim() and markdown.trim() so the test
follows the project's existing trimming pattern.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c2c4d606-7227-4150-a03e-8ccbec600365

📥 Commits

Reviewing files that changed from the base of the PR and between d0300fe and e6e9513.

📒 Files selected for processing (2)
  • src/element_handler/table.rs
  • tests/table_tests.rs

@letmutex
letmutex merged commit fa72dcf into main Mar 21, 2026
1 check passed
@letmutex
letmutex deleted the fix-table-flatten-layout branch March 21, 2026 13:24
blightbow added a commit to blightbow/parkour-mcp that referenced this pull request Apr 16, 2026
Capture fresh numbers against htmd-py==0.1.2 from upstream PyPI, replacing
the pre-port markdownify-era baselines that had been accurate for `main`
but were 37-53x too generous against release/1.1's htmd-backed pipeline.

Captured on Darwin arm64 / Python 3.14.4 against live URLs.

Key deltas vs previous baseline (markdownify):

Generic-HTTP `html_to_markdown_ms`:
- small          88 ms  ->    7 ms  (~12x faster)
- medium       6936 ms  ->  202 ms  (~34x faster)
- pathological 17200 ms ->  362 ms  (~47x faster)

Generic-HTTP `md_bytes` (content recovered by htmd's layout-table handling
from letmutex/htmd#71 — the original motivation for the port):
- small           49497 ->   49222  (flat; PEP 8 is simple prose)
- medium        3137509 -> 3337080  (+6.4%; ECMA-262 has some table work)
- pathological  6337512 -> 8084502  (+27.6%; WHATWG HTML spec is
                                     table-heavy, largest content gain)

The pathological content recovery (+1.75 MB) is the concrete evidence that
the htmd port fixes the silent-truncation class of failure that motivated
the work. The new `test_html_to_markdown_output_size` tripwire guards
against regression at 0.75x of these floors (c00bc15).

Splitter regressions:
- medium        1236 ms -> 1859 ms  (+50%, expected per da4f54a port
                                      commit — htmd emits pretty-printed
                                      tables that cost more at chunk
                                      boundaries)

Splitter improvement:
- pathological  6477 ms -> 4260 ms  (-34%; likely fewer bad chunk
                                      boundaries with the larger but
                                      more table-aligned output, though
                                      single-shot variance is plausible
                                      at this magnitude)

Fast-path end_to_end_ms: within normal network/CDN variance of the prior
capture except github_blob 73 -> 275 ms, which is most likely a cold vs
cached raw.githubusercontent.com response rather than a real regression
(73 ms was suspiciously fast for a cold fetch).

Perf suite (`uv run pytest -m perf`): 16 passed, 2 skipped. The two skips
are the sub-5ms small-tier baselines that opt out of timing assertions
to avoid timer-noise flakiness. All three tiers of the new md_bytes
tripwire pass with ~30% headroom above the 0.75x floor.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant