DOCX table rows with `w:gridBefore` are silently truncated (cells dropped)
Bug
When a Word table contains a row that "starts late", i.e. it has <w:gridBefore w:val="N"/> (Word writes this when leading cells are deleted or merged away), MsWordDocumentBackend drops cells from the table and, in the worst case, aborts parsing the rest of the table.
The failure is an IndexError that is caught and logged only at DEBUG in _walk_linear:
# docling/backend/msword_backend.py
if tag_name == "tbl":
try:
t = self._handle_tables(element, doc)
added_elements.extend(t)
except Exception:
_log.debug("could not parse a table, broken docx table") # <- swallowed
Root cause
python-docx _Row.cells returns only the cells actually present in a row (its own docstring: "Only cells actually present are included in the return value"), so a gridBefore row yields a shorter tuple, indexed from 0.
The vertical-merge scan in _handle_tables reuses the current row's positional col_idx to index into a later row:
# docling/backend/msword_backend.py (~line 2119)
spanned_idx = row_idx
spanned_tc: CT_Tc | None = cell._tc
while spanned_tc == cell._tc:
spanned_idx += 1
spanned_tc = (
table.rows[spanned_idx].cells[col_idx]._tc # <- IndexError if later row is shorter
if spanned_idx < num_rows
else None
)
When the later row is shorter than col_idx + 1 (a gridBefore/gridAfter row, or any short row), table.rows[spanned_idx].cells[col_idx] raises IndexError: tuple index out of range.
There is a second, related defect in the same function: grid_cols_before (a column count) is added to row_idx and used as a row offset and in the header test:
start_row_offset_idx=row.grid_cols_before + row_idx,
end_row_offset_idx=row.grid_cols_before + spanned_idx,
column_header=row.grid_cols_before + row_idx == 0,
So even when it doesn't crash, a late-starting row's cells are shifted down into the wrong grid row (and mislabeled as non-headers) instead of right into the correct grid column.
To reproduce
Input table
import logging
from pathlib import Path
from docx import Document
from docx.oxml.ns import qn
from docling.document_converter import DocumentConverter
DOCX = Path("gridbefore.docx")
# build a 2x2 table whose 2nd row starts late (gridBefore=1)
# grid col: 0 1
# row 0: [A1] [B1]
# row 1: X [B2] <- gridBefore=1
doc = Document()
table = doc.add_table(rows=2, cols=2)
table.style = "Table Grid"
for (r, c), txt in {(0, 0): "A1", (0, 1): "B1",
(1, 0): "A2", (1, 1): "B2"}.items():
table.cell(r, c).text = txt
tr = table.rows[1]._tr
tr.get_or_add_trPr().append(tr.makeelement(qn("w:gridBefore"), {qn("w:val"): "1"}))
tr.remove(tr.findall(qn("w:tc"))[0]) # drop leading cell -> row starts late
doc.save(DOCX)
# Convert
logging.getLogger("docling.backend.msword_backend").setLevel(logging.DEBUG)
logging.basicConfig(level=logging.DEBUG)
md = DocumentConverter().convert(DOCX).document.export_to_markdown()
print(md)
Actual output
| A1 | |
|------|----|
| | |
and, only at DEBUG level:
DEBUG docling.backend.msword_backend: could not parse a table, broken docx table
Cells A2, B1, B2 are silently dropped.
Expected output
All four cells preserved, e.g.:
| A1 | B1 |
|----|----|
| | B2 |
Environment
- docling: 2.107.0
- python-docx: 1.2.0
- Python: 3.13.6
Thanks for the detailed bug report, @DanielNg0729. I can confirm both issues you've identified in the code.
Issue 1 — IndexError in vertical merge scan: The vertical merge scan at line ~2119 uses table.rows[spanned_idx].cells[col_idx] without bounds-checking col_idx against the target row's cell count. Interestingly, a similar IndexError was fixed in December 2025 for the main column iteration loop [1]:
# Handle merged cells: row may have fewer cells than num_cols
if col_idx >= len(row.cells):
break
…but the vertical merge scan was not updated with the same defensive check. An analogous guard (e.g. checking col_idx < len(table.rows[spanned_idx].cells)) would be needed in the while loop as well.
Issue 2 — grid_cols_before misused as a row offset: You're correct that grid_cols_before (a column count) is incorrectly added to row_idx in start_row_offset_idx, end_row_offset_idx, and the column_header check [2]. It should instead be applied to the column offset (e.g. start_col_offset_idx = row.grid_cols_before + col_idx), shifting cells right in the grid rather than down.
No existing issues or PRs cover this specific gridBefore scenario — this is a new report. That said, merged-cell handling has been a recurring pain point across backends (there are related open issues for Excel and PDF table merging as well).
To reply, just mention @dosu.
Share context across your team and agents. Try Dosu.
Hi maintainers, I'd like to work on this. Here's the approach I'm planning
I would stop iterating positional row.cells and instead build a grid matrix keyed by real layout-grid coordinates, then derive every offset/span from those coordinates. row.cells already expands grid_span (one entry per grid column) and resolves vMerge="continue" to the root cell's _tc, so the matrix is cheap to build. This makes gridBefore/gridAfter positions render as genuinely empty grid slots (which is what Word does) instead of crashing or shifting content, and it drops the fragile "scan later rows for the same _tc" logic entirely. Happy to adjust before I open a PR. Thank you very much!
Thanks for the precise root-cause breakdown — the grid-matrix approach (keying by real layout-grid coordinates instead of reusing positional col_idx against a shorter tuple) is the right fix, since row.cells already expands grid_span/resolves vMerge to root _tc, so deriving offsets from a true grid representation is both cheap and correct.
Adding a regulated-corpus angle on why the failure mode matters as much as the crash:
1. gridBefore/gridAfter rows are the default shape of operative legal tables, not an edge case. Fee schedules, penalty matrices, amendment comparison tables, and signature blocks routinely have leading cells merged/deleted away — that's literally what Word emits w:gridBefore for. A "Section 2(c) amendment" table where the first column was merged into a section header is exactly the kind of table whose cells (per-row fee % / penalty / effective date) are operative numeric content. So "broken docx table" is hitting the highest-value content type by default.
2. The swallowed IndexError at _log.debug is the genuinely dangerous part, and it's a new instance of a recurring class. The catch-and-swallow means the entire table aborts, but parsing continues for the rest of the document — so the pipeline returns success while a whole fee schedule is absent from the output, with no signal visible at default log levels. A partner querying "what's the late-delivery penalty in Schedule B" gets a confident refusal or a plausible number reconstructed from adjacent prose, indistinguishable from a correct answer. This is the same boundary-asymmetry signature as #3473 (TextItems exist in texts[] with valid prov.bbox but never reach body.children) and #3713 (table content absorbed into a PICTURE region): content survives the upstream model but vanishes at the export/serialization boundary, no degradation signal, JSON consumer and markdown consumer see different documents.
3. Defect #2 (cells shifted down into the wrong grid row instead of right into the correct column) is silently worse than the crash. The crash at least drops the table (binary: present/absent). The shift produces a structurally valid table where every cell is a real extracted value — but bound to the wrong row/column. For a penalty matrix that means a fee amount attached to the wrong line item, or an effective date attached to the wrong clause. Retrieval then embeds plausible-but-wrong row→value bindings that look more trustworthy than a gap, not less. The grid-matrix fix closes this half too (the crash and the shift share the same positional-indexing root cause), which is good — but it's worth calling out that the silent-shift is the higher-severity failure of the two for any downstream RAG.
Cheap orthogonal companion (separable PR): when the except Exception branch fires, surface a per-table coverage signal — e.g. an HTML comment <!-- table parse aborted: N rows dropped --> in the markdown, or a JSON field {tables_expected, tables_emitted, parse_aborted: true} — instead of logging only at DEBUG. This converts "silently incomplete, looks complete" into "incomplete but flagged," which is the difference between an operator who can detect the gap and one who ships a contract review built on a missing fee schedule. The crash fix closes correctness; a coverage signal closes discoverability.
Can confirm the "any short row" part — this reproduces without gridBefore at all. Any row whose grid width is smaller than the table's (Word writes these when trailing cells get merged or deleted) crashes the vMerge scan the same way, and the blanket except silently truncates the table with nothing in the logs above DEBUG.
Repro on 2.110.0:
from pathlib import Path
from docx import Document
from docx.oxml.ns import qn
from docling.document_converter import DocumentConverter
OUT = Path("short_row.docx")
doc = Document()
table = doc.add_table(rows=3, cols=3)
table.style = "Table Grid"
for r in range(3):
for c in range(3):
table.cell(r, c).text = f"{'ABC'[c]}{r + 1}"
tr = table.rows[2]._tr
tr.remove(tr.findall(qn("w:tc"))[-1]) # last row grid width 2 < 3
doc.save(OUT)
print(DocumentConverter().convert(OUT).document.export_to_markdown())
Output:
| A1 | B1 | C1 |
|------|------|------|
| A2 | B2 | |
| | | |
The short row is dropped entirely, and note C2 is empty too — the scan crashes while processing that cell, so it never gets added.
A bounds check on col_idx in the scan (and col_idx < len(table.rows[spanned_idx].cells)) fixes the crash, but not the grid_cols_before placement problem, so +1 to the grid approach in #3745.