Skip to content

fix(docx): stop long vertical merges from dropping table rows from text_as_html - #4693

Merged
cragwolfe merged 5 commits into
Unstructured-IO:mainfrom
inchang-ing:fix/docx-vmerge-html-recursion
Nov 19, 2026
Merged

cragwolfe merged 5 commits into
Unstructured-IO:mainfrom
inchang-ing:fix/docx-vmerge-html-recursion

Conversation

@inchang-ing

@inchang-ing inchang-ing commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4692

Problem

partition_docx(..., infer_table_structure=True) (the default) silently dropped cells from metadata.text_as_html when a DOCX table has a vertically merged cell spanning about 1000 or more rows. _convert_table_to_html's iter_row_cells walked row.cells, and python-docx resolves each vMerge="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 raised RecursionError. The except Exception guard 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 plain Table.text was never affected, because _iter_table_texts walks row._tr.tc_lst and skips vMerge="continue" without recursing.

Fix

Replace the row.cells walk with a hand-rolled grid walk over the row's own tc elements (row._tr.tc_lst), expanding each gridSpan and tracking the origin tc of every vertical span in a per-table dict as rows are visited top-down. A vMerge="continue" tc resolves to the tracked origin for its grid column — the same underlying tc python-docx would find by recursing upward — so the merge keys feeding collapse_matrix_of_keyed_cells_to_spans() (and the resulting colspan/rowspan geometry) are unchanged, but no recursion runs however long the merge is.

  • Malformed rows still skip their remainder via the same guard, exactly as before.
  • A 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 every continue tc. 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_text memoization by tc is untouched, so a merged cell's text is still computed once.

Testing

New regression test test_partition_docx_very_long_vertical_merge_keeps_every_row builds a 1500-row table with column 0 merged top-to-bottom (raw w:vMerge XML, since python-docx's own merge helpers walk the span with the same recursion):

  • on main (293d235): fails — the rows past ~1000 come back as <td/>, rowspan is gone
  • with this change: passes — <td rowspan="1500">MERGEDHEAD</td> plus all 1500 side-i cells

All 37 existing merge/table/text_as_html tests in test_docx.py pass unchanged (spans, nested-table dedup, rowspan-chunking geometry).

AI-assisted change.

View guided diff

Follow-up: CI lint fix (style only)

The repository-pinned ruff format --check . (ruff 0.15.10, the lint (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 with 1 file would be reformatted; after, exit 0 with 357 files already formatted. ruff check . also passes.
  • An 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).
  • 9 related regression tests in 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_origins fails on the previous head (OLD appears twice, assert 2 == 1) and passes on this head; the full test_docx.py is 223 passed on the repo venv (Python 3.12), and ruff 0.14.14 format --check and check are 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.

…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]>

@cragwolfe cragwolfe 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.

Two issues in malformed DOCX table handling need attention:

  1. Medium — A continuation after an omitted column can reuse stale text. In unstructured/partition/docx.py:634-644, vmerge_origins retains entries when a row omits a leading or trailing column. If a later row has an orphan vMerge="continue" at that position, it resolves to the older cell instead of the continuation itself. For example, a merged cell containing OLD, followed by a row with gridBefore=1, followed by a continuation containing CURRENT, emits OLD again and drops CURRENT from the HTML. Track only origins covered by the immediately preceding row, and add a gap regression test for both leading and trailing omissions.

  2. Medium — Nonpositive cell spans bypass the HTML grid budget. The new iterator expands max(tc.grid_span, 1) at docx.py:636, but _row_grid_width() charges max(count, 0) at docx.py:1254-1262. A cell with gridSpan=0 or a negative value therefore produces one matrix position while consuming none of DOCX_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]>
@inchang-ing

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review — I worked through all four points and pushed a follow-up commit to this branch.

  1. Stale vmerge_origins across a column gap — confirmed and fixed. I reproduced the case you described (merged OLD, a row with gridBefore=1, then an orphan continue carrying CURRENT); the HTML did emit OLD again and dropped CURRENT. The origin map is now pruned after each row to only the columns that row actually covered, so an orphan continue no longer resolves to an origin several rows up. Added a leading-gap regression test.

  2. Nonpositive cell spans bypassing the budget — confirmed and fixed. _row_grid_width() charged max(gridSpan, 0) while the iterator expanded max(gridSpan, 1), so a gridSpan=0/negative cell produced one grid position while consuming none of DOCX_TABLE_MAX_CELLS. Both now normalize cell spans to >=1 (leading/trailing omissions still use max(count, 0)). Added boundary tests for gridSpan=0 and a negative span.

  3. Orphan-continuation recovery contract — decided to keep this consistent with the plain-text and emphasis walkers, which skip every vMerge="continue" tc. An orphan continue (no origin in the row immediately above) now emits an empty grid position rather than its own text, so its text does not appear in text_as_html while being absent from plain text. The gap regression test asserts this explicitly (the orphan cell is empty, and the stale origin is gone).

  4. Long-merge assertion — strengthened. The test now extracts the ordered <td> values and compares the full list against side-0..side-1499, so side-1 can no longer be satisfied by side-10.

Verification: the two new regression tests fail on the previous head (2 failed) and pass after the fix (2 passed); full test_docx.py is 221 passed; ruff 0.15.10 format --check and check are clean. The commit is DCO signed-off and AI assistance is disclosed in its message.

@cragwolfe cragwolfe 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.

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]>
@inchang-ing

Copy link
Copy Markdown
Contributor Author

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 (4c33811). Origins are now pruned to the columns each row actually covered, and _row_grid_width() normalizes cell spans with max(gridSpan, 1) to match the iterator. The second review confirmed these are addressed in the current source.

Review 2 (unresolved multi-column continuation retaining a stale origin): fixed in 105ac00. When a vMerge="continue" spanning several grid columns has no origin at its starting column, the iterator now clears the origin for every column it covers before emitting blanks. Previously the end-of-row pruning only removed origins for columns the row did not cover — the opposite set for a spanned cell — so a later orphan continuation in a covered column resolved to text several rows up. Added a three-row regression (test_partition_docx_unresolved_spanned_continuation_clears_stale_origins): it fails on 4c33811 (OLD appears twice) and passes on 105ac00 (once).

Test details: the long-merge test already compares the exact ordered side-cell values (not substrings); the nonpositive-gridSpan test now selects w:gridSpan by qualified name and asserts its value before mutating it.

Compatibility contract: the current behavior is that an orphan vMerge="continue" with no origin emits an empty grid position, staying consistent with the plain-text and emphasis walkers (which skip every continue cell); its own text is not surfaced. This is deliberate, but it is a behavior change for malformed input — flagging it explicitly for a maintainer decision on whether empty-position is the desired contract.

Verification on 105ac00: new test red-before/green-after shown, full test_docx.py 222 passed, ruff format/check clean.

@cragwolfe cragwolfe 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.

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.
@inchang-ing

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. Addressed the code items in sequence:

  1. Omitted-column stale text and the nonpositive-gridSpan budget mismatch (first review) were fixed in the earlier head; the budget now normalizes spans to >=1 in both the iterator and _row_grid_width, and the negative-span test selects w:gridSpan by qualified name rather than by child index.

  2. The unresolved multi-column continuation leaving a stale origin (second review) was fixed in the previous head: an unresolved spanned continuation now clears the origin of every column it covers before emitting blanks.

  3. The resolved multi-column continuation case (third review) is fixed in this head. A vMerge="continue" spanning several columns whose starting column has an origin now records that origin for all covered columns, not just the starting one, so a later orphan continuation cannot resolve back to stale text. A three-row regression asserts the old text appears once; it fails on the previous head (twice) and passes here. Full test_docx.py: 223 passed; ruff format/check clean.

On the two open decisions: the malformed orphan-continuation compatibility contract (whether its text should appear in text_as_html) I am leaving to maintainers rather than deciding unilaterally; the current behavior emits an empty position to stay consistent with the plain-text and emphasis walkers. The exact-head CI, security, CodeQL and partition-benchmark checks requiring approval should see the new head in this pull request now that the fix is pushed.

All changes are on branch fix/docx-vmerge-html-recursion. AI-assisted, disclosed per repo policy.

@cragwolfe cragwolfe 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.

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 cragwolfe 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.

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)

@inchang-ing

Copy link
Copy Markdown
Contributor Author

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 gridAfter/zero-span budget counterpart. Both are test/comment-level clarity improvements; I don't want to reset the approval and the full CI matrix over them. Happy to fold them in if you'd prefer them here.

@cragwolfe
cragwolfe added this pull request to the merge queue Nov 19, 2026
Merged via the queue into Unstructured-IO:main with commit 1ab3be8 Nov 19, 2026
54 checks passed
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.

bug/partition-docx-vmerge-table-html-recursion

2 participants