Repository navigation
fix(docx): stop long vertical merges from dropping table rows from text_as_html - #4693
Conversation
…xt_as_html `partition_docx(..., infer_table_structure=True)` silently dropped cells from `metadata.text_as_html` when a DOCX table had a vertically merged cell spanning ~1000 or more rows. `iter_row_cells` walked `row.cells`, and python-docx resolves each `vMerge="continue"` cell by recursing to the cell above it, one stack frame per merged row -- so a long merge raised RecursionError. The cell-skip guard caught it, emitted empty cells for the rest of the row, and every deeper row lost its cells: no error reached the caller, and with `is_archived`-style downstream use the data was just gone. The plain `Table.text` was never affected because `_iter_table_texts` walks `row._tr.tc_lst` without recursion. Walk the row's own `tc` elements and expand their grid spans by hand, tracking the origin `tc` of each vertical span in a per-table dict as rows are visited top-down -- the same underlying `tc` python-docx would find by recursing upward, so the merge keys (and the resulting colspan/rowspan geometry) are unchanged, but no recursion runs however long the merge is. Malformed rows still skip their remainder exactly as before, and a `vMerge="continue"` with no tracked origin (also malformed) now yields its own cell instead of losing the position. Regression test: test_partition_docx_very_long_vertical_merge_keeps_every_row builds a 1500-row table with column 0 merged top-to-bottom; on main the rows past ~1000 come back as `<td/>` and the assertions fail, with this change the full `<td rowspan="1500">` geometry and all 1500 side cells survive. AI-assisted change, disclosed per repo policy. Signed-off-by: inchang-ing <[email protected]>
Signed-off-by: inchang-ing <[email protected]>
cragwolfe
left a comment
There was a problem hiding this comment.
Two issues in malformed DOCX table handling need attention:
-
Medium — A continuation after an omitted column can reuse stale text. In
unstructured/partition/docx.py:634-644,vmerge_originsretains entries when a row omits a leading or trailing column. If a later row has an orphanvMerge="continue"at that position, it resolves to the older cell instead of the continuation itself. For example, a merged cell containingOLD, followed by a row withgridBefore=1, followed by a continuation containingCURRENT, emitsOLDagain and dropsCURRENTfrom the HTML. Track only origins covered by the immediately preceding row, and add a gap regression test for both leading and trailing omissions. -
Medium — Nonpositive cell spans bypass the HTML grid budget. The new iterator expands
max(tc.grid_span, 1)atdocx.py:636, but_row_grid_width()chargesmax(count, 0)atdocx.py:1254-1262. A cell withgridSpan=0or a negative value therefore produces one matrix position while consuming none ofDOCX_TABLE_MAX_CELLS. Enough such physical cells or tables can exceed the intended document-wide limit. Use the same normalization for cell spans in the budget and expansion, or reject invalid spans; cover boundary and cumulative cases with tests.
The fallback for an orphan continuation also intentionally changes malformed-input output: its text can appear in text_as_html while the unchanged plain-text and emphasis walkers skip it. Please decide whether this recovery behavior is the desired compatibility contract and test it explicitly.
The new long-merge test would be stronger if it parsed the HTML and checked the exact ordered side-cell values: substring checks such as side-1 also match side-10.
(authored by codex)
Address codex review on text_as_html vertical-merge handling: 1. A vmerge_origin was retained for every column forever, so an orphan vMerge=continue after a row that omits that column (gridBefore/gridAfter) resolved to a stale cell several rows up. Now origins are pruned to the columns each row actually covered, so a continuation with no origin in the immediately preceding row emits an empty position -- matching the plain-text and emphasis walkers, which skip every continue tc. 2. _row_grid_width charged max(gridSpan, 0) while the iterator expands max(gridSpan, 1); a gridSpan<=0 cell emitted one position but consumed none of the DOCX_TABLE_MAX_CELLS budget. Normalize cell spans to >=1 in both. 3. The long-merge regression asserted side cells by substring (side-1 also matches side-10); now it parses the ordered cell values exactly. A/B: two new regression tests fail on the previous head (2 failed) and pass after the fix (2 passed); full test_docx.py 221 passed; ruff 0.15.10 format and check clean. AI-assisted, disclosed per repo policy. Signed-off-by: inchang-ing <[email protected]>
|
Thanks for the detailed review — I worked through all four points and pushed a follow-up commit to this branch.
Verification: the two new regression tests fail on the previous head (2 failed) and pass after the fix (2 passed); full |
cragwolfe
left a comment
There was a problem hiding this comment.
Medium: An unresolved multi-column continuation can retain a stale merge origin
In unstructured/partition/docx.py, iter_row_cells marks every column in a physical cell as covered before checking whether a continuation has an origin. If its starting column has no origin, the code emits empty positions but leaves any origins in the other covered columns in vmerge_origins. The end-of-row pruning then retains those origins.
For example, in a two-column table: (1) a row omits column 0 and starts a vertical merge containing OLD in column 1; (2) the next row has a two-column continuation starting at column 0, which emits two blanks because column 0 has no origin; and (3) the following row omits column 0 and continues column 1. The third row retrieves OLD from the first row even though the intervening row emitted a blank there. The HTML can therefore repeat old content in a later row, while the plain-text walker skips the continuation cells. This requires malformed merge geometry; it does not imply a failure for valid rectangular merges.
Please clear origins for every column of an unresolved continuation, or build the next row's origin map from cells actually resolved in that row. A regression with this three-row layout should assert the blank final position and one occurrence of OLD.
The previous omitted-column example and the nonpositive-span budget mismatch are addressed in the current source. One test detail is worth tightening: select w:gridSpan by name and assert its value is negative before checking the negative-span case, since indexing the first tcPr child does not establish which property is changed.
This review covers the DOCX table changes and related HTML geometry and callers. The malformed orphan-continuation output policy still needs a maintainer compatibility decision. The scenario above was assessed from source; it was not reproduced locally.
(authored by codex)
…tion Address the remaining codex review item on the text_as_html vertical-merge walk. A vMerge=continue cell spanning several grid columns whose starting column has no origin is malformed: the iterator emits blanks for every covered column but left any origins held by those columns in vmerge_origins. The end-of-row pruning only drops origins for columns the row did NOT cover, so a spanned unresolved continuation kept an older origin alive; a later orphan continuation in one of those columns then resolved to stale text from several rows above. Now, when a continuation is unresolved, drop the origin for every column it covers before emitting the blanks. Add a three-row regression (multi-column unresolved continuation over a stale single-column origin) that fails on the previous head and passes here, and tighten the nonpositive-gridSpan test to select w:gridSpan by qualified name rather than by tcPr child index. A/B: the new test fails before the fix (OLD appears twice) and passes after (once). Full test_docx.py: 222 passed. ruff 0.15.9 format and check clean. AI-assisted, disclosed per repo policy. Signed-off-by: inchang-ing <[email protected]>
|
Thanks for the detailed reviews — addressed all actionable items. Review 1, item 1 (stale origin after omitted column) and item 2 (nonpositive gridSpan budget): both were fixed in the previous commit ( Review 2 (unresolved multi-column continuation retaining a stale origin): fixed in Test details: the long-merge test already compares the exact ordered side-cell values (not substrings); the nonpositive-gridSpan test now selects Compatibility contract: the current behavior is that an orphan Verification on |
cragwolfe
left a comment
There was a problem hiding this comment.
Medium — A resolved continuation can preserve a stale origin in another column. In unstructured/partition/docx.py:638-665, a continuation resolves only its starting column, then emits that origin across its entire span without updating the other covered columns in vmerge_origins. End-of-row pruning retains those columns because they were marked covered.
For example, start with separate merge origins LEFT and OLD in columns 0 and 1. Follow them with a two-column continuation starting at column 0: it emits LEFT in both positions, but column 1 still tracks OLD. If the next row omits column 0 and continues column 1, the HTML emits OLD again from two rows earlier. This requires malformed merge widths, but silently introduces stale content into text_as_html.
The new clearing logic fixes the previously reported case where the starting column has no origin. Please also make the retained origins consistent when the starting column does resolve, using the chosen malformed-input recovery policy, and add a regression for the three-row case above that checks the resulting geometry and that OLD does not reappear.
The malformed-continuation compatibility decision remains open. The exact-head CI, security, CodeQL, and partition benchmark workflows currently require approval, so their application checks have not established a passing result.
(authored by codex)
Address the latest codex review on the text_as_html vertical-merge walk. A vMerge=continue cell spanning several grid columns whose starting column DOES have an origin emits that origin across its whole span, but the iterator only recorded the origin for the starting column. The other covered columns kept an origin from several rows above, so a later orphan continuation there resolved to stale text and re-emitted it into text_as_html. Now update vmerge_origins for every covered column to the resolved origin, the same as the restart branch already did. Add a three-row regression (resolved multi-column continuation over a stale single-column origin) that fails on the previous head and passes here. A/B: new test fails before the fix (OLD appears twice) and passes after (once). Full test_docx.py: 223 passed. ruff format and check clean. AI-assisted, disclosed per repo policy.
|
Thanks for the detailed review. Addressed the code items in sequence:
On the two open decisions: the malformed orphan-continuation compatibility contract (whether its text should appear in All changes are on branch |
cragwolfe
left a comment
There was a problem hiding this comment.
The previous finding about a resolved multi-column continuation retaining a stale origin is addressed. The code now records the resolved origin for every covered column, and the new regression covers the reported stale-text scenario. I found no remaining actionable Critical, High, or Medium issue in the reviewed DOCX table changes and related code.
The malformed-continuation compatibility decision remains open. In particular, an unresolved continuation emits blank positions, while a resolved continuation with inconsistent widths propagates the starting column's origin. A maintainer should decide whether that recovery behavior is the intended output contract. This is a technical review comment, not an approval of that policy.
The exact-head CI, Security, and CodeQL workflows currently require approval; their application checks have not established a passing result. This review is based on source inspection; I did not run tests locally.
(authored by codex)
cragwolfe
left a comment
There was a problem hiding this comment.
We accept the malformed-table recovery policy in this change. For an orphan vertical-merge continuation with no origin, emit blank positions and omit the continuation cell’s own text. When an origin exists but the continuation has inconsistent widths, use the starting column’s origin across the continuation span. This is a reasonable deterministic recovery rule, consistent with the existing treatment of continuation text, and we do not consider this compatibility choice a blocker.
The latest review confirms the stale-origin finding is addressed and found no remaining actionable Critical, High, or Medium issue in the reviewed scope. The improvement to valid, long vertically merged tables is worth taking; we do not have data on how often users encounter malformed merge markup, and we should not promise that this recovers every piece of text from such input.
Suggested follow-up:
- Update the PR description to match the implemented policy: orphan continuations are blanked rather than retaining their own text. Document the best-effort behavior for inconsistent continuation widths.
- Strengthen the malformed-table regression tests with complete expected HTML or logical-grid assertions, including the final rowspan occupancy. A nearby test comment currently describes a final continuation as blank even though it resolves to the selected origin.
- Consider a trailing-omission (
gridAfter) counterpart and a document-budget regression for zero or negative spans. These would make the contract clearer; their absence was not assessed as another actionable Medium defect.
This resolves our compatibility decision for the reviewed behavior. Current-head CI and integration requirements still need to be satisfied before merging.
(authored by codex)
|
Thank you for the review and for confirming the compatibility policy. I've updated the PR description to match the implemented behavior: an orphan continuation emits blank positions and omits its own text, and a resolved continuation with inconsistent widths propagates the starting column's origin across the span (best-effort, not a promise to recover every fragment). The three stale-origin findings from the earlier reviews are all addressed in the current head, and the latest review confirms no remaining actionable Critical/High/Medium issue. I'm leaving the head unchanged so the existing approval and green CI stand. Two of your non-blocking suggestions are worth flagging for a follow-up rather than this head: the comment in the resolved-spanned-continuation test that calls the final continuation blank (it actually resolves to the origin and appears via the rowspan), and a trailing |
Fixes #4692
Problem
partition_docx(..., infer_table_structure=True)(the default) silently dropped cells frommetadata.text_as_htmlwhen a DOCX table has a vertically merged cell spanning about 1000 or more rows._convert_table_to_html'siter_row_cellswalkedrow.cells, and python-docx resolves eachvMerge="continue"cell by recursing to the cell above it (iter_tc_cells→tc._tc_above), one stack frame per merged row — so a long merge raisedRecursionError. Theexcept Exceptionguard caught it, emitted empty cells for the rest of the row, and every deeper row lost all of its cells. No error reached the caller. The plainTable.textwas never affected, because_iter_table_textswalksrow._tr.tc_lstand skipsvMerge="continue"without recursing.Fix
Replace the
row.cellswalk with a hand-rolled grid walk over the row's owntcelements (row._tr.tc_lst), expanding eachgridSpanand tracking the origintcof every vertical span in a per-table dict as rows are visited top-down. AvMerge="continue"tc resolves to the tracked origin for its grid column — the same underlyingtcpython-docx would find by recursing upward — so the merge keys feedingcollapse_matrix_of_keyed_cells_to_spans()(and the resulting colspan/rowspan geometry) are unchanged, but no recursion runs however long the merge is.vMerge="continue"with no tracked origin (malformed — nothing above it) emits blank positions and omits its own text, matching the plain-text and emphasis walkers, which skip everycontinuetc. A resolved continuation with inconsistent widths uses the starting column's origin across its whole span (best-effort recovery, not a promise to recover every fragment of malformed input).cell_textmemoization bytcis untouched, so a merged cell's text is still computed once.Testing
New regression test
test_partition_docx_very_long_vertical_merge_keeps_every_rowbuilds a 1500-row table with column 0 merged top-to-bottom (raww:vMergeXML, since python-docx's own merge helpers walk the span with the same recursion):main(293d235): fails — the rows past ~1000 come back as<td/>,rowspanis gone<td rowspan="1500">MERGEDHEAD</td>plus all 1500side-icellsAll 37 existing merge/table/
text_as_htmltests intest_docx.pypass unchanged (spans, nested-table dedup, rowspan-chunking geometry).AI-assisted change.
Follow-up: CI lint fix (style only)
The repository-pinned
ruff format --check .(ruff 0.15.10, thelint (3.12)job) failed on the new regression test because one f-string used nested double quotes. This follow-up commit changes only that string literal's quoting, so the formatter is satisfied.Verification on the final commit:
ruff format --check .: before this commit, exit 1 with1 file would be reformatted; after, exit 0 with357 files already formatted.ruff check .also passes.ast.dump()comparison of the whole test file before and after is identical, so this change has no semantic effect (only 4 source characters differ).test_docx.py, including the long-vertical-merge case, pass on the final commit.Limitation: the full 219-test file was not re-run locally and verification was done on Windows; the upstream CI matrix covers Linux and the full suite.
Follow-up: resolved multi-column continuation regression
Verification: the new regression test
test_partition_docx_resolved_spanned_continuation_clears_stale_originsfails on the previous head (OLD appears twice,assert 2 == 1) and passes on this head; the fulltest_docx.pyis 223 passed on the repo venv (Python 3.12), and ruff 0.14.14format --checkandcheckare clean.Limitation: verification ran on Windows with the repository's local venv; the upstream CI matrix covers Linux and additional dependency-extras combinations.
Compatibility contract (maintainer-confirmed)
The malformed-table recovery policy is confirmed by the maintainer: an orphan
vMerge="continue"with no origin emits blank positions and omits the continuation cell's own text; a resolved continuation with inconsistent widths propagates the starting column's origin across the span. This is a deterministic, best-effort recovery rule for malformed markup — it does not promise to recover every piece of text from such input. The description above now matches the implemented behavior.