Skip to content

IndexError: pop from empty list in read_fld_char on unmatched w:fldChar end/separate #168

Closed

Description

@pramodavansaber

Description

mammoth.convert_to_html (and any other entry point that exercises body_xml.read_fld_char) crashes with IndexError: pop from empty list when it encounters a <w:fldChar w:fldCharType="end"/> (or "separate") that has no matching prior "begin" element.

The root cause is in mammoth/docx/body_xml.py:

def read_fld_char(element):
    fld_char_type = element.attributes.get("w:fldCharType")
    if fld_char_type == "begin":
        complex_field_stack.append(...)
        ...
    elif fld_char_type == "end":
        complex_field = complex_field_stack.pop()      # <-- line 206
        ...
    elif fld_char_type == "separate":
        complex_field_separate = complex_field_stack.pop()  # <-- line 214
        ...

Both .pop() calls assume the stack is non-empty, which is true for well-formed documents but not guaranteed for arbitrary input. A document whose first fldChar is end (or separate) — for example produced by a buggy DOCX generator, hand-edited, recovered from a partially corrupted file, or carved out of a larger document — leaks IndexError to the caller.

This is similar in shape to #158 ('w:ilvl' when parsing malformed docx numbering), which you accepted and fixed by hardening the malformed-input path.

Reproduction

Minimal standalone repro (no template needed — builds the .docx in memory):

import io, zipfile, mammoth

DOCUMENT_XML = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    <w:p>
      <w:r><w:fldChar w:fldCharType="end"/></w:r>
      <w:r><w:t>Hello</w:t></w:r>
    </w:p>
  </w:body>
</w:document>"""

CONTENT_TYPES_XML = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  <Default Extension="xml" ContentType="application/xml"/>
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>"""

PACKAGE_RELS = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>"""

buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
    z.writestr("[Content_Types].xml", CONTENT_TYPES_XML)
    z.writestr("_rels/.rels", PACKAGE_RELS)
    z.writestr("word/document.xml", DOCUMENT_XML)
buf.seek(0)
mammoth.convert_to_html(buf)

Traceback (HEAD as of 2026-05-24, commit on master):

  File ".../mammoth/docx/body_xml.py", line 206, in read_fld_char
    complex_field = complex_field_stack.pop()
IndexError: pop from empty list

Switching the fldCharType in the repro to "separate" hits the matching crash on line 214.

Suggested fix

Guard both pops:

elif fld_char_type == "end":
    if not complex_field_stack:
        return _empty_result
    complex_field = complex_field_stack.pop()
    ...
elif fld_char_type == "separate":
    if not complex_field_stack:
        return _empty_result
    complex_field_separate = complex_field_stack.pop()
    ...

Happy to send a PR if useful.

Context

Found by tailtest, an adversarial test generator I'm building. Filing on behalf of the run; the issue is reproduced and confirmed independently against current master.

Activity

  1. andy-lh-nz commented on Aug 12, 2026

    @andy-lh-nz

    Corroborating this from production — we hit it on real customer documents, not synthetic input.

    Fourteen distinct documents from unrelated customers failed this way in the space of a few weeks: legal contracts and letters in daily use, including one firm's reusable blank template. Via markitdown it surfaces as:

    FileConversionException: File conversion failed after 1 attempts:
     - DocxConverter threw IndexError with message: pop from empty list
    

    The recurring shape is a complex field whose begin fldChar is missing while its instrText runs survive. The orphan markers were always in plain runs — never inside w:del or an mc:Fallback branch, so this isn't a tracked-changes or markup-compatibility artifact. Contexts included IF fields in letterhead signature blocks, DOCPROPERTY merge templates, and nested REF/PAGEREF in tables of contents, spanning several unrelated document-automation systems.

    Reproducer, and what Word does with the same file, in the comment below.

  2. mwilliamson commented on Aug 12, 2026

    @mwilliamson
    Owner

    It would be useful to have any minimal example documents that have been produced by Word.

  3. andy-lh-nz commented on Aug 13, 2026

    @andy-lh-nz

    Reproducer

    Unfortunately we've yet to reproduce this from a pure Word experiment. This reproducer builds a docx that Word reads and renders fine and which is functionally equivalent to the documents we're seeing (of unknown source). It's self-contained (builds the .docx in memory). Triggers both crash sites in one file: orphan separate (line 214) as well as orphan end (line 206).

    """Minimal .docx reproducing python-mammoth#168."""
    
    import io
    import zipfile
    
    import mammoth
    
    W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
    
    # 1. Orphan "separate": the field lost its "begin" but kept its instrText runs.
    # 2. Orphan "end" followed by a well-formed field.
    # 3. Nested well-formed fields, then an orphan "end".
    # 4. A well-formed field on its own, to show normal handling is unaffected.
    BODY = """
      <w:p>
        <w:r><w:t>Paragraph one.</w:t></w:r>
        <w:r><w:instrText xml:space="preserve"> DOCPROPERTY Alpha </w:instrText></w:r>
        <w:r><w:instrText xml:space="preserve"> = "X" "yes" "" </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="separate"/></w:r>
        <w:r><w:t>Displayed result.</w:t></w:r>
      </w:p>
      <w:p>
        <w:r><w:instrText xml:space="preserve"> DOCPROPERTY Beta </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r>
        <w:r><w:fldChar w:fldCharType="begin"/></w:r>
        <w:r><w:instrText xml:space="preserve"> DOCPROPERTY Gamma </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="separate"/></w:r>
        <w:r><w:t>Gamma value</w:t></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r>
      </w:p>
      <w:p>
        <w:r><w:fldChar w:fldCharType="begin"/></w:r>
        <w:r><w:instrText xml:space="preserve"> DOCPROPERTY Delta </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r>
        <w:r><w:instrText xml:space="preserve"> " " </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r>
        <w:r><w:t>Trailing body text.</w:t></w:r>
      </w:p>
      <w:p>
        <w:r><w:fldChar w:fldCharType="begin"/></w:r>
        <w:r><w:instrText xml:space="preserve"> PAGE </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="separate"/></w:r>
        <w:r><w:t>1</w:t></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r>
      </w:p>
    """
    
    DOCUMENT_XML = (
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
        f"<w:document {W}><w:body>{BODY}</w:body></w:document>"
    ).encode()
    
    CONTENT_TYPES = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
      <Default Extension="xml" ContentType="application/xml"/>
      <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
      <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
    </Types>"""
    
    RELS = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
      <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
    </Relationships>"""
    
    buffer = io.BytesIO()
    with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as package:
        package.writestr("[Content_Types].xml", CONTENT_TYPES)
        package.writestr("_rels/.rels", RELS)
        package.writestr("word/document.xml", DOCUMENT_XML)
    buffer.seek(0)
    
    print(mammoth.convert_to_html(buffer).value)

    Fails identically on 1.11.0 and 1.12.1:

      File ".../mammoth/docx/body_xml.py", line 206, in read_fld_char
        complex_field = complex_field_stack.pop()
    IndexError: pop from empty list
    

    What Word does with the same file

    Word opens it without complaint. Re-saving it (we added a trailing newline and saved under a new name) shows Word repairing the markup in two steps:

    1. It deletes the orphan markers. Marker sequence before and after:

    before:  separate end begin separate end begin end end begin separate end
    after:   begin separate end begin end begin separate end
    

    Three orphans gone; the three well-formed fields untouched; no begin inserted.

    2. It rewrites the orphaned instrText runs as ordinary text. The instrText count drops from 7 to 3 - only those inside well-formed fields survive as instructions. The rest become w:t:

    w:t   'Paragraph one. DOCPROPERTY '
    w:t   'Alpha  ='
    w:t   ' "X" "yes" "" Displayed result.'
    

    Which is a defensible reading: instruction text with no opening marker isn't an instruction, so it's text.

    Implication for the fix

    The guard proposed above stops the crash. On this file it yields:

    <p>Paragraph one.Displayed result.</p><p>Gamma value</p><p>Trailing body text.</p><p>1</p>

    Word renders the same document as:

    <p>Paragraph one. DOCPROPERTY Alpha  = "X" "yes" "" Displayed result.</p><p> DOCPROPERTY Beta Gamma value</p><p> " " Trailing body text.</p><p>1</p>

    So the guard silently drops text that Word displays. In our sample that cost real content in a significant fraction of the documents. Elsewhere the dropped text was field plumbing (REF _Ref234398469 \r \h), which Word also renders literally.

    Options for fixing are: mammoth should simply not crash; or should match what Word shows. We're matching Word on our side, since "extract what the user sees" is the invariant our product needs.

    Provenance

    We can't say what produced the imbalance. Word repairs it on save, so these files were most likely last written by something else - legal document-automation tooling is the obvious candidate given our user base. What we can say is that Word opens and renders them fine, so from a user's point of view the document is healthy and the converter is what fails.

    Happy to send a PR with the guard plus tests covering both crash sites.

  4. GokouRuri43 commented on Sep 9, 2026

    @GokouRuri43

    Confirming this still reproduces on current master. I hit it independently via a real-world document rather than a synthetic repro: 090716_Studentische_Arbeit_VWS.docx from LibreOffice core test data (https://github.com/LibreOffice/core/blob/master/sw/qa/extras/ooxmlexport/data/090716_Studentische_Arbeit_VWS.docx). I applied the same two-line guard and added a regression test (test_fld_char_end_without_matching_begin_is_ignored in tests/docx/body_xml_tests.py): it fails on current code and passes with the fix, and the full body_xml_tests.py (157 tests) stays green. The branch is at GokouRuri43/python-mammoth:fix/orphaned-fldchar if useful.

  5. mwilliamson commented on Sep 12, 2026

    @mwilliamson
    Owner

    Thanks for the report. This should be now be fixed on master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions