Skip to content

Python edits: publish from the owner inventory, compare one block, edit properties without staging - #449

Open
hadim wants to merge 3 commits into
tensorbee:mainfrom
hadim:fix/445-edit-publication-cost
Open

hadim wants to merge 3 commits into
tensorbee:mainfrom
hadim:fix/445-edit-publication-cost

Conversation

@hadim

@hadim hadim commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Part of #445 (and of #437, #407, #398, #378 before it). Three commits on main eb980e9 (v0.17.0).

Context: why a change of this size

The history. The cost of Python edits that grows with the document has been reported five times: #378, #398
(fixed by #399), #407 (#415, then #417 to #422), #437 (#443) and #445. Each report named calls, each fix made those
calls cheaper, and the next benchmark found the same cost under other calls. v0.17.0 answers #437 and #445 for the
calls they name: the cell setters no longer grow with the body, and Document.open no longer keeps an inventory.
Both issues stay open for their numerical criteria.

The five whole-document steps. A plan of 2026-10-23 named what one Python edit does in proportion to the
document, whatever it edits: it rebuilds and matches the owner inventory, compares two staged saves to detect a
no-op, flushes the package, reopens it, and walks a whole story to address the element. Profiled on v0.17.0 (release
build, 1000 body paragraphs of three runs, macOS sample), all five are still there:

call story walk for the route save comparison native flush and reopen owner inventory document clone and drop
Paragraph.add_run 45 % 45 % 9 %
Paragraph.text 77 % 21 %
Run.text 7 % 77 % 13 % 2 %
Table.add_row 10 % 52 % 34 % 2 %

Why per-call fixes did not close it. The unit of a publication is the document, and each fix qualifies one call
shape for a local route. Paragraph.text takes its route from the owner inventory since v0.17.0, while append_run,
in the same file, still walked the story. The scaling test of rdocx-skills times every public mutating call at two
body sizes. 127 calls are on its list of costs accepted as linear. Run once each with timers around every step, 126
of them clone the document, 96 publish the whole inventory, 56 walk a story, 40 compare staged saves and 75 reopen
the package. A step that 40 or 126 calls share is not fixed by a route for one of them.

What this pull request changes. Three shared steps:

  1. Routes. A publication whose owner has an inventory record takes its route from that record, for the calls
    whose walk served only the publication: Paragraph.add_run, add_hyperlink and add_equation, Run.text,
    Table.add_row, Table.remove_row, the checked fallback of Cell.text, Document.set_chart_legend and a text
    box ParagraphFormat. Paragraph.add_internal_hyperlink does the same for its publication and keeps one walk.
  2. No-op check. Run.text decides whether its typed edit changed anything from the one plain body paragraph it
    edits, without comparing staged saves. Every other publisher, Run.replace_xml included, keeps the comparison.
  3. Properties. The core, application and custom property setters do not clone the document.

And one guard: a test that states, for each call, which whole-document passes it makes, read from debug counters and
not from a clock.

What it leaves.

  • The document clone and the full inventory publication of every text edit, which are the whole cost of add_run,
    Paragraph.text and Run.text after this change.
  • The story walk of a call whose native edit takes a checked story address: Paragraph.add_internal_hyperlink,
    Run.add_picture, Run.replace_xml, Table.replace_xml, Cell.merge (three walks), Document.add_footnote and
    add_endnote, a text box paragraph edit. The walk there is the address the native call asks for, not a route the
    inventory could give.
  • The native staged transaction (flush and reopen) of table structure, pictures and notes, the table-wide fact read
    of the cell setters, and the two validation passes of open and replace. See "Later".

How the guarantees are kept.

  • Owner facts come from the checked reader, never from the edit. A route is the inventory's own record, which the
    checked reader produced. The no-op answer is read from direct_body_paragraph_facts, the checked reader the
    pieces already use, on the block before and after. Nothing is inferred from what the edit meant to do.
  • The previous path is the fallback and the debug oracle. A handle without an inventory record walks the story as
    before. A paragraph that is not plain, text that XML 1.0 cannot carry, a body whose save is known to fail and facts
    that do not tell keep the staged save comparison. Debug builds check each direct answer: a body paragraph or body
    table route against the story walk (assert_indexed_route), a run route by reading the paragraph there for its run
    path, the no-op answer against the staged comparison whenever that comparison answers, and a properties edit
    against the staged edit on a clone (package graph, identifier registry, models, part names, refusal).
  • Handle retirement and StaleElementError. The publication itself is untouched: the same prepare_word_revision
    runs with the same WordPublication value. Only how the route and the no-op answer are obtained changed.
  • Atomic refusal. A properties edit saves the package graph and the identifier registry and puts them back on
    refusal. A refused Run.text still raises the staged save's error, from the staged save.
  • Saved bytes and held handles. A debug switch restores the checked route. For each call the test compares both
    routes: same result or error, same saved parts, same state of eleven held handles.

One change a caller can see. The staged comparison saved the whole candidate, so Run.text raised when content
elsewhere in the document could not be saved, for instance a control character that Paragraph.text accepted
earlier. The block answer reads one paragraph. In that state Run.text publishes and save raises, which is what
Paragraph.text and Paragraph.add_run already do. Run.text still refuses its own text, with the same error.
test_run_text_publishes_beside_content_that_no_save_accepts_and_save_reports_it pins both routes. If the change is
not wanted, PyRun::set_text calls publish_owner_candidate in every case and the staged comparison is back.

What changed

change where how it keeps the rule
Properties setters without a document clone crates/rdocx/src/document.rs: edit_properties, used by set_core_properties, set_application_properties, set_custom_property, remove_custom_property no owner fact involved. The same reservation and model write run on the document. Debug builds run the staged edit on a clone and compare
Debug counter of document staging clones, debug switch for the staged properties route crates/rdocx/src/document.rs: take_staging_clones, force_staged_properties. without_staging_work keeps the clones of a debug reference out of the count debug builds only, doc-hidden
Routes from the inventory crates/rdocx-py/src/document.rs: paragraph_route (existing), table_route, run_route. Callers in paragraph.rs (append_run, append_internal_run, add_equation), run.rs (set_text), table.rs (add_row, remove_row, Cell.text fallback), formatting.rs (text box paragraph format), document.rs (set_chart_legend) the record the checked reader prepared. Debug builds check it as described above
No-op check from one block crates/rdocx-py/src/document.rs: publish_block_candidate, direct_paragraph_saves_as, typed_run_edit_slot. publish_owner_candidate is unchanged but for its counter checked reader facts of the block before and after. Debug builds assert the answer against saves_as when it answers
Counters and route switch crates/rdocx-py/src/document.rs: _word_publication_work, _word_force_checked_route debug builds only, counted outside the guards
oxml-core as a direct dependency of rdocx-py crates/rdocx-py/Cargo.toml, Cargo.lock for is_xml_1_0_character, instead of a second copy of the Char production
Guards crates/rdocx-py/tests/test_edit_publication_cost.py, one test in crates/rdocx/src/document.rs see "Guards"
HLD docs/hld/10-bindings-spec.md, "Word checked XML owner authority"

The test file is new. It can be folded into test_core.py if a new file is not wanted.

Numbers

Median CPU time per call, release builds with LTO off, macOS arm64, v0.17.0 against the head of this branch. The
body holds N paragraphs of three runs and is opened from a file. Handles are taken before timing (bench.py). The
machine was shared with other builds, so read the columns against each other: both builds were measured back to back,
and the calls this pull request does not touch (Paragraph.text, Document.add_paragraph) agree within
5 %.

call v0.17.0, 1000 paragraphs this pull request, 1000 v0.17.0, 8000 paragraphs this pull request, 8000
Paragraph.add_run 15.9 ms 8.11 ms 169 ms 84.4 ms
Paragraph.add_hyperlink 19.9 ms 11.1 ms 183 ms 97.1 ms
Run.text (new text) 84.7 ms 8.36 ms 826 ms 85.4 ms
Run.text (same text) 77.5 ms 0.92 ms 754 ms 12.0 ms
Paragraph.text 8.67 ms 8.23 ms 85.1 ms 85.0 ms
CoreProperties.title 1.04 ms 0.024 ms 12.4 ms 0.016 ms
AppProperties.company 0.95 ms 0.024 ms 12.0 ms 0.016 ms
CustomProperties.set 0.94 ms 0.025 ms 12.3 ms 0.017 ms
Document.add_paragraph 0.36 ms 0.35 ms 2.84 ms 2.75 ms
Table.add_row (2 to 9 rows) 71.6 ms 61.3 ms 671 ms 588 ms

Run.text with the same text still clones the document before it finds out that nothing changed. Table.add_row
loses its story walk and keeps the rest. In an empty document, on one 2 x 5 table, Table.add_row costs
3.66 ms at rows 2 to 8 and 75.3 ms at rows 165 to 171 on v0.17.0
(4.75 ms and 66.9 ms here).

Whole-document passes per call, from the debug counters. The checked route is what the debug switch restores. It
walks wherever a route is asked for, which is one walk more than v0.17.0 for add_run, since v0.17.0 already bound
the returned run from the inventory:

call checked route this pull request
CoreProperties.title 1 document clone none
Paragraph.add_run 1 clone, 2 story walks, 1 full publication 1 clone, 1 full publication
Run.text 3 clones, 1 story walk, 1 save comparison, 1 full publication 1 clone, 1 full publication
Run.text, same text 3 clones, 1 story walk, 1 save comparison 1 clone
Table.add_row 3 clones, 1 story walk, 1 full publication, 1 inventory rebuild, 1 reopen 3 clones, 1 full publication, 1 inventory rebuild, 1 reopen
Document.set_chart_legend 5 clones, 1 story walk, 1 save comparison, 1 full publication, 1 inventory rebuild, 1 reopen the same without the story walk

Guards

test_edit_publication_cost.py reads the debug counters, so it runs in the "Python bindings" job as it is and is
skipped on a release build. 107 tests pass and 16 are strict expected failures.

  • FLAT, 30 calls: no whole-document pass, and every counter equal in a body of 8 and of 32 paragraphs. The 21
    CoreProperties and AppProperties setters, the four CustomProperties writes, and five calls that were flat
    already and are now guarded: Font.bold, Paragraph.alignment, ParagraphFormat.left_indent, Cell.text,
    Cell.shading.
  • GROWING, 16 calls, with the passes each one makes, asserted exactly: Paragraph.add_run, add_hyperlink,
    add_internal_hyperlink, add_equation, Paragraph.text, Run.text, Run.add_break, Run.add_tab,
    Table.style, Table.add_row, Table.remove_row, Cell.text of a cell that holds a table (the checked
    fallback), Document.set_chart_legend, Settings.track_revisions, Document.add_paragraph,
    Document.add_table. The flat test is a strict expected failure for them. A later change that makes one flat, or
    removes one pass, fails until the entry moves or shrinks. The clone counts leave out the debug references of
    rdocx, so they are what a release build does.
  • Both routes agree, 52 cases: every call above and six variants (same text, text no save accepts, tabs and line
    breaks, empty text, a refused application version, a missing custom property). For Cell.text and Cell.shading
    on a plain table this proves nothing yet: the route switch does not reach the local cell route, so both runs take
    it. The stacked pull request for the cell setters makes the switch send them to the whole-document route and
    compares the two.
  • A refused edit changes nothing, 3 cases.
  • Run.text beside content that no save accepts: publishes on the direct route, raises on the checked route, and
    save raises.
  • A text box ParagraphFormat: two walks for its edit address on the direct route, three on the checked route, the
    same saved parts.
  • In rdocx: the four properties edits stage no document. A refusal before any reservation (a repeated
    relationship id) and one after the part name is reserved (no free relationship id) both leave the package graph,
    the identifier registry and the models as they were. The test fails when the two restore lines of
    edit_properties are removed.

Findings that are in no issue

  • Run.text was the most expensive frequent call, more than four times Paragraph.add_run in the table above.
    77 % of it was the save comparison, which serialized the main part nine times in one call. This pull request
    removes that part.
  • Table.add_row grows with the table it extends, not only with the body: see the empty document figures
    above. The native add_empty_table_row clones the document, flushes and reopens the package, and the publication
    reads the facts of the whole table again. Not changed here.
  • Paragraph.text accepts text that no save accepts. paragraph.text = "a\x00b" publishes and the next save
    raises, where run.text = "a\x00b" is refused at once. Not changed here.
  • The body splice of Document.add_paragraph still visits every owner record: its cost in the table above grows
    about eight times from 1000 to 8000 paragraphs.

Later

Not in this pull request. The figures are measured on v0.17.0 unless marked as an estimate.

  • The clone and the full publication of in-block edits. After this change they are all that grows in add_run,
    Paragraph.text and Run.text. One block transaction would remove both: clone the one body block (as
    direct_body_table_cell_candidate does for a cell), read its facts with the checked reader, and splice its owners
    into the inventory (as the body splice of add_paragraph does for an inserted block). Estimate, not measured:
    about the cost of Document.add_paragraph in the table above.
  • The native staged transaction. 75 of the 127 calls reopen the package inside a native call:
    Table.add_row, clone_row, remove_row, insert_column, Cell.merge, Run.add_picture,
    Document.add_footnote, insert_content and others. It is 52 % of Table.add_row. The binding cannot remove it.
  • Cell setters. 94 % of Cell.shading and 91 % of Cell.text in an empty document is the fact read of the
    whole table (word_block_owners in apply_local_cell_edit): 5.7 ms for a 100-cell table in the profile run. The
    local route also declines some cells and documents, which then take the whole-document route.
  • Open and replace. Document.open, try_replace_text and save cost 1.4 times rdocx replace. The binding
    adds two validation passes whose results are dropped (from_document and validate_word_facts in
    dormant_replacements), 37 % of its time. F-X283 keeps them so that no open error moves to the first handle, and
    test_fx283_missing_external_link_still_refuses_open pins one. Left untouched: removing either would lose an
    error a caller receives today.
  • Settings.track_revisions, update_fields_on_open, Table.style, Run.add_break, Run.add_tab still clone
    the document and do nothing else that grows.

Gates run locally

Run on e142eb0, macOS arm64, Poppler 26.09 through pixi exec -s poppler.

  • cargo fmt --all --check and cargo clippy --workspace --all-targets --all-features -- -D warnings: clean.
  • python3 scripts/prose_check.py: 0 violations. python3 scripts/sync_agent_skills.py --check: clean.
    python3 scripts/hash_harness.py --check: 49 entries match.
  • python3 scripts/readme_doctests.py: passes, with the rdocx archive row re-recorded in its own commit.
  • cargo test -p rdocx --no-fail-fast (debug, so the staged properties edit runs next to every direct one): lib 1048
    passed, 3 failed. integration_test 557 passed, 5 failed. regression_test 2531 passed. The 8 failures pin tool
    versions this machine does not have: lib large_word_and_presentation_pdfs_preserve_logical_reading_order
    (pdftotext 26.01.0), word_and_powerpoint_chart_pixels_are_identical (at the rasterizer version assert),
    fx195_variable_svg_paint_matches_independent_static_instances (HarfBuzz 14.4.0). Integration
    odt_reader_matches_pinned_libreoffice_structure, public_authored_theme_and_fonts_match_pinned_word_resolution,
    section_page_semantics_match_pinned_libreoffice_render and every_conditional_table_region_matches_word
    (LibreOffice 26.2.5.2), sanitized_public_authoring_fixture_passes_every_conformance_stage (cargo run --offline).
  • cargo test -p rdocx-cli --no-fail-fast: 120 passed.
  • Python, built as the CI job builds it (maturin develop --locked, debug assertions on), full
    crates/rdocx-py/tests: 1505 passed, 2 skipped, 16 expected failures (the GROWING list), 61 failed. The 61 pin
    tools: test_issue_253_pdf_text_view (pdftotext 26.01.0),
    test_colour_inputs_and_nested_font_formats_reach_actual_rendering (pdftoppm 26.01.0),
    test_fx200_python_style_saved_output_paints_exact_expected_colours_with_deterministic_native_cli (RDOCX_CLI
    unset), and the 58 tests of test_rendering_threads.py (Poppler 26.01.0 and installed fonts). No debug check fired.
  • Release wheel: mypy --strict on typing_smoke.py and the package, no issues in 9 source files.
    mypy.stubtest rdocx: no issues in 8 modules. The debug-only counters and switches are absent from it.
  • issue445_properties_edits_stage_no_document_and_refuse_without_a_trace goes red when the two restore lines of
    edit_properties are removed.

set_core_properties, set_application_properties, set_custom_property and
remove_custom_property cloned the whole document to protect one fallible
step: reserving the properties part in the package graph and the identifier
registry. The clone and the drop of the previous document cost in
proportion to the body, so a properties setter was linear in a document it
does not read.

edit_properties saves the package graph, whose part bytes are shared, and
the identifier registry, runs the same reservation and model write on the
document, and puts both back on refusal. A success leaves what
commit_staged_mutation leaves for a staged clone: the derived layout is
dropped and a signed package records a package mutation. The cost follows
the package graph and the registry, not the body.

Debug builds run the staged edit on a clone as well and assert the same
package graph, identifier registry, property models, part names and
refusal. They count whole-document staging clones (take_staging_clones),
outside the debug references, which run under without_staging_work, and
can force the staged route (force_staged_properties), so a test of a
binding can state that a call stages no document and compare both routes.

The test covers a refusal before any reservation (a repeated relationship
id) and one after the part name is reserved (no free relationship id),
where the registry must come back as it was.

Part of tensorbee#445.
Two of the whole-document passes a Python edit made when it published.

Routes. Paragraph.add_run, add_hyperlink and add_equation, Run.text,
Table.add_row, Table.remove_row, the checked fallback of Cell.text,
Document.set_chart_legend and a text box ParagraphFormat resolved the route
of their publication by a checked story walk, which serializes the main
part. They take it from the owner inventory record the checked reader
prepared, through paragraph_route (as Paragraph.text does since v0.17.0),
table_route and run_route. Paragraph.add_internal_hyperlink does the same
for its publication and keeps one walk for the address of its native edit.
Debug builds resolve a body paragraph or body table route by the walk too
and assert both agree, and assert that the paragraph at a run route holds
the run path. A handle with no inventory record keeps the walk. Calls whose
native edit takes a checked story address still walk for it: Run.add_picture,
Run.replace_xml, Table.replace_xml, Cell.merge, the note calls.

No-op check. Run.text compared two staged saves of the whole document to
learn whether its typed edit changed anything. For a run of a direct body
paragraph it reads that block: equal paragraph models publish nothing, and
two plain paragraphs whose checked reader facts differ
(direct_body_paragraph_facts) publish. Text XML 1.0 cannot carry, another
paragraph shape, a body with a known save failure and facts that do not
tell keep the staged comparison and its error, as every other publisher
does. Debug builds assert the block answer against the staged comparison
whenever that comparison answers. The block answer does not save the rest
of the document: content elsewhere that no save accepts does not make
Run.text raise, save reports it, as after Paragraph.text.

Guards. Debug builds count document staging clones, route story walks,
staged save comparisons and full inventory publications
(_word_publication_work), outside the guards, and
_word_force_checked_route restores the walk, the staged comparison and the
staged properties edit. test_edit_publication_cost.py lists the calls that
make no whole-document pass and do the same counted work in a body four
times larger (FLAT), and the passes every other call makes (GROWING, a
strict expected failure of the flat test), and checks that both routes of
each call give the same result, saved parts and held handles.

rdocx-py depends on oxml-core directly for is_xml_1_0_character, the XML
1.0 Char production, in place of a second copy of it.

Part of tensorbee#445.

This branch has not been deployed

No deployments
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.

1 participant