From c0db50f677fcaab94994b7cb6033de6232c6c2a8 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 07:59:02 +0100 Subject: [PATCH 1/3] perf(rdocx): edit package properties without staging the document 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 #445. --- crates/rdocx/src/document.rs | 315 +++++++++++++++++++++++++++++------ crates/rdocx/src/lib.rs | 4 + 2 files changed, 272 insertions(+), 47 deletions(-) diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index 7f024a7ac..a09ac66fa 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -7436,6 +7436,40 @@ impl Drop for TransactionReadPhase { } } +#[cfg(debug_assertions)] +thread_local! { + static STAGING_CLONES: Cell = const { Cell::new(0) }; + static STAGED_PROPERTIES_FORCED: Cell = const { Cell::new(false) }; +} + +/// Whole-document staging clones made on this thread since the last read. +/// Debug builds only. Reading resets the count. +#[cfg(debug_assertions)] +#[doc(hidden)] +pub fn take_staging_clones() -> usize { + STAGING_CLONES.with(|count| count.replace(0)) +} + +/// Make the properties setters stage a whole document, the reference their +/// direct route is compared with. Debug builds only. Returns the previous +/// choice. +#[cfg(debug_assertions)] +#[doc(hidden)] +pub fn force_staged_properties(force: bool) -> bool { + STAGED_PROPERTIES_FORCED.with(|forced| forced.replace(force)) +} + +fn staged_properties_forced() -> bool { + #[cfg(debug_assertions)] + { + STAGED_PROPERTIES_FORCED.with(Cell::get) + } + #[cfg(not(debug_assertions))] + { + false + } +} + fn note_transaction_clone() { #[cfg(debug_assertions)] TRANSACTION_WORK.with(|work| { @@ -8735,10 +8769,13 @@ fn assert_kept_main_document_without_initializing( #[allow(dead_code)] fn without_staging_work(run: impl FnOnce() -> T) -> T { let paused = STAGING_WORK_PAUSED.with(|cell| cell.replace(true)); + // A debug reference stages clones of its own, which are not the call's. + let clones = STAGING_CLONES.with(Cell::get); #[cfg(test)] let result = a9_without_lookup_work(run); #[cfg(not(test))] let result = run(); + STAGING_CLONES.with(|count| count.set(clones)); STAGING_WORK_PAUSED.with(|cell| cell.set(paused)); result } @@ -25128,6 +25165,8 @@ impl Document { /// Clone all package and typed state while discarding derived layout caches. pub fn clone_for_staging(&self) -> Self { + #[cfg(debug_assertions)] + STAGING_CLONES.with(|count| count.set(count.get() + 1)); Self { package: self.package.clone(), document: self.document.clone(), @@ -25201,7 +25240,7 @@ impl Document { /// Independent cold reference state for debug agreement oracles only. #[cfg(debug_assertions)] fn clone_for_debug_reference(&self) -> Self { - let mut copy = self.clone_for_staging(); + let mut copy = without_staging_work(|| self.clone_for_staging()); copy.parsed = None; copy.main_part_blocks = None; copy.main_body_scans = Arc::new(Mutex::new(MainBodyScans::default())); @@ -27125,6 +27164,106 @@ impl Document { candidate } + /// Apply `edit`, a properties edit, without staging the whole document. + /// + /// `edit` first reserves the properties part in the package graph and the + /// identifier registry, which can fail, then writes the properties model + /// and its part name, which cannot. The package graph, whose part bytes + /// are shared, and the registry are saved first and put back on refusal, + /// so a refused edit leaves no reserved name or relationship id. A + /// success leaves what [`Self::commit_staged_mutation`] leaves for a + /// staged clone: the derived layout is dropped and a signed package + /// records a package mutation. Debug builds run the staged edit on a + /// clone and compare. `edit` is `Fn` for that second run. + fn edit_properties(&mut self, edit: impl Fn(&mut Self) -> Result<()>) -> Result<()> { + if staged_properties_forced() { + let mut candidate = self.clone_for_staging(); + edit(&mut candidate)?; + self.commit_staged_mutation(candidate); + return Ok(()); + } + #[cfg(debug_assertions)] + let staged = without_staging_work(|| self.clone_for_staging()); + let package = self.package.clone(); + let identifiers = self.identifiers.clone(); + let result = edit(self); + match &result { + Ok(()) => { + self.package_signatures_invalidated |= + self.package.package_rels.items.iter().any(|relationship| { + relationship.rel_type == rel_types::DIGITAL_SIGNATURE_ORIGIN + }) && (self.package_signatures_invalidated + || crate::embedded::synchronized_package_mutation_invalidates_signature( + &package, + &self.package, + )); + self.layout_cache + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + self.deterministic_layout_cache + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + } + Err(_) => { + self.package = package; + self.identifiers = identifiers; + } + } + #[cfg(debug_assertions)] + self.assert_properties_edit_matches_staged(staged, &edit, &result); + result + } + + /// Debug proof that a direct properties edit left the package graph, the + /// properties models and their part names of the staged edit, or + /// refused with its error. + #[cfg(debug_assertions)] + fn assert_properties_edit_matches_staged( + &self, + mut staged: Self, + edit: &impl Fn(&mut Self) -> Result<()>, + result: &Result<()>, + ) { + match (result, edit(&mut staged)) { + (Ok(()), Ok(())) => { + assert!( + staged.package.same_package_as(&self.package), + "direct properties edit changed another package graph" + ); + assert_eq!( + staged.identifiers, self.identifiers, + "direct properties edit left another identifier registry" + ); + assert_eq!(staged.core_properties, self.core_properties); + assert_eq!( + format!("{:?}", staged.application_properties), + format!("{:?}", self.application_properties) + ); + assert_eq!(staged.custom_properties, self.custom_properties); + assert_eq!( + ( + &staged.core_properties_part_name, + &staged.application_properties_part_name, + &staged.custom_properties_part_name, + staged.custom_properties_owned, + ), + ( + &self.core_properties_part_name, + &self.application_properties_part_name, + &self.custom_properties_part_name, + self.custom_properties_owned, + ), + "direct properties edit named another part" + ); + } + (Err(direct), Err(staged)) => assert_eq!(direct.to_string(), staged.to_string()), + (Ok(()), Err(staged)) => panic!("direct properties edit hid the staged error {staged}"), + (Err(direct), Ok(())) => panic!("direct properties edit refused with {direct}"), + } + } + pub(crate) fn commit_staged_mutation(&mut self, candidate: Self) { *self = Self::finish_staged_candidate( &self.package, @@ -47904,11 +48043,11 @@ impl Document { /// Replace the complete core-properties model. pub fn set_core_properties(&mut self, properties: CoreProperties) -> Result<()> { - let mut candidate = self.clone_for_staging(); - candidate.reserve_core_properties_bundle()?; - candidate.core_properties = Some(Box::new(properties)); - self.commit_staged_mutation(candidate); - Ok(()) + self.edit_properties(|document| { + document.reserve_core_properties_bundle()?; + document.core_properties = Some(Box::new(properties.clone())); + Ok(()) + }) } /// Remove the complete core-properties part and its package relationship. @@ -47943,11 +48082,11 @@ impl Document { (two digits, a dot, four digits), which Word requires to open the file" ))); } - let mut candidate = self.clone_for_staging(); - candidate.reserve_application_properties_bundle()?; - candidate.application_properties = Some(properties); - self.commit_staged_mutation(candidate); - Ok(()) + self.edit_properties(|document| { + document.reserve_application_properties_bundle()?; + document.application_properties = Some(properties.clone()); + Ok(()) + }) } /// Remove the complete application-properties part and package relationship. @@ -48002,27 +48141,27 @@ impl Document { ))); } - let mut candidate = self.clone_for_staging(); - let created = candidate.custom_properties_part_name.is_none(); - candidate.reserve_custom_properties_bundle()?; - let properties = candidate - .custom_properties - .get_or_insert_with(CustomProperties::default); - if let Some(index) = properties - .properties - .iter() - .position(|existing| existing.name.as_deref() == Some(name)) - { - properties + self.edit_properties(|document| { + let created = document.custom_properties_part_name.is_none(); + document.reserve_custom_properties_bundle()?; + let properties = document + .custom_properties + .get_or_insert_with(CustomProperties::default); + if let Some(index) = properties .properties - .retain(|existing| existing.name.as_deref() != Some(name)); - properties.properties.insert(index, property); - } else { - properties.properties.push(property); - } - candidate.custom_properties_owned |= created; - self.commit_staged_mutation(candidate); - Ok(()) + .iter() + .position(|existing| existing.name.as_deref() == Some(name)) + { + properties + .properties + .retain(|existing| existing.name.as_deref() != Some(name)); + properties.properties.insert(index, property.clone()); + } else { + properties.properties.push(property.clone()); + } + document.custom_properties_owned |= created; + Ok(()) + }) } /// Remove one named custom property. @@ -48035,23 +48174,24 @@ impl Document { else { return Ok(None); }; - let mut candidate = self.clone_for_staging(); - let properties = candidate - .custom_properties - .as_mut() - .expect("custom property lookup proved the model exists"); - properties - .properties - .retain(|property| property.name.as_deref() != Some(name)); - if properties.properties.is_empty() && candidate.custom_properties_owned { - if let Some(part_name) = candidate.custom_properties_part_name.take() { - candidate - .remove_package_properties_bundle(&part_name, rel_types::CUSTOM_PROPERTIES); + self.edit_properties(|document| { + let properties = document + .custom_properties + .as_mut() + .expect("custom property lookup proved the model exists"); + properties + .properties + .retain(|property| property.name.as_deref() != Some(name)); + if properties.properties.is_empty() && document.custom_properties_owned { + if let Some(part_name) = document.custom_properties_part_name.take() { + document + .remove_package_properties_bundle(&part_name, rel_types::CUSTOM_PROPERTIES); + } + document.custom_properties = None; + document.custom_properties_owned = false; } - candidate.custom_properties = None; - candidate.custom_properties_owned = false; - } - self.commit_staged_mutation(candidate); + Ok(()) + })?; Ok(Some(removed)) } @@ -94632,3 +94772,84 @@ fn issue434_insert_document_keeps_effective_font() { ); } } + +#[cfg(test)] +#[test] +fn issue445_properties_edits_stage_no_document_and_refuse_without_a_trace() { + let custom = |value: &str| CustomProperty { + fmtid: "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}".to_owned(), + pid: 2, + name: Some("Client".to_owned()), + value: crate::CustomPropertyValue::Lpwstr(value.to_owned()), + }; + let titled = |title: &str| CoreProperties { + title: Some(title.to_owned()), + ..CoreProperties::default() + }; + let mut document = Document::new(); + document.add_paragraph("body"); + #[cfg(debug_assertions)] + let _ = take_staging_clones(); + document.set_core_properties(titled("kept")).unwrap(); + let mut application = AppProperties::default(); + application.company = Some("kept".to_owned()); + document.set_application_properties(application).unwrap(); + document.set_custom_property(custom("first")).unwrap(); + assert_eq!( + document.remove_custom_property("Client").unwrap(), + Some(custom("first")) + ); + document.set_custom_property(custom("kept")).unwrap(); + #[cfg(debug_assertions)] + assert_eq!(take_staging_clones(), 0); + + // A relationship id range without a free id refuses after the part name + // of a new bundle is reserved. + let mut exhausted = Document::new(); + exhausted.package.package_rels.items[0].id = "rId4294967295".to_owned(); + let before = exhausted.clone_for_staging(); + let refusal = exhausted + .set_custom_property(custom("refused")) + .unwrap_err(); + assert!( + refusal + .to_string() + .contains("relationship id range is exhausted"), + "{refusal}" + ); + assert_eq!(exhausted.identifiers, before.identifiers); + assert!(before.package.same_package_as(&exhausted.package)); + assert_eq!(exhausted.custom_properties, None); + assert_eq!(exhausted.custom_properties_part_name, None); + + // A repeated package relationship id makes every reservation refuse + // before it reserves anything. + let repeated = document.package.package_rels.items[0].clone(); + document.package.package_rels.items.push(repeated); + let before = document.clone_for_staging(); + let refusals = [ + document.set_core_properties(titled("refused")).unwrap_err(), + document + .set_application_properties(AppProperties::default()) + .unwrap_err(), + document.set_custom_property(custom("refused")).unwrap_err(), + ]; + for refusal in refusals { + assert!( + refusal.to_string().contains("duplicate relationship id"), + "{refusal}" + ); + } + assert!(before.package.same_package_as(&document.package)); + assert_eq!(document.identifiers, before.identifiers); + assert_eq!(document.core_properties, before.core_properties); + assert_eq!(document.custom_properties, before.custom_properties); + assert_eq!( + document + .application_properties + .as_ref() + .and_then(|properties| properties.company.as_deref()), + Some("kept") + ); + assert!(before.saves_as(&document).is_err()); +} diff --git a/crates/rdocx/src/lib.rs b/crates/rdocx/src/lib.rs index 1d4531b13..19615f752 100644 --- a/crates/rdocx/src/lib.rs +++ b/crates/rdocx/src/lib.rs @@ -67,8 +67,12 @@ pub use content_control::{ FormFieldTarget, FormFieldValue, FormResetValue, FormValidationIssue, }; #[cfg(debug_assertions)] +pub use document::force_staged_properties; +#[cfg(debug_assertions)] pub use document::take_reopen_work; #[cfg(debug_assertions)] +pub use document::take_staging_clones; +#[cfg(debug_assertions)] pub use document::take_staging_work; pub use document::{ AccessibilityIssue, BodyContentRef, BodyItemContext, BodyItemOwners, BodyItemRef, From 4b1db54383bc905946e059d780880dbbc1e7d5d2 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 08:17:04 +0100 Subject: [PATCH 2/3] perf(rdocx-py): publish from the owner inventory and compare one block 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 #445. --- Cargo.lock | 1 + crates/rdocx-py/Cargo.toml | 1 + crates/rdocx-py/src/document.rs | 265 +++++++++++- crates/rdocx-py/src/formatting.rs | 4 +- crates/rdocx-py/src/lib.rs | 7 + crates/rdocx-py/src/paragraph.rs | 16 +- crates/rdocx-py/src/run.rs | 15 +- crates/rdocx-py/src/table.rs | 16 +- .../tests/test_edit_publication_cost.py | 404 ++++++++++++++++++ docs/hld/10-bindings-spec.md | 38 ++ 10 files changed, 745 insertions(+), 22 deletions(-) create mode 100644 crates/rdocx-py/tests/test_edit_publication_cost.py diff --git a/Cargo.lock b/Cargo.lock index 3fe79eb4c..fb17b1406 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1597,6 +1597,7 @@ dependencies = [ name = "rdocx-py" version = "0.17.0" dependencies = [ + "oxml-core", "oxml-layout", "oxml-pdf", "oxml-py-support", diff --git a/crates/rdocx-py/Cargo.toml b/crates/rdocx-py/Cargo.toml index 0bb338862..aaeb2abd4 100644 --- a/crates/rdocx-py/Cargo.toml +++ b/crates/rdocx-py/Cargo.toml @@ -27,6 +27,7 @@ default = [] extension-module = ["pyo3/extension-module"] [dependencies] +oxml-core = { workspace = true } oxml-pdf = { workspace = true } oxml-layout = { workspace = true } oxml-py-support = { workspace = true } diff --git a/crates/rdocx-py/src/document.rs b/crates/rdocx-py/src/document.rs index 3047f7d94..c363a1d4a 100644 --- a/crates/rdocx-py/src/document.rs +++ b/crates/rdocx-py/src/document.rs @@ -64,12 +64,108 @@ fn guarded(work: impl FnOnce() -> T) -> T { impl Drop for Restore { fn drop(&mut self) { WORD_GUARDING.with(|cell| cell.set(self.0)); + if !self.0 { + // The guard's own document clones are not the call's. + let _ = rdocx::take_staging_clones(); + } } } - let _restore = Restore(WORD_GUARDING.with(|cell| cell.replace(true))); + let outer = WORD_GUARDING.with(|cell| cell.replace(true)); + if !outer { + WORD_DOCUMENT_CLONES.fetch_add( + rdocx::take_staging_clones(), + std::sync::atomic::Ordering::Relaxed, + ); + } + let _restore = Restore(outer); work() } +// Debug builds also count the whole-document passes a publication can +// make besides the inventory rebuild: staging clones of the document, story +// walks that resolve a route, save comparisons and full owner inventory +// publications, outside the guards that check a direct route against them. +// A test of the extension module then states which of them a call makes. +#[cfg(debug_assertions)] +static WORD_DOCUMENT_CLONES: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +static WORD_STORY_WALKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +static WORD_SAVE_COMPARES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +static WORD_FULL_PUBLICATIONS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); +#[cfg(debug_assertions)] +thread_local! { + static WORD_CHECKED_ROUTE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Count one walk of a whole story that resolves a route. +pub(crate) fn note_word_story_walk() { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_STORY_WALKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Count one comparison of two staged saves. +fn note_word_save_compare() { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_SAVE_COMPARES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Count one publication that matches the whole owner inventory again. +fn note_word_full_publication() { + #[cfg(debug_assertions)] + if !WORD_GUARDING.with(std::cell::Cell::get) { + WORD_FULL_PUBLICATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Whether a test asked every publication for its checked whole-document +/// route, in place of the routes that read the owner inventory or one +/// block. Always false in a release build. +fn checked_route_forced() -> bool { + #[cfg(debug_assertions)] + { + WORD_CHECKED_ROUTE.with(std::cell::Cell::get) + } + #[cfg(not(debug_assertions))] + { + false + } +} + +/// Document staging clones, story walks that resolve a route, save +/// comparisons and full owner inventory publications since the last read. +/// Debug builds only. Reading resets all four. +#[cfg(debug_assertions)] +#[pyfunction] +#[pyo3(name = "_word_publication_work")] +pub(crate) fn word_publication_work() -> (usize, usize, usize, usize) { + use std::sync::atomic::Ordering::Relaxed; + ( + WORD_DOCUMENT_CLONES.swap(0, Relaxed) + rdocx::take_staging_clones(), + WORD_STORY_WALKS.swap(0, Relaxed), + WORD_SAVE_COMPARES.swap(0, Relaxed), + WORD_FULL_PUBLICATIONS.swap(0, Relaxed), + ) +} + +/// Take the checked whole-document route for every publication and stage the +/// document for every properties edit, the references the direct routes are +/// compared with. Debug builds only. Returns the previous choice. +#[cfg(debug_assertions)] +#[pyfunction] +#[pyo3(name = "_word_force_checked_route")] +pub(crate) fn word_force_checked_route(force: bool) -> bool { + rdocx::force_staged_properties(force); + WORD_CHECKED_ROUTE.with(|cell| cell.replace(force)) +} + /// The whole-body work counted so far: owner inventory rebuilds and /// whole-source element reads. Debug builds only. Reading resets both. #[cfg(debug_assertions)] @@ -1875,6 +1971,7 @@ impl PySectionHandle { .ok_or_else(|| PyIndexError::new_err("section index out of range"))? .set_page_border(edge, style, width, space, color) .map_err(|error| rdocx_to_pyerr(py, error))?; + note_word_save_compare(); candidate .saves_as(&candidate) .map_err(|error| rdocx_to_pyerr(py, error))?; @@ -10486,7 +10583,12 @@ impl PyDocument { prepared: Option<(&PreparedWordRevision, &rdocx::Document)>, ) -> rdocx::Result { let document = prepared.map_or(&self.inner, |(_, candidate)| candidate); - match self.indexed_paragraph_location(location, prepared.map(|(prepared, _)| prepared)) { + let indexed = (!checked_route_forced()) + .then(|| { + self.indexed_paragraph_location(location, prepared.map(|(prepared, _)| prepared)) + }) + .flatten(); + match indexed { Some(indexed) => { #[cfg(debug_assertions)] assert_indexed_route(&indexed, || location.native(document), "paragraph"); @@ -10496,6 +10598,85 @@ impl PyDocument { } } + /// The route of the physical owner of a table handle's location in the + /// current document: from the inventory, which holds the route the + /// document resolves, or as the document resolves it. + pub(crate) fn table_route( + &self, + index: usize, + related: &Option, + ) -> rdocx::Result { + let native = || crate::table::TableLocation::new(index, related).native(&self.inner); + let indexed = (!checked_route_forced()) + .then(|| self.indexed_table_location(index, related, None)) + .flatten(); + match indexed { + Some(indexed) => { + // The walk of a related table only reads its story again, + // so the walk checks a body table alone. + #[cfg(debug_assertions)] + if related.is_none() { + assert_indexed_route(&indexed, native, "table"); + } + Ok(indexed) + } + None => native(), + } + } + + /// The route and run path of a run handle's physical owner: from the + /// inventory record of that owner, or as the document resolves it. + pub(crate) fn run_route( + &self, + state: &RevisionState, + ) -> PyResult<(rdocx::ContentLocation, rdocx_oxml::text::AcceptedRunPath)> { + if !checked_route_forced() + && let Some((_, owner)) = self.indexed_owner(state) + && let WordOwnerLocation::Run(location, path) = &owner.location + { + // The story walk of a recorded route only reads its story again, + // so the check is that the paragraph there holds this run path. + #[cfg(debug_assertions)] + assert!( + guarded(|| { + let current = + ParagraphLocation::Related(location.clone()).native(&self.inner)?; + self.inner.read_story_paragraph(¤t, |paragraph| { + (0..paragraph.run_count()) + .any(|index| paragraph.run_path(index).as_ref() == Some(path)) + }) + }) + .expect("an indexed run route resolves in the document"), + "indexed run route holds its run path" + ); + return Ok((location.clone(), path.clone())); + } + self.current_run_owner(state) + } + + /// The direct body slot of the paragraph that a body `location` and the + /// run owner `state` both name, from the inventory. A typed edit made + /// through `location` then changes that block and no other. + pub(crate) fn typed_run_edit_slot( + &self, + location: &ParagraphLocation, + state: &RevisionState, + ) -> Option { + if !matches!(location, ParagraphLocation::Body(_)) { + return None; + } + let (_, run) = self.indexed_owner(state)?; + let paragraph = self.owners.get(run.parent?)?; + let WordOwnerLocation::Paragraph(route) = ¶graph.location else { + return None; + }; + let indexed = self.indexed_paragraph_location(location, None)?; + (route.story().kind() == rdocx::StoryKind::Body + && route.index_path().len() == 1 + && same_content_owner(route, &indexed)) + .then_some(paragraph.body_slot?) + } + pub(crate) fn indexed_table_location( &self, index: usize, @@ -11256,6 +11437,7 @@ impl PyDocument { operation: &'static str, publication: WordPublication, ) -> PyResult { + note_word_full_publication(); self.ensure_word_authority(py)?; let forms = matches!( publication, @@ -11594,6 +11776,7 @@ impl PyDocument { operation: &'static str, publication: WordPublication, ) -> PyResult<()> { + note_word_save_compare(); if self .inner .saves_as(&candidate) @@ -11607,6 +11790,76 @@ impl PyDocument { Ok(()) } + /// Publish `candidate`, this document after one typed edit of the + /// direct body paragraph at `slot`, unless the edit changed nothing. The + /// answer is read from that block when it tells, and from the staged + /// save comparison of [`Self::publish_owner_candidate`] when it does + /// not. + pub(crate) fn publish_block_candidate( + &mut self, + py: Python<'_>, + candidate: rdocx::Document, + operation: &'static str, + publication: WordPublication, + slot: usize, + ) -> PyResult<()> { + let Some(same) = self.direct_paragraph_saves_as(&candidate, slot) else { + return self.publish_owner_candidate(py, candidate, operation, publication); + }; + // The staged comparison saves the whole candidate and refuses when + // content outside this block cannot be saved. It checks the block + // answer whenever it gives one. + #[cfg(debug_assertions)] + if let Ok(saved) = guarded(|| self.inner.saves_as(&candidate)) { + assert_eq!(saved, same, "direct body paragraph save comparison"); + } + if same { + return Ok(()); + } + let prepared = self.prepare_word_revision(py, &candidate, operation, publication)?; + self.commit_word_revision(prepared)?; + self.install_inner(candidate); + Ok(()) + } + + /// Whether `candidate`, this document after one typed edit of the + /// direct body paragraph at `slot`, saves as this document, read from + /// that block alone. Equal paragraph models save the same bytes. Two + /// plain paragraphs whose checked reader facts differ, the text and the + /// run paths of [`rdocx::Document::direct_body_paragraph_facts`], save + /// different bytes, as a plain paragraph holds nothing a save + /// renumbers. `None` leaves the answer to the staged save: another + /// paragraph shape, a body whose save is known to fail, text a save + /// refuses, or facts that do not tell. The block answer does not save + /// the rest of the document, so content elsewhere that no save accepts + /// is reported by the save itself, as after `Paragraph.text`. + fn direct_paragraph_saves_as(&self, candidate: &rdocx::Document, slot: usize) -> Option { + if checked_route_forced() || self.inner.unsavable_body_edit().is_some() { + return None; + } + let ( + rdocx_oxml::BodyContent::Paragraph(current), + rdocx_oxml::BodyContent::Paragraph(edited), + ) = ( + self.inner.body_children().get(slot)?, + candidate.body_children().get(slot)?, + ) + else { + return None; + }; + if current == edited { + return Some(true); + } + let before = self.inner.direct_body_paragraph_facts(current).ok()??; + let after = candidate.direct_body_paragraph_facts(edited).ok()??; + // A save refuses a character XML 1.0 cannot carry, with its place in + // the part. The block reader does not, so the staged save answers. + if !after.0.chars().all(oxml_core::xml::is_xml_1_0_character) { + return None; + } + (before != after).then_some(false) + } + pub(crate) fn local_cell_route( &self, state: &RevisionState, @@ -12233,6 +12486,7 @@ impl PyDocument { candidate: rdocx::Document, operation: &'static str, ) -> PyResult<()> { + note_word_save_compare(); if self .inner .saves_as(&candidate) @@ -12257,6 +12511,7 @@ impl PyDocument { operation: &'static str, publication: WordPublication, ) -> PyResult<()> { + note_word_save_compare(); if self .inner .saves_as(&candidate) @@ -16024,10 +16279,10 @@ impl PyDocument { "chart legend requires a direct body paragraph", )); }; - let location = ParagraphLocation::Body(index) - .native(&slf.borrow(py).inner) - .map_err(|e| rdocx_to_pyerr(py, e))?; let mut document = slf.borrow_mut(py); + let location = document + .paragraph_route(&ParagraphLocation::Body(index), None) + .map_err(|e| rdocx_to_pyerr(py, e))?; let mut candidate = document.inner.clone_for_staging(); candidate .set_chart_legend(index, visible, position, overlay) diff --git a/crates/rdocx-py/src/formatting.rs b/crates/rdocx-py/src/formatting.rs index 1b1209f9a..f6151c77d 100644 --- a/crates/rdocx-py/src/formatting.rs +++ b/crates/rdocx-py/src/formatting.rs @@ -1266,8 +1266,8 @@ pub(crate) fn apply_paragraph_update( ParagraphLocation::Related(related.clone()) .edit(&mut candidate, |paragraph| update.apply(paragraph)) .map_err(|error| crate::rdocx_to_pyerr(py, error))?; - let native = location - .native(&document.inner) + let native = document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?; return document.publish_owner_candidate( py, diff --git a/crates/rdocx-py/src/lib.rs b/crates/rdocx-py/src/lib.rs index 75f49ce75..507084c94 100644 --- a/crates/rdocx-py/src/lib.rs +++ b/crates/rdocx-py/src/lib.rs @@ -139,6 +139,13 @@ fn _rdocx(module: &Bound<'_, PyModule>) -> PyResult<()> { #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_whole_body_work, module)?)?; #[cfg(debug_assertions)] + module.add_function(wrap_pyfunction!(document::word_publication_work, module)?)?; + #[cfg(debug_assertions)] + module.add_function(wrap_pyfunction!( + document::word_force_checked_route, + module + )?)?; + #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_splice_work, module)?)?; #[cfg(debug_assertions)] module.add_function(wrap_pyfunction!(document::word_transaction_work, module)?)?; diff --git a/crates/rdocx-py/src/paragraph.rs b/crates/rdocx-py/src/paragraph.rs index 4b6b5e837..d15ee70b7 100644 --- a/crates/rdocx-py/src/paragraph.rs +++ b/crates/rdocx-py/src/paragraph.rs @@ -177,6 +177,7 @@ impl ParagraphLocation { location: &rdocx::ContentLocation, ) -> rdocx::Result { crate::document::note_fx260_word(document.content_count().max(1)); + crate::document::note_word_story_walk(); let owner = location.story(); let story = document .stories()? @@ -199,6 +200,9 @@ impl ParagraphLocation { document: &rdocx::Document, ) -> rdocx::Result { crate::document::note_fx260_word(document.content_count().max(1)); + if !matches!(self, Self::Related(_)) { + crate::document::note_word_story_walk(); + } match self { Self::Body(index) => document.paragraph_story_location(*index)?.ok_or_else(|| { rdocx::Error::Other("paragraph has no checked physical owner".to_owned()) @@ -546,8 +550,8 @@ impl PyParagraph { .map_err(|error| crate::rdocx_to_pyerr(py, error))? .ok_or_else(|| PyIndexError::new_err("inserted link run was not found"))?; let publication = crate::document::WordPublication::ParagraphAppend( - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?, ); let prepared = document.prepare_word_revision( @@ -640,8 +644,8 @@ impl PyParagraph { "Paragraph.add_run" }; let publication = crate::document::WordPublication::ParagraphAppend( - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?, ); let prepared = @@ -875,8 +879,8 @@ impl PyParagraph { .edit(&mut candidate, |p| p.add_equation(equation)) .map_err(|e| crate::rdocx_to_pyerr(py, e))?; let publication = crate::document::WordPublication::ParagraphAppend( - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map_err(|error| crate::rdocx_to_pyerr(py, error))?, ); let prepared = document.prepare_word_revision( diff --git a/crates/rdocx-py/src/run.rs b/crates/rdocx-py/src/run.rs index f8f8029f6..3b466b8a8 100644 --- a/crates/rdocx-py/src/run.rs +++ b/crates/rdocx-py/src/run.rs @@ -296,20 +296,31 @@ impl PyRun { let mut document = self.document.borrow_mut(py); let publication = match &self.owner { Some(owner) => { - let (location, path) = document.current_run_owner(owner)?; + let (location, path) = document.run_route(owner)?; crate::document::WordPublication::RunText(crate::document::WordOwnerLocation::Run( location, path, )) } None => crate::document::WordPublication::Conservative, }; + // The typed edit below changes the paragraph of this run and nothing + // else, so a run of a direct body paragraph compares that block. + let slot = self + .owner + .as_ref() + .and_then(|owner| document.typed_run_edit_slot(&location, owner)); let mut candidate = document.inner.clone_for_staging(); location .edit(&mut candidate, |paragraph| { paragraph.edit_run(&self.run_path, |run| run.set_text(text)) }) .map_err(|error| crate::rdocx_to_pyerr(py, error))?; - document.publish_owner_candidate(py, candidate, "Run.text", publication) + match slot { + Some(slot) => { + document.publish_block_candidate(py, candidate, "Run.text", publication, slot) + } + None => document.publish_owner_candidate(py, candidate, "Run.text", publication), + } } #[pyo3(signature = (data, filename=None, width=None, height=None, *, options=None))] diff --git a/crates/rdocx-py/src/table.rs b/crates/rdocx-py/src/table.rs index b57d64f0d..89359d968 100644 --- a/crates/rdocx-py/src/table.rs +++ b/crates/rdocx-py/src/table.rs @@ -61,7 +61,7 @@ pub(crate) enum TableLocation { Related(rdocx::ContentLocation), } impl TableLocation { - fn new(index: usize, related: &Option) -> Self { + pub(crate) fn new(index: usize, related: &Option) -> Self { related.as_ref().map_or(Self::Body(index), |location| { Self::Related(location.clone()) }) @@ -74,6 +74,7 @@ impl TableLocation { match self { Self::Related(location) => Self::refreshed(document, location), Self::Body(index) => { + crate::document::note_word_story_walk(); let slot = document.content_index_of_table(*index).ok_or_else(|| { rdocx::Error::Other("table has no checked direct physical owner".into()) })?; @@ -91,6 +92,7 @@ impl TableLocation { location: &rdocx::ContentLocation, ) -> rdocx::Result { crate::document::note_fx260_word(document.content_count().max(1)); + crate::document::note_word_story_walk(); let owner = location.story(); let story = document .stories()? @@ -1202,8 +1204,8 @@ impl PyTable { } .map_err(|error| rdocx_to_pyerr(py, error))?; let publication = crate::document::WordPublication::TableGrid( - TableLocation::new(index, ¤t_related) - .native(&document.inner) + document + .table_route(index, ¤t_related) .map_err(|error| rdocx_to_pyerr(py, error))?, ); let prepared = @@ -1359,8 +1361,8 @@ impl PyTable { } .map_err(|error| rdocx_to_pyerr(py, error))?; let publication = crate::document::WordPublication::TableGrid( - TableLocation::new(table_index, ¤t_related) - .native(&document.inner) + document + .table_route(table_index, ¤t_related) .map_err(|error| rdocx_to_pyerr(py, error))?, ); let prepared = @@ -2585,8 +2587,8 @@ impl PyCell { None => candidate.try_set_cell_text(table, row, cell, value), } .map_err(|error| rdocx_to_pyerr(py, error))?; - let publication = TableLocation::new(table, ¤t_related) - .native(&document.inner) + let publication = document + .table_route(table, ¤t_related) .map(|location| crate::document::WordPublication::CellText(location, row, cell)) .unwrap_or(crate::document::WordPublication::Conservative); let prepared = document.prepare_word_revision(py, &candidate, "Cell.text", publication)?; diff --git a/crates/rdocx-py/tests/test_edit_publication_cost.py b/crates/rdocx-py/tests/test_edit_publication_cost.py new file mode 100644 index 000000000..df1b78563 --- /dev/null +++ b/crates/rdocx-py/tests/test_edit_publication_cost.py @@ -0,0 +1,404 @@ +"""Which whole-document passes a mutating call makes when it publishes, and that the direct routes agree with the +checked ones. + +A whole-document pass is work in proportion to the document whatever the edit: a staging clone of the document, a +walk of a story to resolve a route, a comparison of two staged saves, a publication that matches the whole owner +inventory, a rebuild of that inventory, a reopen of the package. The debug build of the extension counts them +(`_word_publication_work`, `_word_whole_body_work`, `_reopen_work`) outside the guards that check a direct route, so +the counts are those of the call. No timing is read. + +FLAT names the calls that make no such pass and do the same counted work in a body four times larger. GROWING names +the others with the passes each one still makes. The flat test is a strict expected failure for a GROWING call, and +its passes are asserted exactly, so a change that makes a call flat or removes one of its passes fails until the entry +moves or shrinks, and a change that adds a pass fails as well. + +`_word_force_checked_route` makes every publication resolve its route by a story walk and compare staged saves, and +every properties edit stage the document: the checked whole-document routes the direct ones replace. Each call must +give the same result, the same saved parts and the same held handles on both. +""" +import datetime +import re +from io import BytesIO +from types import SimpleNamespace +from zipfile import ZipFile + +import pytest + +import rdocx +from rdocx import _rdocx + +pytestmark = pytest.mark.skipif( + not hasattr(_rdocx, "_word_publication_work"), + reason="the publication counters and the route switch exist in debug builds only", +) + +BODY = 8 +STAMP = datetime.datetime(2026, 10, 1, 12, tzinfo=datetime.timezone.utc) + + +def build(paragraphs): + """A body of `paragraphs` paragraphs, then a 2x2 table and a paragraph of the runs "alpha " and "beta".""" + document = rdocx.Document() + for index in range(paragraphs): + document.add_paragraph(f"Body paragraph {index}") + document.add_table(2, 2) + document.add_paragraph("alpha ").add_run("beta") + return document + + +def targets(document): + paragraph = document.paragraphs[-1] + return SimpleNamespace(document=document, paragraph=paragraph, run=paragraph.runs[1], table=document.tables[0]) + + +def setter(owner, name, value): + """Set `name` on the object `owner` gives, taken before the call is counted.""" + return lambda t: (lambda target=owner(t): setattr(target, name, value)) + + +def method(owner, name, *arguments): + return lambda t: (lambda target=owner(t): getattr(target, name)(*arguments)) + + +def core(t): + return t.document.core_properties + + +def app(t): + return t.document.app_properties + + +def custom(t): + return t.document.custom_properties + + +def with_client(t): + properties = t.document.custom_properties + properties.set("Client", "ACME") + return properties + + +def cell(t): + return t.table.cell(0, 0) + + +def cell_with_table(t): + """A cell that holds a table, which the selected-table candidate of a cell edit declines.""" + t.table.cell(0, 0).add_table(1, 1) + return t.document.tables[0].cell(0, 0) + + +def bookmarked(t): + start, end = rdocx.RunPosition(body_index=0, run_index=0), rdocx.RunPosition(body_index=0, run_index=1) + t.document.add_bookmark("mark", rdocx.RunRange(start=start, end=end)) + return t.document.paragraphs[-1] + + +def with_chart(t): + data = rdocx.CategoryChartData() + data.categories = ["a", "b"] + data.add_series("series", (1.0, 2.0)) + chart = t.document.add_chart(rdocx.XL_CHART_TYPE.COLUMN_CLUSTERED, data, rdocx.Inches(3), rdocx.Inches(2)) + return lambda: t.document.set_chart_legend(chart, visible=True, position="b") + + +CALLS = { + "AppProperties.application": setter(app, "application", "An application"), + "AppProperties.application_version": setter(app, "application_version", "16.0000"), + "AppProperties.company": setter(app, "company", "A company"), + "AppProperties.manager": setter(app, "manager", "A manager"), + "AppProperties.presentation_format": setter(app, "presentation_format", "A format"), + "AppProperties.template": setter(app, "template", "A template"), + "CustomProperties.set": method(custom, "set", "Client", "ACME"), + "CustomProperties.__setitem__": method(custom, "__setitem__", "Client", "ACME"), + "CustomProperties.delete": method(with_client, "delete", "Client"), + "CustomProperties.__delitem__": method(with_client, "__delitem__", "Client"), + "Font.bold": setter(lambda t: t.run.font, "bold", True), + "Paragraph.alignment": setter(lambda t: t.paragraph, "alignment", rdocx.WD_ALIGN_PARAGRAPH.CENTER), + "ParagraphFormat.left_indent": setter(lambda t: t.paragraph.paragraph_format, "left_indent", rdocx.Inches(1)), + "Cell.text": setter(cell, "text", "12.50"), + "Cell.shading": setter(cell, "shading", "D9E2F3"), + "Paragraph.add_run": method(lambda t: t.paragraph, "add_run", " gamma"), + "Paragraph.add_hyperlink": method(lambda t: t.paragraph, "add_hyperlink", "link", "https://example.com/a"), + "Paragraph.add_internal_hyperlink": method(bookmarked, "add_internal_hyperlink", "link", "mark"), + "Paragraph.add_equation": lambda t: (lambda target=t.paragraph: target.add_equation("x^2", format="latex")), + "Cell.text of a cell that holds a table": setter(cell_with_table, "text", "12.50"), + "Document.set_chart_legend": with_chart, + "Paragraph.text": setter(lambda t: t.paragraph, "text", "changed"), + "Run.text": setter(lambda t: t.run, "text", "changed"), + "Run.add_break": method(lambda t: t.run, "add_break"), + "Run.add_tab": method(lambda t: t.run, "add_tab"), + "Table.style": setter(lambda t: t.table, "style", "Table Grid"), + "Table.add_row": method(lambda t: t.table, "add_row"), + "Table.remove_row": method(lambda t: t.table, "remove_row", 1), + "Settings.track_revisions": setter(lambda t: t.document.settings, "track_revisions", True), + "Document.add_paragraph": method(lambda t: t.document, "add_paragraph", "new"), + "Document.add_table": method(lambda t: t.document, "add_table", 1, 1), +} +for name in ("author", "category", "comments", "content_status", "identifier", "keywords", "language", + "last_modified_by", "subject", "title", "version"): + CALLS[f"CoreProperties.{name}"] = setter(core, name, f"A {name}") +for name in ("created", "modified", "last_printed"): + CALLS[f"CoreProperties.{name}"] = setter(core, name, STAMP) +CALLS["CoreProperties.revision"] = setter(core, "revision", 7) + +# Calls that make no whole-document pass and do the same counted work whatever the body. +FLAT = ( + "AppProperties.application", "AppProperties.application_version", "AppProperties.company", + "AppProperties.manager", "AppProperties.presentation_format", "AppProperties.template", + "CoreProperties.author", "CoreProperties.category", "CoreProperties.comments", "CoreProperties.content_status", + "CoreProperties.created", "CoreProperties.identifier", "CoreProperties.keywords", "CoreProperties.language", + "CoreProperties.last_modified_by", "CoreProperties.last_printed", "CoreProperties.modified", + "CoreProperties.revision", "CoreProperties.subject", "CoreProperties.title", "CoreProperties.version", + "CustomProperties.__delitem__", "CustomProperties.__setitem__", "CustomProperties.delete", + "CustomProperties.set", + "Font.bold", "Paragraph.alignment", "ParagraphFormat.left_indent", "Cell.text", "Cell.shading", +) + +# Calls whose work grows with the body, with the whole-document passes each one makes. A walk in an entry resolves +# the story address its native edit takes, not the route of its publication. An empty entry makes no pass but visits +# every owner record. +GROWING = { + "Paragraph.add_run": {"clones": 1, "publications": 1}, + "Paragraph.add_hyperlink": {"clones": 2, "publications": 1}, + "Paragraph.add_internal_hyperlink": {"clones": 6, "walks": 1, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Paragraph.add_equation": {"clones": 1, "publications": 1}, + "Cell.text of a cell that holds a table": {"clones": 4, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Document.set_chart_legend": {"clones": 5, "compares": 1, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Paragraph.text": {"clones": 1, "publications": 1}, + "Run.text": {"clones": 1, "publications": 1}, + "Run.add_break": {"clones": 1}, + "Run.add_tab": {"clones": 1}, + "Table.style": {"clones": 1}, + "Table.add_row": {"clones": 3, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Table.remove_row": {"clones": 4, "publications": 1, "rebuilds": 1, "reopens": 1}, + "Settings.track_revisions": {"clones": 1}, + "Document.add_paragraph": {}, + "Document.add_table": {}, +} + + +def work(): + """The whole-document passes and the other counted work since the last read. Reading resets every counter.""" + clones, walks, compares, publications = _rdocx._word_publication_work() + rebuilds, source_reads = _rdocx._word_whole_body_work() + passes = {"clones": clones, "walks": walks, "compares": compares, "publications": publications, + "rebuilds": rebuilds, "reopens": _rdocx._reopen_work()[0]} + rest = {"source_reads": source_reads, "piece_reads": _rdocx._word_piece_work(), + "alignments": _rdocx._word_piece_alignments(), "owner_visits": _rdocx._word_splice_work()[0], + "staging": list(_rdocx._staging_work())} + return {name: count for name, count in passes.items() if count}, rest + + +def measure(name, paragraphs): + act = CALLS[name](targets(build(paragraphs))) + work() + act() + return work() + + +@pytest.mark.parametrize("name", [ + pytest.param(name, marks=pytest.mark.xfail(strict=True, reason="its work still grows with the body")) + if name in GROWING else name + for name in sorted(CALLS) +]) +def test_call_makes_no_whole_document_pass_and_the_same_work_in_a_larger_body(name): + small, large = measure(name, BODY), measure(name, 4 * BODY) + assert small[0] == {} and large[0] == {} + assert small[1] == large[1] + + +@pytest.mark.parametrize("name", sorted(GROWING)) +def test_growing_call_makes_only_its_declared_whole_document_passes(name): + for paragraphs in (BODY, 4 * BODY): + assert measure(name, paragraphs)[0] == GROWING[name] + + +def test_every_call_is_flat_or_growing(): + assert not set(FLAT) & set(GROWING) + assert sorted(set(FLAT) | set(GROWING)) == sorted(CALLS) + + +def test_run_text_that_changes_nothing_publishes_nothing_and_saves_nothing(): + document = build(BODY) + run = document.paragraphs[-1].runs[1] + held = document.paragraphs[-1].runs[0] + work() + run.text = "beta" + assert work()[0] == {"clones": 1} + assert (run.text, held.text) == ("beta", "alpha ") + + +def test_run_text_of_a_paragraph_that_is_not_plain_keeps_the_staged_save_comparison(): + document = build(BODY) + paragraph = document.paragraphs[-1] + paragraph.add_hyperlink("link", "https://example.com/a") + run = document.paragraphs[-1].runs[1] + work() + run.text = "changed" + passes = work()[0] + assert passes["compares"] == 1 and passes["publications"] == 1 + assert document.paragraphs[-1].text == "alpha changedlink" + + +def test_run_text_publishes_beside_content_that_no_save_accepts_and_save_reports_it(): + def document(): + result = rdocx.Document() + result.add_paragraph("first") + result.add_paragraph("alpha ").add_run("beta") + result.paragraphs[0].text = "a\x00b" + return result + + for text, expected in (("changed", "alpha changed"), ("beta", "alpha beta")): + direct = document() + direct.paragraphs[1].runs[1].text = text + assert direct.paragraphs[1].text == expected + with pytest.raises(rdocx.PackageError, match="U\\+0000"): + direct.save(BytesIO()) + checked = document() + run = checked.paragraphs[1].runs[1] + previous = _rdocx._word_force_checked_route(True) + try: + with pytest.raises(rdocx.PackageError, match="U\\+0000"): + run.text = text + finally: + _rdocx._word_force_checked_route(previous) + assert checked.paragraphs[1].text == "alpha beta" + + +TEXT_BOX = "box" +TEXT_BOX_BODY = ( + "anchor ' + '' + '' + '' + f"{TEXT_BOX}" + f'{TEXT_BOX}' + "" +) + + +def text_box_format(): + """The document and the format of the paragraph in the text box of TEXT_BOX_BODY.""" + result = BytesIO() + with ZipFile(BytesIO(rdocx.Document().to_bytes())) as package, ZipFile(result, "w") as output: + for member in package.infolist(): + data = package.read(member.filename) + if member.filename == "word/document.xml": + data = re.sub(rb".*", TEXT_BOX_BODY.encode(), data, flags=re.S) + output.writestr(member, data) + document = rdocx.Document.from_bytes(result.getvalue()) + paragraph = next(item.paragraph for item in document.story_items + if item.kind == "paragraph" and item.story.kind == "text_box") + return document, paragraph.paragraph_format + + +def test_text_box_paragraph_format_walks_for_its_edit_address_alone(): + saved = {} + for forced, walks in ((False, 2), (True, 3)): + document, paragraph_format = text_box_format() + work() + previous = _rdocx._word_force_checked_route(forced) + try: + paragraph_format.left_indent = rdocx.Inches(1) + finally: + _rdocx._word_force_checked_route(previous) + passes = work()[0] + assert (passes["walks"], passes["compares"], passes["publications"]) == (walks, 1, 1) + saved[forced] = parts(document) + assert saved[False] == saved[True] + + +def parts(document): + stream = BytesIO() + document.save(stream) + with ZipFile(BytesIO(stream.getvalue())) as package: + return {name: package.read(name) for name in package.namelist()} + + +def probe(handle): + """What a held handle reads after the call, or the error that says it is stale.""" + try: + for name in ("text", "bold", "left_indent", "page_width"): + if hasattr(type(handle), name): + return "read", repr(getattr(handle, name)) + return "read", len(handle.rows) + except Exception as error: # noqa: BLE001 - the error is the result compared + return type(error).__name__, str(error) + + +def held_handles(document): + first, last = document.paragraphs[0], document.paragraphs[-1] + table = document.tables[0] + return { + "another paragraph": first, "its run": first.runs[0], "the paragraph": last, "its first run": last.runs[0], + "its second run": last.runs[1], "its font": last.runs[1].font, "its format": last.paragraph_format, + "the table": table, "a cell": table.cell(0, 0), "a cell paragraph": table.cell(1, 1).paragraphs[0], + "the section": document.section(0), + } + + +def outcome(prepare, forced): + document = build(BODY) + held = held_handles(document) + act = prepare(targets(document)) + previous = _rdocx._word_force_checked_route(forced) + try: + try: + value = act() + result = ("returned", type(value).__name__, getattr(value, "text", value if value is None else None)) + except Exception as error: # noqa: BLE001 - the error is the result compared + result = (type(error).__name__, str(error)) + finally: + _rdocx._word_force_checked_route(previous) + return result, {name: probe(handle) for name, handle in held.items()}, parts(document) + + +DIFFERENTIAL = dict(CALLS) +DIFFERENTIAL.update({ + "Run.text unchanged": setter(lambda t: t.run, "text", "beta"), + "Run.text with a character no save accepts": setter(lambda t: t.run, "text", "a\x00b"), + "Run.text with a tab and a line break": setter(lambda t: t.run, "text", "a\tb\nc"), + "Run.text emptied": setter(lambda t: t.run, "text", ""), + "AppProperties.application_version refused": setter(app, "application_version", "sixteen"), + "CustomProperties.delete of a missing name": method(custom, "__delitem__", "Missing"), +}) + + +@pytest.mark.parametrize("name", sorted(DIFFERENTIAL)) +def test_direct_route_gives_the_result_handles_and_saved_parts_of_the_checked_route(name): + direct, checked = outcome(DIFFERENTIAL[name], False), outcome(DIFFERENTIAL[name], True) + assert direct[0] == checked[0] + assert direct[1] == checked[1] + assert direct[2] == checked[2] + + +@pytest.mark.parametrize("name", [ + "Run.text with a character no save accepts", "AppProperties.application_version refused", + "CustomProperties.delete of a missing name", +]) +def test_refused_edit_changes_nothing(name): + untouched = build(BODY) + result, held, saved = outcome(DIFFERENTIAL[name], False) + assert result[0] != "returned" + assert saved == parts(untouched) + assert all(kind == "read" for kind, _ in held.values()) + + +def test_forced_checked_route_makes_the_passes_the_direct_routes_replace(): + forced = {} + previous = _rdocx._word_force_checked_route(True) + try: + for name in ("CoreProperties.title", "Paragraph.add_run", "Run.text", "Table.add_row"): + forced[name] = measure(name, BODY)[0] + finally: + _rdocx._word_force_checked_route(previous) + assert forced["CoreProperties.title"] == {"clones": 1} + assert forced["Paragraph.add_run"]["walks"] == 2 + assert (forced["Run.text"]["walks"], forced["Run.text"]["compares"]) == (1, 1) + assert forced["Table.add_row"]["walks"] == 1 diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index c5493ba53..ce7c154c7 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -5049,6 +5049,44 @@ physical table for local publication. Nested neighboring cells use checked publication so equal row/cell ordinals cannot exchange held authority. Signed width truncation and wrap, border validation and atomic nonnegative margin validation remain field-specific. +These publications take their selected route from the current owner inventory, +the record the checked reader prepared, without a story walk: Paragraph.add_run, +add_hyperlink and add_equation, Run.text, Table.add_row and remove_row, the +checked fallback of Cell.text, Document.set_chart_legend and a text box +ParagraphFormat. They read it through paragraph_route, table_route and +run_route. Debug builds also resolve a body paragraph or body table route by +the checked story walk and assert that both agree, story fingerprints aside. +For a run they assert that the paragraph at the route holds the run path. A +handle with no inventory record keeps the story walk. A call whose native edit +takes a checked story address still walks for that address: +Paragraph.add_internal_hyperlink, Run.add_picture, Run.replace_xml, +Table.replace_xml, Cell.merge, the note calls and a text box paragraph edit. + +Run.text of a run in a direct body paragraph decides whether its typed edit +changed anything from that block alone. Equal paragraph models publish +nothing. Two plain paragraphs whose checked reader text or run paths differ +publish without a staged save comparison. Text holding a character XML 1.0 +cannot carry, a paragraph that is not plain, a body with a known save failure +and facts that do not tell keep the staged comparison and its error. Every +other publisher keeps the staged comparison. The block answer does not save +the rest of the document. Content elsewhere that no save accepts therefore +does not refuse Run.text, and save reports it, as after Paragraph.text. Debug +builds assert the block answer against the staged comparison whenever that +comparison answers. + +Core, application and custom property setters do not stage the document. Their +only fallible step reserves the properties part in the package graph and the +identifier registry, so those two are saved first and put back on refusal. +Success drops the derived layout and records a signed package mutation, as the +staged commit does. Debug builds compare the package graph, the property models +and their part names with the staged edit. + +Debug builds count document staging clones, story walks that resolve a route, +staged save comparisons and full owner inventory publications in +_word_publication_work, outside the guards. _word_force_checked_route restores +the story walk, the staged comparison and the staged properties edit, so a +test can compare both routes of one call. + Current paragraph, table and cell capture uses derived exact-route indexes. Direct body paragraph slot lookup borrows its existing complete ContentLocation key, including fingerprint and end marker. Control-contained lookup retains its constructed key. This changes no retained owner, map insertion or publication policy. Body and cell-paragraph aliases are prepared from the native batch location projections when the owner inventory is prepared, including before candidate From e142eb084acef6cceced782968e824b3139dd423 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 07:59:04 +0100 Subject: [PATCH 3/3] record the archive measurements --- README.md | 2 +- scripts/readme_doctests.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0f39a02a2..b0fe6265c 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ The archive row uses `cargo package --locked --allow-dirty --no-verify` with all | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,501,789 compressed bytes, 56,396,845 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-09 | +| Crates.io archive: rdocx | 4,504,272 compressed bytes, 56,405,981 member bytes, 37 members | 0.17.0 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo package --locked --allow-dirty --no-verify` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-11-16 | | Large-document layout throughput | minimum 250 pages/s, observed 31,019.1 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | | Large-document layout peak allocation | maximum 64 MiB, observed 29.03 MiB | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 one-page paragraphs with deterministic fonts | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | peak live allocation | 2026-09-19 | | Large-document PDF throughput | minimum 1,000 pages/s, observed 60,058.0 pages/s | rdocx 0.14.0 | macOS 26.6.2, Apple M5 Max, arm64 | release, one test thread | 1,000 deterministic layout pages | `cargo test -p rdocx --test regression_test --release a_thousand_page_document_paginates_and_renders_within_the_declared_limits -- --ignored --exact --nocapture --test-threads=1` | pages per wall-clock second | 2026-09-19 | diff --git a/scripts/readme_doctests.py b/scripts/readme_doctests.py index bf17a18d9..abe03dee0 100644 --- a/scripts/readme_doctests.py +++ b/scripts/readme_doctests.py @@ -376,7 +376,7 @@ class ReadmeCase: "oxml-opc": "2026-11-06", "oxml-pdf": "2026-11-06", "oxml-sml": "2026-11-06", - "rdocx": "2026-11-09", + "rdocx": "2026-11-16", "rdocx-cli": "2026-11-07", "rdocx-html": "2026-11-06", "rdocx-layout": "2026-11-09", @@ -402,7 +402,7 @@ class ReadmeCase: "oxml-opc": (119_252, 486_417, 12), "oxml-pdf": (102_219, 478_926, 14), "oxml-sml": (24_956, 115_575, 6), - "rdocx": (4_501_789, 56_396_845, 37), + "rdocx": (4_504_272, 56_405_981, 37), "rdocx-cli": (126_182, 593_817, 8), "rdocx-html": (29_407, 118_370, 11), "rdocx-layout": (463_844, 2_543_127, 15),