From bb5efa0f00529dd467e087d2be913bc060d8ab4b Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 29 Oct 2026 16:24:17 +0100 Subject: [PATCH] fix(domain): V1-2.2 refuse a removal while another element names it sheet.edit remove answers has_dependents, the document unchanged, while dependents lists anything but descendants (owner decision 2026-10-29); the property test checks no removal adds a referential issue. --- crates/core/src/domain/sheet/edit.rs | 23 ++++-- crates/core/tests/sheet_edit.rs | 107 +++++++++++++++++++++++---- crates/core/tests/sheet_review.rs | 65 ++++++++++++---- 3 files changed, 161 insertions(+), 34 deletions(-) diff --git a/crates/core/src/domain/sheet/edit.rs b/crates/core/src/domain/sheet/edit.rs index f20edafc..4025cb62 100644 --- a/crates/core/src/domain/sheet/edit.rs +++ b/crates/core/src/domain/sheet/edit.rs @@ -7,8 +7,9 @@ //! - update: the element's own fields are replaced (its children, categories and marking //! stay); any change of content turns its marking `to_confirm`; an id or code never changes; //! - remove: the element goes with its descendants (a zone with its categories and nodes, a -//! node with its children); references to it are left to the validation panel, which -//! `dependents` lists beforehand; +//! node with its children); refused while anything else names it (`has_dependents`, owner +//! decision 2026-10-29: no orphan annotation, no dangling reference), the list `dependents` +//! gives beforehand; //! - move: reorder among siblings, marking unchanged; //! - set_status: one element to `to_confirm` or `reviewed`, never `inherited`; //! - mark_reviewed: « Marquer comme relu » on one category (and its nodes) or one zone; @@ -17,8 +18,10 @@ //! //! Refused: what would leave an element unaddressable (an id already used among its //! siblings, a key that names nothing), a finding deeper than the 8 levels the editor offers, -//! a position past the end. Referential gaps stay possible: the integrity rules list them. -//! Of elements sharing a key (an integrity error), the first is the one addressed. +//! a position past the end, a removal that would leave a dependent behind. Other referential +//! gaps (a document saved with them, an update naming an unknown element) stay possible: the +//! integrity rules list them. Of elements sharing a key (an integrity error), the first is the +//! one addressed. use std::collections::HashMap; @@ -240,6 +243,8 @@ pub enum EditError { IdChanged, InvalidPosition, TooDeep, + /// A removal while another element names this one (`dependents`, descendants aside). + HasDependents, } impl EditError { @@ -251,6 +256,7 @@ impl EditError { Self::IdChanged => "id_changed", Self::InvalidPosition => "invalid_position", Self::TooDeep => "too_deep", + Self::HasDependents => "has_dependents", } } } @@ -563,6 +569,12 @@ fn update_node( fn remove(doc: &mut AnatomicalSheetDocument, key: &ElementKey) -> Edit { let at = locate(doc, key)?; + let named_elsewhere = dependents(doc, key) + .iter() + .any(|d| d.relation != Relation::Descendant); + if named_elsewhere { + return Err(EditError::HasDependents); + } match key { ElementKey::Sheet => return Err(EditError::InvalidTarget), ElementKey::Reference { .. } => { @@ -877,7 +889,8 @@ pub struct Dependent { pub relation: Relation, } -/// What names `key` or goes with it, for the delete confirmation (document order). +/// What names `key` or goes with it, for the delete confirmation (document order). A removal +/// is refused while the list holds anything but descendants. pub fn dependents(doc: &AnatomicalSheetDocument, key: &ElementKey) -> Vec { let annotation = |a: &Annotation, relation| Dependent { element: ElementKey::Annotation { diff --git a/crates/core/tests/sheet_edit.rs b/crates/core/tests/sheet_edit.rs index 6b45aabb..577039a9 100644 --- a/crates/core/tests/sheet_edit.rs +++ b/crates/core/tests/sheet_edit.rs @@ -1,7 +1,8 @@ //! V1-2.2: the editor's commands (contract §6.6, §8.1). The status rules, case by case; the //! refusals; `dependents`; the facade; and a property test over random command sequences: //! every output reads back strictly, existing keys survive unless removed, an edited or new -//! element is `to_confirm`, nothing ever becomes `inherited`. +//! element is `to_confirm`, nothing ever becomes `inherited`, a removal leaves no new dangling +//! reference and is refused only while something names its element. #![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] mod common; @@ -351,27 +352,88 @@ fn markings_are_set_one_element_category_or_zone_at_a_time() { ); } +/// Owner decision 2026-10-29: a removal never leaves an orphan or a dangling reference. It +/// takes the element's descendants and is refused, the document unchanged, while anything else +/// names it. #[test] -fn a_removal_takes_the_descendants_and_leaves_references_to_the_panel() { +fn a_removal_takes_its_descendants_and_is_refused_while_named() { let doc = small(); let next = edit( &doc, json!({ "op": "remove", "key": finding(&["cat", "n1"]) }), ); assert!(next.finding_zones[0].categories[0].children.is_empty()); - let next = edit( - &doc, + for key in [ + json!({ "kind": "view", "id": "head" }), + json!({ "kind": "view", "id": "main" }), + json!({ "kind": "zone", "id": "z1" }), + json!({ "kind": "category", "id": "c" }), + json!({ "kind": "region", "code": "C" }), + json!({ "kind": "reference", "id": "r1" }), + ] { + let command = json!({ "op": "remove", "key": key }); + assert_eq!( + refused(&doc, command.clone()), + EditError::HasDependents, + "{key}" + ); + let input = json!({ "document": doc, "command": command }).to_string(); + let out: Value = serde_json::from_str(&call("sheet.edit", &input)).unwrap(); + assert_eq!(out["kind"], json!("has_dependents"), "{key}"); + } + // Once nothing names them, the view and the zone go (the zone with its categories). + let mut next = edit(&doc, json!({ "op": "remove", "key": annotation("a2") })); + next = edit(&next, json!({ "op": "remove", "key": annotation("t1") })); + next = edit( + &next, json!({ "op": "remove", "key": { "kind": "view", "id": "head" } }), ); assert_eq!(next.views.len(), 1); - assert_eq!(next.annotations.len(), 3, "a2 and t1 stay, dangling"); - let issues = faunosteo_core::domain::sheet::validate_sheet_document(&next); - assert!(issues.iter().any(|i| i.code == "annotation.view.missing")); - let next = edit( - &doc, + let mut unlinked = serde_json::to_value(&next.annotations[0]).unwrap(); + unlinked["finding_zone_id"] = Value::Null; + next = edit( + &next, + json!({ "op": "update", "key": annotation("a1"), "element": { "kind": "annotation", "value": unlinked } }), + ); + next = edit( + &next, json!({ "op": "remove", "key": { "kind": "zone", "id": "z1" } }), ); assert!(next.finding_zones.is_empty()); + // With no citing finding left, the reference goes too; nothing dangles. + next = edit( + &next, + json!({ "op": "remove", "key": { "kind": "reference", "id": "r1" } }), + ); + let issues = faunosteo_core::domain::sheet::validate_sheet_document(&next); + assert!( + issues + .iter() + .all(|i| !REFERENTIAL.contains(&i.code.as_str())), + "{issues:?}" + ); +} + +/// The integrity rules that name an element that does not exist. +const REFERENTIAL: [&str; 7] = [ + "annotation.view.missing", + "annotation.category.missing", + "annotation.finding_zone.missing", + "annotation.region.missing", + "annotation.opens_view.invalid", + "finding.reference.missing", + "view.parent.missing", +]; + +/// How many issues of each referential rule a document has (paths shift with removals). +fn referential_issues(doc: &AnatomicalSheetDocument) -> HashMap { + let mut counts = HashMap::new(); + for issue in faunosteo_core::domain::sheet::validate_sheet_document(doc) { + if REFERENTIAL.contains(&issue.code.as_str()) { + *counts.entry(issue.code).or_insert(0) += 1; + } + } + counts } #[test] @@ -715,7 +777,7 @@ fn random_command_sequences_keep_every_invariant() { let mut rng = Rng(seed); let mut counter = 0; let mut doc = start; - let (mut applied, mut refusals) = (0, 0); + let (mut applied, mut refusals, mut named) = (0, 0, 0); for _ in 0..400 { let mut raw = random_command(&doc, &mut rng, &mut counter); let changes = raw.as_object_mut().unwrap().remove("changes"); @@ -728,9 +790,28 @@ fn random_command_sequences_keep_every_invariant() { .filter(|s| **s == ReviewStatus::Inherited) .count(); match apply_edit(&doc, command) { - Err(_) => refusals += 1, + Err(error) => { + refusals += 1; + if error == EditError::HasDependents { + let key: ElementKey = serde_json::from_value(raw["key"].clone()).unwrap(); + assert!( + dependents(&doc, &key) + .iter() + .any(|d| d.relation != Relation::Descendant), + "refused with nothing naming it: {raw}" + ); + named += 1; + } + } Ok(next) => { applied += 1; + if raw["op"] == "remove" { + let (old, new) = (referential_issues(&doc), referential_issues(&next)); + let grew = new + .iter() + .any(|(code, n)| old.get(code).is_none_or(|o| n > o)); + assert!(!grew, "orphan left: {raw}"); + } let text = serde_json::to_string(&next).unwrap(); let reread: AnatomicalSheetDocument = serde_json::from_value(parse_json(&text).unwrap()).unwrap(); @@ -750,8 +831,8 @@ fn random_command_sequences_keep_every_invariant() { } } assert!( - applied > 200 && refusals > 0, - "{applied} applied, {refusals} refused" + applied > 200 && refusals > 0 && named > 0, + "{applied} applied, {refusals} refused, {named} named elsewhere" ); } } diff --git a/crates/core/tests/sheet_review.rs b/crates/core/tests/sheet_review.rs index 6d2b4b53..1926fd19 100644 --- a/crates/core/tests/sheet_review.rs +++ b/crates/core/tests/sheet_review.rs @@ -1,6 +1,7 @@ //! V1-2.2: completeness, review groups, digests, removal groups and the change list //! (contract §6.3, §6.6), on the equine draft (the counts of contract §1 and §14.1) and on -//! derived versions built by the edit commands. +//! derived versions built by the edit commands (a zone removed after its annotations are +//! unlinked, since a removal is refused while anything names it). #![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] mod common; @@ -26,6 +27,34 @@ fn edit(document: &AnatomicalSheetDocument, command: Value) -> AnatomicalSheetDo apply_edit(document, command).unwrap() } +/// The document without the zone, as an editor gets there: the annotations linked to it are +/// unlinked first (a removal is refused while they name it), then the zone goes. Answers the +/// ids of the annotations unlinked. +fn without_zone( + document: &AnatomicalSheetDocument, + zone_id: &str, +) -> (AnatomicalSheetDocument, Vec) { + let mut next = document.clone(); + let mut unlinked = Vec::new(); + for annotation in &document.annotations { + let mut value = serde_json::to_value(annotation).unwrap(); + if value["finding_zone_id"] == json!(zone_id) { + value["finding_zone_id"] = Value::Null; + let key = json!({ "kind": "annotation", "id": annotation.id() }); + next = edit( + &next, + json!({ "op": "update", "key": key, "element": { "kind": "annotation", "value": value } }), + ); + unlinked.push(annotation.id().to_owned()); + } + } + let next = edit( + &next, + json!({ "op": "remove", "key": { "kind": "zone", "id": zone_id } }), + ); + (next, unlinked) +} + fn groups( document: &AnatomicalSheetDocument, base: Option<&AnatomicalSheetDocument>, @@ -146,10 +175,8 @@ fn a_group_is_coverable_once_every_element_is_reviewed() { fn a_derived_version_that_deletes_a_zone_has_its_removal_group() { let base = equine(); let zone = base.finding_zones[5].id.clone(); - let derived = edit( - &base, - json!({ "op": "remove", "key": { "kind": "zone", "id": zone } }), - ); + let (derived, unlinked) = without_zone(&base, &zone); + assert!(!unlinked.is_empty(), "every equine zone is linked"); let all = groups(&derived, Some(&base)); assert_eq!( all.len(), @@ -166,10 +193,18 @@ fn a_derived_version_that_deletes_a_zone_has_its_removal_group() { // A second derivation removing the same zone gives the same removal digest (carry). let again = groups(&derived.clone(), Some(&base)); assert_eq!(again.last().unwrap().digest, removal.digest); - // Unchanged groups keep the base's digest; without a base nothing is a removal. + // Unchanged groups keep the base's digest (the views of the unlinked annotations changed); + // without a base nothing is a removal. let base_groups = groups(&base, None); + let redrawn: Vec = base + .annotations + .iter() + .filter(|a| unlinked.iter().any(|id| id == a.id())) + .map(|a| format!("view:{}", a.view_id())) + .collect(); for g in all.iter().filter(|g| !g.removed) { - assert_eq!(g.digest, group(&base_groups, &g.key).digest, "{}", g.key); + let same = g.digest == group(&base_groups, &g.key).digest; + assert_eq!(same, !redrawn.contains(&g.key), "{}", g.key); } assert!(groups(&derived, None).iter().all(|g| !g.removed)); // The change list names the zone and everything that went with it. @@ -186,7 +221,11 @@ fn a_derived_version_that_deletes_a_zone_has_its_removal_group() { ); let zone_size = 1 + count_findings(&base, &zone); assert_eq!(removed.len(), zone_size); - assert_eq!(changes.len(), zone_size, "nothing else changed"); + assert_eq!( + changes.len(), + zone_size + unlinked.len(), + "nothing else changed" + ); } fn count_findings(document: &AnatomicalSheetDocument, zone_id: &str) -> usize { @@ -306,14 +345,8 @@ fn a_removal_digest_is_bound_to_its_group_key() { let base = equine(); let first = base.finding_zones[0].id.clone(); let second = base.finding_zones[1].id.clone(); - let without_first = edit( - &base, - json!({ "op": "remove", "key": { "kind": "zone", "id": first } }), - ); - let derived = edit( - &without_first, - json!({ "op": "remove", "key": { "kind": "zone", "id": second } }), - ); + let (without_first, _) = without_zone(&base, &first); + let (derived, _) = without_zone(&without_first, &second); let removals: Vec = groups(&derived, Some(&base)) .into_iter() .filter(|g| g.removed)