Repository navigation
Conversation
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.
A cell edit on the local route (Cell.text, Cell.vertical_alignment, Cell.shading, Cell.width, Cell.set_border, Cell.set_margins and Paragraph.text of a cell paragraph) cloned its whole table, edited the clone and read the facts of the whole table again with the checked reader, then replaced the owners of every cell. It no longer grew with the body but it grew with the table: 4.2 ms a call for a 20 x 5 table and 15.6 ms for an 80 x 5 table, so filling a table cost the square of its cells. The candidate is now the edited cell alone in a frame of its table: the table properties and grid, and one row with the row properties and that cell. It is validated as a body holding the frame alone, since the model limits bound the nesting along each path and the paths through the cell are the same in the frame and in the table. The checked reader reads the frame for the facts of the cell. The other cells keep the facts it read for the aligned piece. The publication replaces the owner records of the cell, its paragraphs and their runs, the paragraph count of the cell in the table read facts and the paragraph routes of the cell, and updates the piece in place after the revision commit. Debug builds read the whole table again after each such publication and assert that the piece facts the inventory reads, the owner records of the table and the cell paragraph routes are those of that read. The checked route switch sends these setters to the whole-document route, which the differential test compares them with. Debug builds also count the bytes of each block whose owners the checked reader reads again (_word_piece_bytes), so the guard sees a cell edit that reads its whole table: it compares them across table sizes and beside a large cell. A call costs 0.17 ms with a 20 x 5 or an 80 x 5 table, at 0 or 2000 body paragraphs (release build without LTO). What remains in proportion to the table is the alignment of the piece and the search of the cell owner: 0.24 ms at 400 x 5 and 0.78 ms at 2000 x 5. Part of tensorbee#445.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #445. Stacked on #449.
Two commits on top of #449:
perf(rdocx-py): publish a cell edit from the facts of that cellrecord the archive measurements(therdocxarchive row, as every pull request that touches the crate)History
#443 (the reference work). Case 1 of #445 named
Cell.text,Cell.vertical_alignmentandCell.shading. Thereference commit in #443 set a body table cell property in place, as a body paragraph property setter does, with no
candidate and no publication, since each edit validates before it writes
w:tcPr. Writing the firstw:tcProf acell, which a new cell lacks, moves every item of the cell story by one, so the owners of that story moved one item
(
move_cell_story_items).Cell.textedited the first paragraph in the candidate withouttry_set_cell_text. Theproperty setters cost 0.00 to 0.02 ms there.
What v0.17.0 kept. v0.17.0 adapted that work ("the follow-up paths adapt the reference work in PR443") under its
rule that owner facts come from the checked reader, never from what the edit meant to do. So it kept a candidate and a
publication:
direct_body_table_cell_candidateclones the whole table and edits the clone, thenapply_local_cell_editserializes the whole candidate table, reads its facts again with the checked reader(
word_block_owners), walks and matches the owners of every cell, and replaces the piece of the block. The setters nolonger grow with the body, but they grow with the table. On v0.17.0 they cost 4.1 to 6.8 ms a call in the issue
script, at any body size, and filling a table of n cells costs n squared.
Why. A macOS
sampleprofile of v0.17.0 taken before this work (release build, empty body, 20 x 5 table) put 94 %of
Cell.shadingand 91 % ofCell.textin that one call,word_block_ownerson the candidate table: about 57 us percell of the table, per call. The table clone, the walk over every owner of the table and the rebuilt piece make the
rest.
The fix
The unit of a cell edit becomes the cell. Three parts change.
Candidate (
rdocx).direct_body_table_cell_candidatekeeps its name, its checks and its signature. It clonesthe selected cell only, edits it, and returns it alone in a frame of its table: the table properties and grid, and one
row with the row properties, the row's start tag attributes and that cell. It validates a body holding the frame alone,
as it validated a body holding the edited table before.
commit_direct_body_tablebecomescommit_direct_body_table_cell(body_slot, row, cell, frame), which installs the frame's cell at(row, cell)underthe same
LocalCellSourceassertion. Both stay#[doc(hidden)]. Their only consumer isrdocx-py, and the twordocxtests that commit a candidate now commit the cell.Facts (
rdocx-py).apply_local_cell_editreads the frame withword_block_owners, the same checked reader asbefore, on a block of one cell. It requires the frame to read as one table, one cell story, no text box and no link,
with complete cell paragraph routes. The other cells keep the facts the checked reader gave the aligned piece of the
block, which the edit cannot reach: the closure of the candidate only receives the cloned
CT_Tc, and the commitwrites only
rows[row].cells[cell].Publication (
rdocx-py). The delta is the cell's owner subtree: the cell owner, its paragraphs and their runs. Theyare matched with the existing key (property owner key plus paragraph ordinal), so the first
w:tcPr, which shifts theraw item index of every paragraph of the cell, keeps every owner. The cell owner must keep its record. Route buckets,
paragraphs_by_parent,runs_by_parent, the cell'scell_paragraphsentry and the cell's paragraph count in the tableowner's
WordReadFacts::Tableare updated.cells_by_parentandtables_by_parentof the table do not change. Thescope policy is the existing one restricted to that subtree: the old route retired only owners under the selected cell
or paragraph, and the document text scope, as this one does. The piece of the block is updated in place after the
revision commit: the cell of its block, the cell's paragraph facts and story identity, and the table read facts.
The HLD (
docs/hld/10-bindings-spec.md, "Word checked XML owner authority") describes the selected-cell candidate,the frame validation, the in-place piece update and the debug proof.
How each guarantee is kept
that cell. The facts of the other cells are the checked reader's facts of the aligned piece, and
aligned_blockstill proves, before anything is prepared, that the piece's table equals the body's table. The cell story identity
(
StoryIdwith its structural fingerprint) comes from the frame read. It equals the full read's because thefingerprint hashes the
w:tcelement's own bytes, which do not depend on the frame.admit_word_model) bound theweighted nesting along each path and the table nesting. The paths through the edited cell are the same in the frame
and in the table (body, table, row, cell, then the cell's content), and the paths through the other cells are those
of models the edit does not reach.
word_block_owners, outside the counters (guarded), and assert that (a) the piece facts the inventory reads(table and body items, cells, paragraphs, links, counts, routes) equal the full read's, body story fingerprints
aside, (b) every owner record of the table's subtree (location with cell story fingerprints, parent, body slot,
projection ordinal, read facts) equals the one derived from the full read, (c) every
cell_paragraphsentry of thetable equals the full read's routes. The
holds_fieldflag may stay set (see below), so (a) asserts the implicationfor it. The whole Python suite runs these assertions in the "Python bindings" job.
owner, index and piece vectors, scope preparation) precedes the revision commit, and nothing is written before it.
A refused
Cell.text(a character no save accepts) and a refusedset_margins(a negative margin) leave the savedparts and every held handle as they were (
test_refused_edit_changes_nothing). The existingfx283_empty_cell_birth_and_refused_commit_publish_atomically(a refused revision commit) passes.differential test holds fifteen handles, among them the edited cell, its paragraph, its run, a neighbour in the same
row and its paragraph, and compares what each reads after the call on both routes.
_word_force_checked_routenow also sends these setters to thewhole-document route (
local_cell_routereturnsNone), which is the route the differential test compares with:same result or error, same saved parts, same held handles.
items of the cell stories there, which the body splice of
Document.add_tablealready leaves out and which theinventory never reads (it reads the table and body items of a piece). The local edit drops them rather than keep
stale ones. The piece
Arcmust be unique, else the edit takes the checked route.What still depends on the table or the body
aligned_block, which compares the piece's table with the body'stable in memory (the guard of the piece, so it stays), and the linear search of the cell owner among the table's
cells. They were not profiled separately.
Cell.shadingon the first 40 cells of an N x 5 table, median per call,release build of this branch (
table_scale.py): 0.166 ms at 20 rows, 0.175 ms at 80, 0.241 ms at 400 and0.775 ms at 2000 rows.
Cell.text: 0.180, 0.201, 0.233 and 0.781 ms.Cell.textor a cellParagraph.textthat removes an owner of the cell, such as a run, leaves the local route,since every owner of the cell must keep its record there, and takes the whole-document route, which grows with the
body. That rule is v0.17.0's. Measured (
fallback_cost.py, 4 x 5 table, median per call):cell.text = ""on acell holding text costs 2.72 ms at 0 body paragraphs and 44.6 ms at 2000 on this branch, 3.23 ms and 51.9 ms on
v0.17.0. Other edits that remove a run take the same route by the same rule, for instance text set over a picture
or a note reference in the first paragraph (not measured here).
Cell.textover a cell of two runs keeps the localroute (0.18 ms at 0 and 2000).
another story keep the checked whole-document route, unchanged. Measured on this branch at 2000 body paragraphs:
Cell.shading9.3 ms andCell.text57 ms in a table holding one hyperlink.Cell.add_paragraphdoes not share this route: it clones the document and publishes (4.0 ms in an empty body,7.7 ms at 2000 paragraphs). Not changed.
Shapes checked
Each of these opened tables keeps the local route (no whole-document pass) and gives the result, the saved parts and
the held handles of the checked route, for
Cell.shading,Cell.textand a cellParagraph.text, with the debugoracle on:
vMergerestart and continue cell, agridSpan2 cell (both edited)fldSimplefield in one cell (both cells edited)<w:tcPr/>w:rsidRattribute and aw:trPr, a bookmark start between two cells of that row and its end betweentwo rows (cells on each side of the marker and in the next row edited), which the frame leaves out
w:tcPr(the cells ofDocument.add_table, so the first-w:tcPrshift is exercised by everyproperty setter of the guard test)
A picture or a comment does not make these setters leave the local route, before or after this change: measured with
the counters for a picture or a comment in the body and in another cell of the table, and by timing after a save and
reopen, where the setters cost what they cost in a plain document (below). A main part that is not owner-free
(
LocalCellSource) still takes the checked route. That condition comes from the namespace classification of the mainpart (
plain_local_edit_facts), not from pictures or comments, and this pull request does not change it.Numbers
Release builds with LTO off (
CARGO_PROFILE_RELEASE_LTO=off, 16 codegen units), macOS arm64, Python 3.14. The base is#449 built the same way, measured back to back with this branch. v0.17.0 is the published wheel (built with the
workspace release profile, fat LTO), about 15 % faster than the base on the same calls, which is consistent with the
build difference.
445_1.py(case 1 of the issue):The script sets the three properties in turn on the same 100 cells, so the later setters of the base and of v0.17.0
read a table whose cells already hold a run and properties: hence 6.8 to 7.8 ms for
Cell.shadingthere against4.0 ms below.
Mean cost of one call over the first 40 cells of a fresh table, base then this pull request (
bench_cells.py):Cell.textCell.vertical_alignmentCell.shadingCell.widthCell.set_borderCell.set_marginsParagraph.textThe same calls in a document with a picture or a comment, saved and reopened, are within 0.04 ms of these on this
branch and within 0.3 ms on the base.
Counted work of one call (debug build,
_word_splice_workowner visits), cell (0, 0) of a 2 x 5 and of a 40 x 5table: base 45 and 805 for
Cell.shading, 47 and 807 forCell.text, 50 and 810 for a cellParagraph.text. Thispull request: 9 and 9, 12 and 12, 15 and 15.
Case 2: open,
try_replace_textand saveNot changed.
445_2.py, base and this branch with the same CLI build (rdocx-clifrom this branch, release withoutLTO, which no change here touches):
Where the Python time goes (macOS
sample, unstripped release build of this branch, the script's 4000-paragraphinput, open, replace and save in a loop, 7766 samples in these three calls):
Document.openDocument::open996from_document1524: the snapshot read and the parse of every paragraphtry_replace_texttry_replace_all_expected_owned2494validate_word_facts(candidate)1436 (per-paragraph fact reads 1350), document clone 31saveThe two passes are 2960 samples, 38 % of the Python time. Without them the Python path would be about the CLI's
(about 0.59 s against 0.63 s, estimated from these shares, not measured).
Why neither is removed here:
from_documentchecks the opened source, so that an open error is raised byopenand not by the first handle (F-X283, pinned by
test_fx283_missing_external_link_still_refuses_open).validate_word_factsindormant_replacementschecks the replacement candidate before it is installed. The firstpass never reads the candidate, so its result does not stand for the second, and the second cannot raise the open
error at open. That is an argument from what each pass reads. Whether the candidate pass can raise on an input that
opened and whose replacement succeeded was not settled: six tries found none (a 5 MB replacement, a match in a
complex field result, a match across a field boundary, a match in a simple field result, a match across an internal
hyperlink, a match that empties a run between comment anchors). Proving that none exists, which removing the pass
would need, is not contained.
openbuilds the block pieces (WordPieces::assemble) and keepsthem, so that the replace pass re-reads only the blocks the replacement changed. Three costs: (1) the retained memory
v0.17.0 removed and F-X286 qualifies: a piece holds a copy of every body block model besides its facts, and an active
authority (owners, indexes and pieces) adds 52 MiB to a 129 MiB opened document for this input, (2)
openwouldraise the errors of the piece assembly and its full-reader fallback instead of
story_owner_snapshotsand theparagraph parse, the same only under the debug assertion that an assembled inventory has a full rebuild, (3) the
gain is partial: 1000 of the 4000 paragraphs change, so the replace pass would keep about a quarter of its 1350
samples of fact reads, an estimated ratio of about 1.3, still above the 1.2 criterion.
That is a change to what an opened document keeps, which F-X285 and F-X286 own. It is left to them.
Behaviour changes
None a caller can see. Internal ones:
_word_force_checked_route(True)(debug builds only) now also sends the cell setters to the whole-document route.Before, they kept the local route under it, so the differential test compared that route with itself.
checked when they were read or built.
holds_fieldflag may stay set after the field it saw is edited away, until the next full read of thetable. A set flag only asks the next whole-document publication to read the table again, which it already does for
a table holding a field.
Guards
crates/rdocx-py/tests/test_edit_publication_cost.py(no new file):FLATgainsCell.vertical_alignment,Cell.width,Cell.set_border,Cell.set_marginsandParagraph.textof a cell paragraph, next to
Cell.textandCell.shading(seven cell calls inCELL_CALLS)._word_piece_bytes, the standalone XML bytes of each body block whoseowners the checked reader reads again (counted in
word_block_owners, outside the guards, next to the existing countof reads). A count of reads alone could not tell a read of the cell frame from a read of the whole table.
alignments, owner visits, staging) for cell (0, 0) of a 2 x 5 and of a 40 x 5 table. It fails on Python edits: publish from the owner inventory, compare one block, edit properties without staging #449 for all seven
calls (owner visits 45 against 805 for
Cell.shading).word_block_ownersread of the wholecandidate table added to
apply_local_cell_editon purpose, which keeps the owner walk to the cell, all 14 casesfail (for
Cell.shadingbeside the large cell, 101,493 bytes read against 1,494). Without it they pass.and a line break, a character no save accepts, a refused negative margin), with four more held handles.
makes one, and both give the same held handles and saved parts. On Python edits: publish from the owner inventory, compare one block, edit properties without staging #449, before the field and row marker shapes were
added, the six
Cell.shadingandCell.textcases failed, since the switch did not reach these setters there.test_forced_checked_route_makes_the_passes_the_direct_routes_replacestates the checked route ofCell.shading(one document clone) and of
Cell.text(one walk, one full publication).Cell.textwith a character no save accepts andCell.set_marginswith a negative margin.On #449 the file as it was then (without the field and row marker shapes) gave 14 failures: the seven table axis cases,
six opened shapes and the forced route test. On this branch: 152 passed, 16 expected failures (the
GROWINGlist,unchanged).
Gates run locally
On the final tree (
5f4298ffd) unless said otherwise:cargo fmt --all -- --check: clean.cargo clippy --workspace --all-targets --all-features -- -D warnings: clean.python3 scripts/prose_check.py: 0 violations.python3 scripts/readme_doctests.py: passes, with therdocxarchive row re-recorded in its own commit.
cargo test -p rdocx-py --lib(the binding's Rust tests): 30 passed.maturin develop, dev profile at opt-level 2 with debug assertions), underPoppler 26.10, the whole
crates/rdocx-py/testsdirectory: 1550 passed, 2 skipped, 16 expected failures, 61failed. The 61 pin tools or a setup this machine does not have:
test_issue_253_pdf_text_view,test_colour_inputs_and_nested_font_formats_reach_actual_rendering,test_fx200_python_style_saved_output_paints_exact_expected_colours_with_deterministic_native_cliand the 58 testsof
test_rendering_threads.py. No debug assertion fired.mypy --strict crates/rdocx-py/tests/typing_smoke.pyandpython -m mypy.stubtest rdocx: noissues.
On the previous revision of this branch (
89da465a1), whoserdocxcrate is the same as this tree's (the lastchanges touch
rdocx-py, its tests and the HLD only):python3 scripts/sync_agent_skills.py --check: 26 skills in sync.python3 scripts/hash_harness.py --check: 49entries match.
cargo build -p rdocx-cli: builds.cargo test -p rdocx --lib fx283_: 5 passed.cargo test -p rdocx --no-fail-fastunder Poppler 26.10: lib 1048 passed, 3 failed, 13 ignored. Integration 557passed, 5 failed, 8 ignored. Regression 2531 passed, 7 ignored. Doc tests 2 passed. The 8 failures pin renderers or
references this machine does not have: lib
large_word_and_presentation_pdfs_preserve_logical_reading_order,word_and_powerpoint_chart_pixels_are_identical(at the rasterizer version assert, after both SHA-256 checks) andfx195_variable_svg_paint_matches_independent_static_instances, integrationodt_reader_matches_pinned_libreoffice_structure,public_authored_theme_and_fonts_match_pinned_word_resolution,sanitized_public_authoring_fixture_passes_every_conformance_stage,section_page_semantics_match_pinned_libreoffice_renderandevery_conditional_table_region_matches_word.