From c6d69215037b7d8d08a5e35722e9664b97f0cc07 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 17:38:47 +0100 Subject: [PATCH 1/5] fix(rdocx-py): edit table cell paragraphs in place A setter on a table cell paragraph or its run (alignment, style, paragraph_format, font) resolved the checked physical route of the cell on every call: clone the document, serialize the whole body, walk every cell owner before the target and rescan the body for each one, then rewrite the paragraph through a staged reopen. Its cost grew with the cell's place in the table and with the body, so filling a table cell by cell was quadratic. When the cell holds no content control, the mutable cell ordinal and the reader's ordinal name the same paragraph, so the edit now goes through the modeled paragraph in place, as a body paragraph setter does. A cell with a content control keeps the checked route. A run handle takes its paragraph route from the prepared index before the native lookup, and CT_Body::tables is lazy, so selecting an early table stops there. Part of #437. --- crates/rdocx-oxml/src/document.rs | 9 +++--- crates/rdocx-py/src/paragraph.rs | 20 ++++++++++++- crates/rdocx-py/src/run.rs | 2 +- crates/rdocx-py/tests/test_core.py | 45 ++++++++++++++++++++++++++++++ docs/hld/10-bindings-spec.md | 7 +++++ 5 files changed, 77 insertions(+), 6 deletions(-) diff --git a/crates/rdocx-oxml/src/document.rs b/crates/rdocx-oxml/src/document.rs index ee704b0d0..90e5e7d0e 100644 --- a/crates/rdocx-oxml/src/document.rs +++ b/crates/rdocx-oxml/src/document.rs @@ -3669,15 +3669,16 @@ impl CT_Body { /// Get an iterator over only the tables. pub fn tables(&self) -> impl Iterator { - let mut tables = Vec::new(); - for content in &self.content { + // Lazy over the body children, so `nth` stops at the table it finds. + self.content.iter().flat_map(|content| { + let mut tables = Vec::new(); match content { BodyContent::Table(table) => tables.push(table.as_ref()), BodyContent::ContentControl(sdt) => sdt.collect_tables(SdtOwner::Body, &mut tables), BodyContent::Paragraph(_) | BodyContent::RawXml(_) => {} } - } - tables.into_iter() + tables + }) } /// Get a mutable iterator over only the tables. diff --git a/crates/rdocx-py/src/paragraph.rs b/crates/rdocx-py/src/paragraph.rs index 85a525928..ef7d441ab 100644 --- a/crates/rdocx-py/src/paragraph.rs +++ b/crates/rdocx-py/src/paragraph.rs @@ -265,7 +265,25 @@ impl ParagraphLocation { paragraph, } => { // The mutable ordinal accessor excludes controlled paragraphs. - // Resolve through the same checked physical route as the reader. + // When its last index reaches the reader's last paragraph, the + // cell has none, both ordinals name the same paragraph, and it + // is edited in place, as a body paragraph is. + { + let mut table = document.table_mut(*table).ok_or_else(|| { + rdocx::Error::Other("table index out of range".to_owned()) + })?; + let mut cell = table + .cell(*row, *cell) + .ok_or_else(|| rdocx::Error::Other("cell index out of range".to_owned()))?; + let count = cell.paragraph_count(); + if count > 0 && cell.paragraph_mut(count - 1).is_some() { + return edit(&mut cell.paragraph_mut(*paragraph).ok_or_else(|| { + rdocx::Error::Other("cell paragraph index out of range".to_owned()) + })?); + } + } + // Otherwise resolve through the same checked physical route as + // the reader. let location = document.cell_paragraph_story_location(*table, *row, *cell, *paragraph)?; document.edit_story_paragraph(&location, edit) diff --git a/crates/rdocx-py/src/run.rs b/crates/rdocx-py/src/run.rs index 3b65a90d4..884007be5 100644 --- a/crates/rdocx-py/src/run.rs +++ b/crates/rdocx-py/src/run.rs @@ -69,7 +69,7 @@ impl PyRun { )?; { let document = self.document.borrow(py); - match paragraph.native(&document.inner) { + match document.paragraph_route(¶graph, None) { Ok(location) => { let (path, owner) = document.capture_owner( &crate::document::WordOwnerLocation::Run(location, self.run_path.clone()), diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index 226fac421..40891a225 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -12141,6 +12141,51 @@ def test_issue398_controlled_cell_edit_selects_read_owner(target, operation, lea assert [p.text for p in reopened.tables[0].cell(0, 0).paragraphs] == expected +@pytest.mark.parametrize("body", [0, 200]) +@pytest.mark.parametrize("row", [0, 19]) +def test_issue437_cell_paragraph_setters_do_not_restage_the_package(body, row): + """A cell paragraph without content controls is edited in place, as a body + paragraph is, so its cost does not grow with the body or the cell's row.""" + import rdocx + from rdocx import _rdocx + from rdocx.shared import Pt + + staging = getattr(_rdocx, "_staging_work", None) + reopen = getattr(_rdocx, "_reopen_work", None) + if staging is None or reopen is None: + pytest.skip("release build: staging and reopen counters are debug-only") + doc = rdocx.Document() + doc.add_style("TT", based_on="Normal", font_size=Pt(9)) + table = doc.add_table(20, 3) + for r in range(20): + for c in range(3): + table.cell(r, c).text = f"r{r}c{c}" + for index in range(body): + doc.add_paragraph(f"body {index}") + paragraph = doc.tables[0].cell(row, 2).paragraphs[0] + paragraph_format = paragraph.paragraph_format + font = paragraph.runs[0].font + staging() + reopen() + scans = _rdocx._main_body_block_scans() + paragraph.alignment = 1 + paragraph.style = "TT" + paragraph_format.space_after = Pt(4) + font.size = Pt(11) + assert staging() == [0] * 6 + assert reopen() == [0] * 3 + assert _rdocx._main_body_block_scans() == scans + assert paragraph.text == f"r{row}c2" + assert paragraph.style == "TT" + reopened = rdocx.Document.from_bytes(doc.to_bytes()) + cell = reopened.tables[0].cell(row, 2).paragraphs[0] + assert (cell.text, cell.alignment, cell.style) == (f"r{row}c2", 1, "TT") + assert cell.paragraph_format.space_after == Pt(4) + assert cell.runs[0].font.size == Pt(11) + neighbour = reopened.tables[0].cell(row, 1).paragraphs[0] + assert (neighbour.alignment, neighbour.style) == (None, None) + + @pytest.mark.parametrize("run_count", [1, 2]) def test_issue389_first_run_local_publication_keeps_exact_owner_lifetimes(run_count): import rdocx diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index 6c18a1fc3..b7853420b 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -4587,6 +4587,13 @@ causal lifetime semantics. Source facts do not bypass native mutation admission. Ordinary parsing and physical picture snapshots keep their source authority, and invalid replacement or save candidates fail atomically. +A setter on a table cell paragraph or one of its runs edits the modeled +paragraph in place, as the same setter on a body paragraph does, when the +cell holds no content control. The mutable cell ordinal skips controlled +paragraphs, so a cell with a content control keeps the checked physical route +through `cell_paragraph_story_location`. A run handle of a cell paragraph +takes its paragraph route from the prepared index before the native lookup. + Complete Word owner snapshots use the native hidden `Document.story_owner_snapshots` provider across the existing crate boundary. Its four owned families retain full story items, physical cells, paragraph XML From 5043ff416a4059a1489538653c37ae80671a5985 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 17:48:01 +0100 Subject: [PATCH 2/5] perf(rdocx): keep the styles parse across edits Every staged edit cloned the styles model, serialized it and parsed the styles part again to compare the two, and a staged reopen parsed the part once more. Each edit then cost time in proportion to styles.xml, about 40 ms with a 419 KB styles part where the same edit takes 1.5 ms with rdocx's own 6 KB part. The styles model is now one Arc, so a staged clone shares it, and style edits copy it once through Arc::make_mut. The document keeps the styles part bytes it last read with their parse. A flush that finds the same part bytes and the same model Arc compares two pointers and writes nothing. A model that differs is compared by value and serialized when it really changed, as before. A staged reopen whose styles part keeps those bytes takes the kept parse. OpcPackage::get_part_shared returns the shared part bytes for that proof. Part of #437. --- crates/oxml-opc/src/package.rs | 7 ++ crates/rdocx/src/document.rs | 184 ++++++++++++++++++++++++--------- crates/rdocx/src/epub.rs | 41 ++++---- crates/rdocx/src/field.rs | 22 ++-- crates/rdocx/src/html.rs | 3 +- crates/rdocx/src/odt.rs | 3 +- docs/hld/03-architecture.md | 8 ++ 7 files changed, 185 insertions(+), 83 deletions(-) diff --git a/crates/oxml-opc/src/package.rs b/crates/oxml-opc/src/package.rs index 4e51df36a..0564c150b 100644 --- a/crates/oxml-opc/src/package.rs +++ b/crates/oxml-opc/src/package.rs @@ -539,6 +539,13 @@ impl OpcPackage { self.parts.get(key).map(|data| data.as_slice()) } + /// The shared bytes of the part [`Self::get_part`] finds. A clone of the + /// package shares them, so `Arc::ptr_eq` proves the bytes are unchanged. + pub fn get_part_shared(&self, part_name: &str) -> Option<&Arc>> { + let key = deterministic_part_key(&self.parts, part_name)?; + self.parts.get(key) + } + /// Return whether a case-equivalent normalized part name exists. pub fn contains_part(&self, part_name: &str) -> bool { deterministic_part_key(&self.parts, part_name).is_some() diff --git a/crates/rdocx/src/document.rs b/crates/rdocx/src/document.rs index 5065dcd8b..04c529dd3 100644 --- a/crates/rdocx/src/document.rs +++ b/crates/rdocx/src/document.rs @@ -7217,7 +7217,11 @@ pub struct Document { /// value. Reopen keeps it only when the reopened part bytes match. It is /// not a chain of older documents. main_part_blocks: Option, - pub(crate) styles: CT_Styles, + pub(crate) styles: Arc, + /// The styles part bytes the last flush read and their parsed model. A + /// staged clone shares both, so a flush that finds the same bytes and the + /// same model skips the parse, the comparison and the serialization. + styles_part_parse: Option<(Arc>, Arc)>, pub(crate) numbering: Option, /// Boxed, because debug builds keep many copies of `Document` on deep /// stacks, and the fifteen-field model would otherwise grow every one. @@ -22353,7 +22357,7 @@ impl Document { body_namespace_bindings: Vec::new(), plain_local_edit_blocked: false, unsavable_body_edit_cache: OnceLock::from(None), - styles, + styles: Arc::new(styles), numbering: None, core_properties, application_properties, @@ -22407,6 +22411,7 @@ impl Document { parsed: None, main_body_scans: Arc::new(Mutex::new(MainBodyScans::default())), main_part_blocks: None, + styles_part_parse: None, } } @@ -22468,6 +22473,7 @@ impl Document { parsed: self.parsed.clone(), main_body_scans: Arc::clone(&self.main_body_scans), main_part_blocks: self.main_part_blocks.clone(), + styles_part_parse: self.styles_part_parse.clone(), unsavable_body_edit_cache: self .unsavable_body_edit_cache .get() @@ -24347,7 +24353,7 @@ impl Document { } fn from_opened_package(package: OpcPackage, read_from_bytes: bool) -> Result { - Self::from_package_reusing(package, read_from_bytes, None, None, None) + Self::from_package_reusing(package, read_from_bytes, None, None, None, None) } fn from_package_reusing( @@ -24356,6 +24362,7 @@ impl Document { staged: Option<(&DocumentIdentifiers, &Parsed)>, blocks: Option<&MainPartBlocks>, writer_blocks: Option<&MainPartBlocks>, + styles_read: Option<(Arc>, Arc)>, ) -> Result { let (doc_part_name, _) = validated_word_package_class(&package)?; @@ -24410,14 +24417,21 @@ impl Document { Some(OpcPackage::resolve_rel_target(&doc_part_name, &rel.target)) }; - // Try to load styles, remembering where they came from. + // Try to load styles, remembering where they came from. A staged + // reopen whose styles part keeps the bytes it read reuses their parse. let styles_part_name = resolve_part(rel_types::STYLES); - let styles = match styles_part_name + let (styles, styles_part_parse) = match styles_part_name .as_deref() - .and_then(|p| package.get_part(p)) + .and_then(|p| package.get_part_shared(p)) { - Some(styles_xml) => CT_Styles::from_xml(styles_xml)?, - None => CT_Styles::new_default(), + Some(bytes) => { + let parsed = match styles_read { + Some((read, parsed)) if Arc::ptr_eq(&read, bytes) => parsed, + _ => Arc::new(CT_Styles::from_xml(bytes)?), + }; + (Arc::clone(&parsed), Some((Arc::clone(bytes), parsed))) + } + None => (Arc::new(CT_Styles::new_default()), None), }; // Try to load numbering definitions @@ -24661,6 +24675,7 @@ impl Document { ..MainBodyScans::default() })), main_part_blocks: None, + styles_part_parse, }) } @@ -25130,6 +25145,7 @@ impl Document { let embedded_invalidated_signatures = self.embedded_invalidated_signatures.clone(); let package_signatures_invalidated = self.package_signatures_invalidated; let opened = self.parsed.as_deref().filter(|_| in_memory); + let styles_read = self.styles_part_parse.clone(); let mut reopened = match opened { Some(opened) => Self::from_package_reusing( self.package.reread(&opened.package)?, @@ -25137,6 +25153,7 @@ impl Document { Some((&provenance, opened)), carried_blocks.as_ref(), carried_scans.serialized.as_ref(), + styles_read, )?, None => { let mut output = std::io::Cursor::new(Vec::new()); @@ -25778,13 +25795,38 @@ impl Document { } /// Write the in-memory document/styles back into the OPC package parts. + /// Whether the styles model differs from the styles part, as parsing the + /// part and comparing would answer. The parse is memoized on the part's + /// shared bytes. When the model equals it, the model takes the parsed + /// `Arc`, so the next flush of an unchanged model compares two pointers. + fn styles_differ_from_part(&mut self, styles_part: &str) -> bool { + let Some(bytes) = self.package.get_part_shared(styles_part).cloned() else { + return true; + }; + let parsed = match &self.styles_part_parse { + Some((read, parsed)) if Arc::ptr_eq(read, &bytes) => Arc::clone(parsed), + _ => match CT_Styles::from_xml(&bytes) { + Ok(parsed) => Arc::new(parsed), + Err(_) => { + self.styles_part_parse = None; + return true; + } + }, + }; + let differ = !Arc::ptr_eq(&parsed, &self.styles) && *parsed != *self.styles; + if !differ { + self.styles = Arc::clone(&parsed); + } + self.styles_part_parse = Some((bytes, parsed)); + differ + } + pub(crate) fn flush_to_package(&mut self) -> Result<()> { self.flush_document_to_package()?; // Serialize the styles part. A document opened without one still gets // rdocx's defaults written out, so make sure it is reachable: an // unreferenced, untyped part would simply be ignored by Word. - let styles_xml = self.styles.to_xml()?; let styles_part_name = self.styles_part_name.clone(); let styles_part = self .reserve_document_part_bundle( @@ -25797,13 +25839,9 @@ impl Document { Error::Other(format!("styles relationship allocation failed: {error}")) })?; self.styles_part_name = Some(styles_part.clone()); - let styles_changed = self - .package - .get_part(&styles_part) - .and_then(|xml| CT_Styles::from_xml(xml).ok()) - .as_ref() - != Some(&self.styles); + let styles_changed = self.styles_differ_from_part(&styles_part); if styles_changed { + let styles_xml = self.styles.to_xml()?; let styles_xml = if let Some(source) = self.package.get_part(&styles_part) { retain_styles_root_attributes(source, styles_xml)? } else { @@ -37919,8 +37957,7 @@ impl Document { } let mut candidate = self.clone_for_staging(); candidate.reserve_styles_bundle()?; - let defaults = candidate - .styles + let defaults = Arc::make_mut(&mut candidate.styles) .doc_defaults .get_or_insert_with(Default::default); let properties = defaults.rpr.get_or_insert_with(Default::default); @@ -37979,8 +38016,7 @@ impl Document { } let mut candidate = self.clone_for_staging(); candidate.reserve_styles_bundle()?; - let defaults = candidate - .styles + let defaults = Arc::make_mut(&mut candidate.styles) .doc_defaults .get_or_insert_with(Default::default); let properties = defaults.rpr.get_or_insert_with(Default::default); @@ -38009,8 +38045,7 @@ impl Document { } let mut candidate = self.clone_for_staging(); candidate.reserve_styles_bundle()?; - candidate - .styles + Arc::make_mut(&mut candidate.styles) .doc_defaults .get_or_insert_with(Default::default) .ppr = properties; @@ -39229,7 +39264,7 @@ impl Document { ))); } - let properties = candidate.styles.styles[style_index] + let properties = Arc::make_mut(&mut candidate.styles).styles[style_index] .ppr .get_or_insert_with(CT_PPr::default); properties.num_id = Some(num_id); @@ -39346,7 +39381,7 @@ impl Document { candidate.reserve_styles_bundle()?; candidate.reserve_numbering_bundle()?; - let properties = candidate.styles.styles[style_index] + let properties = Arc::make_mut(&mut candidate.styles).styles[style_index] .ppr .as_mut() .expect("the exact style link was validated above"); @@ -39423,9 +39458,9 @@ impl Document { } let linked_style = authored.linked_style.clone(); let style_id = authored.style_id.clone(); - candidate.styles.styles.push(authored); + Arc::make_mut(&mut candidate.styles).styles.push(authored); update_reciprocal_style_link( - &mut candidate.styles, + Arc::make_mut(&mut candidate.styles), &style_id, None, linked_style.as_deref(), @@ -39479,9 +39514,9 @@ impl Document { } let style_id = authored.style_id.clone(); let new_link = authored.linked_style.clone(); - candidate.styles.styles[index] = authored; + Arc::make_mut(&mut candidate.styles).styles[index] = authored; update_reciprocal_style_link( - &mut candidate.styles, + Arc::make_mut(&mut candidate.styles), &style_id, old_link.as_deref(), new_link.as_deref(), @@ -39513,7 +39548,11 @@ impl Document { style_type.to_str() ))); } - for (position, style) in candidate.styles.styles.iter_mut().enumerate() { + for (position, style) in Arc::make_mut(&mut candidate.styles) + .styles + .iter_mut() + .enumerate() + { if style.style_type == style_type { style.is_default = position == index; } @@ -39571,8 +39610,7 @@ impl Document { let mut candidate = self.clone_for_staging(); candidate.reserve_styles_bundle()?; - candidate - .styles + Arc::make_mut(&mut candidate.styles) .styles .retain(|style| style.style_id != style_id); style::validate_style_graph_change(&self.styles, &candidate.styles)?; @@ -39604,7 +39642,7 @@ impl Document { .is_some_and(|(name, common)| name.eq_ignore_ascii_case(common)) }); if !defined { - candidate.styles.styles.push(common); + Arc::make_mut(&mut candidate.styles).styles.push(common); added += 1; } } @@ -39764,7 +39802,7 @@ impl Document { )); } } else { - candidate.styles.styles.push(definition); + Arc::make_mut(&mut candidate.styles).styles.push(definition); } } style::validate_style_graph(&candidate.styles)?; @@ -43361,7 +43399,7 @@ impl Document { let source = self.styles.clone(); for style in &other.styles.styles { if self.styles.get_by_id(&style.style_id).is_none() { - self.styles.styles.push(style.clone()); + Arc::make_mut(&mut self.styles).styles.push(style.clone()); } } style::validate_style_graph_change(&source, &self.styles).map(|_| ()) @@ -43516,8 +43554,7 @@ impl Document { let Some(mapped_num_id) = num_remap.get(&source_num_id).copied() else { continue; }; - let Some(destination_style) = self - .styles + let Some(destination_style) = Arc::make_mut(&mut self.styles) .styles .iter_mut() .find(|style| style.style_id == source_style.style_id) @@ -45849,7 +45886,7 @@ impl Document { rdocx_html::HtmlInput { document: self.document.clone(), - styles: self.styles.clone(), + styles: CT_Styles::clone(&self.styles), numbering: self.numbering.clone(), images, hyperlink_urls, @@ -46460,7 +46497,7 @@ impl Document { // Rendering may consume a sole effects-only default without changing // either authored style part or merging the effects style catalogue. - let mut layout_styles = self.styles.clone(); + let mut layout_styles = CT_Styles::clone(&self.styles); if layout_styles.get_default(StyleType::Table).is_none() { let effects = self.package.get_part_rels(&self.doc_part_name).and_then(|rels| { let mut candidates = rels.items.iter().filter(|rel| { @@ -65092,7 +65129,7 @@ mod tests { source.layout().expect("prime source engine"); receiver.layout().expect("prime receiver engine"); - receiver.styles = CT_Styles::new(); + receiver.styles = Arc::new(CT_Styles::new()); receiver.invalidate_layout(); assert!(!receiver.transfer_reusable_layout_from(&mut source)); assert!( @@ -72158,8 +72195,7 @@ mod tests { #[test] fn numbering_graph_rejects_each_one_sided_style_link() { let mut document = Document::new(); - let normal = document - .styles + let normal = Arc::make_mut(&mut document.styles) .styles .iter_mut() .find(|style| style.style_id == "Normal") @@ -72169,8 +72205,7 @@ mod tests { ..CT_PPr::default() }); assert!(document.validate_numbering_graph().is_err()); - document - .styles + Arc::make_mut(&mut document.styles) .styles .iter_mut() .find(|style| style.style_id == "Normal") @@ -72570,8 +72605,7 @@ mod tests { let instance_id = document .add_numbering_instance(definition_id, &[NumberingLevelOverride::new(0).start(4)]) .unwrap(); - document - .styles + Arc::make_mut(&mut document.styles) .styles .iter_mut() .find(|style| style.style_id == "Normal") @@ -72637,8 +72671,7 @@ mod tests { .add_numbering_definition(&[ListLevel::decimal()]) .unwrap(); let instance_id = source.add_numbering_instance(definition_id, &[]).unwrap(); - source - .styles + Arc::make_mut(&mut source.styles) .styles .iter_mut() .find(|style| style.style_id == "Normal") @@ -73124,8 +73157,7 @@ mod tests { keep_next: Some(true), ..Default::default() }); - let default_style = doc - .styles + let default_style = Arc::make_mut(&mut doc.styles) .styles .iter_mut() .find(|style| style.style_id == "Normal") @@ -75906,6 +75938,60 @@ mod tests { assert_save_matches_old_order("replaced main bytes", &opened, &missed); } + #[test] + fn issue437_edits_keep_the_styles_parse_and_the_styles_part() { + let mut source = Document::new(); + source.add_paragraph("Intro text"); + source.add_table(3, 2); + source + .table_mut(0) + .unwrap() + .cell(0, 0) + .unwrap() + .set_text("r0c0"); + let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + let part = document.styles_part_name.clone().unwrap(); + let styles = Arc::clone(&document.styles); + let bytes = Arc::clone(document.package.get_part_shared(&part).unwrap()); + let unchanged = |document: &Document, what: &str| { + assert!( + Arc::ptr_eq(&document.styles, &styles), + "{what} parsed the styles again" + ); + assert!( + Arc::ptr_eq(document.package.get_part_shared(&part).unwrap(), &bytes), + "{what} rewrote the styles part" + ); + }; + assert_eq!(document.try_replace_text("r0c0", "edited").unwrap(), 1); + unchanged(&document, "try_replace_text"); + document.add_empty_table_row(0).unwrap(); + unchanged(&document, "add_empty_table_row"); + let saved = document.to_bytes().unwrap(); + unchanged(&document, "to_bytes"); + assert_eq!( + Document::from_bytes(&saved) + .unwrap() + .table(0) + .unwrap() + .row_count(), + 4 + ); + + // A real style edit still reaches the saved part. + let (style, _, _) = crate::style::StyleBuilder::paragraph("Issue437", "Issue 437").build(); + Arc::make_mut(&mut document.styles).styles.push(style); + let saved = document.to_bytes().unwrap(); + assert!( + Document::from_bytes(&saved) + .unwrap() + .styles + .styles + .iter() + .any(|style| style.style_id == "Issue437") + ); + } + #[test] fn saves_as_preserves_first_resource_error() { let mut left_source = issue407_document("one", false); @@ -79151,7 +79237,7 @@ mod odttf_tests { #[test] fn fx200_absent_default_getters_and_clears_do_not_materialize_defaults() { let mut document = Document::new(); - document.styles.doc_defaults = None; + Arc::make_mut(&mut document.styles).doc_defaults = None; let before = document.to_bytes().unwrap(); assert!(document.default_font_name().is_none() && document.default_font_size().is_none()); document.set_default_font_name_value(None).unwrap(); diff --git a/crates/rdocx/src/epub.rs b/crates/rdocx/src/epub.rs index 7827f87c4..66ea3d0aa 100644 --- a/crates/rdocx/src/epub.rs +++ b/crates/rdocx/src/epub.rs @@ -4646,7 +4646,7 @@ mod tests { fn epub_bounds_projection_trees_and_relationships_before_cloning() { let mut styles = Document::new(); let template = styles.styles.styles[0].clone(); - styles.styles.styles = vec![template; MAX_STYLE_ITEMS + 1]; + std::sync::Arc::make_mut(&mut styles.styles).styles = vec![template; MAX_STYLE_ITEMS + 1]; let error = styles.to_epub_bytes().err().unwrap().to_string(); assert!(error.contains("too many styles")); @@ -5389,7 +5389,7 @@ mod tests { #[test] fn epub_reports_background_cell_shading_and_visible_default_style_losses() { let mut inert = Document::new(); - inert.styles.doc_defaults = None; + std::sync::Arc::make_mut(&mut inert.styles).doc_defaults = None; inert.add_paragraph("inert default"); let inert_result = inert.to_epub_bytes().unwrap(); assert!( @@ -5413,10 +5413,10 @@ mod tests { } let mut preservation_only = Document::new(); - preservation_only.styles = rdocx_oxml::styles::CT_Styles::from_xml( + preservation_only.styles = std::sync::Arc::new(rdocx_oxml::styles::CT_Styles::from_xml( br#""#, ) - .unwrap(); + .unwrap()); preservation_only.add_paragraph("preservation only"); let preservation_result = preservation_only.to_epub_bytes().unwrap(); assert!( @@ -5428,8 +5428,7 @@ mod tests { let mut document = Document::new(); document.document.background_xml = Some(b"".to_vec()); - let default_style = document - .styles + let default_style = std::sync::Arc::make_mut(&mut document.styles) .styles .iter_mut() .find(|style| style.style_type == StyleType::Paragraph && style.is_default) @@ -6021,19 +6020,19 @@ mod tests { let path = root.join("book.epub"); let mut document = Document::new(); document.document.background_xml = Some(b"".to_vec()); - document.styles.doc_defaults = Some(rdocx_oxml::styles::CT_DocDefaults { - source_xml: None, - ppr: Some(CT_PPr { - space_after: Some(Twips(120)), - ..Default::default() - }), - rpr: Some(CT_RPr { - italic: Some(true), - ..Default::default() - }), - }); - let default_style = document - .styles + std::sync::Arc::make_mut(&mut document.styles).doc_defaults = + Some(rdocx_oxml::styles::CT_DocDefaults { + source_xml: None, + ppr: Some(CT_PPr { + space_after: Some(Twips(120)), + ..Default::default() + }), + rpr: Some(CT_RPr { + italic: Some(true), + ..Default::default() + }), + }); + let default_style = std::sync::Arc::make_mut(&mut document.styles) .styles .iter_mut() .find(|style| style.style_type == StyleType::Paragraph && style.is_default) @@ -6443,7 +6442,7 @@ mod tests { ), _ => (String::new(), String::new(), String::new()), }; - document.styles = rdocx_oxml::styles::CT_Styles::from_xml(format!(r#"{defaults}{base}{selected}"#).as_bytes()).unwrap(); + document.styles = std::sync::Arc::new(rdocx_oxml::styles::CT_Styles::from_xml(format!(r#"{defaults}{base}{selected}"#).as_bytes()).unwrap()); let mut first = document.add_paragraph("first source item"); first.set_style("Selected"); if layer == "direct" { @@ -6577,7 +6576,7 @@ mod tests { } else { style_body }; - document.styles = CT_Styles::from_xml(format!(r#"{base}{selected}exact"#).as_bytes()).unwrap(); + document.styles = std::sync::Arc::new(CT_Styles::from_xml(format!(r#"{base}{selected}exact"#).as_bytes()).unwrap()); document .add_paragraph("first source item") .set_numbering(number, 0); diff --git a/crates/rdocx/src/field.rs b/crates/rdocx/src/field.rs index 31f21e534..0aaa21364 100644 --- a/crates/rdocx/src/field.rs +++ b/crates/rdocx/src/field.rs @@ -5788,8 +5788,7 @@ fn prune_document_fragment_dependencies(fragment: &mut Document, selected: &[u8] // dependency closure. A later definition is neither a dependency nor // compared with the destination style. let mut defined = HashSet::new(); - fragment - .styles + std::sync::Arc::make_mut(&mut fragment.styles) .styles .retain(|style| defined.insert(style.style_id.clone())); let mut body_xml = selected.to_vec(); @@ -5826,7 +5825,7 @@ fn prune_document_fragment_dependencies(fragment: &mut Document, selected: &[u8] .cloned(), ); } - let mut retained_styles = fragment.styles.clone(); + let mut retained_styles = rdocx_oxml::styles::CT_Styles::clone(&fragment.styles); retained_styles .styles .retain(|style| used_styles.contains(&style.style_id)); @@ -5857,8 +5856,7 @@ fn prune_document_fragment_dependencies(fragment: &mut Document, selected: &[u8] break; } } - fragment - .styles + std::sync::Arc::make_mut(&mut fragment.styles) .styles .retain(|style| used_styles.contains(&style.style_id)); if let Some(numbering) = fragment.numbering.as_mut() { @@ -6102,7 +6100,7 @@ fn remap_fragment_style_collisions( if replacements.is_empty() { return Ok(false); } - for style in &mut fragment.styles.styles { + for style in &mut std::sync::Arc::make_mut(&mut fragment.styles).styles { if let Some(replacement) = replacements.get(&style.style_id) { style.style_id = replacement.clone(); // A renamed copy is not the destination default. The destination @@ -10189,7 +10187,9 @@ fn ensure_toc_entry_styles( .unwrap_or_else(|| { let (style, _, _) = style::StyleBuilder::paragraph(&canonical_id, &format!("TOC {level}")).build(); - document.styles.styles.push(style); + std::sync::Arc::make_mut(&mut document.styles) + .styles + .push(style); canonical_id }); let effective = style::resolve_paragraph_properties(Some(&style_id), &document.styles); @@ -22275,7 +22275,9 @@ mod tests { let styles = format!( r#""# ); - document.styles = rdocx_oxml::styles::CT_Styles::from_xml(styles.as_bytes()).unwrap(); + document.styles = std::sync::Arc::new( + rdocx_oxml::styles::CT_Styles::from_xml(styles.as_bytes()).unwrap(), + ); document }; let destination = build(1, 12, "A"); @@ -25245,7 +25247,9 @@ fn generated_ensure_styles(document: &mut Document, sources: &[GeneratedTableSou ..Default::default() }); } - document.styles.styles.push(style); + std::sync::Arc::make_mut(&mut document.styles) + .styles + .push(style); } } diff --git a/crates/rdocx/src/html.rs b/crates/rdocx/src/html.rs index e8d8353ec..a656ac94a 100644 --- a/crates/rdocx/src/html.rs +++ b/crates/rdocx/src/html.rs @@ -5495,8 +5495,7 @@ mod tests { fn fx217_named_template_styles_keep_their_existing_identities() { use crate::StyleBuilder; let mut template = Document::new(); - template - .styles + std::sync::Arc::make_mut(&mut template.styles) .styles .retain(|style| style.style_id != "Quote" && style.style_id != "Heading1"); template diff --git a/crates/rdocx/src/odt.rs b/crates/rdocx/src/odt.rs index b90ae1ad1..7dba1e189 100644 --- a/crates/rdocx/src/odt.rs +++ b/crates/rdocx/src/odt.rs @@ -6991,8 +6991,7 @@ mod tests { br#""# .to_vec(), ); - let defaults = document - .styles + let defaults = std::sync::Arc::make_mut(&mut document.styles) .doc_defaults .as_mut() .and_then(|defaults| defaults.rpr.as_mut()) diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 27fe76d51..5b18c59f2 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -64,6 +64,14 @@ and projection fallback classes remain distinct because their pairwise match relation is not transitive. Earliest matching old ownership determines retained scopes. No historical owner registry is introduced. Word publication keeps a current `WordPieces` cache of one vector of body blocks and one vector of physical parts. Each record is a concrete `Arc`. Reuse requires the current body context and equal block value. A field, a tab stop or a bookmark excludes that block. A duplicate physical part or a failed piece proof uses the full inventory. Physical part identity compares resolved target names without ASCII case distinctions, matching OPC lookup. A changed existing context uses the full inventory before publication, while an initially absent context may build fresh pieces. A changed existing body context uses the old full reader before publication. A document with no cached context remains a cold piece read. A prepared publication installs the pieces assembled for that candidate. An unprepared property install clears that cache. Returned paragraph and table owners read the prepared indexes when they exist and otherwise use the existing native route. The conservative document epoch for regular runs is unchanged. An opened Word package keeps one shared record of that opening. Unchanged main reuse requires the opened bytes, the namespace context, successful serialization equality and cached parsed-model equality. A nonempty pending relationship hold for the current main owner uses the whole canonicalization, which keeps its cleanup for an expired hold, a still-live unreferenced hold, and a now-referenced hold. A checked reopen skips ZIP staging only for literal `PackageReadLimits::UNBOUNDED` on a trusted byte-opened baseline. A new document, an in-memory package, a Flat OPC first commit, a limited reopen and a failure hook keep the checked ZIP path until a later legitimate save and byte open. Reuse copies the current main parse, nested namespace owners and canonicalization, including a cached failure, into a new opening record when the main bytes, name, namespace frame and relationship dependencies match. Relationship facts and identifier categories stay checked for that opening. There is no historical chain of openings. Debug counters record namespace input bytes and reopen input bytes. A changed header story records nonzero identifier input bytes when the main part is unchanged. Child-part staging is not part of this record. Direct body addressing uses the shared document writer. `to_xml_with_body_spans` returns the same bytes and errors as `to_xml`, including the conditional `w14` declaration. The main-body address cache stores XML-only facts. Reuse requires the same head and tail and exact aligned child bytes. A scan is eligible only when one body frame covers the scanned range. A second body, or a raw span that crosses a body child boundary, uses the checked full reader. A split raw paragraph that stays inside one body frame still uses that fallback. Prefix and suffix reuse keeps occurrence and order. `MainBodyScans` is one retained address scan record. It is independent of the parsed opening record and exists for a new document that has no opening record. Both reopen routes carry that address-read memo under an exact current writer frame. Each lookup aligns exact current child bytes before reusing a fact, so a changed child is rescanned while unchanged neighbors remain eligible. A changed partition invalidates the body fingerprint. The carry step uses the existing qualified writer partition. Direct modeled paragraph lookup uses the checked direct-body route, while controlled paragraphs retain their two-segment lookup. There is no history chain. `direct_body_item_location` stays hidden. The piece cache still excludes a field, a tab stop or a bookmark by model. Addressing does not copy those typed facts. Its XML facts come from the fresh serialization. Address-scan facts remain separate from serialization and retained-source proofs. Equality-only writer checks can consume the existing record without assembling a complete output when resource limits, the exact frame, every current child and its private facts qualify. This optional comparison requires an explicit `w14` root declaration. Other cases serialize through the established path. An opening keeps its independently qualified writer record in the existing serialized slot before an older carried record. This is writer provenance and does not supply unread source facts. Owned main output may copy an existing opening normalization only after resource admission, the block-proof switch and complete current writer-byte equality succeed. It returns a writer-only record without retained-source part identity. Every failed or unavailable proof uses the established serializer. No retained output copy is added, and the actual owned-byte copy remains linear work. Each immutable body block also stores the exact case-sensitive field-token substring result for its owned bytes. Constructors compute it, byte replacements create a new block, and frame-only copies retain it with identical bytes. It avoids repeated lexical scans in writer, read, scoped and namespace qualification. It does not replace current mutable-model checks or grant parse, source, writer or namespace authority. The independent whole-item owner scanner remains unchanged. This inline fact belongs to the existing Q22 body-scan memory layer. Picture inventory reuses each current immutable source owner for embedded relationship validation, while the public relationship API still validates the story and fingerprint first. Scoped replacement selects retained physical owners from its already checked canonical view within one immutable candidate phase. Control XML indices assign dense append-position IDs and close elements through checked direct lookup. No historical inventory or cache is added. +The Word styles model is one `Arc`, so a staged clone shares it and +a style edit copies it once through `Arc::make_mut`. The document also keeps +the styles part bytes it last read with their parse, as two `Arc` values. A +flush that finds the same part bytes and the same model `Arc` writes nothing +and parses nothing. A model that differs is compared by value, then serialized +when it really changed, as before. A staged reopen whose styles part keeps +those bytes takes the kept parse. Every other case parses the part. + Word checked replacement and configured picture insertion have consuming internal bridges for an already private owned candidate. The borrowing Rust route and consuming bridge share each actual checked transaction body. The bridge retains the real source package and invalidation flag and moves complete engine mutexes into temporary commit authority. Native commit and the bridge use the same signature and engine finalizer. There is no second typed model copy merely to privatize that owned candidate again. The binding still prepares the full conservative revision before installing it. A private borrowed main-read view shares actual canonical bytes, writer facts and checked spans only during the immutable scoped proof and reopened picture selection phases. It cannot cross a model, package, identifier or namespace mutation. No persistent model-success stamp or additional retained cache is introduced. Production read-phase reporting separates current writer calls, normalized opening copies, canonical record copies, namespace replay outputs, normalized retained/current/restored model outputs, masked rewrites and occurrence writers. Only the successful optional proof's audited debug whole-reference comparison is paused. Force-off and private-tab production fallbacks must expose their actual work and are not held to the qualified one-canonical-producer bound. Splice reporting requires actual successful preparation and consumption, counts every mandatory final owner index visit, and separately counts general-publication index visits. Pinned cold/warm 100/1000 six-run controls require one consumed packet, exact post-edit owner cardinality in the mandatory index, and no general-publication index work. An empty reopened document has no body-story owner, so its actual public insertion must decline the packet after classifying the section and expose all three general-publication index visits. Append paragraph and table survivors retain their existing contract while held ordinary runs become stale. Scoped normalization shares only work already executed on identical immutable bytes and frame. The first and second actual writer outputs must both equal the canonical child before repeating the right rounds can be omitted. Only the fresh producer builder can lend an actual checked source read, with complete partition and namespace provenance. Private owners and field-bearing children or frames retain the old rounds because field parsing allocates source identities. No new model cache or binding API is introduced. A fresh producer record may avoid normalization only after its complete actual source model equals the current immutable document and its independent canonical record requalifies the current writer against actual writer bytes. Source and writer frames, resource admission, reusable private facts and field absence remain checked. Unavailable or unequal proof retains the existing normalization path. This record supplies actual source reads with staged=None, never a manufactured generic correspondence memo. No retained cache or public interface is added. From 6dc9ed82a3c8257e187c26de8060389d472f8060 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sat, 31 Oct 2026 17:51:13 +0100 Subject: [PATCH 3/5] record the archive measurements The rdocx, rdocx-oxml and oxml-opc archives change with the cell edit and styles parse changes and their tests, on main 24af95d3. Their measurement date stays as recorded. Tests, python3 scripts/readme_doctests.py Harness, unchanged, measurements only --- README.md | 2 +- crates/oxml-opc/README.md | 2 +- crates/rdocx-oxml/README.md | 2 +- scripts/readme_doctests.py | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 252d3f986..8d028a1be 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ rows are the enforced release-mode bounds plus one dated observation. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,105,912 compressed bytes, 54,118,469 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx | 4,107,691 compressed bytes, 54,123,423 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | | 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/crates/oxml-opc/README.md b/crates/oxml-opc/README.md index e9ef184b6..38ee81bbf 100644 --- a/crates/oxml-opc/README.md +++ b/crates/oxml-opc/README.md @@ -18,7 +18,7 @@ The archive row is regenerated from the package that carries this README. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: oxml-opc | 117,614 compressed bytes, 477,731 member bytes, 12 members | 0.14.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `oxml-opc` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: oxml-opc | 117,674 compressed bytes, 478,067 member bytes, 12 members | 0.14.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `oxml-opc` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | ## Use it when diff --git a/crates/rdocx-oxml/README.md b/crates/rdocx-oxml/README.md index a170fe67b..ec4e9ade6 100644 --- a/crates/rdocx-oxml/README.md +++ b/crates/rdocx-oxml/README.md @@ -17,7 +17,7 @@ schema order, and retains unmodelled XML alongside typed edits. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx-oxml | 565,559 compressed bytes, 3,484,893 member bytes, 32 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx-oxml` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx-oxml | 565,589 compressed bytes, 3,484,978 member bytes, 32 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx-oxml` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | ## Use it when diff --git a/scripts/readme_doctests.py b/scripts/readme_doctests.py index bafa5ed5b..006fe8c6a 100644 --- a/scripts/readme_doctests.py +++ b/scripts/readme_doctests.py @@ -399,15 +399,15 @@ class ReadmeCase: "oxml-drawing": (226_588, 1_494_418, 24), "oxml-layout": (4_904_118, 9_841_237, 60), "oxml-media": (12_258, 51_016, 6), - "oxml-opc": (117_614, 477_731, 12), + "oxml-opc": (117_674, 478_067, 12), "oxml-pdf": (86_558, 406_477, 14), "oxml-sml": (24_918, 115_416, 6), - "rdocx": (4_105_912, 54_118_469, 37), + "rdocx": (4_107_691, 54_123_423, 37), "rdocx-cli": (111_071, 516_134, 8), "rdocx-html": (27_460, 109_636, 11), "rdocx-layout": (358_235, 1_964_578, 15), "rdocx-opc": (3_906, 10_535, 6), - "rdocx-oxml": (565_559, 3_484_893, 32), + "rdocx-oxml": (565_589, 3_484_978, 32), "rdocx-pdf": (8_125, 26_782, 6), "rpptx": (762_699, 4_061_273, 16), "rpptx-chart": (6_842, 21_809, 6), From 2a4615c34df3ae6294a1b311159748745b729901 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sun, 1 Nov 2026 09:02:49 +0100 Subject: [PATCH 4/5] fix(rdocx-py): set table cell properties and text without restaging A cell property setter (vertical_alignment, shading, width, set_border, set_margins) cloned the document, edited the clone and adopted it, assembling the pieces again and rebuilding every owner location: about 4 ms per call in an empty document, growing with the body. Cell.text on a body table cloned the document a second time, reconciled comment removal through two package flushes and reopened the staged package before its publication, and took the cell route from the physical walk: 43 ms per call at 2000 body paragraphs. Paragraph.text on a cell paragraph took its route from the physical walk too, 160 ms per call at 2000 paragraphs. A body table cell property is now set in place, as a body paragraph property is, since each edit validates before it changes w:tcPr. Only writing the cell's first w:tcPr (or removing it) moves the cell's items, as that element comes first: the owners of that cell story then move one item and change route bucket, and debug builds check the moved inventory against a rebuild. CellRef::has_properties tells whether the cell writes w:tcPr. A cell of a table in another story keeps the staged candidate. Cell.text edits the first paragraph in the candidate, as the story table branch already did (Paragraph::set_text keeps every comment, bookmark and permission anchor), and takes its table route from the owner index. Paragraph.text takes its route from paragraph_route, as Run does. At 2000 body paragraphs a property setter costs 0.02 ms, and Cell.text and a cell Paragraph.text cost what a body Paragraph.text costs (about 10 ms). That remaining cost is the revision publication every text setter shares. Part of #437. --- crates/rdocx-oxml/src/table.rs | 3 +- crates/rdocx-py/src/document.rs | 72 +++++++++++++++++++ crates/rdocx-py/src/paragraph.rs | 4 +- crates/rdocx-py/src/table.rs | 72 +++++++++++++------ crates/rdocx-py/tests/test_core.py | 111 +++++++++++++++++++++++++++++ crates/rdocx/src/table.rs | 8 +++ docs/hld/10-bindings-spec.md | 8 +++ 7 files changed, 254 insertions(+), 24 deletions(-) diff --git a/crates/rdocx-oxml/src/table.rs b/crates/rdocx-oxml/src/table.rs index c61b27e47..61cac39b1 100644 --- a/crates/rdocx-oxml/src/table.rs +++ b/crates/rdocx-oxml/src/table.rs @@ -2012,7 +2012,8 @@ impl CT_TcPr { Ok(()) } - fn is_empty(&self) -> bool { + /// Whether nothing would be written, so the cell has no `w:tcPr` element. + pub fn is_empty(&self) -> bool { self.width.is_none() && self.grid_span.is_none() && self.h_merge.is_none() diff --git a/crates/rdocx-py/src/document.rs b/crates/rdocx-py/src/document.rs index 397e39423..5fad08eb1 100644 --- a/crates/rdocx-py/src/document.rs +++ b/crates/rdocx-py/src/document.rs @@ -4576,6 +4576,22 @@ impl WordOwnerIndexes { self.by_route.retain(|_, bucket| !bucket.is_empty()); } + /// Move owner `index` from the route bucket `from` to the bucket `to`, + /// after its route moved in place. A bucket keeps its owners in order. + fn move_route(&mut self, index: usize, from: u64, to: u64) { + if from == to { + return; + } + if let Some(bucket) = self.by_route.get_mut(&from) { + bucket.retain(|owner| *owner != index); + if bucket.is_empty() { + self.by_route.remove(&from); + } + } + let bucket = self.by_route.entry(to).or_default(); + bucket.insert(bucket.partition_point(|owner| *owner < index), index); + } + /// Index every owner, and return the first body table owner of each /// direct body slot. fn index_owners( @@ -10283,6 +10299,62 @@ impl PyDocument { Some(self.owners[index].location.clone()) } + /// The physical story of a direct body table cell, from the owner index. + pub(crate) fn indexed_body_cell_story( + &self, + table: usize, + row: usize, + cell: usize, + ) -> Option { + let table = self.indexed_table_location(table, &None, None)?; + match self.indexed_cell_location(&table, row, cell)? { + WordOwnerLocation::Cell { story, .. } => Some(story), + _ => None, + } + } + + /// Move every owner route that starts in the cell story `story` by + /// `delta` items, after an in-place cell property edit wrote its first + /// `w:tcPr` or removed it. That element comes before the cell content, + /// so nothing else moves, and only the route indexes change. + pub(crate) fn move_cell_story_items(&mut self, story: &rdocx::StoryId, delta: isize) { + let in_story = |owner: &rdocx::StoryId| { + owner.kind() == story.kind() + && owner.part_name() == story.part_name() + && owner.owner_index() == story.owner_index() + }; + let moved = |location: &mut rdocx::ContentLocation| { + if in_story(location.story()) + && let Some(&head) = location.index_path().first() + { + location.set_index_path_head(head.saturating_add_signed(delta)); + } + }; + for (index, owner) in self.owners.iter_mut().enumerate() { + if !word_owner_story(&owner.location).is_some_and(in_story) { + continue; + } + let from = owner.location.route_hash(); + match &mut owner.location { + WordOwnerLocation::Paragraph(location) + | WordOwnerLocation::Run(location, _) + | WordOwnerLocation::Table(location) + | WordOwnerLocation::Hyperlink(location, _) + | WordOwnerLocation::Cell { + table: location, .. + } => moved(location), + WordOwnerLocation::Section(_) => {} + } + self.indexes + .move_route(index, from, owner.location.route_hash()); + } + for locations in self.indexes.cell_paragraphs.values_mut() { + locations.iter_mut().for_each(&moved); + } + #[cfg(debug_assertions)] + self.assert_word_inventory_rebuilds(); + } + pub(crate) fn capture_current_view( &self, state: &RevisionState, diff --git a/crates/rdocx-py/src/paragraph.rs b/crates/rdocx-py/src/paragraph.rs index ef7d441ab..cc7935d1c 100644 --- a/crates/rdocx-py/src/paragraph.rs +++ b/crates/rdocx-py/src/paragraph.rs @@ -1002,8 +1002,8 @@ impl PyParagraph { py, &candidate, "Paragraph.text", - location - .native(&document.inner) + document + .paragraph_route(&location, None) .map(crate::document::WordPublication::ParagraphText) .unwrap_or(crate::document::WordPublication::Conservative), )?; diff --git a/crates/rdocx-py/src/table.rs b/crates/rdocx-py/src/table.rs index 2dfb69855..2e85ec409 100644 --- a/crates/rdocx-py/src/table.rs +++ b/crates/rdocx-py/src/table.rs @@ -2085,14 +2085,41 @@ impl PyCell { let (table, row, cell) = self.validate(py)?; let current_related = self.current_related(py)?; let mut document = self.document.borrow_mut(py); + let edit_cell = |table: &mut rdocx::Table<'_>| { + let mut cell = table + .cell(row, cell) + .ok_or_else(|| rdocx::Error::Other("cell index out of range".to_owned()))?; + edit(&mut cell) + }; + if current_related.is_none() + && let Some(story) = document.indexed_body_cell_story(table, row, cell) + { + // Each edit validates before it changes the cell properties, so a + // body table cell is edited in place, as a body paragraph is. Only + // writing or removing its `w:tcPr` moves the cell's items. + let location = TableLocation::Body(table); + let has_properties = |document: &rdocx::Document| { + location.read(document, |table| { + table + .cell(row, cell) + .is_some_and(|cell| cell.has_properties()) + }) + }; + let before = + has_properties(&document.inner).map_err(|error| rdocx_to_pyerr(py, error))?; + location + .edit(&mut document.inner, edit_cell) + .map_err(|error| rdocx_to_pyerr(py, error))?; + let after = + has_properties(&document.inner).map_err(|error| rdocx_to_pyerr(py, error))?; + if before != after { + document.move_cell_story_items(&story, if after { 1 } else { -1 }); + } + return Ok(()); + } let mut candidate = document.inner.clone_for_staging(); - TableLocation::new(table, ¤t_related.clone()) - .edit(&mut candidate, |table| { - let mut cell = table - .cell(row, cell) - .ok_or_else(|| rdocx::Error::Other("cell index out of range".to_owned()))?; - edit(&mut cell) - }) + TableLocation::new(table, ¤t_related) + .edit(&mut candidate, edit_cell) .map_err(|error| rdocx_to_pyerr(py, error))?; document.adopt_property_edit(py, candidate, "Cell property edit")?; Ok(()) @@ -2516,24 +2543,27 @@ impl PyCell { let current_related = self.current_related(py)?; let mut document = self.document.borrow_mut(py); let mut candidate = document.inner.clone_for_staging(); - match ¤t_related.clone() { - Some(_) => { - TableLocation::new(table, ¤t_related.clone()).edit(&mut candidate, |table| { - table - .cell(row, cell) - .ok_or_else(|| rdocx::Error::Other("cell index out of range".to_owned()))? - .try_set_text(value) - }) - } - None => candidate.try_set_cell_text(table, row, cell, value), - } - .map_err(|error| rdocx_to_pyerr(py, error))?; + // The first paragraph's text is replaced as Paragraph.text replaces + // it, every anchor kept, so the publication below checks the edit + // without a staged reopen of the package. + TableLocation::new(table, ¤t_related) + .edit(&mut candidate, |table| { + table + .cell(row, cell) + .ok_or_else(|| rdocx::Error::Other("cell index out of range".to_owned()))? + .try_set_text(value) + }) + .map_err(|error| rdocx_to_pyerr(py, error))?; let prepared = document.prepare_word_revision( py, &candidate, "Cell.text", - TableLocation::new(table, ¤t_related) - .native(&document.inner) + document + .indexed_table_location(table, ¤t_related, None) + .map(Ok) + .unwrap_or_else(|| { + TableLocation::new(table, ¤t_related).native(&document.inner) + }) .map(|location| crate::document::WordPublication::CellText(location, row, cell)) .unwrap_or(crate::document::WordPublication::Conservative), )?; diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index 40891a225..d9818ab1b 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -12186,6 +12186,117 @@ def test_issue437_cell_paragraph_setters_do_not_restage_the_package(body, row): assert (neighbour.alignment, neighbour.style) == (None, None) +def _issue437_body(paragraphs): + import rdocx + + return _replace_document_body( + rdocx.Document(), + "".join( + f"Body paragraph {index} with some text in it." + for index in range(paragraphs) + ), + ) + + +@pytest.mark.parametrize("setter", ["vertical_alignment", "shading", "width"]) +def test_issue437_cell_property_setters_do_not_grow_with_the_body(setter): + """A body table cell property is set in place, as a body paragraph + property is, so its cost does not grow with the body.""" + import rdocx + from rdocx import _rdocx + + value = { + "vertical_alignment": rdocx.WD_CELL_VERTICAL_ALIGNMENT.CENTER, + "shading": "D9E2F3", + "width": 914400, + }[setter] + + def per_call(body): + doc = _issue437_body(body) + table = doc.add_table(10, 5) + cells = [table.cell(row, column) for row in range(10) for column in range(5)] + started = time.perf_counter() + for cell in cells: + setattr(cell, setter, value) + elapsed = (time.perf_counter() - started) / len(cells) + reopened = rdocx.Document.from_bytes(doc.to_bytes()).tables[0] + assert all( + getattr(reopened.cell(row, column), setter) is not None + for row in range(10) + for column in range(5) + ) + return elapsed + + def paragraph_per_call(body): + doc = _issue437_body(body) + paragraphs = doc.paragraphs[:50] + started = time.perf_counter() + for paragraph in paragraphs: + paragraph.alignment = 1 + return (time.perf_counter() - started) / len(paragraphs) + + small = per_call(0) + large = per_call(400) + paragraph = paragraph_per_call(400) + if hasattr(_rdocx, "_reopen_work"): + # Debug builds rebuild the whole owner inventory after a cell gains + # its w:tcPr, to check the moved routes, so the timing needs a + # release build. + pytest.skip("debug build: the timing comparison needs a release build") + assert large <= small * 1.5 + 0.0005, ( + f"Cell.{setter} took {1000 * small:.2f} ms per call with an empty body " + f"and {1000 * large:.2f} ms with 400 paragraphs" + ) + assert large <= paragraph * 3 + 0.0002, ( + f"Cell.{setter} took {1000 * large:.2f} ms per call against " + f"{1000 * paragraph:.2f} ms for Paragraph.alignment in the same body" + ) + + +def test_issue437_cell_text_costs_what_body_paragraph_text_costs(): + """Cell.text and a cell paragraph's text go through the same publication + as a body paragraph's text, without a staged reopen or a physical route + walk, so they cost about what Paragraph.text costs in the same body.""" + import rdocx + from rdocx import _rdocx + + doc = _issue437_body(400) + doc.add_table(4, 5) + targets = [(row, column) for row in range(4) for column in range(5)] + if hasattr(_rdocx, "_reopen_work"): + # Debug builds check every indexed route again through the native + # walk, so only the work counters are meaningful there. + _rdocx._reopen_work() + scans = _rdocx._main_body_block_scans() + doc.paragraphs[0].text = "b" + body_scans = _rdocx._main_body_block_scans() - scans + scans = _rdocx._main_body_block_scans() + doc.tables[0].cell(0, 0).text = "c" + assert _rdocx._reopen_work() == [0] * 3 + assert _rdocx._main_body_block_scans() - scans <= body_scans + pytest.skip("debug build: the timing comparison needs a release build") + + def per_call(edit): + started = time.perf_counter() + for index, (row, column) in enumerate(targets): + edit(index, row, column) + return (time.perf_counter() - started) / len(targets) + + body = per_call(lambda index, row, column: setattr(doc.paragraphs[index], "text", "b")) + cell = per_call(lambda index, row, column: setattr(doc.tables[0].cell(row, column), "text", "c")) + paragraph = per_call( + lambda index, row, column: setattr(doc.tables[0].cell(row, column).paragraphs[0], "text", "p") + ) + for name, elapsed in (("Cell.text", cell), ("cell Paragraph.text", paragraph)): + assert elapsed <= body * 1.5 + 0.002, ( + f"{name} took {1000 * elapsed:.2f} ms per call against " + f"{1000 * body:.2f} ms for a body Paragraph.text" + ) + reopened = rdocx.Document.from_bytes(doc.to_bytes()) + assert [reopened.tables[0].cell(row, column).text for row, column in targets] == ["p"] * 20 + assert [paragraph.text for paragraph in reopened.paragraphs[:20]] == ["b"] * 20 + + @pytest.mark.parametrize("run_count", [1, 2]) def test_issue389_first_run_local_publication_keeps_exact_owner_lifetimes(run_count): import rdocx diff --git a/crates/rdocx/src/table.rs b/crates/rdocx/src/table.rs index c690e42e3..fa91b74ea 100644 --- a/crates/rdocx/src/table.rs +++ b/crates/rdocx/src/table.rs @@ -3031,6 +3031,14 @@ pub enum CellItemRef<'a> { } impl<'a> CellRef<'a> { + /// Whether the cell writes a `w:tcPr` element, its first child. + pub fn has_properties(&self) -> bool { + self.inner + .properties + .as_ref() + .is_some_and(|properties| !properties.is_empty()) + } + /// Whether cell properties retain facts outside the public reader model. pub fn has_unmodeled_properties(&self) -> bool { self.inner.properties.as_ref().is_some_and(|properties| { diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index b7853420b..242e589d1 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -4594,6 +4594,14 @@ paragraphs, so a cell with a content control keeps the checked physical route through `cell_paragraph_story_location`. A run handle of a cell paragraph takes its paragraph route from the prepared index before the native lookup. +A property setter on a body table cell (vertical alignment, shading, width, +borders, margins) edits the cell in place as well. Writing the cell's first +`w:tcPr`, or removing it, moves every item of the cell story by one, so the +owners of that story move with it and change route bucket, and debug builds +check them against a rebuilt inventory. `Cell.text` and `Paragraph.text` on a +cell paragraph edit the staged candidate without a staged reopen and take +their routes from the owner index before publishing the revision. + Complete Word owner snapshots use the native hidden `Document.story_owner_snapshots` provider across the existing crate boundary. Its four owned families retain full story items, physical cells, paragraph XML From 7b3dcd0e4a3f89c4ecc7b88718c68a9a58159ad8 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Sun, 1 Nov 2026 09:05:15 +0100 Subject: [PATCH 5/5] record the archive measurements The rdocx and rdocx-oxml archives change with the cell setter change and its tests. Their measurement date stays as recorded. Tests, python3 scripts/readme_doctests.py Harness, unchanged, measurements only --- README.md | 2 +- crates/rdocx-oxml/README.md | 2 +- scripts/readme_doctests.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8d028a1be..e1a14a22a 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ rows are the enforced release-mode bounds plus one dated observation. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx | 4,107,691 compressed bytes, 54,123,423 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx | 4,107,757 compressed bytes, 54,123,669 member bytes, 37 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | | 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/crates/rdocx-oxml/README.md b/crates/rdocx-oxml/README.md index ec4e9ade6..3e68bc406 100644 --- a/crates/rdocx-oxml/README.md +++ b/crates/rdocx-oxml/README.md @@ -17,7 +17,7 @@ schema order, and retains unmodelled XML alongside typed edits. | Measurement | Value | Version | Platform | Build mode | Input | Command | Statistic | Measured on | |---|---|---|---|---|---|---|---|---| -| Crates.io archive: rdocx-oxml | 565,589 compressed bytes, 3,484,978 member bytes, 32 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx-oxml` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | +| Crates.io archive: rdocx-oxml | 565,622 compressed bytes, 3,485,061 member bytes, 32 members | 0.16.4 | macOS 26.6.2, Apple M5 Max, arm64 | `cargo publish --workspace --dry-run --allow-dirty --locked` | Tracked `rdocx-oxml` package inventory | `python3 scripts/readme_doctests.py --record-measurements` | gzip archive bytes, tar member bytes, tar member count | 2026-10-28 | ## Use it when diff --git a/scripts/readme_doctests.py b/scripts/readme_doctests.py index 006fe8c6a..1ba7c33a4 100644 --- a/scripts/readme_doctests.py +++ b/scripts/readme_doctests.py @@ -402,12 +402,12 @@ class ReadmeCase: "oxml-opc": (117_674, 478_067, 12), "oxml-pdf": (86_558, 406_477, 14), "oxml-sml": (24_918, 115_416, 6), - "rdocx": (4_107_691, 54_123_423, 37), + "rdocx": (4_107_757, 54_123_669, 37), "rdocx-cli": (111_071, 516_134, 8), "rdocx-html": (27_460, 109_636, 11), "rdocx-layout": (358_235, 1_964_578, 15), "rdocx-opc": (3_906, 10_535, 6), - "rdocx-oxml": (565_589, 3_484_978, 32), + "rdocx-oxml": (565_622, 3_485_061, 32), "rdocx-pdf": (8_125, 26_782, 6), "rpptx": (762_699, 4_061_273, 16), "rpptx-chart": (6_842, 21_809, 6),