From 9b8b6d71fc82c2c5d7371d05913ea0e863aedb44 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 18:14:13 +0100 Subject: [PATCH 01/11] fix(comparison): write one run per stretch at word and character granularity Since v0.17.0 a word comparison aligns logical words over characters, so that a word split across runs compares equal (F-X279b, issue 434 case 3). The character units then reached the output as they were: every unchanged character of a changed paragraph became its own w:r, and each letter of a revision its own w:delText or w:t inside the revision's run. For the 200 paragraphs of issue 446 case 1 that is 17,180 runs and 517 KiB of document.xml where v0.16.4 wrote 6,200 runs and 245 KiB. Character granularity has always written one run per character, and v0.16.4 wrote one run per word, space and punctuation mark at word granularity. The granularity now sets what is compared, never how the result is cut. Two rules, in the two helpers that the paragraph path and the inline control path share, apply to every granularity, story and revision kind: - coalesced_granular_alignment keeps unchanged pairs together while they continue the same original and the same edited text element, as it already kept the pairs of one change together. Unchanged text is one run between two revisions. - merge_unit_runs joins consecutive fragments of one text element back into one text with one source selection, whole again when every fragment is there. A revision holds its text in one w:delText or w:t, and a fully unchanged element is published from its source as at run granularity. The same 200 paragraphs now give 600 runs and 76 KiB, one run per revision and one per stretch of text around them. Two cases still cut a stretch: under ignore_whitespace an ignored whitespace unit ends it, so unchanged text stays one run per word and per space, and a tab or a break ends it as it ends a text element. The alignment, the text revisions, the logical-word rule, the shared revision of a word split across runs, the custody markers and the refusals are unchanged. One visible difference besides the runs: a formatting change of a run is one w:rPrChange per unchanged stretch, as at run granularity, instead of one per word (v0.16.4) or per character (v0.17.0). The space-flag control of compare_producer_noise pinned the one-run space of the old shape. It now checks the same fact on the stretch that ends with the space. Part of #446. Tests, issue446_* in regression_test.rs state the shape as invariants in the body, a table cell, an inline control, a hyperlink, a header and a footnote (one text element a run, no added run that repeats the properties of the sibling it follows, run count bounded by the revisions, run count and added size independent of the unchanged text), two unit tests in comparison.rs, test_issue446_* in test_core.py Harness, unchanged, the samples make no comparison --- crates/rdocx-py/tests/test_core.py | 34 +++ crates/rdocx/src/comparison.rs | 346 +++++++++++++++++++++++-- crates/rdocx/tests/regression_test.rs | 353 +++++++++++++++++++++++++- docs/hld/03-architecture.md | 11 +- docs/hld/10-bindings-spec.md | 6 +- docs/hld/12-testing-strategy.md | 9 + 6 files changed, 724 insertions(+), 35 deletions(-) diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index d180c0174..7c6c6ada7 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -17328,6 +17328,40 @@ def test_issue434_compare_equal_split_and_one_word_public(granularity): assert [(r.kind, r.text) for r in original.revisions] == [("deletion", "thirty"), ("insertion", "sixty")] +@pytest.mark.parametrize("granularity", ["word", "character"]) +def test_issue446_compare_keeps_unchanged_text_in_whole_runs(granularity): + import rdocx + + def document(word): + document = rdocx.Document() + for index in range(12): + document.add_paragraph(f"Paragraph {index}: the bearing moved about {word} millimetres since the survey.") + return rdocx.Document.from_bytes(document.to_bytes()) + + original = document("twelve") + assert original.compare(document("fifteen"), "R", "2026-11-09T00:00:00Z", granularity=granularity) == () + xml = _document_xml(original) + # One text element a run: a revision is never cut into its compared units. + assert b"" not in xml + revisions = original.revisions + for index, paragraph in enumerate(original.paragraphs): + runs = [run.text for run in paragraph.runs] + assert runs[0] == f"Paragraph {index}: the bearing moved about " + assert runs[-1].endswith(" millimetres since the survey.") + assert "".join(runs) == f"Paragraph {index}: the bearing moved about fifteen millimetres since the survey." + # One run a revision, and one for the text before, between and after them. + assert xml.count(b"") <= 12 + 2 * len(revisions) + if granularity == "word": + assert [(r.kind, r.text) for r in revisions] == [("deletion", "twelve"), ("insertion", "fifteen")] * 12 + assert [run.text for run in original.paragraphs[3].runs] == [ + "Paragraph 3: the bearing moved about ", + "fifteen", + " millimetres since the survey.", + ] + assert xml.count(b"") == 12 * 4 + @pytest.mark.parametrize("normal", [False, True, "distinct"]) def test_issue434_insert_effective_font_and_saved_body(normal): import rdocx diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 71ddfc698..71f9bc33a 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -14373,12 +14373,14 @@ fn compare_granular_paragraph( let mut right_raw = Vec::new(); let mut right_typed = Vec::new(); let left = merge_unit_runs( + &original.runs, &original_units, &left_indices, &mut left_raw, &mut left_typed, )?; let right = merge_unit_runs( + &edited.runs, &edited_units, &right_indices, &mut right_raw, @@ -15554,6 +15556,13 @@ fn retain_projection_separators( Ok(()) } +/// The aligned pairs grouped into the pieces the redline writes as one run. +/// +/// The granularity sets what the diff compares, never how many runs carry the +/// result. A change takes every consecutive pair of its kind that the same +/// physical runs own. Unchanged text takes every consecutive pair that +/// continues the same original and edited text element, so it stays one run +/// between two revisions whether the units are words or characters. fn coalesced_granular_alignment( aligned: &[(Option, Option)], original_units: &[AttributedRunUnit], @@ -15561,6 +15570,23 @@ fn coalesced_granular_alignment( original_signatures: &[String], edited_signatures: &[String], ) -> Vec<(GranularAction, Range)> { + let owners = |at: usize| { + ( + aligned[at].0.map(|index| original_units[index].owner), + aligned[at].1.map(|index| edited_units[index].owner), + ) + }; + // The text element each side of an unchanged pair is a fragment of. + let elements = |at: usize| { + aligned[at] + .0 + .and_then(|index| unit_text_element(&original_units[index])) + .zip( + aligned[at] + .1 + .and_then(|index| unit_text_element(&edited_units[index])), + ) + }; let mut groups = Vec::new(); let mut start = 0usize; while start < aligned.len() { @@ -15571,30 +15597,24 @@ fn coalesced_granular_alignment( original_signatures, edited_signatures, ); - let owners = ( - aligned[start].0.map(|index| original_units[index].owner), - aligned[start].1.map(|index| edited_units[index].owner), - ); + let continues = |at: usize| match action { + GranularAction::Replace | GranularAction::Delete | GranularAction::Insert => true, + GranularAction::Equal => elements(start).is_some() && elements(at) == elements(start), + GranularAction::Preserve | GranularAction::Drop => false, + }; let mut end = start + 1; - if matches!( - action, - GranularAction::Replace | GranularAction::Delete | GranularAction::Insert - ) { - while end < aligned.len() - && granular_action( - aligned[end], - original_units, - edited_units, - original_signatures, - edited_signatures, - ) == action - && ( - aligned[end].0.map(|index| original_units[index].owner), - aligned[end].1.map(|index| edited_units[index].owner), - ) == owners - { - end += 1; - } + while end < aligned.len() + && continues(end) + && granular_action( + aligned[end], + original_units, + edited_units, + original_signatures, + edited_signatures, + ) == action + && owners(end) == owners(start) + { + end += 1; } groups.push((action, start..end)); start = end; @@ -15602,6 +15622,15 @@ fn coalesced_granular_alignment( groups } +/// The content ordinal of the text element a plain unit is a fragment of. +fn unit_text_element(unit: &AttributedRunUnit) -> Option { + unit_plain_text(unit)?; + match unit.typed_sources.as_slice() { + [Some(selected)] => Some(selected.ordinal), + _ => None, + } +} + /// The text of a unit that holds nothing but text, which grouping may move /// into a deletion or an insertion. fn unit_plain_text(unit: &AttributedRunUnit) -> Option<&str> { @@ -15814,7 +15843,13 @@ fn grouped_text_alignment( (grouped, grouped_segments) } +/// The units at `indices`, all fragments of one run of `runs`, as one run. +/// +/// Consecutive fragments of one text element are written back as one text +/// with one source selection, so a merged run holds one `w:t` or `w:delText` +/// per stretch of its source text, never one per compared unit. fn merge_unit_runs( + runs: &[CT_R], units: &[AttributedRunUnit], indices: &[usize], raw_sources: &mut Vec<(usize, usize, usize)>, @@ -15827,6 +15862,7 @@ fn merge_unit_runs( raw_sources.extend_from_slice(&first.raw_sources); typed_sources.extend_from_slice(&first.typed_sources); let property_boundary = usize::from(merged.properties.is_some()); + let mut joined = false; for &index in &indices[1..] { let unit = &units[index]; if unit.owner != first.owner { @@ -15835,9 +15871,14 @@ fn merge_unit_runs( )); } let next = &unit.run; - let content_offset = merged.content.len(); - merged.content.extend(next.content.iter().cloned()); - typed_sources.extend_from_slice(&unit.typed_sources); + let continued = join_text_fragment(&mut merged, typed_sources, unit, property_boundary); + joined |= continued; + // The raw children of a joined fragment follow the text it extends. + let content_offset = merged.content.len() - usize::from(continued); + if !continued { + merged.content.extend(next.content.iter().cloned()); + typed_sources.extend_from_slice(&unit.typed_sources); + } merged .alt_drawings .extend(next.alt_drawings.iter().cloned()); @@ -15870,9 +15911,98 @@ fn merge_unit_runs( "fragment raw source order or multiplicity is invalid".into(), )); } + if joined { + // A joined text reads its space flag as a unit of its own would, and + // one that is its whole source element again selects it whole. + let source = runs + .get(first.owner) + .ok_or_else(|| Error::Other("merged run owner is absent".into()))?; + for (content, selected) in merged.content.iter_mut().zip(typed_sources.iter_mut()) { + let ( + RunContent::Text(text) | RunContent::DeletedText(text), + Some(TypedSourceSelection { + ordinal, + scalars: scalars @ Some(_), + }), + ) = (content, selected) + else { + continue; + }; + let Some(RunContent::Text(actual) | RunContent::DeletedText(actual)) = + source.content.get(*ordinal) + else { + return Err(Error::Other( + "joined text has no actual source element".into(), + )); + }; + text.preserve_space = actual.preserve_space || has_edge_whitespace(&text.text); + if *scalars == Some((0, actual.text.chars().count())) { + *scalars = None; + } + } + } Ok(Some(merged)) } +/// Append `unit` to the text that ends `merged` when it holds the next scalars +/// of the same source text element with no raw child between the two, and +/// report whether it did. `typed` holds one selection per content of `merged`. +fn join_text_fragment( + merged: &mut CT_R, + typed: &mut [Option], + unit: &AttributedRunUnit, + property_boundary: usize, +) -> bool { + let content_end = property_boundary + merged.content.len(); + let raw_positions = |run: &CT_R| { + run.extra_xml_positions + .iter() + .filter(|encoded| !CT_R::raw_child_is_root_attributes(**encoded)) + .map(|encoded| CT_R::raw_child_position(*encoded)) + .collect::>() + }; + if !unit.run.alt_drawings.is_empty() + || raw_positions(merged) + .iter() + .any(|position| *position >= content_end) + || raw_positions(&unit.run) + .iter() + .any(|position| *position <= property_boundary) + { + return false; + } + let ( + Some(TypedSourceSelection { + ordinal: previous, + scalars: Some((_, previous_end)), + }), + [ + Some(TypedSourceSelection { + ordinal, + scalars: Some((start, end)), + }), + ], + ) = ( + typed.last_mut().and_then(Option::as_mut), + unit.typed_sources.as_slice(), + ) + else { + return false; + }; + if *previous != *ordinal || *previous_end != *start { + return false; + } + match (merged.content.last_mut(), unit.run.content.as_slice()) { + (Some(RunContent::Text(text)), [RunContent::Text(fragment)]) + | (Some(RunContent::DeletedText(text)), [RunContent::DeletedText(fragment)]) => { + text.text.push_str(&fragment.text); + *previous_end = *end; + true + } + _ => false, + } +} + /// The paragraph source with `properties` in place of its own `w:pPr`. A /// self-closing paragraph, such as an empty one, is opened first, so the /// properties and runs go inside it. @@ -18720,12 +18850,14 @@ fn compare_control_runs_with_options( let mut right_raw = Vec::new(); let mut right_typed = Vec::new(); let left = merge_unit_runs( + original, &original_units, &left_indices, &mut left_raw, &mut left_typed, )?; let right = merge_unit_runs( + edited, &edited_units, &right_indices, &mut right_raw, @@ -23689,6 +23821,168 @@ mod tests { } } + /// One side of a written piece: its merged run and source selections. + type WrittenSide = Option<(CT_R, Vec>)>; + + /// The alignment of two single-run paragraphs grouped into the pieces + /// the redline writes, each as its original and edited merged run. + fn written_pieces(texts: [&str; 2], options: &ComparisonOptions) -> Vec<[WrittenSide; 2]> { + let runs = texts.map(|text| [CT_R::new(text)]); + let units = [ + attributed_run_units(&runs[0], options), + attributed_run_units(&runs[1], options), + ]; + let signatures = [0, 1].map(|side| { + units[side] + .iter() + .map(attributed_unit_signature) + .collect::>() + }); + let aligned = align(&signatures[0], &signatures[1]); + let (aligned, _) = grouped_text_alignment( + &aligned, + &vec![0; aligned.len()], + &units[0], + &units[1], + &signatures[0], + &signatures[1], + options, + ); + super::coalesced_granular_alignment( + &aligned, + &units[0], + &units[1], + &signatures[0], + &signatures[1], + ) + .into_iter() + .map(|(_, members)| { + [0, 1].map(|side| { + let indices = members + .clone() + .filter_map(|at| [aligned[at].0, aligned[at].1][side]) + .collect::>(); + let (mut raw, mut typed) = (Vec::new(), Vec::new()); + super::merge_unit_runs(&runs[side], &units[side], &indices, &mut raw, &mut typed) + .unwrap() + .map(|run| (run, typed)) + }) + }) + .collect() + } + + #[test] + fn granular_pieces_follow_the_changes_not_the_compared_units() { + for granularity in [ + ComparisonGranularity::Word, + ComparisonGranularity::Character, + ] { + let options = ComparisonOptions { + granularity, + ..Default::default() + }; + let pieces = [2, 200].map(|words| { + let kept = "kept ".repeat(words); + written_pieces( + [&format!("{kept}thirty days"), &format!("{kept}sixty days")], + &options, + ) + }); + // The unchanged text before the edit is one piece however many + // units it holds, so both lengths give the same pieces. + assert_eq!(pieces[0].len(), pieces[1].len(), "{granularity:?}"); + if granularity == ComparisonGranularity::Word { + // The text before, the replaced word and the text after. + assert_eq!(pieces[0].len(), 3); + } + for (run, typed) in pieces.iter().flatten().flatten().flatten() { + // One piece is one text with one source selection. + assert_eq!(run.content.len(), 1, "{granularity:?}: {run:?}"); + assert_eq!(typed.len(), 1, "{granularity:?}: {typed:?}"); + } + let kept = "kept ".repeat(200); + assert!(matches!( + &pieces[1][0], + [Some((left, _)), Some((right, _))] + if matches!(left.content.as_slice(), [RunContent::Text(text)] if text.text == kept) + && left.content == right.content + )); + } + } + + #[test] + fn merged_units_rejoin_the_fragments_of_one_text_element() { + let options = ComparisonOptions { + granularity: ComparisonGranularity::Word, + ..Default::default() + }; + let mut run = CT_R::new("alpha beta"); + run.content.push(RunContent::Tab); + run.content.push(RunContent::Text(CT_Text { + text: "gamma".to_owned(), + preserve_space: false, + })); + let runs = [run]; + // alpha, space, beta, the tab, gamma. + let units = attributed_run_units(&runs, &options); + assert_eq!(units.len(), 5); + let merge = |indices: &[usize]| { + let (mut raw, mut typed) = (Vec::new(), Vec::new()); + let run = super::merge_unit_runs(&runs, &units, indices, &mut raw, &mut typed) + .unwrap() + .unwrap(); + let texts = run + .content + .iter() + .map(|content| match content { + RunContent::Text(text) => Some((text.text.clone(), text.preserve_space)), + _ => None, + }) + .collect::>(); + let scalars = typed + .iter() + .map(|selected| selected.unwrap().scalars) + .collect::>(); + (texts, scalars) + }; + // Every fragment of an element is that element again, selected whole. + let whole = runs[0].content[0].clone(); + let RunContent::Text(whole) = whole else { + unreachable!() + }; + assert_eq!( + merge(&[0, 1, 2]), + ( + vec![Some(("alpha beta".to_owned(), whole.preserve_space))], + vec![None] + ) + ); + // Some of its fragments are one text over their scalars, which keeps + // the space a new edge exposes. + assert_eq!( + merge(&[0, 1]), + (vec![Some(("alpha ".to_owned(), true))], vec![Some((0, 6))]) + ); + assert_eq!( + merge(&[1, 2]), + (vec![Some((" beta".to_owned(), true))], vec![Some((5, 10))]) + ); + // Fragments that do not follow each other stay apart, and so does + // text on either side of other content. + assert_eq!(merge(&[0, 2]).0.len(), 2); + assert_eq!( + merge(&[0, 1, 2, 3, 4]), + ( + vec![ + Some(("alpha beta".to_owned(), whole.preserve_space)), + None, + Some(("gamma".to_owned(), false)) + ], + vec![None, None, None] + ) + ); + } + #[test] fn mixed_owner_gap_pairing_is_deterministic_and_preserves_every_owner() { let original = (0..48) diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 52ba847e8..862f822b5 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -41448,14 +41448,15 @@ mod compare_producer_noise { } } - // A space split out of a text keeps reading as a space in the redline. - for granularity in [ - ComparisonGranularity::Word, - ComparisonGranularity::Character, + // A space that a split leaves at the edge of a text keeps reading as + // a space in the redline. + for (granularity, edited) in [ + (ComparisonGranularity::Word, "two wordy"), + (ComparisonGranularity::Character, "two xords"), ] { let (kinds, tracked) = compared_kinds_with( ¶graph("two words"), - ¶graph("two wordy"), + ¶graph(&format!("{edited}")), &ComparisonOptions { granularity, ..Default::default() @@ -41463,9 +41464,9 @@ mod compare_producer_noise { ); let tracked = comparison_structure_xml(&tracked); assert_eq!(kinds, changed, "{granularity:?}"); - assert!(!tracked.contains(" "), "{tracked}"); + assert!(!tracked.contains("two "), "{tracked}"); assert!( - tracked.contains(r#" "#), + tracked.contains(r#"two "#), "{tracked}" ); } @@ -412775,6 +412776,344 @@ fn issue434_compare_one_word_beside_split_invoice() { } } +/// One `w:r` of a story part: the element that holds it, the text of each of +/// its text elements, and whether it directly follows a sibling run that has +/// the same `w:rPr`. +struct Issue446Run { + parent: String, + texts: Vec, + repeats_sibling: bool, +} + +fn issue446_runs(xml: &str) -> Vec { + #[derive(Default)] + struct Open { + name: String, + start: usize, + // The `w:rPr` of the run that is the last child read so far. + last_run: Option, + // For a run, the `w:rPr` of the run it directly follows, then its own. + follows: Option, + properties: String, + texts: Vec, + } + let mut reader = XmlReader::from_str(xml); + let mut open = vec![Open::default()]; + let mut runs = Vec::new(); + loop { + let start = reader.buffer_position() as usize; + let event = reader.read_event().unwrap(); + let end = reader.buffer_position() as usize; + if let XmlEvent::Start(element) | XmlEvent::Empty(element) = &event { + let name = String::from_utf8(element.name().as_ref().to_vec()).unwrap(); + let parent = open.last_mut().unwrap(); + let follows = parent.last_run.take().filter(|_| name == "w:r"); + if parent.name == "w:r" && matches!(name.as_str(), "w:t" | "w:delText") { + parent.texts.push(String::new()); + } + open.push(Open { + name, + start, + follows, + ..Default::default() + }); + } + match event { + XmlEvent::Text(text) => { + if let [.., run, leaf] = open.as_mut_slice() + && run.name == "w:r" + && matches!(leaf.name.as_str(), "w:t" | "w:delText") + { + run.texts + .last_mut() + .unwrap() + .push_str(&text.decode().unwrap()); + } + } + XmlEvent::End(_) | XmlEvent::Empty(_) => { + let closed = open.pop().unwrap(); + let parent = open.last_mut().unwrap(); + if closed.name == "w:rPr" && parent.name == "w:r" { + parent.properties = xml[closed.start..end].to_owned(); + } + if closed.name == "w:r" { + runs.push(Issue446Run { + parent: parent.name.clone(), + repeats_sibling: closed.follows.as_ref() == Some(&closed.properties), + texts: closed.texts, + }); + parent.last_run = Some(closed.properties); + } + } + XmlEvent::Eof => break, + _ => {} + } + } + runs +} + +/// A story a comparison revises: its name, its part and the document that +/// holds a text in it as one run. +type Issue446Story = (&'static str, &'static str, fn(&str) -> Document); + +fn issue446_stories() -> Vec { + fn body(content: &str) -> Document { + document_with_content_controls(&wrap_word_body(content)) + } + fn run(text: &str) -> String { + format!("{text}") + } + vec![ + ("body", "/word/document.xml", |text| { + body(&format!("{}", run(text))) + }), + ("table cell", "/word/document.xml", |text| { + body(&format!( + r#"{}"#, + run(text) + )) + }), + ("inline control", "/word/document.xml", |text| { + body(&format!( + "{}", + run(text) + )) + }), + ("hyperlink", "/word/document.xml", |text| { + body(&format!( + r#"{}"#, + run(text) + )) + }), + ("header", "/word/header1.xml", |text| { + document_with_comparison_header(&format!("{}", run(text))) + }), + ("footnote", "/word/footnotes.xml", |text| { + let mut document = Document::new(); + document.add_paragraph("The survey is on file."); + let location = document.paragraph_story_location(0).unwrap().unwrap(); + document.create_footnote(&location, text).unwrap(); + Document::from_bytes(&document.to_bytes().unwrap()).unwrap() + }), + ] +} + +#[test] +fn issue446_comparison_writes_one_run_per_stretch_in_every_story() { + // The granularity sets what is compared, not how the result is cut: the + // text between two revisions stays one run with one text element, and a + // revision holds its text in one `w:delText` or `w:t`. + let original_text = "The bearing at pier 4 moved about twelve millimetres since the survey."; + let edited_text = "The bearing at pier 4 moved about fifteen millimetres since the survey."; + for (story, part, document) in issue446_stories() { + for granularity in [ + rdocx::ComparisonGranularity::Word, + rdocx::ComparisonGranularity::Character, + ] { + let context = format!("{story} {granularity:?}"); + let options = rdocx::ComparisonOptions { + granularity, + ..Default::default() + }; + let mut tracked = document(original_text); + let before = issue446_runs(&comparison_part_xml(&mut tracked, part)); + tracked + .compare_with_options( + &document(edited_text), + "Ada", + "2026-11-15T09:00:00Z", + &options, + ) + .unwrap_or_else(|error| panic!("{context}: {error}")); + let revisions = tracked.story_revisions().unwrap(); + if granularity == rdocx::ComparisonGranularity::Word { + assert_eq!( + revisions + .iter() + .map(|revision| revision.text().to_owned()) + .collect::>(), + ["twelve", "fifteen"], + "{context}" + ); + } + let xml = comparison_part_xml(&mut tracked, part); + let runs = issue446_runs(&xml); + for run in &runs { + assert!(run.texts.len() <= 1, "{context}: {:?} in {xml}", run.texts); + } + // The redline adds no run that repeats the properties of the + // sibling run it follows. + let repeats = + |runs: &[Issue446Run]| runs.iter().filter(|run| run.repeats_sibling).count(); + assert_eq!(repeats(&runs), repeats(&before), "{context}: {xml}"); + // One run a revision, and one for the text before, between and + // after them. + assert!( + runs.len() <= before.len() + 2 * revisions.len(), + "{context}: {} runs for {} revisions in {xml}", + runs.len(), + revisions.len() + ); + let pieces = |parent: &str| { + runs.iter() + .filter(|run| run.parent == parent) + .flat_map(|run| run.texts.iter().map(String::as_str)) + .collect::>() + }; + for (parent, kind) in [ + ("w:del", RevisionKind::Deletion), + ("w:ins", RevisionKind::Insertion), + ] { + // Each revision is one run holding its whole text. + assert_eq!( + pieces(parent), + revisions + .iter() + .filter(|revision| revision.kind() == kind) + .map(|revision| revision.text()) + .collect::>(), + "{context}: {xml}" + ); + } + if granularity == rdocx::ComparisonGranularity::Word { + assert_eq!(pieces("w:del"), ["twelve"], "{context}"); + assert_eq!(pieces("w:ins"), ["fifteen"], "{context}"); + assert!( + runs.iter() + .any(|run| run.texts == ["The bearing at pier 4 moved about "]) + && runs + .iter() + .any(|run| run.texts == [" millimetres since the survey."]), + "{context}: {xml}" + ); + } + let story_text = |document: &mut Document| { + issue446_runs(&comparison_part_xml(document, part)) + .into_iter() + .flat_map(|run| run.texts) + .collect::() + }; + let bytes = tracked.to_bytes().unwrap(); + for (resolve, wanted) in [ + (Document::accept_all as fn(&mut Document) -> _, edited_text), + (Document::reject_all, original_text), + ] { + let mut resolved = Document::from_bytes(&bytes).unwrap(); + resolve(&mut resolved).unwrap(); + assert_eq!( + story_text(&mut resolved), + story_text(&mut document(wanted)), + "{context}" + ); + } + } + } +} + +#[test] +fn issue446_comparison_keeps_the_runs_a_change_does_not_reach() { + let document = |last: &str| { + document_with_content_controls(&wrap_word_body(&format!( + r#"Plain bold and a tail of {last} days"# + ))) + }; + for granularity in [ + rdocx::ComparisonGranularity::Word, + rdocx::ComparisonGranularity::Character, + ] { + let mut tracked = document("thirty"); + tracked + .compare_with_options( + &document("ninety"), + "Ada", + "2026-11-15T09:00:00Z", + &rdocx::ComparisonOptions { + granularity, + ..Default::default() + }, + ) + .unwrap(); + let xml = document_xml(&mut tracked); + let pieces = issue446_runs(&xml) + .into_iter() + .map(|run| (run.parent, run.texts.concat())) + .collect::>(); + let pieces = pieces + .iter() + .map(|(parent, text)| (parent.as_str(), text.as_str())) + .collect::>(); + // The two runs before the edited one are whole, and the edited run + // is cut only where a revision starts or ends. + assert_eq!( + pieces[..3], + [ + ("w:p", "Plain "), + ("w:p", "bold"), + ("w:p", " and a tail of ") + ], + "{granularity:?}: {xml}" + ); + assert!( + matches!(pieces.last(), Some(("w:p", text)) if text.ends_with(" days")), + "{granularity:?}: {xml}" + ); + if granularity == rdocx::ComparisonGranularity::Word { + assert_eq!( + pieces[3..], + [("w:del", "thirty"), ("w:ins", "ninety"), ("w:p", " days")], + "{xml}" + ); + } + } +} + +#[test] +fn issue446_comparison_cost_follows_the_changes_not_the_unchanged_text() { + // Every later stage reads the redline run by run, so its run count and + // its size over the original are the structural cost of a comparison. + // Both depend on the edit alone, whatever the length of the text around + // it and whatever the unit the granularity compares. + for granularity in [ + rdocx::ComparisonGranularity::Word, + rdocx::ComparisonGranularity::Character, + ] { + let cost = |words: usize| { + let document = |last: &str| { + let mut document = Document::new(); + for _ in 0..3 { + document.add_paragraph(&format!("{}{last} days.", "kept ".repeat(words))); + } + Document::from_bytes(&document.to_bytes().unwrap()).unwrap() + }; + let mut tracked = document("thirty"); + let original = document_xml(&mut tracked); + tracked + .compare_with_options( + &document("sixty"), + "Ada", + "2026-11-15T09:00:00Z", + &rdocx::ComparisonOptions { + granularity, + ..Default::default() + }, + ) + .unwrap(); + let xml = document_xml(&mut tracked); + ( + issue446_runs(&xml).len(), + tracked.story_revisions().unwrap().len(), + xml.len() - original.len(), + ) + }; + assert_eq!(cost(4), cost(400), "{granularity:?}"); + if granularity == rdocx::ComparisonGranularity::Word { + // Three paragraphs, each with the text before, the deletion, the + // insertion and the text after. + assert_eq!((cost(4).0, cost(4).1), (12, 6)); + } + } +} + #[test] fn issue434_comparison_crossing_reply_composition() { let mut original = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 491226411..6e7a3ac85 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1513,7 +1513,16 @@ Fields, drawings, ignored units, opaque children, bookmark and comment markers, hyperlinks, controls and formatting transitions stop grouping. Formatting-only changes and replacements using ignored formatting also stop it. Different runs retain their own formatting and coalescing ownership. Run granularity retains -its existing alignment and revision output. Supported inline controls retain raw +its existing alignment and revision output. The granularity sets the compared +unit, never the written run. Unchanged units that continue one original and one +edited text element are written as one run, and the fragments of one text +element inside a written run rejoin as one text element with one source +selection, whole again when every fragment is there. A redline therefore holds +one run for each revision and for each stretch of text between two of them, +whatever the unit, in every story, with two exceptions. Under +`ignore_whitespace` an ignored whitespace unit ends a stretch, so unchanged text +is written one run per word and per space. A tab, a break or other run content +ends a stretch as it ends a text element. Supported inline controls retain raw child run cuts before extraction, align Word and Character units within those shell segments and copy each shell before its first inserted unit. Non-text content remains atomic. Unmatched identical owners become move pairs diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index c5493ba53..6ba457c27 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3075,7 +3075,11 @@ folds only when its joined word count is strictly shorter than both changed sides before and after it. Character units count joined words rather than letters. Structural, opaque and formatting boundaries, fields, drawings and ignored units remain barriers. Default and explicit run granularity retain their -existing output. Inside supported inline controls, retained raw children keep +existing output. Word and character redlines keep the text between two revisions +as one run with one text element, and each revision holds its text in one text +element, so the run count follows the revisions and not the compared units. Two +exceptions remain. With `ignore_whitespace` unchanged text is written one run +per word and per space, and a tab or a break between two texts ends a run. Inside supported inline controls, retained raw children keep their physical text ownership on both sides through accept, reject and reopen. No comparison option or existing public signature changes. The additive doc-hidden lower native `properties::protected_source_residual(xml, inherited_bindings)` diff --git a/docs/hld/12-testing-strategy.md b/docs/hld/12-testing-strategy.md index 8c0ca6f86..00935da88 100644 --- a/docs/hld/12-testing-strategy.md +++ b/docs/hld/12-testing-strategy.md @@ -1296,6 +1296,15 @@ reconstruction controls remain active. A bounded unit matrix checks coverage, deterministic output and retained segment identity without timing thresholds or an additional alignment algorithm. +The Issue446 regressions state the written shape as invariants at word and +character granularity in the body, a table cell, an inline control, a hyperlink, +a header and a footnote. No run holds two text elements, no run repeats the +properties of the sibling run it follows, each revision is one run with its +whole text, and the run count is bounded by the revision count. The run count +and the size a redline adds over its original do not depend on the length of +the unchanged text. Unit controls check that merged fragments rejoin one text +element with one source selection. None of these uses a timing threshold. + Chart comparison regressions cover chart-only Word and Run granularity, adjacent text edits and an unchanged-chart control. Saved and reopened resolutions follow the surviving drawing relationships and independently check exact ChartML, From 6260c5eef35d1b2fcf19c470fe0db0b6dc7123e7 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 18:39:54 +0100 Subject: [PATCH 02/11] perf(comparison): read each parent once per snapshot and resolve the candidate once A comparison became slower in v0.17.0 at every granularity, the default run granularity included (about 4 times on the documents of issue 446, with the same output), and quadratic in the children of one paragraph or table. Four causes, none of them in the alignment: - The source guard of F-X272 (af99e9d13) read a parent from its start once per child. RunSource::capture did it for each run of a paragraph, publication_parent_at and source_child for each row of a table, cell of a row, child of a cell or a control and inline control of a paragraph, in the five source snapshots of a comparison and again in the compare and mark paths (compare_table, compare_row, compare_cell_from_xml, compare_granular_controls, compare_complex_paragraph, paragraph_children_xml, marked rows and cells, and the parent of each written piece in compare_granular_paragraph). capture_all, publication_parents_at and source_children read a parent once for all its children. Each answer, an error included, is the one a read for that child alone gives, and each is taken where that read was made, so the errors keep their order. ParentScopes reads the scopes a paragraph path may ask on its first question. - Each postcondition direction resolved the candidate twice, once for the package guard and once more inside verify_footnote_destination (F-X272a, 1c69b7e0a). resolved_candidate resolves it once and both checks read it. - The postcondition signature of an ordinary part is taken at character granularity so that run splits do not change it (F-X279b, 2d387312d). It built one unit, one copy of the run properties and one token per character of all four documents. A run with no raw child and no deleted text is now read one stretch at a time, and consecutive plain characters are one token, in paragraphs and in the direct runs of a control. Two signatures read equal exactly when their character tokens did. - A paragraph snapshot computed its run spans twice. It computes them once. The package guard still reads each cleaned story a second time, as v0.17.0 does. That read refuses a drawing that shares its run with the begin mark of a complex field, whatever else changes ("comparison could not correlate split field run 2"), and a test pins that refusal: a speed change must not change which inputs a guard refuses. compare() CPU time, median of 5 runs alternated between builds, release wheels (0.16.4 and v0.17.0 from PyPI with fat LTO, this branch with LTO off and 16 codegen units, which favours the older wheels), measured on the final tree of this series: case granularity 0.16.4 v0.17.0 branch issue 446, 200 changed run 0.11 s 0.44 s 0.31 s issue 446, 200 changed word 0.64 s 6.65 s 0.45 s issue 446, 200 changed character 1.74 s 6.95 s 0.76 s issue 446, 400 changed run 0.21 s 0.89 s 0.62 s issue 446, 400 changed word 1.38 s 14.40 s 0.94 s 1000 paragraphs, 100 chg. run 0.33 s 1.14 s 0.81 s 1000 paragraphs, 100 chg. word 0.73 s 4.33 s 0.94 s 1000 paragraphs, 100 chg. character 1.57 s 4.62 s 1.01 s one paragraph of 400 runs run 0.06 s 0.53 s 0.12 s one paragraph of 400 runs word 0.09 s 9.29 s 0.15 s table of 100 rows run 0.21 s 1.74 s 0.88 s table of 100 rows word 0.33 s 2.34 s 0.95 s Growth for 4 times the rows of a table is 4.2 (0.16.4 4.2, v0.17.0 6.9) and for 4 times the runs of one paragraph 4.4 at run and 4.6 at word granularity (v0.17.0 13.2 at run). Run granularity stays 2.5 to 3 times 0.16.4 on paragraphs and 4.2 on a table. Restoring the guard's second read accounts for part of it. A release profile of the issue 446 script at run granularity (400 paragraphs) attributes 24 percent of a comparison to the footnote custody validation in a document with no note, 18.5 percent to canonicalize_drawing_ids in a document with no drawing, 19 percent to the package guard and 15 percent to compare_body. Checked on the final tree of this series against the v0.17.0 release wheel, with a debug build and every debug oracle on. The 1,080 cases of a refusal map around revisions, notes, comments, moves, controls, fields and bookmarks give the same refusals and messages and leave refused inputs intact. 792 guard cases give the same refusals, messages and run-granularity bytes. 500 random pairs give the same accepted and rejected text and formatting, and the same insertions, deletions and run bytes except 3 pure resplits inside an inline control, which a later commit of this series compares as equal. Part of #446. Tests, comparison.rs units compare the one-read answers with lone reads, errors included, check the stretch tokens, and count the source bytes a comparison reads for few and many runs, rows, hyperlink runs and inserted paragraphs and tables at the three granularities, issue446_comparison_keeps_refusing_a_drawing_in_a_field_begin_run in regression_test.rs, no timing threshold Harness, unchanged, the samples make no comparison --- crates/rdocx/src/comparison.rs | 1367 +++++++++++++++++++------ crates/rdocx/tests/regression_test.rs | 70 ++ docs/hld/03-architecture.md | 14 +- docs/hld/12-testing-strategy.md | 9 +- 4 files changed, 1138 insertions(+), 322 deletions(-) diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 71f9bc33a..586f2f763 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -615,6 +615,10 @@ pub(crate) fn apply_comment_snapshot( #[cfg(test)] thread_local! { static FAIL_AFTER_COMPARISON_STAGING: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// The bytes of the parents [`RunSource::capture_all`], + /// [`publication_parents_at`] and [`source_children`] have read, which the + /// tests of the cost of a comparison count instead of timing it. + static SOURCE_READ_BYTES: std::cell::Cell = const { std::cell::Cell::new(0) }; } type ControlPropertySignature<'a> = Option<( @@ -1611,14 +1615,13 @@ impl Document { &new_ids, )?; } - let mut accepted_body = resolved_package( + let accepted = resolved_candidate( &candidate, |document| document.accept_revision_ids(&new_ids), - &original_stories, - options, - &text_box_markers, Some(&new_ids), )?; + let mut accepted_body = + normalized_package(&accepted, &original_stories, options, &text_box_markers)?; let mut edited_package = normalized_package(&edited, &edited_stories, options, &text_box_markers)?; let main_ignored = story_ignored(options, ComparisonStoryKind::Main); @@ -1688,7 +1691,7 @@ impl Document { 1, &new_ids, )?; - verify_footnote_destination(&candidate, &edited, &new_ids, true, options)?; + verify_footnote_destination(&accepted, &edited, true, options)?; if accepted_body != edited_package { return Err(comparison_postcondition_error( "acceptance", @@ -1706,14 +1709,13 @@ impl Document { )); } } - let mut rejected_package = resolved_package( + let rejected = resolved_candidate( &candidate, |document| document.reject_revision_ids(&new_ids), - &original_stories, - options, - &text_box_markers, Some(&new_ids), )?; + let mut rejected_package = + normalized_package(&rejected, &original_stories, options, &text_box_markers)?; let mut original_package = normalized_package(&original, &original_stories, options, &text_box_markers)?; if main_ignored { @@ -1728,7 +1730,7 @@ impl Document { 0, &new_ids, )?; - verify_footnote_destination(&candidate, &original, &new_ids, false, options)?; + verify_footnote_destination(&rejected, &original, false, options)?; if rejected_package != original_package { return Err(comparison_postcondition_error( "rejection", @@ -3726,79 +3728,217 @@ fn source_fragment(xml: &str, bindings: &[(String, String)]) -> Result { } fn publication_parent_at(parent: &str, at: usize) -> Result { + publication_parents_at(parent, &[at]) + .pop() + .expect("one result per position") +} + +/// The scope of the element that holds each position of `parent`, as +/// [`publication_parent_at`] gives it for that position alone. +/// +/// One read of `parent` answers every position, so a parent of many children +/// is read once, not once per child. Each result, an error included, is the +/// one a read for that position alone gives, and is only met when a caller +/// takes it. +fn publication_parents_at(parent: &str, positions: &[usize]) -> Vec> { + if positions.is_empty() { + return Vec::new(); + } + #[cfg(test)] + SOURCE_READ_BYTES.with(|bytes| bytes.set(bytes.get() + parent.len())); let opening = format!(r#""#); let wrapped = format!("{opening}{parent}"); let mut reader = NsReader::from_str(&wrapped); - let mut scopes = Vec::new(); - loop { + let mut scopes = Vec::::new(); + let mut results = positions.iter().map(|_| None).collect::>(); + // The positions still to reach, the nearest last. + let mut pending = (0..positions.len()).collect::>(); + pending.sort_by_key(|index| std::cmp::Reverse(positions[*index])); + // A position the read passed holds no event. Its read goes on to the end. + let mut passed = Vec::new(); + let failure = loop { + if pending.is_empty() && passed.is_empty() { + break None; + } let before = reader.buffer_position() as usize; - let (_, event) = reader - .read_resolved_event() - .map_err(|error| Error::Other(error.to_string()))?; - if before == opening.len() + at { - return scopes - .last() - .cloned() - .ok_or_else(|| Error::Other("publication boundary has no actual parent".into())); + let event = match reader.read_resolved_event() { + Ok((_, event)) => event, + Err(error) => break Some(error.to_string()), + }; + while let Some(&index) = pending.last() + && opening.len() + positions[index] <= before + { + pending.pop(); + if opening.len() + positions[index] == before { + results[index] = Some(scopes.last().cloned().ok_or_else(|| { + Error::Other("publication boundary has no actual parent".into()) + })); + } else { + passed.push(index); + } } match event { - Event::Start(_) => scopes.push(resolved_source_bindings(&reader)?), + Event::Start(_) => match resolved_source_bindings(&reader) { + Ok(bindings) => scopes.push(bindings), + Err(error) => break Some(error.to_string()), + }, Event::End(_) => { scopes.pop(); } Event::Eof => { - return Err(Error::Other( - "publication boundary is absent from its actual shell".into(), - )); + break Some("publication boundary is absent from its actual shell".into()); } _ => {} } + }; + if let Some(message) = failure { + for index in pending.into_iter().chain(passed) { + results[index] = Some(Err(Error::Other(message.clone()))); + } + } + results + .into_iter() + .map(|result| result.expect("every position is answered")) + .collect() +} + +/// The scopes [`publication_parent_at`] gives for the positions of one +/// parent that a caller may ask, read in one pass on the first question. +/// A position outside that set is read alone. +struct ParentScopes<'a> { + parent: &'a str, + positions: Vec, + scopes: std::cell::OnceCell>>, +} + +impl<'a> ParentScopes<'a> { + fn new(parent: &'a str, positions: Vec) -> Self { + Self { + parent, + positions, + scopes: std::cell::OnceCell::new(), + } + } + + fn at(&self, position: usize) -> Result { + let scopes = self.scopes.get_or_init(|| { + self.positions + .iter() + .copied() + .zip(publication_parents_at(self.parent, &self.positions)) + .collect() + }); + match scopes.get(&position) { + Some(Ok(scope)) => Ok(scope.clone()), + // Every error of that read is `Error::Other`, so this is that error. + Some(Err(error)) => Err(Error::Other(error.to_string())), + None => publication_parent_at(self.parent, position), + } } } fn source_child(parent: &str, span: Range) -> Result { + source_children(parent, &[span]) + .pop() + .expect("one result per span") +} + +/// The child of `parent` at each span with the namespaces in scope declared +/// on its root, as [`source_child`] gives it for that span alone. +/// +/// One read of `parent` answers every span. Each result, an error included, +/// is the one a read for that span alone gives. +fn source_children(parent: &str, spans: &[Range]) -> Vec> { + if spans.is_empty() { + return Vec::new(); + } + #[cfg(test)] + SOURCE_READ_BYTES.with(|bytes| bytes.set(bytes.get() + parent.len())); let opening = format!(r#""#); let wrapped = format!("{opening}{parent}"); let mut reader = NsReader::from_str(&wrapped); - loop { + let mut results = spans.iter().map(|_| None).collect::>(); + // The spans still to reach, the nearest last. + let mut pending = (0..spans.len()).collect::>(); + pending.sort_by_key(|index| std::cmp::Reverse(spans[*index].start)); + // A span the read passed opens no element. Its read goes on to the end. + let mut passed = Vec::new(); + let failure = loop { + if pending.is_empty() && passed.is_empty() { + break None; + } let before = reader.buffer_position() as usize; - let (_, event) = reader - .read_resolved_event() - .map_err(|error| Error::Other(format!("source namespace scan failed: {error}")))?; - if before == opening.len() + span.start - && matches!(event, Event::Start(_) | Event::Empty(_)) - { - let bindings = reader - .resolver() - .bindings() - .map(|(prefix, uri)| { - let prefix = match prefix { - quick_xml::name::PrefixDeclaration::Default => String::new(), - quick_xml::name::PrefixDeclaration::Named(prefix) => { - String::from_utf8(prefix.to_vec()).map_err(utf8_error)? - } - }; - let uri = std::str::from_utf8(uri.as_ref()).map_err(utf8_error)?; - Ok(( - if prefix.is_empty() { - "xmlns".to_owned() - } else { - format!("xmlns:{prefix}") - }, - quick_xml::escape::unescape(uri) - .map_err(|error| Error::Other(error.to_string()))? - .into_owned(), - )) - }) - .collect::>>()?; - return source_fragment(&parent[span], &bindings); + let event = match reader.read_resolved_event() { + Ok((_, event)) => event, + Err(error) => break Some(format!("source namespace scan failed: {error}")), + }; + let opens = matches!(event, Event::Start(_) | Event::Empty(_)); + while let Some(&index) = pending.last() { + let start = opening.len() + spans[index].start; + if start < before { + pending.pop(); + passed.push(index); + } else if start == before && opens { + pending.pop(); + results[index] = Some(source_child_at(&reader, parent, spans[index].clone())); + } else { + break; + } } if matches!(event, Event::Eof) { - return Err(Error::Other( - "source child has no opening at its span".into(), - )); + break Some("source child has no opening at its span".into()); + } + }; + if let Some(message) = failure { + for index in pending.into_iter().chain(passed) { + results[index] = Some(Err(Error::Other(message.clone()))); } } + results + .into_iter() + .map(|result| result.expect("every span is answered")) + .collect() +} + +/// The parent scope and the scoped source of the child of `parent` at each +/// span, from one read of `parent` for each, in the order of `spans`. +fn child_scopes( + parent: &str, + spans: &[Range], +) -> std::iter::Zip>, std::vec::IntoIter>> +{ + let starts = spans.iter().map(|span| span.start).collect::>(); + publication_parents_at(parent, &starts) + .into_iter() + .zip(source_children(parent, spans)) +} + +/// The child at `span` with the bindings `reader` holds at its opening. +fn source_child_at(reader: &NsReader<&[u8]>, parent: &str, span: Range) -> Result { + let bindings = reader + .resolver() + .bindings() + .map(|(prefix, uri)| { + let prefix = match prefix { + quick_xml::name::PrefixDeclaration::Default => String::new(), + quick_xml::name::PrefixDeclaration::Named(prefix) => { + String::from_utf8(prefix.to_vec()).map_err(utf8_error)? + } + }; + let uri = std::str::from_utf8(uri.as_ref()).map_err(utf8_error)?; + Ok(( + if prefix.is_empty() { + "xmlns".to_owned() + } else { + format!("xmlns:{prefix}") + }, + quick_xml::escape::unescape(uri) + .map_err(|error| Error::Other(error.to_string()))? + .into_owned(), + )) + }) + .collect::>>()?; + source_fragment(&parent[span], &bindings) } fn root_namespace_bindings( @@ -5987,25 +6127,18 @@ fn bind_note_reference_revisions( Ok(()) } +/// Check the footnote part of `actual`, a [`resolved_candidate`], against the +/// input that resolution must reproduce. fn verify_footnote_destination( - candidate: &Document, + actual: &Document, wanted: &Document, - ids: &HashSet, accept: bool, options: &ComparisonOptions, ) -> Result<()> { if story_ignored(options, ComparisonStoryKind::Footnote) { return Ok(()); } - let mut actual = candidate.clone_for_staging(); - if accept { - actual.accept_revision_ids(ids)?; - } else { - actual.reject_revision_ids(ids)?; - } - let units = validate_footnote_custody(candidate, &crate::revision::RevisionScope::Ids(ids))?; - project_resolved_note_tombstones(candidate, &mut actual, &units)?; - let left = FootnotePart::of(&actual)?; + let left = FootnotePart::of(actual)?; let right = FootnotePart::of(wanted)?; match (&left, &right) { (None, None) => Ok(()), @@ -6269,6 +6402,7 @@ fn refuse_changed_existing_revisions( Ok(()) } +#[cfg(test)] fn resolved_package( candidate: &Document, resolve: impl FnOnce(&mut Document) -> Result, @@ -6277,6 +6411,18 @@ fn resolved_package( text_box_markers: &TextBoxMarkers, custody_ids: Option<&HashSet>, ) -> Result { + let resolved = resolved_candidate(candidate, resolve, custody_ids)?; + normalized_package(&resolved, stories, options, text_box_markers) +} + +/// The candidate with its revisions resolved one way and the transient note +/// pairs of fully resolved units projected out. Every postcondition of that +/// resolution reads this one document, so the package is resolved once. +fn resolved_candidate( + candidate: &Document, + resolve: impl FnOnce(&mut Document) -> Result, + custody_ids: Option<&HashSet>, +) -> Result { let mut resolved = candidate.clone_for_staging(); let units = custody_ids .map(|ids| validate_footnote_custody(candidate, &crate::revision::RevisionScope::Ids(ids))) @@ -6285,7 +6431,7 @@ fn resolved_package( if let Some(units) = units { project_resolved_note_tombstones(candidate, &mut resolved, &units)?; } - normalized_package(&resolved, stories, options, text_box_markers) + Ok(resolved) } /// Comparison guards may omit only the current fully resolved units' transient @@ -8626,42 +8772,82 @@ struct RunSource { } impl RunSource { - fn capture(run: Option<&CT_R>, parent: &str, span: Range) -> Result { + /// The source of the run at each span of `parent`, in the order given. + /// + /// One read of `parent` serves every run. A read per run reads the parent + /// again up to that run, which is quadratic in the runs it holds. Each + /// result, an error included, is the one a read for that run alone gives. + fn capture_all(runs: &[(Option<&CT_R>, Range)], parent: &str) -> Vec> { + if runs.is_empty() { + return Vec::new(); + } #[cfg(test)] if destination_diagnostic_enabled() { - policy_diagnostic( - "destination_actual_parent", - serde_json::json!({"parent_source":parent,"run_span":[span.start,span.end]}), - ); + for (_, span) in runs { + policy_diagnostic( + "destination_actual_parent", + serde_json::json!({"parent_source":parent,"run_span":[span.start,span.end]}), + ); + } } + #[cfg(test)] + SOURCE_READ_BYTES.with(|bytes| bytes.set(bytes.get() + parent.len())); let opening = format!(r#""#); let wrapped = format!("{opening}{parent}"); let mut reader = NsReader::from_str(&wrapped); - let mut scopes = Vec::new(); - loop { + let mut scopes = Vec::::new(); + let mut results = runs.iter().map(|_| None).collect::>(); + // The runs still to reach, the nearest last. + let mut pending = (0..runs.len()).collect::>(); + pending.sort_by_key(|index| std::cmp::Reverse(runs[*index].1.start)); + // A run the read passed opens no element. Its read goes on to the end. + let mut passed = Vec::new(); + let capture = |(run, span): &(Option<&CT_R>, Range), + bindings: &NamespaceBindings, + parent_scope: Option<&NamespaceBindings>| + -> Result { + let raw = parent[span.clone()].to_owned(); + let mut source = Self { + owner: run.map_or(0, |run| run as *const CT_R as usize), + scoped: source_fragment(&raw, bindings)?, + raw, + parent: parent_scope.cloned().unwrap_or_default(), + raw_slots: Vec::new(), + typed_slots: Vec::new(), + projected_raw_slots: HashSet::new(), + projected_typed_slots: HashSet::new(), + }; + if let Some(run) = run { + source.capture_children(run)?; + } + Ok(source) + }; + let failure = loop { + if pending.is_empty() && passed.is_empty() { + break None; + } let before = reader.buffer_position() as usize; - let (_, event) = reader - .read_resolved_event() - .map_err(|error| Error::Other(error.to_string()))?; + let event = match reader.read_resolved_event() { + Ok((_, event)) => event, + Err(error) => break Some(error.to_string()), + }; + while let Some(&index) = pending.last() + && opening.len() + runs[index].1.start < before + { + pending.pop(); + passed.push(index); + } match event { Event::Start(_) | Event::Empty(_) => { - let bindings = resolved_source_bindings(&reader)?; - if before == opening.len() + span.start { - let raw = parent[span].to_owned(); - let mut source = Self { - owner: run.map_or(0, |run| run as *const CT_R as usize), - scoped: source_fragment(&raw, &bindings)?, - raw, - parent: scopes.last().cloned().unwrap_or_default(), - raw_slots: Vec::new(), - typed_slots: Vec::new(), - projected_raw_slots: HashSet::new(), - projected_typed_slots: HashSet::new(), - }; - if let Some(run) = run { - source.capture_children(run)?; - } - return Ok(source); + let bindings = match resolved_source_bindings(&reader) { + Ok(bindings) => bindings, + Err(error) => break Some(error.to_string()), + }; + while let Some(&index) = pending.last() + && opening.len() + runs[index].1.start == before + { + pending.pop(); + results[index] = Some(capture(&runs[index], &bindings, scopes.last())); } if matches!(event, Event::Start(_)) { scopes.push(bindings); @@ -8670,10 +8856,19 @@ impl RunSource { Event::End(_) => { scopes.pop(); } - Event::Eof => return Err(Error::Other("run source has no actual opening".into())), + Event::Eof => break Some("run source has no actual opening".into()), _ => {} } + }; + if let Some(message) = failure { + for index in pending.into_iter().chain(passed) { + results[index] = Some(Err(Error::Other(message.clone()))); + } } + results + .into_iter() + .map(|result| result.expect("every run is answered")) + .collect() } } @@ -9798,7 +9993,8 @@ impl SourceSnapshots { let mut parent_writer = Writer::new(Vec::new()); parent_writer.write_event(Event::Start(root))?; let opening = String::from_utf8(parent_writer.into_inner()).map_err(utf8_error)?; - let mut field_spans = modeled_paragraph_run_spans(paragraph, xml)?; + let spans = modeled_paragraph_run_spans(paragraph, xml)?; + let mut field_spans = spans.clone(); // Legacy rendering keeps zero-length continuation placeholders. A source // witness instead retains the proven whole physical span at every actual // logical slot of that same shared group. @@ -9843,6 +10039,20 @@ impl SourceSnapshots { .ok_or_else(|| { Error::Other("field owner namespace closure changed its source boundary".into()) })?; + // One read of the paragraph answers the scope of every field. + let field_starts = paragraph + .runs + .iter() + .enumerate() + .flat_map(|(run_index, run)| { + run.content + .iter() + .filter(|content| matches!(content, RunContent::Field(_))) + .map(move |_| run_index) + }) + .map_while(|run_index| field_spans.get(run_index).map(|span| span.start)) + .collect::>(); + let mut field_parents = publication_parents_at(xml, &field_starts).into_iter(); let mut field_slot = 0usize; for (run_index, run) in paragraph.runs.iter().enumerate() { for content in &run.content { @@ -9861,7 +10071,7 @@ impl SourceSnapshots { let actual_field_source = &physical_owner[physical_span.clone()]; let actual_scope = actual_root_bindings( actual_field_source, - &publication_parent_at(xml, span.start)?, + &field_parents.next().expect("one scope per field")?, )?; self.capture_field_occurrence( std::ptr::from_ref(paragraph) as usize, @@ -9900,28 +10110,42 @@ impl SourceSnapshots { } if !self.properties_only { - let spans = modeled_paragraph_run_spans(paragraph, xml)?; let (opening, closing) = paragraph_shell(Some(xml))?; + // The runs the paragraph source holds as they are are captured in + // one read after this walk. Each was read in turn before, so an + // error capturing one still comes before any later error. + let mut plain = Vec::new(); + let mut failure = None; let mut index = 0; - while index < paragraph.runs.len() { - if let Some((coverage, fragments)) = - paragraph.field_source_run_fragments_at(index)? - { + 'runs: while index < paragraph.runs.len() { + let fragments = match paragraph.field_source_run_fragments_at(index) { + Ok(fragments) => fragments, + Err(error) => { + failure = Some(Error::from(error)); + break; + } + }; + if let Some((coverage, fragments)) = fragments { for (run, fragment) in paragraph.runs[index..index + coverage] .iter() .zip(fragments) { if let Some(raw) = fragment { - let raw = String::from_utf8(raw).map_err(utf8_error)?; - let wrapped = format!("{opening}{raw}{closing}"); - self.runs.insert( - run as *const CT_R as usize, - RunSource::capture( - Some(run), - &wrapped, - opening.len()..opening.len() + raw.len(), - )?, - ); + let source = + String::from_utf8(raw).map_err(utf8_error).and_then(|raw| { + let wrapped = format!("{opening}{raw}{closing}"); + let span = opening.len()..opening.len() + raw.len(); + RunSource::capture_all(&[(Some(run), span)], &wrapped).remove(0) + }); + match source { + Ok(source) => { + self.runs.insert(run as *const CT_R as usize, source); + } + Err(error) => { + failure = Some(error); + break 'runs; + } + } } } index += coverage; @@ -9929,18 +10153,25 @@ impl SourceSnapshots { } let run = ¶graph.runs[index]; if !run_is_field(run) { - self.runs.insert( - run as *const CT_R as usize, - RunSource::capture(Some(run), xml, spans[index].clone())?, - ); + plain.push((Some(run), spans[index].clone())); } index += 1; } + for ((run, _), source) in plain.iter().zip(RunSource::capture_all(&plain, xml)) { + if let Some(run) = run { + self.runs.insert(*run as *const CT_R as usize, source?); + } + } + if let Some(error) = failure { + return Err(error); + } } let controls = direct_word_element_spans(xml, "sdt")?; + let mut scopes = child_scopes(xml, &controls); for (index, ((_, _, _, control), span)) in paragraph.content_controls.iter().zip(controls).enumerate() { + let (parent, source) = scopes.next().expect("one scope per control span"); self.inherit_owner_path( std::ptr::from_ref(paragraph) as usize, std::ptr::from_ref(control) as usize, @@ -9966,6 +10197,7 @@ impl SourceSnapshots { .ok_or_else(|| { Error::Other("control budget interval precedes physical owner".into()) })?; + let parent = parent?; self.budget_holes .entry(std::ptr::from_ref(paragraph) as usize) .or_default() @@ -9973,19 +10205,13 @@ impl SourceSnapshots { path, 1, hole, - actual_root_bindings( - &xml[span.clone()], - &publication_parent_at(xml, span.start)?, - )?, + actual_root_bindings(&xml[span.clone()], &parent)?, )); self.roots.insert( control as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span.clone()].to_owned(), parent), ); - self.control(control, &source_child(xml, span)?)?; + self.control(control, &source?)?; } for (ordinal, (at, raw_before, revision)) in paragraph.revisions.iter().enumerate() { let raw = paragraph @@ -10018,12 +10244,10 @@ impl SourceSnapshots { } self.tables .insert(table as *const CT_Tbl as usize, xml.to_owned()); - for (index, (row, span)) in table - .rows - .iter() - .zip(direct_word_element_spans(xml, "tr")?) - .enumerate() - { + let rows = direct_word_element_spans(xml, "tr")?; + let mut scopes = child_scopes(xml, &rows); + for (index, (row, span)) in table.rows.iter().zip(rows).enumerate() { + let (parent, source) = scopes.next().expect("one scope per row span"); self.inherit_owner_path( std::ptr::from_ref(table) as usize, std::ptr::from_ref(row) as usize, @@ -10038,19 +10262,16 @@ impl SourceSnapshots { )?; self.roots.insert( row as *const CT_Row as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.row(row, &source_child(xml, span)?)?; + self.row(row, &source?)?; } - for (index, ((_, _, control), span)) in table - .content_controls - .iter() - .zip(direct_word_element_spans(xml, "sdt")?) - .enumerate() + let controls = direct_word_element_spans(xml, "sdt")?; + let mut scopes = child_scopes(xml, &controls); + for (index, ((_, _, control), span)) in + table.content_controls.iter().zip(controls).enumerate() { + let (parent, source) = scopes.next().expect("one scope per control span"); self.inherit_owner_path( std::ptr::from_ref(table) as usize, std::ptr::from_ref(control) as usize, @@ -10065,12 +10286,9 @@ impl SourceSnapshots { )?; self.roots.insert( control as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.control(control, &source_child(xml, span)?)?; + self.control(control, &source?)?; } Ok(()) } @@ -10085,12 +10303,10 @@ impl SourceSnapshots { } self.rows .insert(row as *const CT_Row as usize, xml.to_owned()); - for (index, (cell, span)) in row - .cells - .iter() - .zip(direct_word_element_spans(xml, "tc")?) - .enumerate() - { + let cells = direct_word_element_spans(xml, "tc")?; + let mut scopes = child_scopes(xml, &cells); + for (index, (cell, span)) in row.cells.iter().zip(cells).enumerate() { + let (parent, source) = scopes.next().expect("one scope per cell span"); self.inherit_owner_path( std::ptr::from_ref(row) as usize, std::ptr::from_ref(cell) as usize, @@ -10105,19 +10321,16 @@ impl SourceSnapshots { )?; self.roots.insert( cell as *const CT_Tc as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.cell(cell, &source_child(xml, span)?)?; + self.cell(cell, &source?)?; } - for (index, ((_, _, control), span)) in row - .content_controls - .iter() - .zip(direct_word_element_spans(xml, "sdt")?) - .enumerate() + let controls = direct_word_element_spans(xml, "sdt")?; + let mut scopes = child_scopes(xml, &controls); + for (index, ((_, _, control), span)) in + row.content_controls.iter().zip(controls).enumerate() { + let (parent, source) = scopes.next().expect("one scope per control span"); self.inherit_owner_path( std::ptr::from_ref(row) as usize, std::ptr::from_ref(control) as usize, @@ -10132,12 +10345,9 @@ impl SourceSnapshots { )?; self.roots.insert( control as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), + (xml[span].to_owned(), parent?), ); - self.control(control, &source_child(xml, span)?)?; + self.control(control, &source?)?; } Ok(()) } @@ -10152,12 +10362,13 @@ impl SourceSnapshots { } self.cells .insert(cell as *const CT_Tc as usize, xml.to_owned()); - for (index, (child, (_, span))) in cell - .content - .iter() - .zip(cell_child_spans(cell, xml, "source snapshot")?) - .enumerate() - { + let children = cell_child_spans(cell, xml, "source snapshot")? + .into_iter() + .map(|(_, span)| span) + .collect::>(); + let mut scopes = child_scopes(xml, &children); + for (index, (child, span)) in cell.content.iter().zip(children).enumerate() { + let (parent, source) = scopes.next().expect("one scope per cell child span"); let child_key = match child { CellContent::Paragraph(p) => std::ptr::from_ref(p) as usize, CellContent::Table(t) => std::ptr::from_ref(t) as usize, @@ -10170,36 +10381,21 @@ impl SourceSnapshots { xml, span.start, )?; - let source = source_child(xml, span.clone())?; + let source = source?; match child { CellContent::Paragraph(p) => { - self.roots.insert( - p as *const CT_P as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), - ); + self.roots + .insert(p as *const CT_P as usize, (xml[span].to_owned(), parent?)); self.paragraph(p, &source)? } CellContent::Table(t) => { - self.roots.insert( - t as *const CT_Tbl as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), - ); + self.roots + .insert(t as *const CT_Tbl as usize, (xml[span].to_owned(), parent?)); self.table(t, &source)? } CellContent::ContentControl(c) => { - self.roots.insert( - c as *const CT_Sdt as usize, - ( - xml[span.clone()].to_owned(), - publication_parent_at(xml, span.start)?, - ), - ); + self.roots + .insert(c as *const CT_Sdt as usize, (xml[span].to_owned(), parent?)); self.control(c, &source)? } } @@ -10265,6 +10461,56 @@ impl SourceSnapshots { )); } let spans = modeled_control_source_spans(&content, &payload)?; + // One read of the content answers every child. Each answer, an error + // included, is met where a read for that child alone was made. + let elements = content + .iter() + .zip(&spans) + .enumerate() + .filter(|(_, (child, _))| !matches!(child, SdtContent::RawXml(_))) + .map(|(index, (_, span))| (index, span.clone())) + .collect::>(); + let element_spans = elements + .iter() + .map(|(_, span)| span.clone()) + .collect::>(); + let element_starts = element_spans + .iter() + .map(|span| span.start) + .collect::>(); + let mut child_sources = content.iter().map(|_| None).collect::>(); + let mut child_parents = content.iter().map(|_| None).collect::>(); + for (((index, _), source), parent) in elements + .iter() + .zip(source_children(&payload, &element_spans)) + .zip(publication_parents_at(&payload, &element_starts)) + { + child_sources[*index] = Some(source); + child_parents[*index] = Some(parent); + } + let mut captured = content.iter().map(|_| None).collect::>(); + if !self.properties_only { + let plain = content + .iter() + .zip(&spans) + .enumerate() + .filter_map(|(index, (child, span))| match child { + SdtContent::Run(run) + if !run + .content + .iter() + .any(|content| matches!(content, RunContent::Field(_))) => + { + Some((index, (Some(run), span.clone()))) + } + _ => None, + }) + .collect::>(); + let runs = plain.iter().map(|(_, run)| run.clone()).collect::>(); + for ((index, _), source) in plain.iter().zip(RunSource::capture_all(&runs, &payload)) { + captured[*index] = Some(source); + } + } let mut field_slot = 0usize; for (index, (child, span)) in content.into_iter().zip(spans).enumerate() { let child_key = match child { @@ -10296,45 +10542,40 @@ impl SourceSnapshots { if matches!(child, SdtContent::RawXml(_)) { continue; } - let source = source_child(&payload, span.clone())?; + let source = child_sources[index] + .take() + .expect("an element child has its source")?; + let mut parent = || { + child_parents[index] + .take() + .expect("an element child has its parent scope") + }; match child { SdtContent::Paragraph(p) => { self.roots.insert( p as *const CT_P as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.paragraph(p, &source)?; } SdtContent::Table(t) => { self.roots.insert( t as *const CT_Tbl as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.table(t, &source)?; } SdtContent::Row(r) => { self.roots.insert( r as *const CT_Row as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.row(r, &source)?; } SdtContent::Cell(c) => { self.roots.insert( c as *const CT_Tc as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), parent()?), ); self.cell(c, &source)?; } @@ -10358,24 +10599,14 @@ impl SourceSnapshots { .ok_or_else(|| { Error::Other("nested control source-budget interval overflow".into()) })?; + let scope = parent()?; self.budget_holes .entry(std::ptr::from_ref(control) as usize) .or_default() - .push(( - path, - 6, - hole, - actual_root_bindings( - &source, - &publication_parent_at(&payload, span.start)?, - )?, - )); + .push((path, 6, hole, actual_root_bindings(&source, &scope)?)); self.roots.insert( c as *const CT_Sdt as usize, - ( - payload[span.clone()].to_owned(), - publication_parent_at(&payload, span.start)?, - ), + (payload[span.clone()].to_owned(), scope), ); self.control(c, &source)?; } @@ -10388,44 +10619,46 @@ impl SourceSnapshots { _ => None, }) .collect::>(); - if fields.is_empty() { - if !self.properties_only { - self.runs.insert( - r as *const CT_R as usize, - RunSource::capture(Some(r), &payload, span)?, - ); - } - } else { - for field in fields { - let scope = actual_root_bindings( - &source, - &actual_root_bindings(&payload, &Vec::new())?, - )?; - self.capture_field_occurrence( - std::ptr::from_ref(control) as usize, - field, - field_slot, - raw_payload, - span.start.checked_sub(closure_growth) - .zip(span.end.checked_sub(closure_growth)) - .map(|(start, end)| start..end) - .ok_or_else(|| Error::Other("control field source precedes its actual content owner".into()))?, - scope.clone(), - )?; - field_slot += 1; - self.field_scopes - .insert(std::ptr::from_ref(field) as usize, scope.clone()); - self.fields.insert( - std::ptr::from_ref(field) as usize, - field_source_metadata( - &source_without_text_properties( - &field_result_source_paragraph(&source, &scope)?, - &Vec::new(), - )?, - field.is_complex(), + if fields.is_empty() + && let Some(source) = captured[index].take() + { + self.runs.insert(r as *const CT_R as usize, source?); + } + for field in fields { + let scope = actual_root_bindings( + &source, + &actual_root_bindings(&payload, &Vec::new())?, + )?; + self.capture_field_occurrence( + std::ptr::from_ref(control) as usize, + field, + field_slot, + raw_payload, + span.start + .checked_sub(closure_growth) + .zip(span.end.checked_sub(closure_growth)) + .map(|(start, end)| start..end) + .ok_or_else(|| { + Error::Other( + "control field source precedes its actual content owner" + .into(), + ) + })?, + scope.clone(), + )?; + field_slot += 1; + self.field_scopes + .insert(std::ptr::from_ref(field) as usize, scope.clone()); + self.fields.insert( + std::ptr::from_ref(field) as usize, + field_source_metadata( + &source_without_text_properties( + &field_result_source_paragraph(&source, &scope)?, + &Vec::new(), )?, - ); - } + field.is_complex(), + )?, + ); } } SdtContent::RawXml(_) => {} @@ -13963,11 +14196,21 @@ fn compare_granular_paragraph( .map(str::to_owned) .map_or_else(|| paragraph_xml(original), Ok)?; let actual_spans = modeled_paragraph_run_spans(original, &actual_source)?; + // One read of the paragraph answers the scope of every run, on first use. + // Reading it again for each written piece is quadratic in its runs. + let run_parents = ParentScopes::new( + &actual_source, + actual_spans + .iter() + .map(|span| span.start) + .chain(element_opening(&actual_source).ok().map(|(end, ..)| end)) + .collect(), + ); let parent_for = |owner: usize| { let at = actual_spans .get(owner) .map_or(element_opening(&actual_source)?.0, |span| span.start); - publication_parent_at(&actual_source, at) + run_parents.at(at) }; let boundary_error = || { Error::Other(format!( @@ -16151,6 +16394,7 @@ fn compare_granular_controls( } let mut child_leaves = Vec::new(); let mut control_replacements = Vec::with_capacity(control_spans.len()); + let mut sources = source_children(output, &control_spans).into_iter(); for (index, ((_, _, _, left), (_, _, _, right))) in original .content_controls .iter() @@ -16158,13 +16402,14 @@ fn compare_granular_controls( .enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per control span"); control_replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(output, control_spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -16753,11 +16998,18 @@ fn compare_complex_paragraph( location, )?; } + // One read of the paragraph answers the scope at every run edge. + let parents = ParentScopes::new( + &source, + std::iter::once(0) + .chain(run_spans.iter().flat_map(|span| [span.start, span.end])) + .collect(), + ); let mut output = String::new(); let mut cursor = 0usize; for (left, right) in aligned { let at = left.map_or(cursor, |index| run_spans[index].start); - let destination_parent = publication_parent_at(&source, at)?; + let destination_parent = parents.at(at)?; let revision_parent = metadata.ids.revision_parent_scope(&destination_parent); if let Some(index) = left { let span = &run_spans[index]; @@ -16846,19 +17098,21 @@ fn compare_complex_paragraph( ))); } let mut replacements = Vec::with_capacity(spans.len()); + let mut sources = source_children(&output, &spans).into_iter(); for (index, ((_, _, _, left), (_, _, _, right))) in original .content_controls .iter() .zip(&edited.content_controls) .enumerate() { + let source = sources.next().expect("one source per control span"); replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(&output, spans[index].clone())?, + &source?, )?); } replace_direct_word_elements(&output, "sdt", &replacements) @@ -17370,6 +17624,8 @@ fn paragraph_children_xml( } let mut xml = paragraph_xml(&children)?; let spans = modeled_paragraph_run_spans(&children, &xml)?; + // One read of the paragraph answers the scope of every run. + let parents = ParentScopes::new(&xml, spans.iter().map(|span| span.start).collect()); let mut replacements = Vec::new(); let mut index = 0; while index < children.runs.len() { @@ -17389,9 +17645,7 @@ fn paragraph_children_xml( &children.runs[index], &raw, &typed, - &metadata - .ids - .revision_parent_scope(&publication_parent_at(&xml, span.start)?), + &metadata.ids.revision_parent_scope(&parents.at(span.start)?), &metadata.ids, ) }?)); @@ -17521,6 +17775,11 @@ fn compare_table( ))); } let aligned = align(&original_signatures, &edited_signatures); + // One read of the table answers the source of every row. + let mut row_sources = source_children(&source, &row_spans) + .into_iter() + .map(Some) + .collect::>(); let mut output = String::new(); let mut cursor = 0usize; for (alignment_index, &(left, right)) in aligned.iter().enumerate() { @@ -17543,7 +17802,7 @@ fn compare_table( output.push_str(&compare_row( &original.rows[i], &edited.rows[j], - Some(&source_child(&source, row_spans[i].clone())?), + Some(&row_sources[i].take().expect("a row is compared once")?), &format!("{location}/row[{j}]"), metadata, diagnostics, @@ -17569,6 +17828,7 @@ fn compare_table( } let mut child_leaves = Vec::new(); let mut replacements = Vec::with_capacity(spans.len()); + let mut sources = source_children(&output, &spans).into_iter(); for (index, ((_, _, left), (_, _, right))) in original .content_controls .iter() @@ -17576,13 +17836,14 @@ fn compare_table( .enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per control span"); replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(&output, spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -17795,9 +18056,10 @@ fn marked_row_xml(row: &str, kind: &str, metadata: &mut Metadata<'_>) -> Result< xml = insert_first_child(&xml, &properties)?; } } - let cells = direct_word_element_spans(&xml, "tc")? + let cell_spans = direct_word_element_spans(&xml, "tc")?; + let cells = source_children(&xml, &cell_spans) .into_iter() - .map(|span| marked_cell_xml(&source_child(&xml, span)?, kind, metadata)) + .map(|source| marked_cell_xml(&source?, kind, metadata)) .collect::>>()?; metadata .ids @@ -17808,19 +18070,23 @@ fn marked_cell_xml(cell: &str, kind: &str, metadata: &mut Metadata<'_>) -> Resul #[cfg(test)] let _destination_diagnostic_scope = PolicyDiagnosticScope::enter("destination:marked_cell_xml", cell); - let paragraphs = direct_word_element_spans(cell, "p")? + let paragraph_spans = direct_word_element_spans(cell, "p")?; + let paragraphs = source_children(cell, ¶graph_spans) .into_iter() - .map(|span| { + .map(|source| { let marker = metadata .ids .marker(kind, metadata.author, metadata.timestamp)?; - let source = source_child(cell, span)?; + let source = source?; let paragraph = marked_paragraph_xml(&source, &marker, &metadata.ids)?; let paragraph = marked_direct_runs_xml(¶graph, kind, metadata)?; - let hyperlinks = direct_word_element_spans(¶graph, "hyperlink")? - .into_iter() - .map(|span| { - let scoped = source_child(¶graph, span.clone())?; + let hyperlink_spans = direct_word_element_spans(¶graph, "hyperlink")?; + let hyperlinks = hyperlink_spans + .iter() + .cloned() + .zip(source_children(¶graph, &hyperlink_spans)) + .map(|(span, scoped)| { + let scoped = scoped?; let marked = marked_direct_runs_xml(&scoped, kind, metadata)?; let destination = root_namespace_bindings(¶graph, "p", &[])?; retain_source_root_namespaces(&marked, ¶graph[span], &destination) @@ -17830,14 +18096,16 @@ fn marked_cell_xml(cell: &str, kind: &str, metadata: &mut Metadata<'_>) -> Resul }) .collect::>>()?; let cell = replace_direct_word_elements(cell, "p", ¶graphs)?; - let tables = direct_word_element_spans(&cell, "tbl")? + let table_spans = direct_word_element_spans(&cell, "tbl")?; + let tables = source_children(&cell, &table_spans) .into_iter() - .map(|span| { - let scoped_table = source_child(&cell, span)?; + .map(|scoped_table| { + let scoped_table = scoped_table?; let table = scoped_table.as_str(); - let rows = direct_word_element_spans(table, "tr")? + let row_spans = direct_word_element_spans(table, "tr")?; + let rows = source_children(table, &row_spans) .into_iter() - .map(|span| marked_row_xml(&source_child(table, span)?, kind, metadata)) + .map(|source| marked_row_xml(&source?, kind, metadata)) .collect::>>()?; replace_direct_word_elements(table, "tr", &rows) }) @@ -17853,10 +18121,14 @@ fn marked_direct_runs_xml(owner: &str, kind: &str, metadata: &mut Metadata<'_>) #[cfg(test)] let _destination_diagnostic_scope = PolicyDiagnosticScope::enter("destination:marked_direct_runs_xml", owner); - let runs = direct_word_element_spans(owner, "r")? + let spans = direct_word_element_spans(owner, "r")? .into_iter() - .map(|span| { - let source = RunSource::capture(None, owner, span)?; + .map(|span| (None, span)) + .collect::>(); + let runs = RunSource::capture_all(&spans, owner) + .into_iter() + .map(|source| { + let source = source?; let mut run = source.scoped.clone(); if kind == "del" { for (local, deleted_local) in [("t", "delText"), ("instrText", "delInstrText")] { @@ -17926,15 +18198,17 @@ fn compare_row( } let mut child_leaves = Vec::new(); let mut cell_replacements = Vec::with_capacity(cell_spans.len()); + let mut sources = source_children(&output, &cell_spans).into_iter(); for (index, (left, right)) in original.cells.iter().zip(&edited.cells).enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per cell span"); cell_replacements.push(compare_cell_from_xml( left, right, &format!("{location}/cell[{index}]"), metadata, diagnostics, - &source_child(&output, cell_spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -17955,6 +18229,7 @@ fn compare_row( } let mut child_leaves = Vec::new(); let mut control_replacements = Vec::with_capacity(control_spans.len()); + let mut sources = source_children(&output, &control_spans).into_iter(); for (index, ((_, _, left), (_, _, right))) in original .content_controls .iter() @@ -17962,13 +18237,14 @@ fn compare_row( .enumerate() { let child_mark = metadata.leaf_publications.len(); + let source = sources.next().expect("one source per control span"); control_replacements.push(compare_control_from_xml( left, right, &format!("{location}/content-control[{index}]"), metadata, diagnostics, - &source_child(&output, control_spans[index].clone())?, + &source?, )?); child_leaves.push(metadata.leaf_publications.split_off(child_mark)); } @@ -18028,7 +18304,12 @@ fn compare_cell_from_xml( let children = cell_child_spans(original, original_xml, location)?; let mut child_leaves = Vec::new(); let mut replacements = Vec::with_capacity(children.len()); - for (index, ((left, right), (_, span))) in original + let child_spans = children + .iter() + .map(|(_, span)| span.clone()) + .collect::>(); + let mut sources = source_children(original_xml, &child_spans).into_iter(); + for (index, ((left, right), _)) in original .content .iter() .zip(&edited.content) @@ -18036,7 +18317,7 @@ fn compare_cell_from_xml( .enumerate() { let child_location = format!("{location}/content[{index}]"); - let source = source_child(original_xml, span.clone())?; + let source = sources.next().expect("one source per cell child span")?; let source = source.as_str(); let child_mark = metadata.leaf_publications.len(); replacements.push(match (left, right) { @@ -21717,6 +21998,10 @@ fn paragraph_signature_with_options(paragraph: &CT_P, options: &ComparisonOption enum ParagraphToken { /// A compared unit, or a whole run on the whole-run path. Unit(String), + /// Consecutive plain characters at character granularity. One token + /// holds the whole stretch, so the signature costs one token per stretch + /// of text and still reads the same however the runs split it. + Scalars(String), /// A unit the options ignore, such as whitespace, a field or a comment /// reference. Ignored(String), @@ -21734,12 +22019,6 @@ enum ParagraphToken { /// marker on either side of ignored content still differs. fn paragraph_tokens(paragraph: &CT_P, options: &ComparisonOptions) -> Vec { let attributed = uses_attributed_run_path(options); - let units = if attributed { - attributed_run_units(¶graph.runs, options) - } else { - Vec::new() - }; - let mut next_unit = 0; let mut tokens = Vec::new(); let mut open_hyperlink = None; for boundary in 0..=paragraph.runs.len() { @@ -21777,13 +22056,20 @@ fn paragraph_tokens(paragraph: &CT_P, options: &ComparisonOptions) -> Vec Vec::new(); + for (token, _) in tokens.into_iter().zip(keep).filter(|(_, keep)| *keep) { + // A stretch continues over ignored units that left no token. + if let (ParagraphToken::Scalars(text), Some(ParagraphToken::Scalars(stretch))) = + (&token, kept.last_mut()) + { + stretch.push_str(text); + } else { + kept.push(token); + } + } + kept.into_iter() + .map(|token| match token { ParagraphToken::Unit(signature) => format!("unit:{signature}"), + ParagraphToken::Scalars(text) => format!("scalars:{text:?}"), ParagraphToken::Ignored(signature) | ParagraphToken::Boundary(signature) => signature, }) .collect() } +/// The units a signature reads `run` as. +/// +/// At character granularity a run of plain content is read one stretch at a +/// time, which gives the tokens its characters would give once +/// [`signature_scalars`] joins them. A raw child and deleted text belong to +/// single characters, so a run that holds one is read character by character. +fn signature_run_units(run: &CT_R, options: &ComparisonOptions) -> Vec { + let stretches = options.granularity == ComparisonGranularity::Character + && run.extra_xml.is_empty() + && run.alt_drawings.is_empty() + && !run + .content + .iter() + .any(|content| matches!(content, RunContent::DeletedText(_))); + if stretches { + attributed_run_units( + std::slice::from_ref(run), + &ComparisonOptions { + granularity: ComparisonGranularity::Run, + ..options.clone() + }, + ) + } else { + attributed_run_units(std::slice::from_ref(run), options) + } +} + +/// The plain characters of a unit, which a character-granularity signature +/// holds with those before and after them as one token. +fn signature_scalars<'a>( + unit: &'a AttributedRunUnit, + options: &ComparisonOptions, +) -> Option<&'a str> { + (options.granularity == ComparisonGranularity::Character) + .then(|| unit_plain_text(unit)) + .flatten() + .filter(|text| !text.is_empty()) +} + /// Push the raw children, comment markers and inline controls at one run /// boundary in the order `CT_P` serialization writes them. fn push_boundary_tokens( @@ -21985,20 +22319,36 @@ fn cell_signature_with_options(cell: &CT_Tc, options: &ComparisonOptions) -> Str fn control_signature_with_options(control: &CT_Sdt, options: &ComparisonOptions) -> String { let mut content = Vec::new(); + // The plain characters since the last token, written as one token. + let mut scalars = String::new(); + let close = |scalars: &mut String, content: &mut Vec| { + if !scalars.is_empty() { + content.push(format!("u:scalars:{:?}", std::mem::take(scalars))); + } + }; for child in &control.content { match child { SdtContent::RawXml(raw) if raw.iter().all(u8::is_ascii_whitespace) => {} SdtContent::Run(run) if uses_attributed_run_path(options) => { - content.extend( - attributed_run_units(std::slice::from_ref(run), options) - .into_iter() - .filter(|unit| !unit_is_ignorable(unit) && !unit_is_empty(unit)) - .map(|unit| format!("u:{}", attributed_unit_signature(&unit))), - ); + for unit in signature_run_units(run, options) + .into_iter() + .filter(|unit| !unit_is_ignorable(unit) && !unit_is_empty(unit)) + { + if let Some(text) = signature_scalars(&unit, options) { + scalars.push_str(text); + } else { + close(&mut scalars, &mut content); + content.push(format!("u:{}", attributed_unit_signature(&unit))); + } + } + } + child => { + close(&mut scalars, &mut content); + content.push(control_content_signature_with_options(child, options)); } - child => content.push(control_content_signature_with_options(child, options)), } } + close(&mut scalars, &mut content); format!("{:?}:{:?}", control_property_signature(control), content) } @@ -23983,6 +24333,380 @@ mod tests { ); } + #[test] + fn character_signatures_hold_one_token_per_text_stretch() { + let scalar = ComparisonOptions { + granularity: ComparisonGranularity::Character, + ..Default::default() + }; + let bindings = vec![("xmlns:w".to_owned(), W_NS.to_owned())]; + let tokens = |runs: &str, options: &ComparisonOptions| { + let model = story_document(&format!("{runs}"), &bindings).unwrap(); + let BodyContent::Paragraph(paragraph) = &model.body.content[0] else { + unreachable!() + }; + super::paragraph_tokens(paragraph, options) + }; + let run = |text: &str| format!(r#"{text}"#); + // The cost of a signature follows its stretches, not its characters. + assert_eq!(tokens(&run("word"), &scalar).len(), 1); + assert_eq!(tokens(&run(&"word ".repeat(2000)), &scalar).len(), 1); + // The reading is the same however runs split the text. + let whole = tokens(&run("invoice thirty days"), &scalar); + assert_eq!( + whole, + tokens( + &[run("invoi"), run("ce thi"), run("rty days")].concat(), + &scalar + ) + ); + assert_ne!(whole, tokens(&run("invoice sixty days"), &scalar)); + // A run read one character at a time, because it holds a raw child, + // continues the stretch of a run read whole. + let raw = r#""#; + let with_raw = |text: &str| format!(r#"{text}{raw}"#); + assert_eq!( + tokens(&[run("ab"), with_raw("cd")].concat(), &scalar), + tokens(&[run("abc"), with_raw("d")].concat(), &scalar) + ); + assert_ne!( + tokens(&[run("ab"), with_raw("cd")].concat(), &scalar), + tokens(&[run("abcd"), with_raw("")].concat(), &scalar) + ); + // Deleted text reads one character at a time, whatever holds it. + let deleted = |texts: &[&str]| { + texts + .iter() + .map(|text| format!("{text}")) + .collect::() + }; + assert_eq!( + tokens(&deleted(&["abc"]), &scalar), + tokens(&deleted(&["a", "bc"]), &scalar) + ); + assert_ne!( + tokens(&deleted(&["abc"]), &scalar), + tokens(&run("abc"), &scalar) + ); + // Other content and empty text still stand between two stretches. + assert_eq!( + tokens("ab", &scalar).len(), + 3 + ); + assert_ne!( + tokens(&run("ab"), &scalar), + tokens("ab", &scalar) + ); + // The direct runs of an inline control follow the same rule. + let control = |runs: &str| { + let model = story_document( + &format!("{runs}"), + &bindings, + ) + .unwrap(); + let BodyContent::Paragraph(paragraph) = &model.body.content[0] else { + unreachable!() + }; + super::control_signature_with_options(¶graph.content_controls[0].3, &scalar) + }; + assert_eq!( + control(&run("invoice thirty days")), + control(&[run("invoi"), run("ce thi"), run("rty days")].concat()) + ); + assert_ne!( + control(&run("invoice thirty days")), + control(&run("invoice sixty days")) + ); + assert_eq!( + control(&[run("ab"), with_raw("cd")].concat()), + control(&[run("abc"), with_raw("d")].concat()) + ); + // Ignored whitespace leaves no token and does not end a stretch. + let ignoring = ComparisonOptions { + ignore_whitespace: true, + ..scalar.clone() + }; + assert_eq!(tokens(&run("a b c"), &ignoring).len(), 1); + assert_eq!( + tokens(&run("a b c"), &ignoring), + tokens(&[run("ab "), run(" c")].concat(), &ignoring) + ); + assert_ne!( + tokens(&run("a b c"), &scalar), + tokens(&[run("ab "), run(" c")].concat(), &scalar) + ); + } + + #[test] + fn run_sources_of_one_parent_are_captured_in_one_pass() { + let xml = format!( + r#"abcde"# + ); + let paragraph = rdocx_oxml::text::CT_P::from_xml_fragment(xml.as_bytes()).unwrap(); + let spans = super::modeled_paragraph_run_spans(¶graph, &xml).unwrap(); + assert_eq!(spans.len(), 5); + let runs = paragraph + .runs + .iter() + .map(Some) + .zip(spans) + .collect::>(); + // A span inside a run opens no element. It is answered among the + // others as it is alone, and leaves the other answers as they are. + let mut asked = runs.clone(); + asked.insert(2, (None, runs[1].1.start + 3..runs[1].1.end)); + super::SOURCE_READ_BYTES.set(0); + let together = super::RunSource::capture_all(&asked, &xml); + assert_eq!(super::SOURCE_READ_BYTES.get(), xml.len()); + let facts = |source: &super::Result| { + source.as_ref().map_err(ToString::to_string).map(|source| { + ( + source.owner, + source.scoped.clone(), + source.raw.clone(), + source.parent.clone(), + source.raw_slots.clone(), + source.typed_slots.clone(), + ) + }) + }; + for (run, source) in asked.iter().zip(&together) { + let alone = super::RunSource::capture_all(std::slice::from_ref(run), &xml); + assert_eq!(facts(source), facts(&alone[0])); + } + assert_eq!( + facts(&together[2]), + Err("run source has no actual opening".to_owned()) + ); + let together = together + .into_iter() + .filter_map(Result::ok) + .collect::>(); + assert_eq!(together.len(), 5); + // The scope of each run is the one its own ancestors declare. + let link = ("xmlns:x".to_owned(), "urn:link".to_owned()); + assert_eq!( + together + .iter() + .map(|source| source.parent.contains(&link)) + .collect::>(), + [false, true, true, false, false] + ); + assert!( + together + .iter() + .all(|source| !source.parent.iter().any(|(_, uri)| uri == "urn:run")) + ); + } + + #[test] + fn parent_scopes_of_many_children_are_read_in_one_pass() { + let xml = format!( + r#""# + ); + let rows = super::direct_word_element_spans(&xml, "tr").unwrap(); + let control = super::direct_word_element_spans(&xml, "sdt").unwrap()[0].clone(); + // Rows, a control between them, a span inside a tag, the end of the + // table and a span past it. + let mut spans = rows.clone(); + spans.insert(1, control.clone()); + spans.push(control.start + 2..control.end); + spans.push(xml.len() - "".len()..xml.len()); + spans.push(xml.len() + 5..xml.len() + 9); + let starts = spans.iter().map(|span| span.start).collect::>(); + fn text(result: &super::Result) -> Result { + result.as_ref().map_err(ToString::to_string).cloned() + } + super::SOURCE_READ_BYTES.set(0); + let parents = super::publication_parents_at(&xml, &starts); + let children = super::source_children(&xml, &spans); + assert_eq!(super::SOURCE_READ_BYTES.get(), 2 * xml.len()); + // Each answer, an error included, is the one a read for that + // position alone gives. + for ((start, span), (parent, child)) in + starts.iter().zip(&spans).zip(parents.iter().zip(&children)) + { + assert_eq!( + text(parent), + text(&super::publication_parents_at(&xml, &[*start])[0]) + ); + assert_eq!( + text(child), + text(&super::source_children(&xml, std::slice::from_ref(span))[0]) + ); + } + // The rows and the control open elements, and the end of the table + // is the start of an event, so all have a scope. The others are + // refused. + let absent = Err("publication boundary is absent from its actual shell".to_owned()); + assert!(parents[..3].iter().all(Result::is_ok) && parents[4].is_ok()); + assert_eq!( + [text(&parents[3]), text(&parents[5])], + [absent.clone(), absent] + ); + assert!(children[..3].iter().all(Result::is_ok)); + assert!(children[3..].iter().all(|child| { + text(child) == Err("source child has no opening at its span".to_owned()) + })); + // A row declares its own namespace for its source, not its scope. + assert!( + children[0] + .as_ref() + .unwrap() + .contains(r#"xmlns:x="urn:row""#) + && !parents[0] + .as_ref() + .unwrap() + .iter() + .any(|(_, uri)| uri == "urn:row") + ); + // The same request in another order gets the same answers. + let reversed = starts.iter().rev().copied().collect::>(); + assert_eq!( + super::publication_parents_at(&xml, &reversed) + .iter() + .rev() + .map(text) + .collect::>(), + parents.iter().map(text).collect::>() + ); + } + + /// The source bytes one comparison of the documents `body` makes for the + /// original and the edited text reads. + fn comparison_reads(body: &dyn Fn(&str) -> String, options: &ComparisonOptions) -> usize { + let document = |text: &str| { + let xml = format!( + r#"{}"#, + body(text) + ); + let mut document = Document::new(); + document + .package + .set_part(&document.doc_part_name, xml.into_bytes()); + Document::from_package(document.package).unwrap() + }; + let mut original = document("thirty days"); + let edited = document("sixty days"); + super::SOURCE_READ_BYTES.set(0); + original + .compare_with_options(&edited, "Ada", "2026-11-15T09:00:00Z", options) + .unwrap(); + assert!(!original.story_revisions().unwrap().is_empty()); + super::SOURCE_READ_BYTES.get() + } + + #[test] + fn comparison_reads_a_parent_once_per_snapshot_whatever_its_children() { + // Reading a paragraph or a table again for each run, row or cell made + // the cost quadratic in its children. The count of reads is the same + // for few and for many children. + let runs = |count: usize| { + (0..count) + .map(|index| { + format!( + r#"{}word{index} "#, + if index % 2 == 0 { + "" + } else { + "" + } + ) + }) + .collect::() + }; + let paragraph = |count: usize| { + move |text: &str| format!("{}{text}", runs(count)) + }; + let linked = |count: usize| { + move |text: &str| { + format!( + r#"{}{text}"#, + runs(count) + ) + } + }; + let added = |count: usize| { + move |text: &str| { + let extra = if text.starts_with("sixty") { + format!("{}", runs(count)) + } else { + String::new() + }; + format!("{text}{extra}") + } + }; + let table = |count: usize| { + move |text: &str| { + let rows = (0..count) + .map(|index| { + format!( + r#"row {index}{}"#, + if index == count / 2 { text } else { "kept" } + ) + }) + .collect::(); + format!( + r#"{rows}"# + ) + } + }; + let added_table = |count: usize| { + move |text: &str| { + let paragraph = format!("{text}"); + if text.starts_with("sixty") { + format!("{paragraph}{}", table(count)("kept")) + } else { + paragraph + } + } + }; + for granularity in [ + ComparisonGranularity::Run, + ComparisonGranularity::Word, + ComparisonGranularity::Character, + ] { + let options = ComparisonOptions { + granularity, + ..Default::default() + }; + // 16 times the children read at most 32 times the bytes, where a + // read of the parent for each child reads about 256 times more. + for (name, few, many) in [ + ( + "paragraph", + comparison_reads(¶graph(3), &options), + comparison_reads(¶graph(48), &options), + ), + ( + "hyperlink", + comparison_reads(&linked(3), &options), + comparison_reads(&linked(48), &options), + ), + ( + "added paragraph", + comparison_reads(&added(3), &options), + comparison_reads(&added(48), &options), + ), + ( + "table", + comparison_reads(&table(3), &options), + comparison_reads(&table(48), &options), + ), + ( + "added table", + comparison_reads(&added_table(3), &options), + comparison_reads(&added_table(48), &options), + ), + ] { + assert!( + many <= 32 * few, + "{name} {granularity:?}: {few} then {many} bytes" + ); + } + } + } + #[test] fn mixed_owner_gap_pairing_is_deterministic_and_preserves_every_owner() { let original = (0..48) @@ -25500,7 +26224,9 @@ mod tests { let spans = story_content_spans(body, &bindings).unwrap(); let xml = &body[spans[0].clone()]; let spans = modeled_paragraph_run_spans(p, xml).unwrap(); - RunSource::capture(Some(&p.runs[0]), xml, spans[0].clone()).unwrap() + RunSource::capture_all(&[(Some(&p.runs[0]), spans[0].clone())], xml) + .remove(0) + .unwrap() }; let left_source = source(original_body, &left); let right_source = source(edited_body, &right); @@ -26414,7 +27140,8 @@ mod tests { let pspan = story_content_spans(body, bindings)?[0].clone(); let closed = source_fragment(&body[pspan], bindings)?; let spans = modeled_paragraph_run_spans(p, &closed)?; - RunSource::capture(Some(&p.runs[0]), &closed, spans[0].clone()) + RunSource::capture_all(&[(Some(&p.runs[0]), spans[0].clone())], &closed) + .remove(0) }; let left_source = capture(left_body, left, &bindings_left)?; let right_source = capture(right_body, right, &bindings_right)?; diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 862f822b5..774c45e99 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -413114,6 +413114,76 @@ fn issue446_comparison_cost_follows_the_changes_not_the_unchanged_text() { } } +#[test] +fn issue446_comparison_keeps_refusing_a_drawing_in_a_field_begin_run() { + // The source guard reads the cleaned clone of each story again, as + // v0.17.0 does. That read refuses a drawing that shares its run with + // the begin mark of a complex field, whatever else changes. Speeding the + // comparison up must not change which inputs it refuses. + let png: &[u8] = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, + 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, + 0xcf, 0xc0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0xc9, 0xfe, 0x92, 0xef, 0x00, 0x00, 0x00, + 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + let mut seed = Document::new(); + seed.add_picture(png, "a.png", Length::emu(914400), Length::emu(914400)); + let seed = seed.to_bytes().unwrap(); + let package = oxml_opc::OpcPackage::from_reader(std::io::Cursor::new(&seed)).unwrap(); + let xml = String::from_utf8(package.get_part("/word/document.xml").unwrap().to_vec()).unwrap(); + let drawing = &xml[xml.find("").unwrap() + ..xml.find("").unwrap() + "".len()]; + let head = &xml[..xml.find("").unwrap() + "".len()]; + let tail = &xml[xml.find("{text}"#, + r#"{drawing}"#, + r#" PAGE "#, + r#"1"#, + r#""#, + ), + text = text, + drawing = drawing, + ); + let mut package = oxml_opc::OpcPackage::from_reader(std::io::Cursor::new(&seed)).unwrap(); + package.set_part( + "/word/document.xml", + format!("{head}{body}{tail}").into_bytes(), + ); + let mut bytes = std::io::Cursor::new(Vec::new()); + package.write_to(&mut bytes).unwrap(); + Document::from_bytes(bytes.get_ref()).unwrap() + }; + for granularity in [ + rdocx::ComparisonGranularity::Run, + rdocx::ComparisonGranularity::Word, + rdocx::ComparisonGranularity::Character, + ] { + let mut original = document("alpha beta"); + let before = original.to_bytes().unwrap(); + let error = original + .compare_with_options( + &document("alpha gamma"), + "Ada", + "2026-11-16T09:00:00Z", + &rdocx::ComparisonOptions { + granularity, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "comparison could not correlate split field run 2", + "{granularity:?}" + ); + assert_eq!(original.to_bytes().unwrap(), before, "{granularity:?}"); + } +} + #[test] fn issue434_comparison_crossing_reply_composition() { let mut original = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 6e7a3ac85..0504cf1f5 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1522,7 +1522,19 @@ one run for each revision and for each stretch of text between two of them, whatever the unit, in every story, with two exceptions. Under `ignore_whitespace` an ignored whitespace unit ends a stretch, so unchanged text is written one run per word and per space. A tab, a break or other run content -ends a stretch as it ends a text element. Supported inline controls retain raw +ends a stretch as it ends a text element. + +The cost of a comparison follows its changes, not its units or the size of the +parents that hold them, with one exception. A comparison reads the source of a +paragraph, table, row, cell or control a fixed number of times whatever +children it holds: one read answers all its children, every answer, an error +included, being the one a read for that child alone gives. A +character-granularity signature holds one token per stretch of plain text, and +each postcondition direction resolves the candidate once for both the package +guard and the footnote destination check. The package guard still reads each +cleaned story a second time, which keeps its refusals. The exception is the +alignment of one shell segment, a full longest-common-subsequence table, +quadratic in the units it compares. Supported inline controls retain raw child run cuts before extraction, align Word and Character units within those shell segments and copy each shell before its first inserted unit. Non-text content remains atomic. Unmatched identical owners become move pairs diff --git a/docs/hld/12-testing-strategy.md b/docs/hld/12-testing-strategy.md index 00935da88..7144e7a47 100644 --- a/docs/hld/12-testing-strategy.md +++ b/docs/hld/12-testing-strategy.md @@ -1303,7 +1303,14 @@ properties of the sibling run it follows, each revision is one run with its whole text, and the run count is bounded by the revision count. The run count and the size a redline adds over its original do not depend on the length of the unchanged text. Unit controls check that merged fragments rejoin one text -element with one source selection. None of these uses a timing threshold. +element with one source selection, that a character-granularity signature holds +one token per stretch and reads the same for every run split, and that run +sources and parent scopes read together equal those read alone, errors +included. A count of the source bytes a comparison reads shows that it reads a +paragraph, a hyperlink, a table and an inserted paragraph or table a fixed +number of times whatever their children, at every granularity. A further +regression pins the v0.17.0 refusal of a drawing that shares its run with a +field begin mark. None of these uses a timing threshold. Chart comparison regressions cover chart-only Word and Run granularity, adjacent text edits and an unchanged-chart control. Saved and reopened resolutions follow From 30e6db23288debad081bed4501ce55d4b4255c8a Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 18:40:03 +0100 Subject: [PATCH 03/11] fix(comparison): split text that holds a character or entity reference A word or character comparison of a changed paragraph whose w:t holds a reference refused with "split text has opaque mixed events", in the body and in every related story. That covers &, <, > and ", which rdocx writes itself on save, and numeric references such as é: saving and reopening "Smith & Sons pay now." and comparing it with "... later." refused. 0.16.4 compared it. source_text_fragment (F-X272, af99e9d13) checks that the source of a split text is one element holding text, and took exactly one text event. The XML reader reports a reference as an event of its own between two pieces of text. Any number of text and reference events now pass at the text's depth. A nested element, CDATA, a comment or a processing instruction still refuses. The value written comes from the parsed model and is escaped again on output, as before. Part of #446. Tests, issue446_comparison_splits_text_that_holds_references in regression_test.rs, with the reference in the changed token, at word and character granularity, in the body and a header, accepted and rejected back to each input Harness, unchanged, the samples make no comparison --- crates/rdocx/src/comparison.rs | 7 ++- crates/rdocx/tests/regression_test.rs | 70 +++++++++++++++++++++++++++ docs/hld/03-architecture.md | 3 +- docs/hld/10-bindings-spec.md | 4 +- docs/hld/12-testing-strategy.md | 8 +-- 5 files changed, 83 insertions(+), 9 deletions(-) diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 586f2f763..136ada028 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -12848,7 +12848,6 @@ fn source_text_fragment( )); }; let mut reader = Reader::from_str(xml); - let mut texts = 0; let mut depth = 0; loop { match reader @@ -12865,9 +12864,9 @@ fn source_text_fragment( Event::End(_) => { depth -= 1; } - Event::Text(_) if depth == 1 && texts == 0 => { - texts += 1; - } + // The reader splits text around each character or entity + // reference, such as `&`. The value comes from the model. + Event::Text(_) | Event::GeneralRef(_) if depth == 1 => {} Event::Eof => break, _ => return Err(Error::Other("split text has opaque mixed events".into())), } diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 774c45e99..75884285f 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -413184,6 +413184,76 @@ fn issue446_comparison_keeps_refusing_a_drawing_in_a_field_begin_run() { } } +#[test] +fn issue446_comparison_splits_text_that_holds_references() { + // The reader reports `&`, `"` and numeric references as events + // of their own between pieces of text. A word or character comparison + // that splits such a text refused it ("split text has opaque mixed + // events"), including text rdocx writes itself. + let original = r#"Smith&Sons pay "now", café 😀."#; + let edited = r#"Smith+Sons pay "later", café 😀."#; + let body: fn(&str) -> Document = + |paragraph| document_with_content_controls(&wrap_word_body(paragraph)); + let header: fn(&str) -> Document = document_with_comparison_header; + for (story, document) in [("body", body), ("header", header)] { + for granularity in [ + rdocx::ComparisonGranularity::Word, + rdocx::ComparisonGranularity::Character, + ] { + let context = format!("{story} {granularity:?}"); + let mut tracked = document(original); + tracked + .compare_with_options( + &document(edited), + "Ada", + "2026-11-16T09:00:00Z", + &rdocx::ComparisonOptions { + granularity, + ..Default::default() + }, + ) + .unwrap_or_else(|error| panic!("{context}: {error}")); + let revisions = tracked + .story_revisions() + .unwrap() + .iter() + .map(|revision| (revision.kind(), revision.text().to_owned())) + .collect::>(); + assert!( + revisions.contains(&(RevisionKind::Deletion, "&".to_owned())), + "{context}: {revisions:?}" + ); + if granularity == rdocx::ComparisonGranularity::Word { + assert_eq!( + revisions, + [ + (RevisionKind::Deletion, "&".to_owned()), + (RevisionKind::Insertion, "+".to_owned()), + (RevisionKind::Deletion, "now".to_owned()), + (RevisionKind::Insertion, "later".to_owned()), + ], + "{context}" + ); + } + let bytes = tracked.to_bytes().unwrap(); + for (resolve, wanted) in [ + (Document::accept_all as fn(&mut Document) -> _, edited), + (Document::reject_all, original), + ] { + let mut resolved = Document::from_bytes(&bytes).unwrap(); + resolve(&mut resolved).unwrap(); + resolved + .compare(&document(wanted), "Ada", "2026-11-16T09:01:00Z") + .unwrap(); + assert!( + resolved.story_revisions().unwrap().is_empty(), + "{context}: {wanted}" + ); + } + } + } +} + #[test] fn issue434_comparison_crossing_reply_composition() { let mut original = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 0504cf1f5..f45fbfd07 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1522,7 +1522,8 @@ one run for each revision and for each stretch of text between two of them, whatever the unit, in every story, with two exceptions. Under `ignore_whitespace` an ignored whitespace unit ends a stretch, so unchanged text is written one run per word and per space. A tab, a break or other run content -ends a stretch as it ends a text element. +ends a stretch as it ends a text element. Text that holds a character or entity +reference, such as `&`, splits like any other text. The cost of a comparison follows its changes, not its units or the size of the parents that hold them, with one exception. A comparison reads the source of a diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index 6ba457c27..01439537a 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3079,7 +3079,9 @@ existing output. Word and character redlines keep the text between two revisions as one run with one text element, and each revision holds its text in one text element, so the run count follows the revisions and not the compared units. Two exceptions remain. With `ignore_whitespace` unchanged text is written one run -per word and per space, and a tab or a break between two texts ends a run. Inside supported inline controls, retained raw children keep +per word and per space, and a tab or a break between two texts ends a run. Word +and character comparisons split text that holds a character or entity +reference, such as `&`. Inside supported inline controls, retained raw children keep their physical text ownership on both sides through accept, reject and reopen. No comparison option or existing public signature changes. The additive doc-hidden lower native `properties::protected_source_residual(xml, inherited_bindings)` diff --git a/docs/hld/12-testing-strategy.md b/docs/hld/12-testing-strategy.md index 7144e7a47..5406f6760 100644 --- a/docs/hld/12-testing-strategy.md +++ b/docs/hld/12-testing-strategy.md @@ -1308,9 +1308,11 @@ one token per stretch and reads the same for every run split, and that run sources and parent scopes read together equal those read alone, errors included. A count of the source bytes a comparison reads shows that it reads a paragraph, a hyperlink, a table and an inserted paragraph or table a fixed -number of times whatever their children, at every granularity. A further -regression pins the v0.17.0 refusal of a drawing that shares its run with a -field begin mark. None of these uses a timing threshold. +number of times whatever their children, at every granularity. Further +regressions pin the v0.17.0 refusal of a drawing that shares its run with a +field begin mark +and compare text holding references in the body and a header. None of these +uses a timing threshold. Chart comparison regressions cover chart-only Word and Run granularity, adjacent text edits and an unchanged-chart control. Saved and reopened resolutions follow From 7ebb978d3728c85f1c7702e32fe460fbbd41cf9d Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 18:40:11 +0100 Subject: [PATCH 04/11] fix(comparison): compare a resplit inline control as equal A paragraph whose runs only split the same text differently compares equal since v0.17.0 (F-X279b). An inline content control did not: its runs were aligned one by one, so one run against three with the same text and formatting gave 4 revisions at run granularity, as in 0.16.4. A word redline of one sentence inside a control, accepted or rejected and compared again with its input, gave 25 revisions at word granularity and 70 at character granularity on 0.16.4 and v0.17.0, and 4 and 8 before this commit. It now gives none. When every child of both controls is a run and the runs differ, compare_control_from_xml now reads them with the equality the paragraph path trusts, coalesced_paragraphs_equal, and keeps the original source when they are equal. It does not apply under leaf capture, to a control holding a raw child or a revision, or to runs holding a field, whose source facts it cannot read from copies, which keep the path below. Part of #446. Tests, issue446_comparison_reads_a_resplit_inline_control_as_equal in regression_test.rs at the three granularities, with a real change kept as a revision Harness, unchanged, the samples make no comparison --- crates/rdocx/src/comparison.rs | 34 ++++++++++++++++++ crates/rdocx/tests/regression_test.rs | 51 +++++++++++++++++++++++++++ docs/hld/03-architecture.md | 4 ++- docs/hld/10-bindings-spec.md | 3 +- docs/hld/12-testing-strategy.md | 6 ++-- 5 files changed, 93 insertions(+), 5 deletions(-) diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 136ada028..da520dba5 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -18418,6 +18418,40 @@ fn compare_control_from_xml( control_metadata_diagnostics(original, edited, location, diagnostics)?; let original_content = modeled_control_content(original); let edited_content = modeled_control_content(edited); + // Runs that only split the same text differently read as equal, as + // they do in a paragraph, and keep the original source. Equal runs + // keep the path below. + let only_runs = |content: &[&SdtContent]| { + !content.is_empty() + && content + .iter() + .all(|child| matches!(child, SdtContent::Run(_))) + }; + if !metadata.leaf_capture + && only_runs(&original_content) + && only_runs(&edited_content) + && original_content != edited_content + { + let runs_of = |content: &[&SdtContent]| { + let mut paragraph = CT_P::new(); + paragraph.runs = content + .iter() + .filter_map(|child| match child { + SdtContent::Run(run) => Some(run.clone()), + _ => None, + }) + .collect(); + paragraph + }; + if coalesced_paragraphs_equal( + &runs_of(&original_content), + &runs_of(&edited_content), + metadata.options, + metadata, + ) { + return Ok(original_xml.to_owned()); + } + } let direct_run_or_raw = |content: &&SdtContent| matches!(content, SdtContent::Run(_) | SdtContent::RawXml(_)); if uses_attributed_run_path(metadata.options) diff --git a/crates/rdocx/tests/regression_test.rs b/crates/rdocx/tests/regression_test.rs index 75884285f..1d576b84d 100644 --- a/crates/rdocx/tests/regression_test.rs +++ b/crates/rdocx/tests/regression_test.rs @@ -413254,6 +413254,57 @@ fn issue446_comparison_splits_text_that_holds_references() { } } +#[test] +fn issue446_comparison_reads_a_resplit_inline_control_as_equal() { + // Runs that only split the same text differently read as equal inside an + // inline control as they do in a paragraph, so accepting a granular + // redline there and comparing again gives no revision. + let control = |runs: &str| { + issue434_paragraph_document(&format!( + r#"Before {runs}"# + )) + }; + let run = |text: &str| { + format!(r#"{text}"#) + }; + let one = run("alpha beta gamma delta"); + let three = [run("alpha beta "), run("gamma"), run(" delta")].concat(); + for granularity in [ + rdocx::ComparisonGranularity::Run, + rdocx::ComparisonGranularity::Word, + rdocx::ComparisonGranularity::Character, + ] { + let options = rdocx::ComparisonOptions { + granularity, + ..Default::default() + }; + let mut original = control(&one); + let before = document_xml(&mut original); + original + .compare_with_options(&control(&three), "Ada", "2026-11-16T09:00:00Z", &options) + .unwrap(); + assert!( + original.story_revisions().unwrap().is_empty(), + "{granularity:?}" + ); + assert_eq!(document_xml(&mut original), before, "{granularity:?}"); + // A real change inside the control is still revised. + let mut original = control(&one); + original + .compare_with_options( + &control(&[run("alpha beta "), run("gamma"), run(" epsilon")].concat()), + "Ada", + "2026-11-16T09:00:00Z", + &options, + ) + .unwrap(); + assert!( + !original.story_revisions().unwrap().is_empty(), + "{granularity:?}" + ); + } +} + #[test] fn issue434_comparison_crossing_reply_composition() { let mut original = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index f45fbfd07..8dbce047a 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1523,7 +1523,9 @@ whatever the unit, in every story, with two exceptions. Under `ignore_whitespace` an ignored whitespace unit ends a stretch, so unchanged text is written one run per word and per space. A tab, a break or other run content ends a stretch as it ends a text element. Text that holds a character or entity -reference, such as `&`, splits like any other text. +reference, such as `&`, splits like any other text. An inline control whose +runs only split the same text differently keeps its original source, as an +equal paragraph does. The cost of a comparison follows its changes, not its units or the size of the parents that hold them, with one exception. A comparison reads the source of a diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index 01439537a..fea349d43 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3081,7 +3081,8 @@ element, so the run count follows the revisions and not the compared units. Two exceptions remain. With `ignore_whitespace` unchanged text is written one run per word and per space, and a tab or a break between two texts ends a run. Word and character comparisons split text that holds a character or entity -reference, such as `&`. Inside supported inline controls, retained raw children keep +reference, such as `&`. An inline control whose runs only split the same +text differently compares equal. Inside supported inline controls, retained raw children keep their physical text ownership on both sides through accept, reject and reopen. No comparison option or existing public signature changes. The additive doc-hidden lower native `properties::protected_source_residual(xml, inherited_bindings)` diff --git a/docs/hld/12-testing-strategy.md b/docs/hld/12-testing-strategy.md index 5406f6760..d946d25ad 100644 --- a/docs/hld/12-testing-strategy.md +++ b/docs/hld/12-testing-strategy.md @@ -1310,9 +1310,9 @@ included. A count of the source bytes a comparison reads shows that it reads a paragraph, a hyperlink, a table and an inserted paragraph or table a fixed number of times whatever their children, at every granularity. Further regressions pin the v0.17.0 refusal of a drawing that shares its run with a -field begin mark -and compare text holding references in the body and a header. None of these -uses a timing threshold. +field begin mark, compare text holding references in the body and a header, +and compare a resplit inline control as equal. None of these uses a timing +threshold. Chart comparison regressions cover chart-only Word and Run granularity, adjacent text edits and an unchanged-chart control. Saved and reopened resolutions follow From d3c5dc4e793273af0879cb3b19e3884e925df657 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 18:40:23 +0100 Subject: [PATCH 05/11] record the archive measurements The rdocx archive grows with the issue 446 comparison changes and their tests, on main eb980e94. It is the only crate whose member bytes change. It was measured on 2026-11-16, which its row and the remeasurement date now record. Tests, scripts/readme_doctests.py build_package_archive and archive_measurement for rdocx, member bytes stable on a second pass Harness, unchanged, measurements only --- 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..89e13bede 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,517,067 compressed bytes, 56,462,895 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..dde0d01d4 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_517_067, 56_462_895, 37), "rdocx-cli": (126_182, 593_817, 8), "rdocx-html": (29_407, 118_370, 11), "rdocx-layout": (463_844, 2_543_127, 15), From f17295c8191ac1f21fa10ef9d86605a0d584d5ff Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 17:34:59 +0100 Subject: [PATCH 06/11] fix(comparison): place the note custody pair after the note reference mark Microsoft Word for Mac 16.115 drops a zero-width bookmark pair that precedes the reference mark of a footnote that is not the first of its part, and keeps one that follows it (observed on every such save of the issue 430 shapes, again on a second save of the same file, and kept in 8 of 8 shapes once moved after the mark). A compare result whose note pair Word dropped can no longer prove its note owner, so later resolutions of that note refuse or lose its custody. The note pair now follows the reference-mark run inside the note's content insertion or deletion. A note without a reference-mark run keeps the earlier position, the start of its insertion or the paragraph boundary outside its deletion. Recognition is unchanged: it already admits a note pair as a direct child of the one wrapper that holds the note content. Part of #430 (F-X287). Tests, issue430_custody_note_pair_follows_the_note_reference_mark checks the emitted position in both directions with and without a reference mark, issue430_word_saved_note_pair_after_the_reference_mark_resolves_and_compares runs a Word-saved result through every choice and an unrelated comparison Harness, unchanged, the samples make no comparison --- crates/rdocx/src/comparison.rs | 23 ++- crates/rdocx/tests/integration_test.rs | 205 +++++++++++++++++++++++++ docs/hld/03-architecture.md | 7 +- 3 files changed, 230 insertions(+), 5 deletions(-) diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index da520dba5..e63c0ad28 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -5975,9 +5975,26 @@ fn insert_note_marker( at = node.end; continue; } - if addition && node.word && node.local == "ins" { - at = node.open_end; - insertion = true; + let wrapper = if addition { "ins" } else { "del" }; + if node.word && node.local == wrapper { + // Word 16.115 drops a zero-width pair that precedes the note's + // reference mark, and keeps one that follows it. Place the pair + // after the first reference-mark run of the content wrapper. + let mark = node.children.iter().copied().find(|&run| { + let run_node = &tree.elements[run]; + run_node.word + && run_node.local == "r" + && run_node.children.iter().any(|&leaf| { + tree.elements[leaf].word && tree.elements[leaf].local == "footnoteRef" + }) + }); + if let Some(run) = mark { + at = tree.elements[run].end; + insertion = addition; + } else if addition { + at = node.open_end; + insertion = true; + } } break; } diff --git a/crates/rdocx/tests/integration_test.rs b/crates/rdocx/tests/integration_test.rs index 26e2678cb..eadb8b0d1 100644 --- a/crates/rdocx/tests/integration_test.rs +++ b/crates/rdocx/tests/integration_test.rs @@ -39287,6 +39287,211 @@ fn issue430_custody_note_rejection_preserves_opaque_deleted_text_literals() { } } +// F-X287 Word-save fixtures. Each one is the body content and the footnote +// owners of a package that rdocx compared and Microsoft Word for Mac 16.115 +// (26110837) then opened and saved with "save as" (AppleScript `save as`, +// `format document`). Only rsid and w14 paragraph identity attributes are +// removed, everything else is the bytes Word wrote, including its note and +// bookmark renumbering, its localized reference style and its merged wrappers. +fn issue430_markers(document: &mut Document) -> Vec { + let package = issue430_package(document); + let mut names = Vec::new(); + for xml in package.parts.values() { + let text = String::from_utf8_lossy(xml); + let mut rest = text.as_ref(); + while let Some(at) = rest.find("_rdocxCmpNoteF") { + let tail = &rest[at..]; + let end = tail.find('"').unwrap_or(tail.len()); + names.push(tail[..end].to_owned()); + rest = &tail[end..]; + } + } + names.sort(); + names +} +fn issue430_texts(document: &Document) -> Vec { + document.paragraphs().iter().map(|p| p.text()).collect() +} +fn issue430_word_separators() -> &'static str { + r#""# +} +fn issue430_word_delivery_note() -> &'static str { + r#" Delivery note, p.1."# +} +/// A one-author Word-saved result reaches its input destination through every +/// whole-document and author choice, with a reopen after each, and leaves no +/// revision and no custody marker behind. +fn issue430_word_save_destinations( + body: &str, + notes: &str, + accepted: (&[i32], &[&str]), + rejected: (&[i32], &[&str]), +) { + let mut source = issue430_fixture(body, Some(notes)); + for (accept, all) in [(true, true), (true, false), (false, true), (false, false)] { + let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + let count = match (accept, all) { + (true, true) => document.accept_all(), + (true, false) => document.accept_revisions_by_author("A"), + (false, true) => document.reject_all(), + (false, false) => document.reject_revisions_by_author("A"), + } + .unwrap(); + assert!(count > 0); + let mut document = issue430_roundtrip(&mut document); + let (ids, texts) = if accept { accepted } else { rejected }; + assert_eq!( + issue430_texts(&document), + texts, + "accept {accept} all {all}" + ); + issue430_assert_settled(&mut document, ids, true); + } +} +/// An unrelated paragraph edit compares over the Word-saved pending result +/// without touching its custody, and both destinations then follow. +fn issue430_word_save_unrelated_comparison( + body: &str, + notes: &str, + edit: (&str, &str), + accepted: &[i32], + rejected: &[i32], +) { + let mut document = issue430_fixture(body, Some(notes)); + let package = issue430_package(&mut document); + let xml = String::from_utf8(package.get_part("/word/document.xml").unwrap().to_vec()).unwrap(); + assert_eq!(xml.matches(edit.0).count(), 1); + let edited = issue430_replace_parts(&mut document, Some(xml.replace(edit.0, edit.1)), None); + let markers = issue430_markers(&mut document); + let notes_before = issue430_note_xml(&mut document); + document.compare(&edited, "C", ISSUE430_DATE).unwrap(); + assert_eq!(issue430_markers(&mut document), markers); + assert_eq!(issue430_note_xml(&mut document), notes_before); + let mut document = issue430_roundtrip(&mut document); + let mut unrelated = issue430_roundtrip(&mut document); + unrelated.reject_revisions_by_author("C").unwrap(); + assert!(!issue430_texts(&unrelated).concat().contains(edit.1)); + let mut accept = issue430_roundtrip(&mut document); + accept.accept_all().unwrap(); + assert!(issue430_texts(&accept).concat().contains(edit.1)); + issue430_assert_settled(&mut accept, accepted, true); + let mut reject = issue430_roundtrip(&mut document); + reject.reject_all().unwrap(); + assert!(issue430_texts(&reject).concat().contains(edit.0)); + issue430_assert_settled(&mut reject, rejected, true); +} + +#[test] +fn issue430_custody_note_pair_follows_the_note_reference_mark() { + // Word 16.115 drops a note pair placed before the reference mark of a note + // that is not the first of its part, and keeps one placed after it. The + // pair goes after the reference-mark run of the content wrapper, in both + // directions. A note without a reference mark keeps the earlier position. + let marked = |id: i32, text: &str| { + format!( + r#" {text}"# + ) + }; + let unmarked = |id: i32, text: &str| { + format!(r#"{text}"#) + }; + for with_mark in [true, false] { + for addition in [true, false] { + let owner = if with_mark { marked } else { unmarked }; + let existing = marked(1, "existing"); + let short = format!( + "{}{}", + issue430_p("seller", Some(1)), + issue430_p("payment", None) + ); + let long = format!( + "{}{}", + issue430_p("seller", Some(1)), + issue430_p("payment", Some(2)) + ); + let short_notes = existing.clone(); + let long_notes = format!("{existing}{}", owner(2, "added")); + let (mut original, edited) = if addition { + ( + issue430_fixture(&short, Some(&short_notes)), + issue430_fixture(&long, Some(&long_notes)), + ) + } else { + ( + issue430_fixture(&long, Some(&long_notes)), + issue430_fixture(&short, Some(&short_notes)), + ) + }; + original.compare(&edited, "A", ISSUE430_DATE).unwrap(); + let notes = issue430_note_xml(&mut original).unwrap(); + let owner_at = notes.find(r#"").unwrap()]; + let pair = owner_xml.find(""), + "{owner_xml}" + ); + let open = owner_xml[..pair].rfind(&format!("<{wrapper} ")).unwrap(); + assert!(!owner_xml[open..pair].contains(&format!(""))); + } else if addition { + let open = owner_xml[..pair].rfind(""), + "{owner_xml}" + ); + } else { + assert!(owner_xml[..pair].ends_with(""), "{owner_xml}"); + } + let mut saved = issue430_roundtrip(&mut original); + for accept in [true, false] { + let mut resolved = Document::from_bytes(&saved.to_bytes().unwrap()).unwrap(); + if accept { + resolved.accept_all().unwrap(); + } else { + resolved.reject_all().unwrap(); + } + let retained = if accept == addition { + vec![1, 2] + } else { + vec![1] + }; + issue430_assert_settled(&mut resolved, &retained, true); + } + } + } +} + +#[test] +fn issue430_word_saved_note_pair_after_the_reference_mark_resolves_and_compares() { + // rdocx compared a three-paragraph original with an edit that adds a + // second footnote to its second paragraph, the note pair placed after the + // reference mark, and Word saved it. Word kept both pairs. + let body = r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in September."#; + let added = r#" Contract, clause 7."#; + let notes = format!( + "{}{}{added}", + issue430_word_separators(), + issue430_word_delivery_note() + ); + let texts = [ + "The buyer took delivery on 12 June.", + "Payment was due in thirty days.", + "The parties met in September.", + ]; + issue430_word_save_destinations(body, ¬es, (&[1, 2], &texts), (&[1], &texts)); + issue430_word_save_unrelated_comparison( + body, + ¬es, + ("met in September", "met in October"), + &[1, 2], + &[1], + ); +} + #[test] fn issue432_note_mark_order_separators_and_space() { let mut doc = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 8dbce047a..10a1ab5ae 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1605,8 +1605,11 @@ uses each attribute's effective Word namespace, including local prefix shadows. Added and removed definitions use paired hidden standard bookmarks in the body and first note paragraph. Names carry a persistent token and the emitting transaction's original and edited part-presence bits. The body pair precedes the -first actual reference outside its revision wrapper. An added note's pair is -inside its content insertion. A deleted note's pair stays outside the deletion. +first actual reference outside its revision wrapper. The note pair follows the +note's reference-mark run inside its content insertion or deletion, because +Word 16.115 drops a pair that precedes the reference mark of a note that is not +the first of its part. A note without a reference-mark run keeps the pair at the +start of its insertion, or outside its deletion. Tokens and bookmark ids are reserved before allocating new comparison ids. A token is identity, independent of every current revision id and token order. Listing and id, author and date scopes still operate on revision elements. From bb6848d410314f5dd1f5608200d3eb3c60400b36 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 20:14:39 +0100 Subject: [PATCH 07/11] fix(comparison): admit a body custody pair that Word moved into its reference's insertion Word for Mac 16.115 merges adjacent insertions of one author and date. When a comparison adds a paragraph with a new footnote, the paragraph's text insertion and the reference insertion meet around the body custody pair, and the saved file has the pair inside the merged insertion, right before the reference run (the issue's own "a footnote added" case). note_markers refused every body pair inside a revision, so Accept All, Reject All, selective resolution and an unrelated comparison all refused with "body custody pair is inside a revision". A body pair is now also admitted as a direct child of the one insertion of a main-story paragraph whose next child is the reference run, and only when its note pair is present. That is the same proof as at the direct position: the next sibling names the reference, and the note pair binds the owner, which must agree. The insertion is the reference's own revision element, so it resolves with the unit. Everything else inside a revision still refuses, atomically: an unmatched pair (no note pair), a pair inside a deletion (Word was not observed to put one there), a pair folded into a preceding insertion or placed before another run, a pair in a move destination, and a pair nested one level deeper. An insertion whose content a resolution removes now keeps such a pair in its place instead of dropping it with the content. When another unit is still pending, the pair stays a tombstone and its part-presence bits still vote, so the lifetime does not depend on Word's merging. Word's own Reject All also keeps the pair. Part of #430 (F-X287). Tests, issue430_word_saved_body_pair_in_its_reference_insertion_resolves_and_compares on the Word-saved bytes through every choice, an unrelated comparison and a partial id, issue430_body_pair_in_any_other_revision_position_still_refuses for six positions (the deletion, the unmatched pair and the nested pair among them) and three operations, atomic, issue430_body_pair_lifted_out_of_a_rejected_insertion_keeps_its_vote for both author orders and choices with reopens, which fails without the lift-out (the created part would survive) Harness, unchanged, the samples make no comparison --- crates/rdocx/src/comparison.rs | 56 ++++++- crates/rdocx/src/revision.rs | 21 ++- crates/rdocx/tests/integration_test.rs | 213 +++++++++++++++++++++++++ docs/hld/03-architecture.md | 13 +- docs/hld/10-bindings-spec.md | 2 +- 5 files changed, 296 insertions(+), 9 deletions(-) diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index e63c0ad28..8abe1818d 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -4621,6 +4621,8 @@ struct NoteMarker { pair_id: i32, owner: Option, reference: Option, + /// A body pair that Word moved into its own reference's revision wrapper. + wrapped: bool, } #[derive(Clone)] @@ -4632,6 +4634,10 @@ pub(crate) struct FootnoteCustody { addition: Option, selected: bool, revisions: Vec, + /// The main-story span of a body pair that sits inside its reference's + /// insertion. Resolving that insertion keeps the pair, so the unit's + /// lifetime and bits do not depend on Word's wrapper merging. + pub(crate) wrapped_body: Option>, } fn note_marker_name(name: &str) -> Option<(i32, bool, bool, char)> { @@ -4779,10 +4785,35 @@ fn note_markers(document: &Document) -> Result> { "custody pair has no direct paragraph owner".into(), )); }; - if family == 'B' && paragraph != parent { - return Err(Error::Other( - "body custody pair is inside a revision".into(), - )); + // Word for Mac 16.115 merges adjacent insertions of one author and + // date, which can move the body pair into its own reference's + // insertion. Admit only that position: an insertion directly in a + // main-story paragraph whose next child after the pair is the + // reference run, the same next-sibling proof as for a direct pair. + // validate_footnote_custody also requires the note pair there. + let wrapped = family == 'B' && paragraph != parent; + if wrapped { + let wrapper = &tree.elements[parent]; + let own_reference = part == document.doc_part_name + && wrapper.word + && wrapper.local == "ins" + && wrapper.revision.as_ref().is_some_and(|metadata| { + metadata.kind == crate::revision::RevisionKind::Insertion + }) + && siblings.get(position + 2).is_some_and(|&next| { + let run = &tree.elements[next]; + run.word + && run.local == "r" + && run.children.iter().any(|&leaf| { + tree.elements[leaf].word + && tree.elements[leaf].local == "footnoteReference" + }) + }); + if !own_reference { + return Err(Error::Other( + "body custody pair is inside a revision".into(), + )); + } } let mut owner = None; let mut owner_index = None; @@ -4862,6 +4893,7 @@ fn note_markers(document: &Document) -> Result> { pair_id, owner, reference, + wrapped, }); } } @@ -4884,6 +4916,12 @@ pub(crate) fn validate_footnote_custody( if markers.iter().any(|marker| marker.family == 'N') { return Err(Error::Other("custody marker has no footnotes part".into())); } + // Without its note pair, a body pair inside a revision has no proof. + if markers.iter().any(|marker| marker.wrapped) { + return Err(Error::Other( + "body custody pair is inside a revision".into(), + )); + } // Physical reference coherence is independent of the orphan bookmark. validate_footnote_reference_owners(None, &footnote_reference_sites(document)?)?; return Ok(markers @@ -4897,6 +4935,7 @@ pub(crate) fn validate_footnote_custody( addition: None, selected: false, revisions: Vec::new(), + wrapped_body: marker.wrapped.then(|| marker.span.clone()), }) .collect()); }; @@ -4918,6 +4957,14 @@ pub(crate) fn validate_footnote_custody( )); } let note = notes.first().copied(); + // The next-sibling proof inside a revision holds only with the note + // pair, which binds the owner. An unmatched pair stays where Word left + // it only at the direct position. + if note.is_none() && body.wrapped { + return Err(Error::Other( + "body custody pair is inside a revision".into(), + )); + } if let Some(note) = note { if note.owner.is_none() { return Err(Error::Other( @@ -5034,6 +5081,7 @@ pub(crate) fn validate_footnote_custody( addition, selected: selected > 0, revisions, + wrapped_body: body.wrapped.then(|| body.span.clone()), }); } if markers diff --git a/crates/rdocx/src/revision.rs b/crates/rdocx/src/revision.rs index 55c1eb2a3..4f08542ea 100644 --- a/crates/rdocx/src/revision.rs +++ b/crates/rdocx/src/revision.rs @@ -293,6 +293,9 @@ struct RenderState<'a> { leaf_ranges: Vec>>, leaf_updates: Vec, retiring_simple_fields: HashSet, + /// Source spans of custody pairs that sit inside a revision wrapper. A + /// wrapper whose content the resolution removes keeps them in its place. + custody_pairs: Vec>, } impl RenderState<'_> { @@ -526,6 +529,10 @@ impl Document { leaf_ranges: Vec::new(), leaf_updates: Vec::new(), retiring_simple_fields: HashSet::new(), + custody_pairs: footnote_custody + .iter() + .filter_map(|unit| unit.wrapped_body.clone()) + .collect(), }; state.retiring_simple_fields = tree.carried_simple_field_retirements(&state)?; let mut output = Vec::with_capacity(source.len()); @@ -993,6 +1000,7 @@ fn render_with_source_ranges( leaf_elements: selected, leaf_updates: Vec::new(), retiring_simple_fields: HashSet::new(), + custody_pairs: Vec::new(), }; state.retiring_simple_fields = tree.carried_simple_field_retirements(&state)?; let mut output = Vec::with_capacity(tree.source.len()); @@ -2567,7 +2575,18 @@ impl<'a> XmlTree<'a> { ) } else { self.validate_selected_descendants(index, state)?; - Ok(Vec::new()) + let mut kept = Vec::new(); + for &child in &self.elements[index].children { + let node = &self.elements[child]; + if state + .custody_pairs + .iter() + .any(|pair| pair.start <= node.start && node.end <= pair.end) + { + kept.extend(self.render_with_namespaces(child, state, false, destination)?); + } + } + Ok(kept) } } diff --git a/crates/rdocx/tests/integration_test.rs b/crates/rdocx/tests/integration_test.rs index eadb8b0d1..da4eecace 100644 --- a/crates/rdocx/tests/integration_test.rs +++ b/crates/rdocx/tests/integration_test.rs @@ -39492,6 +39492,219 @@ fn issue430_word_saved_note_pair_after_the_reference_mark_resolves_and_compares( ); } +fn issue430_word_added_paragraph(pair_in_body: &str) -> String { + format!( + r#"The buyer took delivery on 12 June.{pair_in_body}Payment was due in thirty days."# + ) +} +fn issue430_word_added_paragraph_notes() -> String { + format!( + r#"{}{} Letter of 1 July, p.2."#, + issue430_word_separators(), + issue430_word_delivery_note() + ) +} +const ISSUE430_WORD_PAIR: &str = + r#""#; +const ISSUE430_WORD_REFERENCE: &str = r#""#; + +#[test] +fn issue430_word_saved_body_pair_in_its_reference_insertion_resolves_and_compares() { + // The issue's "a footnote added" result: a new middle paragraph with a new + // note, the note pair placed after the reference mark. Word merged the + // paragraph's text insertion with the reference insertion (same author + // and date), which moved the body pair inside the merged insertion, right + // before the reference run. Word kept the note pair. + let merged = format!( + r#"The seller wrote twice to ask for payment.{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"# + ); + let body = issue430_word_added_paragraph(&merged); + let notes = issue430_word_added_paragraph_notes(); + let accepted = [ + "The buyer took delivery on 12 June.", + "The seller wrote twice to ask for payment.", + "Payment was due in thirty days.", + ]; + let rejected = [ + "The buyer took delivery on 12 June.", + "Payment was due in thirty days.", + ]; + issue430_word_save_destinations(&body, ¬es, (&[1, 2], &accepted), (&[1], &rejected)); + issue430_word_save_unrelated_comparison( + &body, + ¬es, + ("due in thirty days", "due in forty days"), + &[1, 2], + &[1], + ); + // A selector that covers only the merged wrapper is still a partial unit. + let mut document = issue430_fixture(&body, Some(¬es)); + let before = document.to_bytes().unwrap(); + assert!( + document + .reject_revision_id(1) + .unwrap_err() + .to_string() + .contains("partial footnote custody") + ); + assert_eq!(document.to_bytes().unwrap(), before); +} + +#[test] +fn issue430_body_pair_in_any_other_revision_position_still_refuses() { + let text = r#"The seller wrote twice to ask for payment."#; + let deleted = r#"The seller wrote twice to ask for payment."#; + let open = r#""#; + let other = r#""#; + let inside = "body custody pair is inside a revision"; + let notes = issue430_word_added_paragraph_notes(); + let variants = [ + // folded into the preceding text insertion, with no reference after it + format!("{open}{text}{ISSUE430_WORD_PAIR}{other}{ISSUE430_WORD_REFERENCE}"), + // inside the reference's insertion, but before a text run + format!("{open}{ISSUE430_WORD_PAIR}{text}{ISSUE430_WORD_REFERENCE}"), + // a move destination is not an insertion + format!( + r#"{open}{text}{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"# + ), + // a deletion: Word was never observed to put a pair there + format!( + r#"{deleted}{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"# + ), + ] + .map(|variant| (issue430_word_added_paragraph(&variant), notes.clone(), inside)); + // nested one level deeper, inside a hyperlink of the reference's insertion + let nested = ( + issue430_word_added_paragraph(&format!( + r#"{open}{text}{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"# + )), + notes.clone(), + "custody pair has no direct paragraph owner", + ); + // An unmatched pair (no note pair) inside another author's insertion, + // before the re-inserted reference of an existing untracked note. + let unmatched = ( + format!( + r#"Text more"# + ), + format!( + "{}{}", + issue430_word_separators(), + issue430_word_delivery_note() + ), + inside, + ); + for (body, notes, message) in variants.into_iter().chain([nested, unmatched]) { + for action in 0..3 { + let mut document = issue430_fixture(&body, Some(¬es)); + let before = document.to_bytes().unwrap(); + let error = match action { + 0 => document.accept_all().unwrap_err(), + 1 => document.reject_revisions_by_author("A").unwrap_err(), + _ => { + let mut edited = issue430_fixture(&body, Some(¬es)); + let edited = issue430_roundtrip(&mut edited); + document.compare(&edited, "C", ISSUE430_DATE).unwrap_err() + } + }; + assert!(error.to_string().contains(message), "{error}"); + assert_eq!(document.to_bytes().unwrap(), before); + } + } +} + +#[test] +fn issue430_body_pair_lifted_out_of_a_rejected_insertion_keeps_its_vote() { + // Hand-built, not a Word save: it combines two observed Word shapes so that + // the only creation bits sit on a merged pair. Note 1 was created with the + // part (bits 01) and its body pair sits inside the inserted paragraph's + // insertion, as Word 16.115 writes it after merging that insertion with + // the reference insertion. Note 2 came from a later comparison (bits 11). + // Rejecting note 1 removes the insertion around its pair: the pair stays as + // a direct child of the merged paragraph, so its creation bits still vote + // and rejecting note 2 then removes the part. + let date = ISSUE430_DATE; + let body = format!( + r#"Added paragraph.Kept paragraph."# + ); + let note = |id: i32, author: &str, ids: (i32, i32), pair: &str, text: &str| { + format!( + r#"{pair} {text}"#, + ids.0, ids.1 + ) + }; + let notes = format!( + "{}{}{}", + issue430_word_separators(), + note( + 1, + "A", + (3, 4), + r#""#, + "First." + ), + note( + 2, + "Y", + (6, 7), + r#""#, + "Second." + ) + ); + let mut source = issue430_fixture(&body, Some(¬es)); + for (first, second) in [("A", "Y"), ("Y", "A")] { + for accept_first in [false, true] { + for accept_second in [false, true] { + let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + for (author, accept) in [(first, accept_first), (second, accept_second)] { + if accept { + document.accept_revisions_by_author(author).unwrap(); + } else { + document.reject_revisions_by_author(author).unwrap(); + } + document = issue430_roundtrip(&mut document); + if author == first { + // The other unit is pending: every pair is still present, + // except the note pair of a rejected (removed) note. + let markers = issue430_markers(&mut document); + assert!(markers.contains(&"_rdocxCmpNoteF7P01B".to_owned())); + assert!(markers.contains(&"_rdocxCmpNoteF8P11B".to_owned())); + if author == "A" && !accept { + let body = String::from_utf8( + issue430_package(&mut document) + .get_part("/word/document.xml") + .unwrap() + .to_vec(), + ) + .unwrap(); + let pair = body.find("_rdocxCmpNoteF7P01B").unwrap(); + assert!(body[pair..].starts_with( + r#"_rdocxCmpNoteF7P01B"/>Kept paragraph."# + ), "{body}"); + assert!(!body.contains(">(); + issue430_assert_settled(&mut document, &retained, !retained.is_empty()); + } + } + } +} + #[test] fn issue432_note_mark_order_separators_and_space() { let mut doc = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 10a1ab5ae..44790f638 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1605,8 +1605,15 @@ uses each attribute's effective Word namespace, including local prefix shadows. Added and removed definitions use paired hidden standard bookmarks in the body and first note paragraph. Names carry a persistent token and the emitting transaction's original and edited part-presence bits. The body pair precedes the -first actual reference outside its revision wrapper. The note pair follows the -note's reference-mark run inside its content insertion or deletion, because +first actual reference outside its revision wrapper. Word for Mac 16.115 merges +adjacent insertions of one author and date, which can move the pair inside the +reference's own insertion. A body pair is admitted there only in the main story, +only with its note pair, and only as a direct child of the one insertion whose +next child is the reference run, the same next-sibling proof as outside it. +Resolving that insertion keeps the pair in its place, so its lifetime and +part-presence vote do not depend on Word's merging. Any other position inside a +revision refuses, as does an unmatched pair inside one. The note pair follows +the note's reference-mark run inside its content insertion or deletion, because Word 16.115 drops a pair that precedes the reference mark of a note that is not the first of its part. A note without a reference-mark run keeps the pair at the start of its insertion, or outside its deletion. @@ -1644,7 +1651,7 @@ before editing its owner or part or emitting new custody there. Ignored notes retain original bytes and cannot supply a dangling new body reference. Endnote topology retains its existing refusal while ordinary text edits remain supported. -Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair inside a revision and drop its note counterpart. Such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved. +Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair into its own reference's merged insertion, which is admitted while the note pair remains, and Word for Mac 16.115 can drop the note counterpart. Without the note pair, such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically when the body pair sits inside the merged insertion, and rejecting an added note or accepting a removed one refuses atomically otherwise. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved. Inputs may hold existing modeled revisions, such as the redline of an earlier comparison. A story owner that holds one, a paragraph, table, or diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index fea349d43..c72ab73bb 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3067,7 +3067,7 @@ that would leave a missing note target. Endnote text comparison remains supported, while new endnote topology remains refused. These operations use existing held-handle invalidation and leave all live state unchanged on refusal. -Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair inside a revision and drop its note counterpart. Such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved. +Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair into its own reference's merged insertion, which is admitted while the note pair remains, and Word for Mac 16.115 can drop the note counterpart. Without the note pair, such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically when the body pair sits inside the merged insertion, and rejecting an added note or accepting a removed one refuses atomically otherwise. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved. Word and character revisions group changed stretches as deletions followed by insertions. Whitespace between changes folds, while a non-whitespace anchor From 479880136cc72a490753973db3699a51a87c19f0 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 20:17:19 +0100 Subject: [PATCH 08/11] fix(comparison): retire leftover custody pairs when a resolution settles the note part When Word drops a note custody pair, its body pair is left without a note counterpart. Q-A430-29 keeps such a pair unassociated, so no unit is recognized and settle_footnote_custody returned early: accepting the whole Word-saved comparison left the hidden body bookmark behind, while a library-only result settles with no marker at all. A resolution that edits the note part or resolves a note reference, and leaves no revision in a normal note owner or a note reference, now settles the part even when no unit is recognized, and retires the pairs left in it, at the same point as any settlement. Resolving the reference alone counts, so the pair also retires when the note side settled first, in an earlier call or in Word. Whether a reference was resolved is read from the render that resolved it, only when the document holds custody pairs. A pair in a part that the resolution leaves untouched stays, as before, and while any note revision is pending every pair stays. This matches the contract for markers Word leaves in a completed part: kept while untouched, retired once the library edits that part. Part of #430 (F-X287). Tests, issue430_word_saved_unmatched_body_pair_retires_when_its_part_settles on Word-saved bytes, with Word for Mac 16.115's own Accept All output as the untouched and the edited-part controls, issue430_settling_only_the_reference_retires_the_leftover_body_pair (the note side settled first by id, or already settled as Word leaves it, both choices), issue430_word_saved_mixed_authors_keep_pairs_until_the_last_note_settles for both author orders with reopens, test_issue430_word_saved_merged_body_pair_and_lost_note_pair_settle in test_core.py for the merged body pair (part B) and the leftover pair through the binding Harness, unchanged, the samples make no comparison --- crates/rdocx-py/tests/test_core.py | 101 +++++++++++++++ crates/rdocx/src/comparison.rs | 31 +++++ crates/rdocx/src/revision.rs | 15 ++- crates/rdocx/tests/integration_test.rs | 165 +++++++++++++++++++++++++ docs/hld/03-architecture.md | 5 +- docs/hld/10-bindings-spec.md | 46 +++---- 6 files changed, 339 insertions(+), 24 deletions(-) diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index 7c6c6ada7..682163844 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -16927,6 +16927,107 @@ def renumber(match): assert "word/footnotes.xml" not in archive.namelist() + +# F-X287 Word-save fixtures: the body content and footnote owners of rdocx +# comparisons that Microsoft Word for Mac 16.115 (26110837) opened and saved +# with "save as". rsid and w14 paragraph identities are removed, the rest is +# what Word wrote, including its renumbering and merged insertions. +ISSUE430_W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" +ISSUE430_DATE = 'w:date="2026-10-30T12:00:00Z"' +ISSUE430_DELIVERY = ( + '' + ' Delivery note, p.1.' +) + + +def _issue430_word_saved(body, notes): + import rdocx + + base = rdocx.Document() + base.add_footnote(base.add_paragraph("seed"), "seed") + output = io.BytesIO() + with zipfile.ZipFile(io.BytesIO(base.to_bytes())) as source: + with zipfile.ZipFile(output, "w") as destination: + for info in source.infolist(): + payload = source.read(info.filename) + if info.filename == "word/document.xml": + payload = (f'{body}' + "").encode() + elif info.filename == "word/footnotes.xml": + payload = f'{notes}'.encode() + destination.writestr(info, payload) + return output.getvalue() + + +def _issue430_markers(document): + with zipfile.ZipFile(io.BytesIO(document.to_bytes())) as archive: + return sorted(set(match.decode() for name in archive.namelist() + for match in re.findall(rb"_rdocxCmpNoteF\w+", archive.read(name)))) + + +def _issue430_note_ids(document): + with zipfile.ZipFile(io.BytesIO(document.to_bytes())) as archive: + if "word/footnotes.xml" not in archive.namelist(): + return None + notes = archive.read("word/footnotes.xml") + return [int(value) for value in re.findall(rb'The buyer took delivery on 12 June.' + f'' + f'The seller wrote twice to ask for payment.' + '' + '' + 'Payment was due in thirty days.' + ) + added_notes = ( + f'{ISSUE430_DELIVERY}' + f'' + '' + ' Letter of 1 July, p.2.' + ) + pending = _issue430_word_saved(added, added_notes) + for accept, notes, texts in ( + (True, [1, 2], ["The buyer took delivery on 12 June.", + "The seller wrote twice to ask for payment.", + "Payment was due in thirty days."]), + (False, [1], ["The buyer took delivery on 12 June.", "Payment was due in thirty days."]), + ): + document = rdocx.Document.from_bytes(pending) + count = (document.accept_revisions_by_author("A") if accept + else document.reject_revisions_by_author("A")) + assert count > 0 + document = rdocx.Document.from_bytes(document.to_bytes()) + assert [paragraph.text for paragraph in document.paragraphs] == texts + assert _issue430_note_ids(document) == notes + assert document.revisions == () + assert _issue430_markers(document) == [] + # A footnote added to an existing paragraph, saved by Word, which dropped + # the note pair. Accepting settles the note part and its leftover pair. + note_only = ( + 'Payment was due in thirty days.' + '' + f'' + ) + note_only_notes = ( + f'{ISSUE430_DELIVERY}' + f'' + ' Contract, clause 7.' + ) + document = rdocx.Document.from_bytes(_issue430_word_saved(note_only, note_only_notes)) + assert _issue430_markers(document) == ["_rdocxCmpNoteF4P11B"] + document.accept_all() + assert _issue430_note_ids(document) == [1, 2] + assert _issue430_markers(document) == [] + + @pytest.mark.parametrize("family", ("footnote", "endnote")) @pytest.mark.parametrize("text", ("", "Source note", " text")) def test_issue432_note_defaults_and_space(family, text): diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 8abe1818d..76c303c67 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -5162,9 +5162,18 @@ pub(crate) fn settle_footnote_custody( document: &mut Document, units: &[FootnoteCustody], accept: bool, + note_part_resolved: bool, mut publication: Option<&mut crate::revision::NotePublication>, ) -> Result<()> { if !units.iter().any(|unit| !unit.revisions.is_empty()) { + // No unit is recognized as pending, for example after Word dropped a + // note pair. A resolution that edits the note part or resolves a note + // reference, and leaves no note revision pending, still settles the + // part, and settlement retires its remaining custody pairs. A pair in + // an untouched part stays. + if note_part_resolved && !units.is_empty() && !note_revisions_pending(document)? { + retire_note_markers(document, units, publication)?; + } return Ok(()); } let Some(mut part) = FootnotePart::of(document)? else { @@ -5217,6 +5226,28 @@ pub(crate) fn settle_footnote_custody( Ok(()) } +/// Whether a normal note owner or a note reference still carries a revision. +fn note_revisions_pending(document: &Document) -> Result { + if footnote_reference_sites(document)? + .iter() + .any(|site| site.revision.is_some()) + { + return Ok(true); + } + let Some(part) = FootnotePart::of(document)? else { + return Ok(false); + }; + let mut tree = crate::revision::XmlTree::parse(part.xml.as_bytes())?; + tree.qualify_note_revisions()?; + let owners = part.normal(); + Ok(tree.elements.iter().any(|node| { + node.revision.is_some() + && owners + .values() + .any(|owner| node.start >= owner.inner.start && node.end <= owner.inner.end) + })) +} + fn retire_note_markers( document: &mut Document, units: &[FootnoteCustody], diff --git a/crates/rdocx/src/revision.rs b/crates/rdocx/src/revision.rs index 4f08542ea..25d2df940 100644 --- a/crates/rdocx/src/revision.rs +++ b/crates/rdocx/src/revision.rs @@ -539,6 +539,16 @@ impl Document { output.extend_from_slice(&source[..tree.elements[tree.root].start]); output.extend_from_slice(&tree.render(tree.root, &mut state, false)?); output.extend_from_slice(&source[tree.elements[tree.root].end..]); + // Resolving a note reference settles the note side of a custody unit as + // much as resolving the note itself, so it counts for settlement. Read + // from this render, only when the document holds custody pairs. + let reference_resolved = !footnote_custody.is_empty() + && tree.elements.iter().enumerate().any(|(index, node)| { + node.word + && node.local == "footnoteReference" + && std::iter::successors(Some(index), |&at| tree.elements[at].parent) + .any(|at| state.resolved.contains(&at)) + }); let mut resolved = state.resolved.len(); if resolved > 0 { @@ -557,8 +567,9 @@ impl Document { resolved = resolved .checked_add(removed_note_revisions) .ok_or_else(|| Error::Other("resolved revision count overflowed".into()))?; + let mut note_part_resolved = removed_note_revisions > 0 || reference_resolved; let story_parts = crate::comparison::revision_story_parts(&candidate)?; - for (_, part_name) in story_parts { + for (kind, part_name) in story_parts { let part = candidate .package .get_part(&part_name) @@ -604,6 +615,7 @@ impl Document { resolve_story_xml(&part, resolution, scope.clone())? }; if count > 0 { + note_part_resolved |= matches!(kind, crate::StoryKind::Footnote); candidate.package.set_part(&part_name, updated); resolved = resolved .checked_add(count) @@ -665,6 +677,7 @@ impl Document { &mut candidate, &footnote_custody, matches!(resolution, Resolution::Accept), + note_part_resolved, publication.as_deref_mut(), )?; candidate.reconcile_comment_removal(self)?; diff --git a/crates/rdocx/tests/integration_test.rs b/crates/rdocx/tests/integration_test.rs index da4eecace..5d7317d3f 100644 --- a/crates/rdocx/tests/integration_test.rs +++ b/crates/rdocx/tests/integration_test.rs @@ -39705,6 +39705,171 @@ fn issue430_body_pair_lifted_out_of_a_rejected_insertion_keeps_its_vote() { } } +fn issue430_word_note_only_body() -> &'static str { + r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in September."# +} +fn issue430_word_note_only_notes() -> String { + format!( + r#"{}{} Contract, clause 7."#, + issue430_word_separators(), + issue430_word_delivery_note() + ) +} +fn issue430_word_mixed_body() -> &'static str { + r#"The buyer took delivery on 12 June.Payment was due in thirty daysThe seller wrote twice to ask for payment.Payment was due in sixty days.The parties met in SeptemberOctober."# +} +fn issue430_word_mixed_notes() -> String { + format!( + r#"{}{} Letter of 1 July, p.2. Minutes of the meeting, p.4."#, + issue430_word_separators(), + issue430_word_delivery_note() + ) +} + +#[test] +fn issue430_word_saved_unmatched_body_pair_retires_when_its_part_settles() { + // rdocx compared the three-paragraph original with an edit that adds a + // second footnote to its second paragraph (the pair before the reference + // mark, as v0.17.0 wrote it), and Word saved it. Word dropped the note + // pair, so the body pair has no note counterpart. Accepting settles every + // note revision, and settlement retires the leftover pair. + let accepted = [ + "The buyer took delivery on 12 June.", + "Payment was due in thirty days.", + "The parties met in September.", + ]; + let mut source = issue430_fixture( + issue430_word_note_only_body(), + Some(&issue430_word_note_only_notes()), + ); + for all in [true, false] { + let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + if all { + document.accept_all().unwrap(); + } else { + document.accept_revisions_by_author("A").unwrap(); + } + let mut document = issue430_roundtrip(&mut document); + assert_eq!(issue430_texts(&document), accepted); + issue430_assert_settled(&mut document, &[1, 2], true); + } + // Word's own Accept All of that file (Word 16.115, AppleScript `accept all + // revisions` then `save as`) keeps the body pair in a settled part. It stays + // while a resolution leaves the note part untouched, and retires once a + // resolution edits the part and leaves no note revision pending. + let settled_body = r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in September."#; + // The control adds one unrelated tracked paragraph to Word's bytes, and in + // the second case one tracked run to the second note. + let unrelated = format!( + r#"{settled_body}Unrelated."# + ); + let settled_notes = format!( + r#"{}{} Contract, clause 7.{{extra}}"#, + issue430_word_separators(), + issue430_word_delivery_note() + ); + let pair = vec!["_rdocxCmpNoteF4P11B".to_owned()]; + let mut untouched = issue430_fixture(&unrelated, Some(&settled_notes.replace("{extra}", ""))); + assert_eq!(untouched.accept_revision_id(100).unwrap(), 1); + assert_eq!(issue430_markers(&mut untouched), pair); + let edited_note = settled_notes.replace( + "{extra}", + &format!( + r#" Also clause 8."# + ), + ); + for both in [false, true] { + let mut document = issue430_fixture(&unrelated, Some(&edited_note)); + if both { + assert_eq!(document.accept_all().unwrap(), 2); + assert!(issue430_markers(&mut document).is_empty()); + } else { + assert_eq!(document.accept_revision_id(100).unwrap(), 1); + assert_eq!(issue430_markers(&mut document), pair); + assert_eq!(document.reject_revision_id(101).unwrap(), 1); + assert!(issue430_markers(&mut document).is_empty()); + } + } +} + +#[test] +fn issue430_settling_only_the_reference_retires_the_leftover_body_pair() { + // The Word-saved result whose note pair Word dropped. Accepting the note's + // own two elements first leaves only the reference pending, and the pair + // stays. Accepting the reference then settles the part, and its leftover + // pair retires, whichever side settles last. + let pair = vec!["_rdocxCmpNoteF4P11B".to_owned()]; + let mut document = issue430_fixture( + issue430_word_note_only_body(), + Some(&issue430_word_note_only_notes()), + ); + for id in [2, 3] { + document.accept_revision_id(id).unwrap(); + document = issue430_roundtrip(&mut document); + assert_eq!(issue430_markers(&mut document), pair); + } + assert_eq!(document.story_revisions().unwrap().len(), 1); + assert_eq!(document.accept_revision_id(1).unwrap(), 1); + let mut document = issue430_roundtrip(&mut document); + issue430_assert_settled(&mut document, &[1, 2], true); + // The same state as Word leaves it after accepting only the note side: + // the note is settled and only the reference insertion is pending. + let settled_note = issue430_word_note_only_notes() + .replace( + r#""#, + "", + ) + .replace( + r#""#, + "", + ) + .replace("", ""); + assert!(!settled_note.contains(" Date: Mon, 16 Nov 2026 20:33:25 +0100 Subject: [PATCH 09/11] fix(comparison): refuse a note reference that moves to another site Footnote comparison pairs the owners of both inputs by note id. When the edited input inserts a note before an existing one, as Word and the add_footnote producer number notes, the new note takes the existing note's id and the existing note moves to the next id. The comparison then paired two different notes as one text change, deleted the original reference and inserted the edited one, both naming the same owner. The pending result held two physical references to one note, the shared-reference shape of Q-A430-28. Accept and reject still gave the edited and original notes, but Word for Mac 16.115 could not open the pending file (review A, the "a new note before an existing one" result, the same on v0.17.0). A footnote that both inputs reference now refuses atomically, before any note custody is written, when the pending result would give it more physical references than either input does. That is the "refuse a moved reference" rule of the note contract. Producing a pending result for this edit instead would need note ids that differ from one destination, which the exact-identity contract does not allow. Part of #430. Tests, issue430_comparison_refuses_a_note_reference_that_moves_to_another_site (the refusal, atomic, and the same edit with the new note after the existing one still compares to both exact destinations) Harness, unchanged, the samples make no comparison --- crates/rdocx/src/comparison.rs | 46 ++++++++++++++++ crates/rdocx/tests/integration_test.rs | 73 ++++++++++++++++++++++++++ docs/hld/03-architecture.md | 17 +++--- docs/hld/10-bindings-spec.md | 5 +- 4 files changed, 134 insertions(+), 7 deletions(-) diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 76c303c67..8e6a9c687 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -5727,6 +5727,45 @@ fn note_fragment_envelope(xml: &str, bindings: &NamespaceBindings, note: bool) - String::from_utf8(writer.into_inner()).map_err(utf8_error) } +/// A footnote that both inputs reference must not reach the pending result +/// with more physical references than either input gives it. That happens +/// when its reference moves to another site, for example a new note inserted +/// before it takes its id in the edited input: the deleted original reference +/// and the inserted edited one then name one owner, a shared reference that +/// Word for Mac 16.115 cannot open, and the owner's text change pairs two +/// different notes. Refuse before any note custody is written. +fn refuse_shared_pending_references( + candidate: &Document, + left_refs: &[FootnoteReferenceSite], + right_refs: &[FootnoteReferenceSite], + left_normal: &BTreeMap, + right_normal: &BTreeMap, +) -> Result<()> { + let count = |sites: &[FootnoteReferenceSite], id: i32| { + sites.iter().filter(|site| site.id == id).count() + }; + let common = left_normal + .keys() + .filter(|id| right_normal.contains_key(id)) + .filter(|&&id| count(left_refs, id) > 0 && count(right_refs, id) > 0) + .copied() + .collect::>(); + if common.is_empty() { + return Ok(()); + } + let pending = footnote_reference_sites(candidate)?; + for id in common { + let most = count(left_refs, id).max(count(right_refs, id)); + let actual = count(&pending, id); + if actual > most { + return Err(Error::Other(format!( + "comparison would give footnote {id} {actual} physical references where each input has at most {most}: its reference moved to another site" + ))); + } + } + Ok(()) +} + fn compare_footnote_parts( original: &Document, edited: &Document, @@ -5766,6 +5805,13 @@ fn compare_footnote_parts( .unwrap_or_else(|| empty.clone()); let left_refs = footnote_reference_sites(original)?; let right_refs = footnote_reference_sites(edited)?; + refuse_shared_pending_references( + candidate, + &left_refs, + &right_refs, + &left_normal, + &right_normal, + )?; let added = right .as_ref() .map(|part| { diff --git a/crates/rdocx/tests/integration_test.rs b/crates/rdocx/tests/integration_test.rs index 5d7317d3f..afdab7a78 100644 --- a/crates/rdocx/tests/integration_test.rs +++ b/crates/rdocx/tests/integration_test.rs @@ -39613,6 +39613,79 @@ fn issue430_body_pair_in_any_other_revision_position_still_refuses() { } } +#[test] +fn issue430_comparison_refuses_a_note_reference_that_moves_to_another_site() { + // Review A's "a new note before an existing one". The edited input adds a + // note to the first paragraph, which takes id 2, and the existing note + // moves to id 3. Pairing by id would leave the deleted original reference + // and the inserted edited reference both naming note 2, a shared pending + // reference that Word for Mac 16.115 cannot open, with note 2's text + // change pairing two different notes. The comparison refuses atomically. + let note = |id: i32, text: &str| { + format!( + r#" {text}"# + ) + }; + let mut original = issue430_fixture( + &format!( + "{}{}", + issue430_p("The buyer took delivery.", None), + issue430_p("Payment was due.", Some(2)) + ), + Some(¬e(2, "Contract, clause 7.")), + ); + let edited = issue430_fixture( + &format!( + "{}{}", + issue430_p("The buyer took delivery.", Some(2)), + issue430_p("Payment was due.", Some(3)) + ), + Some(&format!( + "{}{}", + note(2, "Delivery note, p.1."), + note(3, "Contract, clause 7.") + )), + ); + let before = original.to_bytes().unwrap(); + let error = original + .compare(&edited, "A", ISSUE430_DATE) + .unwrap_err() + .to_string(); + assert!( + error.contains("footnote 2") && error.contains("moved to another site"), + "{error}" + ); + assert_eq!(original.to_bytes().unwrap(), before); + // The same edit with the new note after the existing one keeps the ids + // apart and still compares, both destinations exact. + let mut original = issue430_fixture( + &format!( + "{}{}", + issue430_p("Payment was due.", Some(2)), + issue430_p("The buyer took delivery.", None) + ), + Some(¬e(2, "Contract, clause 7.")), + ); + let edited = issue430_fixture( + &format!( + "{}{}", + issue430_p("Payment was due.", Some(2)), + issue430_p("The buyer took delivery.", Some(3)) + ), + Some(&format!( + "{}{}", + note(2, "Contract, clause 7."), + note(3, "Delivery note, p.1.") + )), + ); + original.compare(&edited, "A", ISSUE430_DATE).unwrap(); + let mut rejected = issue430_roundtrip(&mut original); + rejected.reject_all().unwrap(); + issue430_assert_settled(&mut rejected, &[2], true); + original.accept_all().unwrap(); + issue430_assert_settled(&mut original, &[2, 3], true); +} + #[test] fn issue430_body_pair_lifted_out_of_a_rejected_insertion_keeps_its_vote() { // Hand-built, not a Word save: it combines two observed Word shapes so that diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 7944285bf..63ff8a195 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1595,12 +1595,17 @@ with differing story shells are rejected unless their story category is ignored or the change is a supported normal-footnote topology change. Footnote comparison binds physical reference occurrences to their actual note ids. It aligns the body owners and run boundaries, preserves repeated references -without synthesizing another site, and preserves original unused definitions. -A new unreferenced definition is refused. Omitted type and explicit `normal` -identify normal notes at every signed id. The three explicit separator types -remain special. Empty and unknown types keep their legacy read projection, but -their owner bytes and reference identity must remain unchanged. Classification -uses each attribute's effective Word namespace, including local prefix shadows. +without synthesizing another site, and preserves original unused definitions. A +footnote that both inputs reference refuses atomically when its pending result +would hold more physical references than either input gives it, which happens +when its reference moves to another site, for example when a new note inserted +before it takes its id. Such a pending result would name one owner from a +deleted and an inserted reference. A new unreferenced definition is refused. +Omitted type and explicit `normal` identify normal notes at every signed id. The +three explicit separator types remain special. Empty and unknown types keep +their legacy read projection, but their owner bytes and reference identity must +remain unchanged. Classification uses each attribute's effective Word namespace, +including local prefix shadows. Added and removed definitions use paired hidden standard bookmarks in the body and first note paragraph. Names carry a persistent token and the emitting diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index a3f1f2923..dafeb40cd 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3065,7 +3065,10 @@ removal of a comparison-owned footnotes part also retires its settings references while preserving other note policy. Completed markers retire before an affected comparison edits their owner or part or adds custody. Ignored footnote stories retain original parts and refuse body changes that would leave -a missing note target. Endnote text comparison remains supported, while new +a missing note target. A comparison whose pending result would give a +referenced footnote more physical references than either input, because its +reference moved to another site, refuses atomically. Endnote text comparison +remains supported, while new endnote topology remains refused. These operations use existing held-handle invalidation and leave all live state unchanged on refusal. From 9fa771e330a2fe32d375c1d1586ba11a23710a72 Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 20:57:40 +0100 Subject: [PATCH 10/11] fix(comparison): resolve a wholly tracked note whose custody pair Word dropped A comparison that Word for Mac 16.115 saved before the note pair moved after the reference mark has lost its note pair for good: the RC3 packets of F-X287 are such files. Q-A430-29 forbids recovering the owner from the remaining body pair, so the note resolved as ordinary revisions. Rejecting an added note, or accepting a removed one, then had to remove the note's only paragraph mark and refused with "cannot remove the final paragraph mark". With another author pending, resolving the first author could also retire every custody pair while the second author's revisions stayed pending, because only marked units counted as pending. A tracked-note unit is a normal owner that no pair binds and whose own bytes prove that the whole definition is tracked as one insertion or one deletion: every paragraph carries a paragraph-mark revision of that kind, every other paragraph child is a wrapper of that kind or a zero-width range marker, and its one reference, bound by footnote id, is wrapped the same way. The proof reads no marker and no adjacent element, so an unmatched body pair stays unassociated. An unmatched body pair inside its reference's insertion is admitted only when that reference's note is a tracked note, and only keeps its place there. A selection of all its elements resolves it as one: the owner goes before rendering when the resolution removes its content. A partial selection keeps the ordinary element rules. A whole selection of an unreferenced tracked note removes it. An owner with two or more references keeps the shared-reference rules (Q-A430-28). A tracked note has no token or bits and does not vote on part presence, but it is pending for the open lifetime, so pairs stay while it is pending and retire at the last settlement. When a tracked note settles while a note owner outside every unit still holds a revision (a note with a hyperlink, say), the pairs stay too, as on v0.17.0. A comparison on top keeps an earlier author's unmatched body pair instead of retiring it at entry. The proof uses the note tree and the reference inventory that validate_footnote_custody already reads. Each reference site now carries its wrapper's revision, which also drops the per-site reparse of the reference story in the marked-unit check. Settlement reads the reference inventory only when it removes an owner, and does not read the note part again when it removes nothing and either a unit is still pending or no marked unit settles. Retirement returns at once when no unit carries a token, and projection returns before reading markers when no marked unit is retained or projected. Reverting this commit brings back, for files whose note pair Word already dropped and for hand-built wholly tracked notes: the refusals when rejecting a tracked note in a mixed save (review scenarios L1.2 and L1.4) or without any comparison (C2), and when removing an unreferenced tracked note (C3), and the first-author marker loss on the mixed shape with one pair kept and one lost. Its archive row must then be re-recorded. Part of #430 (F-X287). This needs the maintainer's decision D1. Tests, issue430_word_saved_lost_note_pair_resolves_as_a_tracked_note on four Word-saved shapes (added note, added note with text and a new paragraph, merged body pair, removed note) through every choice and an unrelated comparison, issue430_word_saved_mixed_authors_resolve_in_both_orders_and_choices for both author orders, both choices and reopens, with both note pairs lost and with one kept, issue430_word_saved_mixed_note_outside_the_grammar_keeps_both_pairs (from review B: a mixed note with a hyperlink keeps both pairs, either author first, either choice), issue430_comparison_over_a_word_saved_tracked_note_keeps_both_lifetimes (a comparison that adds custody over a pending tracked note), issue430_word_saved_created_part_with_a_lost_note_pair_settles_to_its_destination (the discriminator: a part created with two notes rejected in either order ends absent, and without any pair a separator-only part stays), issue430_tracked_note_needs_its_whole_owner_and_its_only_reference_tracked_one_way (four shapes that keep the old refusal atomically, and both partial selections), test_issue430_word_saved_lost_note_pairs_resolve_in_both_author_orders in test_core.py Harness, unchanged, the samples make no comparison --- crates/rdocx-py/tests/test_core.py | 54 +++ crates/rdocx/src/comparison.rs | 380 +++++++++++++++----- crates/rdocx/tests/integration_test.rs | 472 +++++++++++++++++++++++++ docs/hld/03-architecture.md | 18 +- docs/hld/10-bindings-spec.md | 9 +- 5 files changed, 851 insertions(+), 82 deletions(-) diff --git a/crates/rdocx-py/tests/test_core.py b/crates/rdocx-py/tests/test_core.py index 682163844..f64729b82 100644 --- a/crates/rdocx-py/tests/test_core.py +++ b/crates/rdocx-py/tests/test_core.py @@ -17028,6 +17028,60 @@ def test_issue430_word_saved_merged_body_pair_and_lost_note_pair_settle(): assert _issue430_markers(document) == [] +def test_issue430_word_saved_lost_note_pairs_resolve_in_both_author_orders(): + import rdocx + + # Author A added a footnote with a body change, author B compared on top + # of it and added another, and Word saved the result, dropping both note + # pairs. Each note is still wholly tracked with its one reference. + body = ( + 'The buyer took delivery on 12 June.' + f'Payment was due in thirty days' + f'The seller wrote twice to ask for payment' + '.' + f'' + 'The parties met in ' + 'September' + 'October' + '.' + '' + ) + notes = ( + f'{ISSUE430_DELIVERY}' + f'' + ' Letter of 1 July, p.2.' + '' + '' + ' Minutes of the meeting, p.4.' + ) + pending = _issue430_word_saved(body, notes) + pairs = ["_rdocxCmpNoteF18P11B", "_rdocxCmpNoteF8P11B"] + for first, second in (("A", "B"), ("B", "A")): + for accept_first in (False, True): + for accept_second in (False, True): + document = rdocx.Document.from_bytes(pending) + for author, accept in ((first, accept_first), (second, accept_second)): + if accept: + document.accept_revisions_by_author(author) + else: + document.reject_revisions_by_author(author) + document = rdocx.Document.from_bytes(document.to_bytes()) + if author == first: + assert _issue430_markers(document) == pairs + assert {revision.author for revision in document.revisions} == {second} + keep_a = accept_first if first == "A" else accept_second + keep_b = accept_first if first == "B" else accept_second + expected = [1] + [2] * keep_a + [3] * keep_b + assert _issue430_note_ids(document) == expected + texts = [paragraph.text for paragraph in document.paragraphs] + assert texts[1] == ("The seller wrote twice to ask for payment." if keep_a + else "Payment was due in thirty days.") + assert texts[-1] == ("The parties met in October." if keep_b + else "The parties met in September.") + assert document.revisions == () + assert _issue430_markers(document) == [] + + @pytest.mark.parametrize("family", ("footnote", "endnote")) @pytest.mark.parametrize("text", ("", "Source note", " text")) def test_issue432_note_defaults_and_space(family, text): diff --git a/crates/rdocx/src/comparison.rs b/crates/rdocx/src/comparison.rs index 8e6a9c687..62aa9c326 100644 --- a/crates/rdocx/src/comparison.rs +++ b/crates/rdocx/src/comparison.rs @@ -4194,6 +4194,23 @@ struct FootnotePart { impl FootnotePart { fn of(document: &Document) -> Result> { + let Some(name) = Self::name_of(document)? else { + return Ok(None); + }; + let xml = std::str::from_utf8( + document + .package + .get_part(&name) + .ok_or_else(|| Error::Other(format!("missing footnotes part {name}")))?, + ) + .map_err(utf8_error)? + .to_owned(); + Self::parse(name, xml).map(Some) + } + + /// The footnotes part name, from the one internal relationship and its + /// content type, without reading the part. + fn name_of(document: &Document) -> Result> { let relationships = document.package.get_part_rels(&document.doc_part_name); let links = relationships .into_iter() @@ -4214,15 +4231,10 @@ impl FootnotePart { "footnotes content type is invalid in {name}" ))); } - let xml = std::str::from_utf8( - document - .package - .get_part(&name) - .ok_or_else(|| Error::Other(format!("missing footnotes part {name}")))?, - ) - .map_err(utf8_error)? - .to_owned(); - Self::parse(name, xml).map(Some) + if !document.package.contains_part(&name) { + return Err(Error::Other(format!("missing footnotes part {name}"))); + } + Ok(Some(name)) } fn parse(name: String, xml: String) -> Result { @@ -4354,6 +4366,8 @@ struct FootnoteReferenceSite { run: Range, paragraph: Range, revision: Option>, + /// The metadata of that nearest revision wrapper, read with the site. + metadata: Option, } fn footnote_reference_sites(document: &Document) -> Result> { @@ -4386,10 +4400,12 @@ fn footnote_reference_sites(document: &Document) -> Result Result, original: bool, edited: bool, owner: Option, @@ -4928,7 +4947,7 @@ pub(crate) fn validate_footnote_custody( .iter() .filter(|marker| marker.family == 'B') .map(|marker| FootnoteCustody { - token: marker.token, + token: Some(marker.token), original: marker.original, edited: marker.edited, owner: None, @@ -4946,6 +4965,7 @@ pub(crate) fn validate_footnote_custody( let mut units = Vec::new(); let mut used_notes = HashSet::new(); let mut owned_definitions = HashSet::new(); + let mut wrapped_unmatched = Vec::new(); for body in markers.iter().filter(|marker| marker.family == 'B') { let notes = markers .iter() @@ -4959,11 +4979,9 @@ pub(crate) fn validate_footnote_custody( let note = notes.first().copied(); // The next-sibling proof inside a revision holds only with the note // pair, which binds the owner. An unmatched pair stays where Word left - // it only at the direct position. + // it only at the direct position, or before a tracked note's reference. if note.is_none() && body.wrapped { - return Err(Error::Other( - "body custody pair is inside a revision".into(), - )); + wrapped_unmatched.push(body.reference); } if let Some(note) = note { if note.owner.is_none() { @@ -5025,21 +5043,7 @@ pub(crate) fn validate_footnote_custody( } } for site in sites.iter().filter(|site| site.id == id) { - let bytes = document - .package - .get_part(&site.part) - .expect("reference part"); - let tree = crate::revision::XmlTree::parse(bytes)?; - let metadata = site - .revision - .as_ref() - .and_then(|range| { - tree.elements - .iter() - .find(|node| node.start == range.start && node.end == range.end) - }) - .and_then(|node| node.revision.clone()); - if let Some(metadata) = metadata { + if let Some(metadata) = site.metadata.clone() { let add = match metadata.kind { crate::revision::RevisionKind::Insertion => true, crate::revision::RevisionKind::Deletion => false, @@ -5074,7 +5078,7 @@ pub(crate) fn validate_footnote_custody( ))); } units.push(FootnoteCustody { - token: body.token, + token: Some(body.token), original: body.original, edited: body.edited, owner, @@ -5093,9 +5097,166 @@ pub(crate) fn validate_footnote_custody( "note custody marker is missing its body counterpart".into(), )); } + let tracked = tracked_note_units(&part, ¬e_tree, &sites, &owned_definitions, scope); + // An unmatched pair inside its reference's insertion stays only when that + // reference's note is a tracked note, proved from the note's own bytes. + // The pair is still not associated with it: it only keeps its place, and + // the insertion resolves with the tracked note. + if wrapped_unmatched.iter().any(|reference| { + !reference.is_some_and(|id| tracked.iter().any(|unit| unit.owner == Some(id))) + }) { + return Err(Error::Other( + "body custody pair is inside a revision".into(), + )); + } + units.extend(tracked); Ok(units) } +/// Tracked-note units. Word can drop a note pair, which leaves its body pair +/// without an owner (Q-A430-29). A normal owner that no marker binds is still +/// a unit when its own bytes prove that the whole definition and its only +/// reference are tracked as one insertion or one deletion. The proof reads the +/// owner and binds the reference by its footnote id. It never reads a marker +/// or an adjacent element, so an unmatched body pair stays unassociated. +fn tracked_note_units( + part: &FootnotePart, + note_tree: &crate::revision::XmlTree<'_>, + sites: &[FootnoteReferenceSite], + owned: &HashSet>, + scope: &crate::revision::RevisionScope<'_>, +) -> Vec { + let mut references = BTreeMap::>::new(); + for site in sites { + references.entry(site.id).or_default().push(site); + } + let mut units = Vec::new(); + for (&id, owner) in &part.normal() { + if owned.contains(&Some(id)) { + continue; + } + let sites = references.get(&id).map(Vec::as_slice).unwrap_or_default(); + // Two or more references belong to the shared-reference rules. + if sites.len() > 1 { + continue; + } + let Some((kind, mut revisions)) = tracked_note_owner(note_tree, owner) else { + continue; + }; + if let Some(site) = sites.first() { + match &site.metadata { + Some(metadata) if metadata.kind == kind => revisions.push(metadata.clone()), + _ => continue, + } + } + let selected = revisions + .iter() + .filter(|metadata| scope.matches(metadata)) + .count(); + units.push(FootnoteCustody { + token: None, + original: true, + edited: true, + owner: Some(id), + addition: Some(kind == crate::revision::RevisionKind::Insertion), + // Only a whole selection resolves the unit as one. A partial one + // keeps the ordinary element rules, and the final-paragraph rule. + selected: selected == revisions.len(), + revisions, + wrapped_body: None, + }); + } + units +} + +/// The revision kind and every revision of a note owner whose paragraphs all +/// carry a paragraph-mark revision of one kind, and whose other paragraph +/// children are all wrappers of that kind or zero-width range markers. +fn tracked_note_owner( + tree: &crate::revision::XmlTree<'_>, + owner: &FootnoteOwner, +) -> Option<( + crate::revision::RevisionKind, + Vec, +)> { + use crate::revision::RevisionKind; + let first = tree + .elements + .partition_point(|node| node.start < owner.span.start); + let node = tree.elements.get(first)?; + if node.start != owner.span.start || !node.word || node.local != "footnote" { + return None; + } + let mut kind = None; + let mut agrees = |metadata: &crate::revision::RevisionMetadata| { + matches!( + metadata.kind, + RevisionKind::Insertion | RevisionKind::Deletion + ) && *kind.get_or_insert(metadata.kind) == metadata.kind + }; + if node.children.is_empty() { + return None; + } + for ¶graph in &node.children { + let p = &tree.elements[paragraph]; + if !p.word || p.local != "p" { + return None; + } + let mut mark = false; + for &child in &p.children { + let element = &tree.elements[child]; + if element.word && element.local == "pPr" { + for &properties in &element.children { + let run_properties = &tree.elements[properties]; + if !run_properties.word || run_properties.local != "rPr" { + continue; + } + for &marker in &run_properties.children { + if let Some(metadata) = &tree.elements[marker].revision { + if !agrees(metadata) { + return None; + } + mark = true; + } + } + } + continue; + } + match &element.revision { + Some(metadata) + if element.word && matches!(element.local.as_str(), "ins" | "del") => + { + if !agrees(metadata) { + return None; + } + } + None if element.word + && matches!( + element.local.as_str(), + "bookmarkStart" | "bookmarkEnd" | "proofErr" + ) => {} + _ => return None, + } + } + if !mark { + return None; + } + } + let mut revisions = Vec::new(); + for element in tree.elements[first..] + .iter() + .take_while(|element| element.start < owner.span.end) + { + if let Some(metadata) = &element.revision { + if !agrees(metadata) { + return None; + } + revisions.push(metadata.clone()); + } + } + Some((kind?, revisions)) +} + /// Selected definition retirement precedes the ordinary story renderer, whose /// final-paragraph rule applies to retained owners, not a removed note owner. pub(crate) fn remove_selected_footnote_definitions( @@ -5171,31 +5332,54 @@ pub(crate) fn settle_footnote_custody( // reference, and leaves no note revision pending, still settles the // part, and settlement retires its remaining custody pairs. A pair in // an untouched part stays. - if note_part_resolved && !units.is_empty() && !note_revisions_pending(document)? { + if note_part_resolved && !units.is_empty() && !note_revisions_pending(document, true)? { retire_note_markers(document, units, publication)?; } return Ok(()); } + let removed = units + .iter() + .filter(|unit| unit.selected && unit.addition.is_some_and(|addition| addition != accept)) + .filter_map(|unit| unit.owner) + .collect::>(); + let unit_pending = units + .iter() + .any(|unit| !unit.revisions.is_empty() && !unit.selected); + // Nothing to remove, and either a unit still pending or no marked unit + // whose pairs or bits settlement would act on: nothing settles here, so + // the note part is not read again. A publication trace still checks its + // source. + if removed.is_empty() + && publication.is_none() + && (unit_pending || !units.iter().any(|unit| unit.token.is_some())) + { + return if FootnotePart::name_of(document)?.is_some() { + Ok(()) + } else { + Err(Error::Other( + "footnotes part disappeared before custody settlement".into(), + )) + }; + } let Some(mut part) = FootnotePart::of(document)? else { return Err(Error::Other( "footnotes part disappeared before custody settlement".into(), )); }; - let refs = footnote_reference_sites(document)?; + let refs = if removed.is_empty() { + Vec::new() + } else { + footnote_reference_sites(document)? + }; let mut removals = Vec::new(); - for unit in units - .iter() - .filter(|unit| unit.selected && unit.addition.is_some_and(|addition| addition != accept)) - { - if let Some(id) = unit.owner { - if refs.iter().any(|site| site.id == id) { - return Err(Error::Other( - "resolved note deletion retained a live reference".into(), - )); - } - if let Some(owner) = part.normal().get(&id) { - removals.push(owner.span.clone()); - } + for id in removed { + if refs.iter().any(|site| site.id == id) { + return Err(Error::Other( + "resolved note deletion retained a live reference".into(), + )); + } + if let Some(owner) = part.normal().get(&id) { + removals.push(owner.span.clone()); } } removals.sort_by_key(|range| range.start); @@ -5203,34 +5387,45 @@ pub(crate) fn settle_footnote_custody( if let Some(trace) = publication.as_deref_mut() { trace.remove_ranges(&part.name, part.xml.as_bytes(), &removals)?; } - for range in removals.into_iter().rev() { - part.xml.replace_range(range, ""); + if !removals.is_empty() || publication.is_some() { + for range in removals.into_iter().rev() { + part.xml.replace_range(range, ""); + } + crate::document::set_story_source_xml(document, &part.name, part.xml.into_bytes())?; + part = FootnotePart::of(document)?.expect("installed notes"); + } + // A tracked note that settles here leaves the pairs in place while a note + // owner outside every recognized unit still holds a revision, the rule of + // a settlement that recognizes no unit. Only marked units carry pairs. + let pending = unit_pending + || (units + .iter() + .any(|unit| unit.token.is_none() && unit.selected) + && units.iter().any(|unit| unit.token.is_some()) + && note_revisions_pending(document, false)?); + if pending { + return Ok(()); } - crate::document::set_story_source_xml(document, &part.name, part.xml.into_bytes())?; - let part = FootnotePart::of(document)?.expect("installed notes"); - let pending = units - .iter() - .any(|unit| !unit.revisions.is_empty() && !unit.selected); - let unowned = part.unowned_record_count()?; let open = units.iter().any(|unit| !unit.revisions.is_empty()); + let mut marked = units.iter().filter(|unit| unit.token.is_some()); let absent = open && part.normal().is_empty() - && unowned == 0 - && (units.iter().any(|unit| !unit.original) || units.iter().any(|unit| !unit.edited)); - if !pending { - retire_note_markers(document, units, publication)?; - if absent { - remove_footnotes_part(document, &part.name)?; - } + && marked.any(|unit| !unit.original || !unit.edited) + && part.unowned_record_count()? == 0; + retire_note_markers(document, units, publication)?; + if absent { + remove_footnotes_part(document, &part.name)?; } Ok(()) } -/// Whether a normal note owner or a note reference still carries a revision. -fn note_revisions_pending(document: &Document) -> Result { - if footnote_reference_sites(document)? - .iter() - .any(|site| site.revision.is_some()) +/// Whether a normal note owner, or with `references` a note reference, still +/// carries a revision. +fn note_revisions_pending(document: &Document, references: bool) -> Result { + if references + && footnote_reference_sites(document)? + .iter() + .any(|site| site.revision.is_some()) { return Ok(true); } @@ -5253,7 +5448,13 @@ fn retire_note_markers( units: &[FootnoteCustody], mut publication: Option<&mut crate::revision::NotePublication>, ) -> Result<()> { - let tokens = units.iter().map(|unit| unit.token).collect::>(); + let tokens = units + .iter() + .filter_map(|unit| unit.token) + .collect::>(); + if tokens.is_empty() { + return Ok(()); + } let mut by_part = BTreeMap::>>::new(); for marker in note_markers(document)? .into_iter() @@ -5516,8 +5717,20 @@ fn rewrite_note_marker_pair( /// Input collisions change only the positively associated bookmark identities. /// Numeric footnote and current revision identities remain untouched. fn reconcile_footnote_custody_inputs(original: &Document, edited: &mut Document) -> Result<()> { - let left = validate_footnote_custody(original, &crate::revision::RevisionScope::All)?; - let right = validate_footnote_custody(edited, &crate::revision::RevisionScope::All)?; + let marked = |units: Vec| { + units + .into_iter() + .filter(|unit| unit.token.is_some()) + .collect::>() + }; + let left = marked(validate_footnote_custody( + original, + &crate::revision::RevisionScope::All, + )?); + let right = marked(validate_footnote_custody( + edited, + &crate::revision::RevisionScope::All, + )?); let left_markers = note_markers(original)?; if left_markers.is_empty() { return Ok(()); @@ -5557,7 +5770,7 @@ fn reconcile_footnote_custody_inputs(original: &Document, edited: &mut Document) } else { let right_marker = note_markers(edited)? .into_iter() - .find(|marker| marker.token == unit.token && marker.family == 'B'); + .find(|marker| Some(marker.token) == unit.token && marker.family == 'B'); left.iter().find(|other| { other.owner.is_none() && other.token == unit.token @@ -5565,7 +5778,7 @@ fn reconcile_footnote_custody_inputs(original: &Document, edited: &mut Document) && other.edited == unit.edited && right_marker.as_ref().is_some_and(|right| { left_markers.iter().any(|left| { - left.token == other.token + Some(left.token) == other.token && left.family == 'B' && left.part == right.part && left.pair_id == right.pair_id @@ -5592,18 +5805,18 @@ fn reconcile_footnote_custody_inputs(original: &Document, edited: &mut Document) for family in ['B', 'N'] { let left = left_markers .iter() - .find(|marker| marker.token == other.token && marker.family == family); + .find(|marker| Some(marker.token) == other.token && marker.family == family); let right = note_markers(edited)? .into_iter() - .find(|marker| marker.token == unit.token && marker.family == family); + .find(|marker| Some(marker.token) == unit.token && marker.family == family); if let (Some(left), Some(right)) = (left, right) { - rewrite_note_marker_pair(edited, &right, other.token, left.pair_id)?; + rewrite_note_marker_pair(edited, &right, left.token, left.pair_id)?; } } } else { let markers = note_markers(edited)? .into_iter() - .filter(|marker| marker.token == unit.token) + .filter(|marker| Some(marker.token) == unit.token) .collect::>(); let collision = left.iter().any(|other| other.token == unit.token) || markers.iter().any(|right| { @@ -6590,8 +6803,17 @@ fn project_resolved_note_tombstones( let retained = units .iter() .filter(|unit| !unit.selected) - .map(|unit| unit.token) + .filter_map(|unit| unit.token) .collect::>(); + // Only marked units carry pairs to project. A pending tracked note alone + // has none. + if retained.is_empty() + && !units + .iter() + .any(|unit| unit.selected && unit.token.is_some()) + { + return Ok(()); + } let prior = note_markers(before)? .into_iter() .filter(|marker| retained.contains(&marker.token)) @@ -6623,7 +6845,7 @@ fn project_resolved_note_tombstones( } let projected = units .iter() - .filter(|unit| unit.selected) + .filter(|unit| unit.selected && unit.token.is_some()) .cloned() .collect::>(); for unit in &projected { @@ -25300,7 +25522,7 @@ mod tests { let units = super::validate_footnote_custody(&right, &crate::revision::RevisionScope::All).unwrap(); assert_eq!(units.len(), 1); - assert_ne!(units[0].token, 7); + assert_ne!(units[0].token, Some(7)); assert_eq!(units[0].owner, Some(6)); assert_eq!(right.footnotes(), before_notes); assert_eq!( @@ -25450,7 +25672,7 @@ mod tests { ) .unwrap(); assert_eq!(units.len(), 1); - assert!(note_ids.iter().all(|id| *id != units[0].token)); + assert!(note_ids.iter().all(|id| Some(*id) != units[0].token)); let inventory = original.story_revisions().unwrap(); assert!( inventory diff --git a/crates/rdocx/tests/integration_test.rs b/crates/rdocx/tests/integration_test.rs index afdab7a78..8e18636d3 100644 --- a/crates/rdocx/tests/integration_test.rs +++ b/crates/rdocx/tests/integration_test.rs @@ -39943,6 +39943,478 @@ fn issue430_word_saved_mixed_authors_keep_pairs_until_the_last_note_settles() { } } +#[test] +fn issue430_word_saved_lost_note_pair_resolves_as_a_tracked_note() { + // rdocx comparisons that Word saved, and in which Word dropped the note + // pair (placed before the reference mark, as v0.17.0 wrote it). Each note + // is still wholly tracked, with its one reference tracked the same way. + let buyer = "The buyer took delivery on 12 June."; + // A footnote added to an existing paragraph. + let notes = issue430_word_note_only_notes(); + let texts = [ + buyer, + "Payment was due in thirty days.", + "The parties met in September.", + ]; + issue430_word_save_destinations( + issue430_word_note_only_body(), + ¬es, + (&[1, 2], &texts), + (&[1], &texts), + ); + issue430_word_save_unrelated_comparison( + issue430_word_note_only_body(), + ¬es, + ("met in September", "met in October"), + &[1, 2], + &[1], + ); + // A footnote added with a body text change and a new paragraph. + let middle = r#"The buyer took delivery on 12 June.Payment was due in thirty daysThe seller wrote twice to ask for payment.Payment was due in sixty days.The parties met in September."#; + let middle_notes = format!( + r#"{}{} Letter of 1 July, p.2."#, + issue430_word_separators(), + issue430_word_delivery_note() + ); + issue430_word_save_destinations( + middle, + &middle_notes, + ( + &[1, 2], + &[ + buyer, + "The seller wrote twice to ask for payment.", + "Payment was due in sixty days.", + "The parties met in September.", + ], + ), + ( + &[1], + &[ + buyer, + "Payment was due in thirty days.", + "The parties met in September.", + ], + ), + ); + issue430_word_save_unrelated_comparison( + middle, + &middle_notes, + ("met in September", "met in October"), + &[1, 2], + &[1], + ); + // The issue's "a footnote added" result: Word also merged the body pair + // into the inserted paragraph's insertion. + let merged = format!( + r#"The seller wrote twice to ask for payment.{ISSUE430_WORD_PAIR}{ISSUE430_WORD_REFERENCE}"# + ); + let added = issue430_word_added_paragraph(&merged); + let added_notes = issue430_word_added_paragraph_notes().replace( + r#""#, + "", + ); + issue430_word_save_destinations( + &added, + &added_notes, + ( + &[1, 2], + &[ + buyer, + "The seller wrote twice to ask for payment.", + "Payment was due in thirty days.", + ], + ), + (&[1], &[buyer, "Payment was due in thirty days."]), + ); + issue430_word_save_unrelated_comparison( + &added, + &added_notes, + ("due in thirty days", "due in forty days"), + &[1, 2], + &[1], + ); + // A second footnote removed while the last paragraph changed: the deletion + // direction, where accepting removes the note. + let removed = r#"The buyer took delivery on 12 June.Payment was due in thirty days.The parties met in SeptemberOctober."#; + let removed_notes = format!( + r#"{}{} Contract, clause 7."#, + issue430_word_separators(), + issue430_word_delivery_note() + ); + issue430_word_save_destinations( + removed, + &removed_notes, + ( + &[1], + &[ + buyer, + "Payment was due in thirty days.", + "The parties met in October.", + ], + ), + ( + &[1, 2], + &[ + buyer, + "Payment was due in thirty days.", + "The parties met in September.", + ], + ), + ); +} + +fn issue430_word_mixed_choices(body: &str, notes: &str) { + let buyer = "The buyer took delivery on 12 June."; + let mut source = issue430_fixture(body, Some(notes)); + for (first, second) in [("A", "B"), ("B", "A")] { + for accept_first in [false, true] { + for accept_second in [false, true] { + let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + for (step, (author, accept)) in [(first, accept_first), (second, accept_second)] + .into_iter() + .enumerate() + { + let before = document.to_bytes().unwrap(); + let result = if accept { + document.accept_revisions_by_author(author) + } else { + document.reject_revisions_by_author(author) + }; + assert!( + result.is_ok(), + "{first}{accept_first}{second}{accept_second} {result:?}" + ); + assert_ne!(document.to_bytes().unwrap(), before); + document = issue430_roundtrip(&mut document); + if step == 0 { + // The other author is still pending, so both body + // pairs are retained tombstones or open custody. + let markers = issue430_markers(&mut document); + for pair in ["_rdocxCmpNoteF8P11B", "_rdocxCmpNoteF18P11B"] { + assert!(markers.contains(&pair.to_owned()), "{markers:?}"); + } + let revisions = document.story_revisions().unwrap(); + assert!(!revisions.is_empty()); + assert!(revisions.iter().all(|revision| revision.author() == second)); + } + } + let keep_a = if first == "A" { + accept_first + } else { + accept_second + }; + let keep_b = if first == "B" { + accept_first + } else { + accept_second + }; + let mut texts = vec![buyer]; + if keep_a { + texts.extend([ + "The seller wrote twice to ask for payment.", + "Payment was due in sixty days.", + ]); + } else { + texts.push("Payment was due in thirty days."); + } + texts.push(if keep_b { + "The parties met in October." + } else { + "The parties met in September." + }); + let ids = [(1, true), (2, keep_a), (3, keep_b)] + .into_iter() + .filter_map(|(id, keep)| keep.then_some(id)) + .collect::>(); + assert_eq!(issue430_texts(&document), texts); + issue430_assert_settled(&mut document, &ids, true); + } + } + } +} + +#[test] +fn issue430_word_saved_mixed_authors_resolve_in_both_orders_and_choices() { + // Author A's result (a footnote added with a body text change), then + // author B compared on top of it (a footnote and a text change in the + // last paragraph), then Word saved it and dropped both note pairs. + issue430_word_mixed_choices(issue430_word_mixed_body(), &issue430_word_mixed_notes()); + // The same result with A's note pair moved after its reference mark before + // the save (the placement of the first commit), then saved by Word 16.115: + // Word kept A's note pair and dropped B's. A is a marked unit and B a + // tracked note, so resolving A first must not retire B's body pair. + let keep_a_body = r#"The buyer took delivery on 12 June.Payment was due in thirty daysThe seller wrote twice to ask for payment.Payment was due in sixty days.The parties met in SeptemberOctober."#; + let keep_a_notes = format!( + r#"{}{} Letter of 1 July, p.2. Minutes of the meeting, p.4."#, + issue430_word_separators(), + issue430_word_delivery_note() + ); + issue430_word_mixed_choices(keep_a_body, &keep_a_notes); +} + +#[test] +fn issue430_word_saved_mixed_note_outside_the_grammar_keeps_both_pairs() { + // From review B. The mixed Word save with both note pairs lost, where one + // author's note also holds an internal hyperlink, so it is not a tracked + // note. Resolving the other author's tracked note, either way, keeps both + // body pairs while that note's revisions are pending, as v0.17.0 does. + let link = |author: &str, date: &str| { + format!( + r#"minutes"# + ) + }; + let both = [ + "_rdocxCmpNoteF18P11B".to_owned(), + "_rdocxCmpNoteF8P11B".to_owned(), + ]; + let b_linked = issue430_word_mixed_notes().replace( + " Minutes of the meeting, p.4.", + &format!( + " Minutes of the meeting, p.4.{}", + link("B", "2026-10-31T12:00:00Z") + ), + ); + let a_linked = issue430_word_mixed_notes().replace( + " Letter of 1 July, p.2.", + &format!( + " Letter of 1 July, p.2.{}", + link("A", "2026-10-30T12:00:00Z") + ), + ); + for (notes, first) in [(&b_linked, "A"), (&a_linked, "B")] { + assert_ne!(notes, &issue430_word_mixed_notes()); + for accept in [true, false] { + let mut document = issue430_fixture(issue430_word_mixed_body(), Some(notes)); + if accept { + document.accept_revisions_by_author(first).unwrap(); + } else { + document.reject_revisions_by_author(first).unwrap(); + } + let mut document = issue430_roundtrip(&mut document); + assert!(!document.story_revisions().unwrap().is_empty()); + assert_eq!( + issue430_markers(&mut document), + both, + "first {first} accept {accept}" + ); + } + } +} + +#[test] +fn issue430_comparison_over_a_word_saved_tracked_note_keeps_both_lifetimes() { + // Author B compares on top of A's Word-saved result whose note pair Word + // dropped (A's note is a pending tracked note), adding a referenced note to + // the last paragraph. The comparison keeps A's unmatched body pair and + // emits B's custody. Every order and choice reaches its destination and + // keeps every pair until the last note settles. + let mut original = issue430_fixture( + issue430_word_note_only_body(), + Some(&issue430_word_note_only_notes()), + ); + let package = issue430_package(&mut original); + let body = String::from_utf8(package.get_part("/word/document.xml").unwrap().to_vec()).unwrap(); + let notes = + String::from_utf8(package.get_part("/word/footnotes.xml").unwrap().to_vec()).unwrap(); + let edited = issue430_replace_parts( + &mut original, + Some(body.replace( + "The parties met in September.", + r#"The parties met in September."#, + )), + Some(notes.replace( + "", + r#" Minutes."#, + )), + ); + original.compare(&edited, "B", ISSUE430_DATE).unwrap(); + let mut pending = issue430_roundtrip(&mut original); + let markers = issue430_markers(&mut pending); + assert!( + markers.contains(&"_rdocxCmpNoteF4P11B".to_owned()), + "{markers:?}" + ); + assert_eq!(markers.iter().filter(|name| name.ends_with('B')).count(), 2); + for (first, second) in [("A", "B"), ("B", "A")] { + for accept_first in [false, true] { + for accept_second in [false, true] { + let mut document = issue430_roundtrip(&mut pending); + for (author, accept) in [(first, accept_first), (second, accept_second)] { + if accept { + document.accept_revisions_by_author(author).unwrap(); + } else { + document.reject_revisions_by_author(author).unwrap(); + } + document = issue430_roundtrip(&mut document); + if author == first { + let left = issue430_markers(&mut document); + assert!(left.contains(&"_rdocxCmpNoteF4P11B".to_owned()), "{left:?}"); + assert_eq!(left.iter().filter(|name| name.ends_with('B')).count(), 2); + } + } + let keep_a = if first == "A" { + accept_first + } else { + accept_second + }; + let keep_b = if first == "B" { + accept_first + } else { + accept_second + }; + let retained = [(1, true), (2, keep_a), (3, keep_b)] + .into_iter() + .filter_map(|(id, keep)| keep.then_some(id)) + .collect::>(); + issue430_assert_settled(&mut document, &retained, true); + } + } + } +} + +#[test] +fn issue430_word_saved_created_part_with_a_lost_note_pair_settles_to_its_destination() { + // One comparison created the footnotes part (bits 01) with two notes, the + // second re-authored Y, and Word saved it. Word kept the first note's pair + // and dropped the second's. Every path must end at its input's part + // presence: absent when both notes are rejected, whatever the order. + let body = r#"The buyer took delivery on 12 June.Payment was due in thirtysixty days.The parties met in September."#; + let notes = format!( + r#"{} Delivery note, p.1. Contract, clause 7."#, + issue430_word_separators() + ); + let mut source = issue430_fixture(body, Some(¬es)); + let pairs = ["_rdocxCmpNoteF15P01B", "_rdocxCmpNoteF7P01B"]; + for (steps, retained) in [ + (vec![(false, "A"), (false, "Y")], vec![]), + (vec![(false, "Y"), (false, "A")], vec![]), + (vec![(true, "A"), (false, "Y")], vec![1]), + (vec![(false, "A"), (true, "Y")], vec![2]), + (vec![(true, "Y"), (true, "A")], vec![1, 2]), + ] { + let mut document = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + for (step, (accept, author)) in steps.iter().enumerate() { + if *accept { + document.accept_revisions_by_author(author).unwrap(); + } else { + document.reject_revisions_by_author(author).unwrap(); + } + document = issue430_roundtrip(&mut document); + if step == 0 { + let markers = issue430_markers(&mut document); + for pair in pairs { + assert!(markers.contains(&pair.to_owned()), "{steps:?} {markers:?}"); + } + } + } + issue430_assert_settled(&mut document, &retained, !retained.is_empty()); + } + let mut rejected = Document::from_bytes(&source.to_bytes().unwrap()).unwrap(); + rejected.reject_all().unwrap(); + issue430_assert_settled(&mut rejected, &[], false); + // Without any custody pair, nothing records that the part was created: + // rejecting both tracked notes keeps the separator-only part, as Word does. + let mut plain_body = body.to_owned(); + let mut plain_notes = notes.clone(); + for (id, name) in [ + (0, "_rdocxCmpNoteF7P01B"), + (7, "_rdocxCmpNoteF15P01B"), + (3, "_rdocxCmpNoteF7P01N"), + ] { + let pair = format!( + r#""# + ); + plain_body = plain_body.replace(&pair, ""); + plain_notes = plain_notes.replace(&pair, ""); + } + let mut native = issue430_fixture(&plain_body, Some(&plain_notes)); + native.reject_all().unwrap(); + issue430_assert_settled(&mut native, &[], true); +} + +#[test] +fn issue430_tracked_note_needs_its_whole_owner_and_its_only_reference_tracked_one_way() { + let body = issue430_word_note_only_body(); + let notes = issue430_word_note_only_notes(); + let reference_ins = r#""#; + let note_end = ""; + assert_eq!(notes.matches(note_end).count(), 1); + let variants = [ + // an untracked run in the owner + ( + body.to_owned(), + notes.replace(note_end, "plain"), + ), + // the reference is not tracked + (body.replace(reference_ins, "").replace("", ""), notes.clone()), + // the content is deleted while the paragraph mark is inserted + ( + body.to_owned(), + notes + .replace( + r#""#, + r#""#, + ) + .replace(" Contract, clause 7.", " Contract, clause 7.") + .replace(r#" Contract"#, r#" Contract"#) + .replace(note_end, ""), + ), + // two tracked references to the note stay with the shared-reference rules + ( + body.replace( + "The parties met in September.", + r#"The parties met in September."#, + ), + notes.clone(), + ), + ]; + for (body, notes) in variants { + assert!(body != issue430_word_note_only_body() || notes != issue430_word_note_only_notes()); + let mut document = issue430_fixture(&body, Some(¬es)); + let before = document.to_bytes().unwrap(); + let error = document.reject_all().unwrap_err(); + assert!( + error.to_string().contains("final paragraph mark"), + "{error}" + ); + assert_eq!(document.to_bytes().unwrap(), before); + } + // A partial selection keeps the ordinary element rules. Rejecting only the + // reference leaves an unreferenced tracked note, which a later whole + // selection removes. Rejecting only the note's own elements still refuses. + let mut document = issue430_fixture(body, Some(¬es)); + assert_eq!(document.reject_revision_id(1).unwrap(), 1); + let mut document = issue430_roundtrip(&mut document); + assert_eq!( + document + .footnotes() + .iter() + .map(|(id, _)| *id) + .collect::>(), + [1, 2] + ); + assert_eq!(document.story_revisions().unwrap().len(), 2); + document.reject_all().unwrap(); + issue430_assert_settled(&mut document, &[1], true); + let referenced = body.replace( + reference_ins, + r#""#, + ); + let mut document = issue430_fixture(&referenced, Some(¬es)); + let before = document.to_bytes().unwrap(); + let error = document.reject_revisions_by_author("A").unwrap_err(); + assert!( + error.to_string().contains("final paragraph mark"), + "{error}" + ); + assert_eq!(document.to_bytes().unwrap(), before); + document.reject_revisions_by_author("Ref").unwrap(); + let mut document = issue430_roundtrip(&mut document); + document.reject_revisions_by_author("A").unwrap(); + issue430_assert_settled(&mut document, &[1], true); +} + #[test] fn issue432_note_mark_order_separators_and_space() { let mut doc = Document::new(); diff --git a/docs/hld/03-architecture.md b/docs/hld/03-architecture.md index 63ff8a195..f74e1e4cd 100644 --- a/docs/hld/03-architecture.md +++ b/docs/hld/03-architecture.md @@ -1632,6 +1632,22 @@ Within the positively admitted custody grammar, resolved units retain zero-width A valid body pair without a note pair has no surviving note-owner identity. It stays a tombstone in an open part or completed imported metadata in a settled part. A following reference or revision wrapper cannot identify its former owner. +A normal owner that no pair binds is still a unit, a tracked note, when its own +bytes prove that the whole definition is tracked as one insertion or one +deletion: every paragraph carries a paragraph-mark revision of that kind, every +other paragraph child is a wrapper of that kind or a zero-width range marker, +and its reference, when it has one, bound by footnote id, is wrapped the same +way. A tracked note left without a reference is removed by a whole selection of +its own elements. The proof reads no marker, so an unmatched body pair stays +unassociated. An unmatched body pair inside its reference's insertion is +admitted only when that reference's note is a tracked note, and only keeps its +place there. A tracked note has no token or bits and does not vote on part +presence, but it is pending for the open lifetime, so pairs stay while it is +pending. When a tracked note settles while a note owner outside every unit still +holds a revision, the pairs also stay. Selecting all its elements resolves it as +one and removes the owner when the resolution removes its content. A partial +selection keeps the ordinary element rules. An owner with two or more references +keeps the shared-reference rules. Collision reconciliation preserves a completed body pair when its token, bits, pair id, part and exact source paragraph boundary agree between inputs. This does not reconstruct a missing note owner. An unrelated paragraph edit keeps @@ -1659,7 +1675,7 @@ for example after Word dropped a note pair, and retires the pairs left in it. Ig retain original bytes and cannot supply a dangling new body reference. Endnote topology retains its existing refusal while ordinary text edits remain supported. -Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair into its own reference's merged insertion, which is admitted while the note pair remains, and Word for Mac 16.115 can drop the note counterpart. Without the note pair, such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically when the body pair sits inside the merged insertion, and rejecting an added note or accepting a removed one refuses atomically otherwise. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved. +Word-save interoperability is qualified on reconstructed Word for Mac 16.115 saves, not on the retained RC3 packets. Word 16.115 can drop a note pair placed before the reference mark of a note that is not the first of its part, merge the body pair into its reference's insertion, and renumber notes, bookmarks and revisions. The note pair follows the reference mark, a body pair inside its own reference's insertion is admitted with its note pair, or without it before a tracked note's reference, and a note whose pair Word dropped resolves as a tracked note. A note outside the tracked-note grammar, for example one that holds a hyperlink, keeps the earlier limits once Word drops its pair: rejecting it refuses atomically, and when Word kept the other author's pair, resolving that author first retires the outside note's body pair while its revisions remain pending, as on v0.17.0. A footnote inserted in Word 16.115 with Track Changes on is not a tracked note, because Word tracks its reference and content but not its paragraph mark, so rejecting it keeps an empty unreferenced footnote where Word's own Reject All removes the note, as on v0.17.0. A completed body pair that an earlier Word resolution left in a part still votes when a later tracked note settles that part, so such a stale creation bit can remove a part that held only special records. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Native qualification of these families on the RC3 packets remains with F-X287. Issue430 remains open and Q-A430-28 remains independently unproved. Inputs may hold existing modeled revisions, such as the redline of an earlier comparison. A story owner that holds one, a paragraph, table, or diff --git a/docs/hld/10-bindings-spec.md b/docs/hld/10-bindings-spec.md index dafeb40cd..5ea9edabb 100644 --- a/docs/hld/10-bindings-spec.md +++ b/docs/hld/10-bindings-spec.md @@ -3052,7 +3052,12 @@ resolves a note reference, and leaves no note revision pending, settles it even when no unit is recognized, and retires its remaining pairs. An unmatched body pair has no surviving note-owner identity and cannot group or select an adjacent reference, even inside a revision wrapper. Its ordinary revisions keep their -ordinary selectors. Exact note-present owner, reference, token, bits and pair +ordinary selectors. A normal note whose whole definition and only reference, if +any, are tracked one way, proved from its own bytes and the reference's footnote id, +resolves as one tracked note under a selection of all its elements, and keeps +the ordinary selectors otherwise. An unmatched body pair inside a revision is +admitted only before such a note's reference. Exact note-present owner, +reference, token, bits and pair checks remain mandatory, and a note pair without its body pair refuses. Missing note-pair corruption cannot always be distinguished from identical valid removed-note histories. Opaque revision-shaped payload does not add listing or @@ -3072,7 +3077,7 @@ remains supported, while new endnote topology remains refused. These operations use existing held-handle invalidation and leave all live state unchanged on refusal. -Word-save interoperability is qualified only for actual admitted marker layouts. A note-plus-body-text Word save can move the body custody pair into its own reference's merged insertion, which is admitted while the note pair remains, and Word for Mac 16.115 can drop the note counterpart. Without the note pair, such a package can open, list and no-op serialize while Accept All, Reject All and an unrelated comparison refuse atomically when the body pair sits inside the merged insertion, and rejecting an added note or accepting a removed one refuses atomically otherwise. Some mixed-author Word saves refuse rejection of a remaining author's revisions. On a fully pending mixed input, an earlier successful selective action can retire all custody markers while another author's revisions remain pending. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Successful return or reopen therefore does not prove the unresolved-marker lifetime for these two native families. These are current Word-save limitations carried to pending F-X287, not a blanket restriction on ordinary note authoring, reading or otherwise admitted comparison. Issue430 remains open and Q-A430-28 remains independently unproved. +Word-save interoperability is qualified on reconstructed Word for Mac 16.115 saves, not on the retained RC3 packets. Word 16.115 can drop a note pair placed before the reference mark of a note that is not the first of its part, merge the body pair into its reference's insertion, and renumber notes, bookmarks and revisions. The note pair follows the reference mark, a body pair inside its own reference's insertion is admitted with its note pair, or without it before a tracked note's reference, and a note whose pair Word dropped resolves as a tracked note. A note outside the tracked-note grammar, for example one that holds a hyperlink, keeps the earlier limits once Word drops its pair: rejecting it refuses atomically, and when Word kept the other author's pair, resolving that author first retires the outside note's body pair while its revisions remain pending, as on v0.17.0. A footnote inserted in Word 16.115 with Track Changes on is not a tracked note, because Word tracks its reference and content but not its paragraph mark, so rejecting it keeps an empty unreferenced footnote where Word's own Reject All removes the note, as on v0.17.0. A completed body pair that an earlier Word resolution left in a part still votes when a later tracked note settles that part, so such a stale creation bit can remove a part that held only special records. A failing action preserves its immediate pre-action state, not the state before earlier successful calls. Native qualification of these families on the RC3 packets remains with F-X287. Issue430 remains open and Q-A430-28 remains independently unproved. Word and character revisions group changed stretches as deletions followed by insertions. Whitespace between changes folds, while a non-whitespace anchor From 3513f67c2d135065e19b61767ee2412c5d3e464e Mon Sep 17 00:00:00 2001 From: Hadrien Mary Date: Mon, 16 Nov 2026 20:57:41 +0100 Subject: [PATCH 11/11] record the archive measurements The rdocx archive grows with the issue 430 custody changes and their tests, on #450 (d3c5dc4e7). It is the only crate whose member bytes change. Its measurement date moves to the day of this measurement. Tests, scripts/readme_doctests.py build_package_archive and archive_measurement for rdocx, member bytes stable on a second pass Harness, unchanged, measurements only --- README.md | 2 +- scripts/readme_doctests.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 89e13bede..b79e97f7e 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,517,067 compressed bytes, 56,462,895 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 | +| Crates.io archive: rdocx | 4,531,634 compressed bytes, 56,539,892 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 dde0d01d4..9dd0495fe 100644 --- a/scripts/readme_doctests.py +++ b/scripts/readme_doctests.py @@ -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_517_067, 56_462_895, 37), + "rdocx": (4_531_634, 56_539_892, 37), "rdocx-cli": (126_182, 593_817, 8), "rdocx-html": (29_407, 118_370, 11), "rdocx-layout": (463_844, 2_543_127, 15),