[bug] Preferred python-docx parser moves chapter tables to the end of the document

Author: xujiantop-cryptoCreated Sep 30, 2026Updated Sep 30, 2026

What happened

When python-docx is installed, extraction emits all top-level paragraphs first and all tables last. A table placed between Chapter 1 and Chapter 2 in Word moves beneath Chapter 2 in full_text.txt. The stdlib fallback preserves the original order for the same document.

I reproduced this using a DOCX created by the real python-docx 1.2.0 library and the unmodified CLI:

Word/source order and stdlib output:
Chapter 1: Validation
First chapter explanation.
CH1_RULE<TAB>Reject negative balances.
Chapter 2: Settlement
Second chapter explanation.
CH2_RULE<TAB>Settle accepted balances.

Preferred python-docx and CLI output:
Chapter 1: Validation
First chapter explanation.
Chapter 2: Settlement
Second chapter explanation.
CH1_RULE<TAB>Reject negative balances.
CH2_RULE<TAB>Settle accepted balances.

CLI exit code: 0
sources[0].extraction_method: python-docx
chapters_detected: 2

All the words survive and the chapter count is correct, but the relationship between a chapter and its decision table is lost.

What you expected

Paragraphs and tables should remain interleaved in document order. A Chapter 1 table must stay between its heading and the Chapter 2 heading, regardless of whether the optional dependency is installed.

Source document

  • Format: DOCX; synthetic English document generated by Document.save().
  • Pages / size: 2 chapter headings, 2 prose paragraphs and 2 one-row tables; approximately 36 KB. Pagination is not needed for this block-order defect.
  • --check: DOCX reports ready with python-docx installed.

Repro

In a checkout with python-docx available, run:

python
from docx import Document
from book_to_skill.parsers.docx import (
    extract_docx_with_python_docx,
    extract_docx_with_zipfile,
)

document = Document()
document.add_heading("Chapter 1: Validation", level=1)
document.add_paragraph("First chapter explanation.")
first = document.add_table(rows=1, cols=2)
first.cell(0, 0).text = "CH1_RULE"
first.cell(0, 1).text = "Reject negative balances."
document.add_heading("Chapter 2: Settlement", level=1)
document.add_paragraph("Second chapter explanation.")
second = document.add_table(rows=1, cols=2)
second.cell(0, 0).text = "CH2_RULE"
second.cell(0, 1).text = "Settle accepted balances."
document.save("interleaved-tables.docx")

preferred = extract_docx_with_python_docx("interleaved-tables.docx")
fallback = extract_docx_with_zipfile("interleaved-tables.docx")
print("preferred:\n" + preferred)
print("fallback:\n" + fallback)
assert preferred.index("CH1_RULE") < preferred.index("Chapter 2:")

Observed: the assertion fails (99 < 49 is false). The fallback keeps CH1_RULE before Chapter 2.

Also run:

python scripts/extract.py interleaved-tables.docx --mode text --install-missing no

The emitted full_text.txt contains the same reordering. This does not require nested tables, merged cells, malformed XML or headings inside tables.

Cause and downstream impact

docx.py:24-31 builds parts from document.paragraphs and only afterwards loops over document.tables. Those two collections discard the interleaving of the underlying document body.

The generator's Step 7 reads the corresponding chapter section from full_text.txt. For this fixture, a slice from Chapter 1 to Chapter 2 cannot include the Chapter 1 rule because extraction already moved it past that boundary. A Chapter 2 slice instead contains both chapters' rules. This is a deterministic corpus-boundary error; an actual wrong LLM summary or answer was not measured.

Installing the recommended parser therefore worsens ordering compared with the stdlib implementation, while a successful CLI exit, word counts and chapter counts do not expose the loss.

Relationship to previous fixes

#61 made the stdlib DOCX fallback reconstruct table rows in document order and explicitly left the python-docx path unchanged. #238/#239 addressed inline tabs and breaks in the fallback. This is the preferred parser's top-level paragraph/table order and is independent of those fixes.

Smallest correction and acceptance plan

Walk the top-level document body in order, emitting a paragraph or table at the position where it occurs. Document.iter_inner_content() can provide that on versions which expose it; because the dependency is currently unpinned, an equivalent ordered-element compatibility helper is another option. Keep row tab joining, cell.text semantics and the existing XML safety validation. Avoid globally replacing the preferred parser with the fallback, which would change additional fidelity behavior.

Regression coverage should include:

  1. The real two-chapter interleaved-table fixture against the preferred parser and full CLI; assert the Chapter 1 rule stays before Chapter 2.
  2. Paragraph → table → paragraph, a table before the first paragraph, consecutive tables, and paragraph-only input.
  3. Empty cells and multi-paragraph cells, to preserve existing cell/row formatting while changing block traversal.
  4. Dependency-present and dependency-absent paths, plus the existing XML safety tests. Nested-table or content-control handling can remain a separately scoped improvement.

Environment and validation limits

  • Windows 11; Python 3.12.14; python-docx 1.2.0.
  • master at c108d25b0cb58e1bdc361f3de02ed9f37075152f; pyproject.toml declares 1.4.0.
  • Unmodified full CLI reproduced the failure; a new expected-order regression fails.
  • Existing EPUB-spine and DOCX-table focused tests: 17 passed on Python 3.14.0; the two new expected-order tests fail there. Those table tests call the stdlib parser directly. The complete CLI was separately reproduced on Python 3.12.14.
  • No repository code changed, no full-suite claim, and no live-model quality claim.

Source: virgiliojr94/book-to-skill