Skip to content

rdocx Python: in a document saved by Word or Google Docs most edits cost the whole body (0.1 to 4 s a call on public reports), the shared cause behind #389, #407, #437 and #445 #455

Open

Description

@hadim

Follows #389, #398, #407, #437 and #445. Each one named calls and a script, and each release made those calls local for the paragraphs of the script. This issue is about what they share, measured on public documents. v0.17.0 (main eb980e94), release wheel from PyPI, Linux x86_64.

What happens

The same edits on a public 22-page report saved by Word (796 paragraphs, document.xml 458 kB), milliseconds per call:

Call python-docx 1.2.0 0.16.0 0.16.4 0.17.0
Run.text 0.03 0.00 101 129
Paragraph.text 0.03 0.02 12 11
Paragraph.add_run 0.02 0.00 12 17
Table.add_row 0.11 192 225
Document.remove_content 151 193 216
Paragraph.replace_xml 213 269
Document.add_footnote 98 125
Cell.text 0.03 153 214 27
Paragraph.insert_paragraph_before 0.02 0.7 0.8
Document.add_paragraph 0.03 0.00 0.2 0.3

An empty cell is a call that library or version does not have in this form.

On a public 66-page report (817 paragraphs, 48 tables, document.xml 4.3 MB) with 0.17.0: Run.text 0.78 s, Paragraph.text 0.21 s, Table.add_row 1.4 s, remove_content 1.3 s, add_footnote 1.7 s, Paragraph.replace_xml 4.3 s, and 4.1 s to open (1.0 s with 0.16.4). On the same file insert_paragraph_before costs 2.2 ms and Cell.text 0.8 ms.

So the local routes work, and every call outside them costs the body. An agent that rewrites 200 runs of the 66-page report waits 2.6 minutes.

The two files (Open Government Licence):

Why

Read in the source and counted with callgrind on hadim/rdocx 2543cf63 (v0.17.0 plus #448 to #452 and #454):

  • A saved paragraph is never plain. The local routes ask for a plain paragraph (paragraph_is_plain, behind plain_removable_paragraph, plain_direct_paragraph and direct_body_paragraph_facts). Word and Google Docs write w:rsid* and w14:paraId on their paragraphs, which are kept as retained markup, so the paragraph is not plain: in the script below remove_content of a paragraph costs 0.2 ms in the body as rdocx writes it and 67 ms in the saved one. Every paragraph of the four public documents we measured carries them.
  • The fallback walks the whole body many times in one call. On a body of 100 paragraphs as Google Docs saves list items (identity attributes, its paragraph and run properties, one tab stop each), one remove_content serializes each block alone 23 times and parses it 6 times. 86 % of that call is in try_remove_content: canonicalize_all_drawing_ids takes 31 % of the call with no drawing in the document, reconcile_comment_removal 15 % with no comment. One Run.text serializes each block 18 times, with 82 % of the call in saves_as (96 % on the 22-page file). One Paragraph.text reads the owner facts of each block twice.
  • A block with a field, a bookmark or a tab stop is parsed again at each read, and its owner facts are read again at each publication (owner_facts_reusable_by_value, F-X268). The headings of a document with a table of contents hold a bookmark, and its entries a tab stop and a field.

Script

It builds its own input, prints PASS or FAIL per call and exits 1 while a call fails. Two calls that are already local are in it as controls.

case1_saved_body.py
"""Case 1: an edit costs the whole body when the document holds what Word and Google Docs save.

Builds its own input: bodies of N paragraphs of two runs with one 6 x 3 table, written two ways. "As rdocx writes
it" holds the text alone. "As saved" holds the same text with what Word and Google Docs write: w:rsid* on every
paragraph and run, w14:paraId on every paragraph, a bookmark on one paragraph in ten (the headings of a document
with a table of contents) and a tab stop on one in ten. No timed call touches a paragraph that holds a bookmark or
a tab stop.

Each call is timed on three targets of a document opened for it, the median counting. PASS when the call costs at
most 1.5 times as much in the saved body of 400 paragraphs as in the saved body of 100, plus 1 ms. The cost in the
body of 400 as rdocx writes it is printed beside it. Exits 1 while a call fails.
"""
import io
import platform
import statistics
import sys
import time
import zipfile
from importlib.metadata import version

import rdocx

print(f"rdocx {version('rdocx')}, Python {platform.python_version()}, {platform.system()} {platform.machine()}")
SMALL, LARGE = 100, 400
W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
W14 = "http://schemas.microsoft.com/office/word/2010/wordml"
CONTENT_TYPES = (
    '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
    '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
    '<Default Extension="xml" ContentType="application/xml"/>'
    '<Override PartName="/word/document.xml" ContentType='
    '"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>'
)
RELATIONSHIPS = (
    '<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>'
)


def paragraph(index, saved, texts):
    """One paragraph of one run per text. Body paragraph `index` holds a tab stop or a bookmark one time in ten."""
    identity = f' w:rsidR="00A31F2C" w:rsidRDefault="00A31F2C" w14:paraId="{index + 1:08X}"' if saved else ""
    run = ' w:rsidRPr="00B7440E"' if saved else ""
    tab_stop = '<w:pPr><w:tabs><w:tab w:val="left" w:pos="720"/></w:tabs></w:pPr>' if saved and index % 10 == 1 else ""
    runs = "".join(f'<w:r{run}><w:t xml:space="preserve">{text}</w:t></w:r>' for text in texts)
    if saved and index % 10 == 2:
        runs = f'<w:bookmarkStart w:id="{index}" w:name="_Toc{index}"/>{runs}<w:bookmarkEnd w:id="{index}"/>'
    return f"<w:p{identity}>{tab_stop}{runs}</w:p>"


def table(saved):
    cells = [f'<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>{paragraph(10000 + 10 * k, saved, [f"cell {k}"])}'
             "</w:tc>" for k in range(18)]
    rows = "".join("<w:tr>" + "".join(cells[3 * row:3 * row + 3]) + "</w:tr>" for row in range(6))
    return ('<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tblGrid>' + '<w:gridCol w:w="2000"/>' * 3
            + f"</w:tblGrid>{rows}</w:tbl>")


def package(count, saved):
    blocks = [paragraph(k, saved, [f"Paragraph {k} first run. ", "second run."]) for k in range(count)]
    blocks.insert(count // 4, table(saved))      # body index of paragraph k: k + 1 from count // 4 on
    document = (f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:w14="{W14}">'
                f'<w:body>{"".join(blocks)}<w:sectPr/></w:body></w:document>')
    out = io.BytesIO()
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as archive:
        archive.writestr("[Content_Types].xml", CONTENT_TYPES)
        archive.writestr("_rels/.rels", RELATIONSHIPS)
        archive.writestr("word/document.xml", document)
    return out.getvalue(), len(document)


def body_paragraph(document, k):
    return next(p for p in document.paragraphs if p.text.startswith(f"Paragraph {k} "))


CALLS = {
    "Run.text": (lambda d, k: body_paragraph(d, k).runs[0], lambda d, run: setattr(run, "text", "changed ")),
    "Paragraph.text": (body_paragraph, lambda d, p: setattr(p, "text", "changed")),
    "Paragraph.add_run": (body_paragraph, lambda d, p: p.add_run(" more")),
    "Table.add_row": (lambda d, k: d.tables[0], lambda d, t: t.add_row()),
    "Document.add_footnote": (body_paragraph, lambda d, p: d.add_footnote(p, "note")),
    "Document.remove_content": (lambda d, k: k + 1, lambda d, index: d.remove_content(index)),
    # Two calls that are already local in every body.
    "Document.insert_paragraph": (lambda d, k: k + 1, lambda d, index: d.insert_paragraph(index, "inserted")),
    "Cell.text": (lambda d, k: d.tables[0].cell(k % 6, 1), lambda d, cell: setattr(cell, "text", "changed")),
}


def cost(count, saved, target, call):
    document = rdocx.Document.from_bytes(package(count, saved)[0])
    times = []
    # Paragraphs 95, 75, 55 of 100 and 245, 225, 205 of 400, the last one first: an edit shifts what follows it.
    for k in (count // 2 + 45, count // 2 + 25, count // 2 + 5):
        subject = target(document, k)
        started = time.perf_counter()
        call(document, subject)
        times.append(time.perf_counter() - started)
    return 1000 * statistics.median(times)


print(f"document.xml of {LARGE} paragraphs: {package(LARGE, False)[1]} bytes as rdocx writes it, "
      f"{package(LARGE, True)[1]} bytes as saved")
failed = False
for name, (target, call) in CALLS.items():
    small, large = cost(SMALL, True, target, call), cost(LARGE, True, target, call)
    written = cost(LARGE, False, target, call)
    ok = large <= 1.5 * small + 1
    failed |= not ok
    print(f"{'PASS' if ok else 'FAIL'} {name}: as saved {small:.2f} ms at {SMALL} paragraphs, {large:.2f} ms at "
          f"{LARGE} (x{large / small:.1f}); as rdocx writes it {written:.2f} ms at {LARGE}")
sys.exit(1 if failed else 0)

Output on v0.17.0:

rdocx 0.17.0, Python 3.13.16, Linux x86_64
document.xml of 400 paragraphs: 55773 bytes as rdocx writes it, 106444 bytes as saved
FAIL Run.text: as saved 14.58 ms at 100 paragraphs, 54.75 ms at 400 (x3.8); as rdocx writes it 16.32 ms at 400
FAIL Paragraph.text: as saved 2.40 ms at 100 paragraphs, 8.79 ms at 400 (x3.7); as rdocx writes it 1.74 ms at 400
FAIL Paragraph.add_run: as saved 3.46 ms at 100 paragraphs, 12.61 ms at 400 (x3.6); as rdocx writes it 3.50 ms at 400
FAIL Table.add_row: as saved 17.45 ms at 100 paragraphs, 59.62 ms at 400 (x3.4); as rdocx writes it 14.91 ms at 400
FAIL Document.add_footnote: as saved 18.60 ms at 100 paragraphs, 63.85 ms at 400 (x3.4); as rdocx writes it 13.88 ms at 400
FAIL Document.remove_content: as saved 17.24 ms at 100 paragraphs, 67.28 ms at 400 (x3.9); as rdocx writes it 0.20 ms at 400
PASS Document.insert_paragraph: as saved 0.09 ms at 100 paragraphs, 0.24 ms at 400 (x2.6); as rdocx writes it 0.23 ms at 400
PASS Cell.text: as saved 1.77 ms at 100 paragraphs, 1.78 ms at 400 (x1.0); as rdocx writes it 1.42 ms at 400
exit=1

Suggested acceptance: every line prints PASS, and on the two public files the calls of the table cost what the local routes cost there today, a few milliseconds.

How we got here

What we ask

#437 and #445 stay open for their own criteria. A comment below proposes how the work could be split.

How the table was measured

One venv per version (pip install rdocx==X, or python-docx), then python measure_public_file.py FILE or python measure_public_file.py FILE python-docx.

"""The cost of one edit in a public document, with the rdocx installed or with python-docx.

Usage: measure_public_file.py FILE [python-docx]
Each call is timed on three paragraphs with text in the middle of the body, in a document opened for that call.
Prints the median in milliseconds. A call the library does not have prints its error.
"""
import io
import re
import statistics
import sys
import time
import zipfile
from xml.etree import ElementTree

raw = open(sys.argv[1], "rb").read()
W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
children = list(ElementTree.fromstring(zipfile.ZipFile(io.BytesIO(raw)).read("word/document.xml")).find(W + "body"))
texted = [k for k, child in enumerate(children) if child.tag == W + "p"
          and child.find(f"{W}pPr/{W}sectPr") is None and (child.findtext(f"{W}r/{W}t") or "").strip()]
slots = texted[len(texted) // 2:len(texted) // 2 + 3]                     # direct body indexes
ordinals = [sum(child.tag == W + "p" for child in children[:k]) for k in slots]   # indexes in Document.paragraphs
if sys.argv[2:] == ["python-docx"]:
    import docx
    opened, save = (lambda: docx.Document(io.BytesIO(raw))), (lambda d: d.save(io.BytesIO()))
else:
    import rdocx
    opened, save = (lambda: rdocx.Document.from_bytes(raw)), (lambda d: d.to_bytes())
paragraph = lambda d, i: d.paragraphs[ordinals[i]]
changed = lambda p: (p, re.sub(r"(<w:t[^>]*>)[^<]", r"\1Z", p.xml, count=1))
CALLS = {
    "Run.text": (lambda d, i: paragraph(d, i).runs[0], lambda d, run: setattr(run, "text", "changed text")),
    "Paragraph.text": (paragraph, lambda d, p: setattr(p, "text", "changed paragraph")),
    "Paragraph.add_run": (paragraph, lambda d, p: p.add_run(" more")),
    "Paragraph.insert_paragraph_before": (paragraph, lambda d, p: p.insert_paragraph_before("inserted")),
    "Document.add_paragraph": (lambda d, i: None, lambda d, _: d.add_paragraph("appended")),
    "Cell.text": (lambda d, i: d.tables[0].cell(0, 0), lambda d, cell: setattr(cell, "text", "changed")),
    "Table.add_row": (lambda d, i: d.tables[0], lambda d, table: table.add_row()),
    "Paragraph.replace_xml": (lambda d, i: changed(paragraph(d, i)), lambda d, pair: pair[0].replace_xml(pair[1])),
    "Document.remove_content": (lambda d, i: slots[-1 - i], lambda d, index: d.remove_content(index)),
    "Document.add_footnote": (paragraph, lambda d, p: d.add_footnote(p, "note")),
    "save": (lambda d, i: None, lambda d, _: save(d)),
}
started = time.perf_counter()
opened()
print(f"{'open':36s} {1000 * (time.perf_counter() - started):10.2f} ms")
for name, (target, call) in CALLS.items():
    try:
        document, times = opened(), []
        for i in range(3):
            subject = target(document, i)
            started = time.perf_counter()
            call(document, subject)
            times.append(time.perf_counter() - started)
        print(f"{name:36s} {1000 * statistics.median(times):10.2f} ms")
    except Exception as error:
        print(f"{name:36s} {type(error).__name__}: {str(error)[:60]}")

Activity

  1. hadim commented on Nov 18, 2026

    @hadim
    ContributorAuthor

    @mantissaman do you want us to take this on, or would you rather do it in S96.1? Either is fine with us. If we do it, here is roughly how we would split it. Each pull request would be measured on the script above and on the two public files, and would compare its route with the whole path in debug builds, as #415 did.

    # Pull request What it changes Calls it covers Size
    1 Measure The script above as a test on a saved body, two debug counters that are missing (staged save comparisons, full inventory publications), an optional benchmark job on the public files. No behaviour change none small
    2 Text edits without the staged save comparison A text edit learns whether it changed anything from the edited block, for every paragraph shape. #449 does it for plain paragraphs Run.text, add_run, Paragraph.text small
    3 Shared body blocks A candidate shares the unchanged blocks of its document, copy on write, as parts do since #413. No behaviour change, the base of 4 and 5 none by itself wide, mechanical
    4 Binding inventory by identity A block that is the same object keeps its piece, whatever it holds Paragraph.text, add_run, and the half of Table.add_row and of the notes that follows the reopen medium
    5 Staged transaction by identity The passes of prepare_and_reopen_staged and of saves_as read what an unchanged block already gave remove_content, replace_xml, table structure, notes, pictures large

    Pull request 5 is the one where your invariants matter most, so it may be the one you prefer to write.

    One question decides 4 and 5: does a fact of a block depend on the blocks before it? The F-X268 plan names "bookmark prefix facts" and "the tab source occurrence". If some facts do, tell us which ones, and the record of a block needs them in its key.

    If you would rather do it yourselves, we would stop at 1 and measure your branches on the public files. #449 and #451 stay as they are in both cases.

  2. hadim commented on Nov 20, 2026

    @hadim
    ContributorAuthor

    @mantissaman, a heads-up rather than a question.

    First, thank you. You started rdocx and drove it to a full Word and PowerPoint stack in pure Rust, with a depth and a pace that are genuinely impressive. We have relied on it every day for months, and you integrated a very large number of our reports. Hats off.

    Our use, agents editing documents saved by Word and Google Docs, needs a faster edit path and shorter release cycles than your sprint process is built for, and we would rather not keep loading your queue with our timelines. So we are starting a friendly fork from v0.17.0, under a different name to avoid any confusion with the rdocx crates, beginning with the plan above. We will share the link once it is public.

    This is not a disagreement about the project. We will keep filing issues here, with reproduction scripts, whenever a bug we find also affects rdocx, and once the fork is public you are welcome to take anything from it under the same MIT/Apache-2.0 licence. #448 to #454 stay open for you to use or close as you prefer.

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