From 99a83201b59a63abdd99165db8fcac61bb53b877 Mon Sep 17 00:00:00 2001 From: STE1200 <319441566+STE1200@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:19:37 +0100 Subject: [PATCH 1/3] DXF/DWG: prune kept ACDBASSOCDEPENDENCY objects whose target handle is unmapped MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When dxf_raw::finish remaps handles on kept associative objects, a dangling dependentOnObject pointer (group 330 inside the AcDbAssocDependency subclass) was rewritten to "0" while the dependency remained active and stayed listed in its owning ACDBASSOCACTION 360 dependency list. dxf_raw::finish now drops any kept AcDbAssocDependency whose non-null dependentOnObject handle does not resolve to a written object/entity (along with kept objects owned only by it), while leaving originally unbound dependencies (330 = 0 in the input) untouched. In Map::object, AcDbAssocAction filters dropped handles out of its 360 dependency list and updates its 90 dependency count. Tests: assoc_dependency_prune::{orphaned_assoc_dependency_is_pruned_along_with_action_entry_and_body,originally_unbound_assoc_dependency_with_null_target_is_kept}. 👾 Generated with [Letta Code](https://letta.com) Co-Authored-By: Letta Code --- crates/io/src/dxf_raw.rs | 91 ++++++++++++++++++- crates/io/tests/assoc_dependency_prune.rs | 105 ++++++++++++++++++++++ 2 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 crates/io/tests/assoc_dependency_prune.rs diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 3c1b7d124..ebe6e0c2c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -903,6 +903,44 @@ pub fn object_records(d: &Drawing) -> Vec { .collect() } +/// The `dependentOnObject` handle (first group 330 inside the `AcDbAssocDependency` subclass) of +/// a kept associative dependency, when it is non-null. +fn assoc_dependency_target(o: &ForeignObject) -> Option { + let mut in_dep = false; + for r in &o.tags { + if r.code == 100 { + if in_dep { + break; + } + in_dep = r.value.trim().eq_ignore_ascii_case("AcDbAssocDependency"); + } else if in_dep && r.code == 330 { + let v = norm(&r.value); + return (!v.is_empty() && v != "0").then_some(v); + } + } + None +} + +/// If `tags[at]` is the dependency-count group (90) of an `AcDbAssocAction` subclass (`100 +/// AcDbAssocAction`, `90` version, `90` status, `330` network, `360` body, `90` index, `90` +/// max_dep_idx, `90` count, followed by `count` group-360 dependency handles), returns `count`. +fn assoc_action_dep_count(tags: &[RawTag], at: usize) -> Option { + const HEADER: [i32; 7] = [100, 90, 90, 330, 360, 90, 90]; + if at < HEADER.len() || tags.get(at)?.code != 90 { + return None; + } + let start = at - HEADER.len(); + if !tags[start].value.trim().eq_ignore_ascii_case("AcDbAssocAction") { + return None; + } + if !HEADER.iter().enumerate().all(|(k, &c)| tags[start + k].code == c) { + return None; + } + let count = usize::try_from(tags[at].value.trim().parse::().ok()?).ok()?; + let deps = tags.get(at + 1..at + 1 + count)?; + deps.iter().all(|t| t.code == 360).then_some(count) +} + /// Remaps the kept data's handles onto a written file. struct Map<'a> { f: &'a Foreign, @@ -997,6 +1035,13 @@ impl Map<'_> { } continue; } + if let Some(count) = assoc_action_dep_count(&o.tags, i - 1) { + let live: Vec = o.tags[i..i + count].iter().filter_map(|n| self.get(&n.value)).filter(|h| h != "0").collect(); + out.push(Tag::i(90, i64::try_from(live.len()).unwrap_or(i64::MAX))); + out.extend(live.into_iter().map(|h| Tag::s(360, h))); + i += count; + continue; + } if r.code == 5 { out.push(Tag::s(5, self.get(&r.value).unwrap_or_else(|| "0".into()))); continue; @@ -1166,7 +1211,7 @@ pub(crate) fn finish( (o.handle.hex(), head(&t).owner) }) .collect(); - let alive_memo = settle(&hard, |kept: &HashMap| { + let mut alive_memo = settle(&hard, |kept: &HashMap| { // Keep established live paths available to descendants during this pass as well. let mut alive_memo: HashMap = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect(); let kept = |h: &str| kept.get(h) == Some(&true); @@ -1207,6 +1252,49 @@ pub(crate) fn finish( } alive_memo }); + // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written, along + // with any kept objects owned only by them (e.g. a dependency body). Leaving an active + // dependency with its group 330 remapped to "0" breaks the associative reactor invariant. + let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); + for _ in 0..MAX_DEPTH { + let mut changed = false; + for o in &f.objects { + let h = o.handle.hex(); + if alive_memo.get(&h) != Some(&true) { + continue; + } + let dead_target = assoc_dependency_target(o).is_some_and(|t| { + if objs.contains_key(&t) { + alive_memo.get(&t) != Some(&true) + } else if let Some(role) = handle(&t).and_then(|th| f.targets.get(&th)) { + !roles.contains_key(role) + } else { + !entities.contains(&t) + } + }); + if dead_target { + alive_memo.insert(h, false); + changed = true; + } + } + if !changed { + break; + } + let mut cascade = true; + while cascade { + cascade = false; + for o in &f.objects { + let h = o.handle.hex(); + if alive_memo.get(&h) != Some(&true) { + continue; + } + if own.get(&h).and_then(|v| v.as_deref()).is_some_and(|owner| objs.contains_key(owner) && alive_memo.get(owner) != Some(&true)) { + alive_memo.insert(h, false); + cascade = true; + } + } + } + } // New handles for the written kept objects, above every written handle and the seed. let mut fresh = Fresh::new(tags); // The entities of unmodeled types join the records only below, so their handles are not in @@ -1224,7 +1312,6 @@ pub(crate) fn finish( } } let merged_into: HashMap = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect(); - let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities }; let mut out: Vec = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::()); let mut block = String::new(); diff --git a/crates/io/tests/assoc_dependency_prune.rs b/crates/io/tests/assoc_dependency_prune.rs new file mode 100644 index 000000000..589f09694 --- /dev/null +++ b/crates/io/tests/assoc_dependency_prune.rs @@ -0,0 +1,105 @@ +//! A kept `ACDBASSOCDEPENDENCY` whose `dependentOnObject` (group 330 in `AcDbAssocDependency`) +//! names a handle that is no longer written must not be emitted with `330 = 0` as an active +//! dependency: it is dropped together with objects owned only by it, and its owning +//! `ACDBASSOCACTION` drops its `360` entry and decrements its dependency count. + +fn dxf_with_assoc_action(dep1_target: &str, dep2_target: &str) -> String { + format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1024\n0\nENDSEC\n\ + 0\nSECTION\n2\nCLASSES\n\ + 0\nCLASS\n1\nACDBASSOCNETWORK\n2\nAcDbAssocNetwork\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n\ + 0\nCLASS\n1\nACDBASSOCACTION\n2\nAcDbAssocAction\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n\ + 0\nCLASS\n1\nACDBASSOCDEPENDENCY\n2\nAcDbAssocDependency\n3\nObjectDBX Classes\n90\n1025\n280\n0\n281\n0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\n100\n102\n{{ACAD_REACTORS\n330\n504\n102\n}}\n330\n1F\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n\ + 10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nACAD_ASSOCNETWORK\n350\n501\n\ + 0\nDICTIONARY\n5\n501\n102\n{{ACAD_REACTORS\n330\nC\n102\n}}\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nACAD_ASSOCNETWORK\n350\n502\n\ + 0\nACDBASSOCNETWORK\n5\n502\n102\n{{ACAD_REACTORS\n330\n501\n102\n}}\n330\n501\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n330\n0\n360\n0\n90\n0\n90\n0\n90\n0\n\ + 100\nAcDbAssocNetwork\n90\n0\n90\n1\n90\n1\n360\n503\n\ + 0\nACDBASSOCACTION\n5\n503\n330\n502\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n330\n502\n360\n0\n90\n1\n90\n2\n90\n2\n360\n504\n360\n505\n\ + 0\nACDBASSOCDEPENDENCY\n5\n504\n330\n503\n\ + 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n0\n290\n1\n290\n1\n90\n0\n330\n{dep1_target}\n290\n0\n330\n0\n330\n0\n360\n0\n90\n1\n\ + 0\nACDBASSOCDEPENDENCY\n5\n505\n330\n503\n\ + 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n1\n290\n1\n290\n1\n90\n0\n330\n{dep2_target}\n290\n0\n330\n0\n330\n0\n360\n506\n90\n2\n\ + 0\nXRECORD\n5\n506\n330\n505\n100\nAcDbXrecord\n280\n1\n1\nDEP_BODY_MARKER\n\ + 0\nENDSEC\n0\nEOF\n" + ) +} + +fn objects_of(dxf: &str, kind: &str) -> Vec> { + let lines: Vec<&str> = dxf.lines().collect(); + let mut out = Vec::new(); + let mut i = 0; + let mut in_objects = false; + while i + 1 < lines.len() { + let c = lines[i].trim(); + let v = lines[i + 1].trim(); + if c == "2" && v == "OBJECTS" { + in_objects = true; + i += 2; + continue; + } + if in_objects && c == "0" { + if v == "ENDSEC" { + break; + } + let obj_kind = v; + let mut pairs = Vec::new(); + i += 2; + while i + 1 < lines.len() && lines[i].trim() != "0" { + pairs.push((lines[i].trim().to_string(), lines[i + 1].trim().to_string())); + i += 2; + } + if obj_kind == kind { + out.push(pairs); + } + continue; + } + i += 2; + } + out +} + +#[test] +fn orphaned_assoc_dependency_is_pruned_along_with_action_entry_and_body() { + // dep1 points at live LINE 100; dep2 points at missing handle 999 and owns XRECORD 506. + let dxf = dxf_with_assoc_action("100", "999"); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 1, "only the live dependency should be written, got {deps:?}"); + let dep_handle = deps[0].iter().find(|(c, _)| c == "5").map(|(_, v)| v.as_str()).unwrap(); + let dep_target = + deps[0].iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocDependency")).find(|(c, _)| c == "330").map(|(_, v)| v.as_str()); + assert_eq!(dep_target, Some("100"), "live dependency keeps its target handle"); + + // The child XRECORD owned by the dropped dependency must be dropped too. + assert!(!saved.contains("DEP_BODY_MARKER"), "child owned by dropped dependency must not be written"); + + // The owning ACDBASSOCACTION must list only the surviving dependency with count = 1. + let actions = objects_of(&saved, "ACDBASSOCACTION"); + assert_eq!(actions.len(), 1); + let action_sub: Vec<&(String, String)> = actions[0].iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocAction")).collect(); + assert_eq!(action_sub[7], &("90".to_string(), "1".to_string()), "dependency count should be decremented to 1"); + assert_eq!(action_sub[8], &("360".to_string(), dep_handle.to_string()), "only the live dependency remains in 360 list"); + assert_eq!(action_sub.len(), 9, "no stale 360 entry remains"); +} + +#[test] +fn originally_unbound_assoc_dependency_with_null_target_is_kept() { + // dep2 already had dependentOnObject = 0 in the input file, so it is not an unmapped handle. + let dxf = dxf_with_assoc_action("100", "0"); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_null.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 2, "originally unbound dependency should remain kept"); + assert!(saved.contains("DEP_BODY_MARKER")); +} From 10a493d24c48f67db4952e6fd43a3c4a5a2fc945 Mon Sep 17 00:00:00 2001 From: STE1200 <319441566+STE1200@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:54:48 +0100 Subject: [PATCH 2/3] DXF/DWG: rewrite assoc action lists with non-owned dependencies acadrust writes each AcDbAssocAction dependency entry as group 360 (owned) or 330 (not owned). The list rewrite accepted only 360 entries, so an action with a 330 entry kept a stale count and a null entry after a dependency was pruned. The rewrite now accepts both codes, keeps each surviving entry's code, keeps input-null entries, and drops only entries whose object is gone. A dependency is no longer pruned when an action of unknown header shape owns it or names it in any group 330 or 360, so that action's count and list stay consistent. The prune loop runs until nothing changes instead of at most 64 passes, and the cascade finds owners through owner_of, so a null-owner body goes with its pruned hard owner and stays while another live object holds it. Tests: assoc_dependency_prune gains a mixed 330/360 list, a null-owner body with one and with two hard owners, an unknown action header, and an unknown action that lists a dependency of a known action by 330. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 83 +++++++++++--- crates/io/tests/assoc_dependency_prune.rs | 132 +++++++++++++++++++++- 2 files changed, 192 insertions(+), 23 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index ebe6e0c2c..c48648146 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -921,24 +921,53 @@ fn assoc_dependency_target(o: &ForeignObject) -> Option { None } -/// If `tags[at]` is the dependency-count group (90) of an `AcDbAssocAction` subclass (`100 -/// AcDbAssocAction`, `90` version, `90` status, `330` network, `360` body, `90` index, `90` -/// max_dep_idx, `90` count, followed by `count` group-360 dependency handles), returns `count`. +/// The groups of an `AcDbAssocAction` subclass before its dependency count: `100 AcDbAssocAction`, +/// `90` version, `90` status, `330` network, `360` body, `90` index and `90` highest dependency index. +const ASSOC_ACTION_HEADER: [i32; 7] = [100, 90, 90, 330, 360, 90, 90]; + +/// If `tags[at]` is the dependency count (group 90) of an `AcDbAssocAction` subclass, returns the count. +/// The count is followed by one group per dependency: 360 for an owned dependency, 330 for one the +/// action does not own. acadrust writes this layout (`write_assoc_action` in acadrust 0.6.6's +/// `io/dxf/writer/section_writer/associative.rs`) and reads it back (`read_action` in +/// `io/dxf/reader/section_reader/associative.rs`). A DWG reaches this code through that writer, so a +/// kept action from a DWG has this form too. +/// +/// The match is positional on purpose. When the class version is above 1, the list is followed by +/// `90 0`, `90 n` and n group-360 owned parameters. A loose match on a group 90 before handles also +/// takes that second list. fn assoc_action_dep_count(tags: &[RawTag], at: usize) -> Option { - const HEADER: [i32; 7] = [100, 90, 90, 330, 360, 90, 90]; - if at < HEADER.len() || tags.get(at)?.code != 90 { + if at < ASSOC_ACTION_HEADER.len() || tags.get(at)?.code != 90 { return None; } - let start = at - HEADER.len(); + let start = at - ASSOC_ACTION_HEADER.len(); if !tags[start].value.trim().eq_ignore_ascii_case("AcDbAssocAction") { return None; } - if !HEADER.iter().enumerate().all(|(k, &c)| tags[start + k].code == c) { + if !ASSOC_ACTION_HEADER.iter().enumerate().all(|(k, &c)| tags[start + k].code == c) { return None; } let count = usize::try_from(tags[at].value.trim().parse::().ok()?).ok()?; let deps = tags.get(at + 1..at + 1 + count)?; - deps.iter().all(|t| t.code == 360).then_some(count) + deps.iter().all(|t| matches!(t.code, 330 | 360)).then_some(count) +} + +/// The index of a kept object's `100 AcDbAssocAction` marker. An associative network derives from +/// an action, so it has one too. +fn assoc_action_marker(tags: &[RawTag]) -> Option { + tags.iter().position(|t| t.code == 100 && t.value.trim().eq_ignore_ascii_case("AcDbAssocAction")) +} + +/// The dependency list of a kept action that [`assoc_action_dep_count`] recognizes: the index of +/// its count group and the count. +fn assoc_action_list(tags: &[RawTag]) -> Option<(usize, usize)> { + let at = assoc_action_marker(tags)? + ASSOC_ACTION_HEADER.len(); + Some((at, assoc_action_dep_count(tags, at)?)) +} + +/// Whether a kept object is an action whose dependency list has a form we do not know. Its list +/// cannot be rewritten, so the dependencies it owns are not pruned. +fn is_unknown_assoc_action(tags: &[RawTag]) -> bool { + assoc_action_marker(tags).is_some() && assoc_action_list(tags).is_none() } /// Remaps the kept data's handles onto a written file. @@ -992,6 +1021,7 @@ impl Map<'_> { fn object(&self, o: &ForeignObject, out: &mut Vec) { out.push(Tag::s(0, o.kind.clone())); let dict = is_dictionary(&o.kind); + let list = assoc_action_list(&o.tags); let mut i = 0; while let Some(r) = o.tags.get(i) { i += 1; @@ -1035,10 +1065,13 @@ impl Map<'_> { } continue; } - if let Some(count) = assoc_action_dep_count(&o.tags, i - 1) { - let live: Vec = o.tags[i..i + count].iter().filter_map(|n| self.get(&n.value)).filter(|h| h != "0").collect(); + if let Some((_, count)) = list.filter(|&(at, _)| at == i - 1) { + // An entry keeps its own group code. A null entry stays null, because [`Map::get`] + // gives "0" only for a null handle. An entry whose object is gone is left out, and + // the count follows. + let live: Vec = o.tags[i..i + count].iter().filter_map(|n| self.get(&n.value).map(|h| Tag::s(n.code, h))).collect(); out.push(Tag::i(90, i64::try_from(live.len()).unwrap_or(i64::MAX))); - out.extend(live.into_iter().map(|h| Tag::s(360, h))); + out.extend(live); i += count; continue; } @@ -1252,15 +1285,28 @@ pub(crate) fn finish( } alive_memo }); - // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written, along - // with any kept objects owned only by them (e.g. a dependency body). Leaving an active - // dependency with its group 330 remapped to "0" breaks the associative reactor invariant. + // Drop kept AcDbAssocDependency objects whose dependentOnObject is no longer written. Also drop + // the kept objects whose owner, as [`owner_of`] finds it, is a dropped dependency. Leaving an + // active dependency with its group 330 remapped to "0" breaks the associative reactor invariant. let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); - for _ in 0..MAX_DEPTH { + // A dependency stays when an action of unknown form names it by group 330 or 360, or is its + // owner. That action's list and count stay as read, and only the dangling target becomes null. + let unknown_refs: HashSet = f + .objects + .iter() + .filter(|o| is_unknown_assoc_action(&o.tags)) + .flat_map(|o| o.tags.iter().take_while(|t| t.code < 1000).filter(|t| matches!(t.code, 330 | 360)).map(|t| norm(&t.value))) + .collect(); + let in_unknown_action = |h: &str| { + unknown_refs.contains(h) + || own.get(h).cloned().flatten().and_then(|owner| objs.get(&owner)).is_some_and(|owner| is_unknown_assoc_action(&owner.tags)) + }; + // Each pass that changes something drops at least one live object, so the loop ends. + loop { let mut changed = false; for o in &f.objects { let h = o.handle.hex(); - if alive_memo.get(&h) != Some(&true) { + if alive_memo.get(&h) != Some(&true) || in_unknown_action(&h) { continue; } let dead_target = assoc_dependency_target(o).is_some_and(|t| { @@ -1280,6 +1326,8 @@ pub(crate) fn finish( if !changed { break; } + // The owner is found as for the first liveness pass ([`owner_of`]). A null-owner child goes + // with its hard owner, and a child with another live hard owner stays. let mut cascade = true; while cascade { cascade = false; @@ -1288,7 +1336,8 @@ pub(crate) fn finish( if alive_memo.get(&h) != Some(&true) { continue; } - if own.get(&h).and_then(|v| v.as_deref()).is_some_and(|owner| objs.contains_key(owner) && alive_memo.get(owner) != Some(&true)) { + let owner = owner_of(own.get(&h).cloned().flatten(), &h, &hard, |x| alive_memo.get(x) == Some(&true)); + if owner.is_some_and(|owner| objs.contains_key(&owner) && alive_memo.get(&owner) != Some(&true)) { alive_memo.insert(h, false); cascade = true; } diff --git a/crates/io/tests/assoc_dependency_prune.rs b/crates/io/tests/assoc_dependency_prune.rs index 589f09694..da8a05549 100644 --- a/crates/io/tests/assoc_dependency_prune.rs +++ b/crates/io/tests/assoc_dependency_prune.rs @@ -1,9 +1,40 @@ //! A kept `ACDBASSOCDEPENDENCY` whose `dependentOnObject` (group 330 in `AcDbAssocDependency`) //! names a handle that is no longer written must not be emitted with `330 = 0` as an active -//! dependency: it is dropped together with objects owned only by it, and its owning -//! `ACDBASSOCACTION` drops its `360` entry and decrements its dependency count. +//! dependency: it is dropped together with the objects whose owner it is, and its owning +//! `ACDBASSOCACTION` drops its list entry (group 330 or 360) and decrements its dependency count. + +/// The parts of the fixture that the tests change. +struct Parts<'a> { + dep1_target: &'a str, + dep2_target: &'a str, + /// Groups added to the action's `AcDbAssocAction` header after its status. + action_extra: &'a str, + /// The action's dependency list after its count (group 330 or 360 per entry). + action_list: &'a str, + /// The body handle (group 360) of dependency 504. + dep1_body: &'a str, + /// The owner (group 330) of XRECORD 506, which dependency 505 hard-owns. + body_owner: &'a str, + /// Objects added at the end of the OBJECTS section. + extra_objects: &'a str, +} + +const PARTS: Parts<'static> = Parts { + dep1_target: "100", + dep2_target: "999", + action_extra: "", + action_list: "360\n504\n360\n505\n", + dep1_body: "0", + body_owner: "505", + extra_objects: "", +}; fn dxf_with_assoc_action(dep1_target: &str, dep2_target: &str) -> String { + dxf(&Parts { dep1_target, dep2_target, ..PARTS }) +} + +fn dxf(p: &Parts) -> String { + let Parts { dep1_target, dep2_target, action_extra, action_list, dep1_body, body_owner, extra_objects } = p; format!( "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1024\n0\nENDSEC\n\ 0\nSECTION\n2\nCLASSES\n\ @@ -22,13 +53,13 @@ fn dxf_with_assoc_action(dep1_target: &str, dep2_target: &str) -> String { 100\nAcDbAssocAction\n90\n1\n90\n0\n330\n0\n360\n0\n90\n0\n90\n0\n90\n0\n\ 100\nAcDbAssocNetwork\n90\n0\n90\n1\n90\n1\n360\n503\n\ 0\nACDBASSOCACTION\n5\n503\n330\n502\n\ - 100\nAcDbAssocAction\n90\n1\n90\n0\n330\n502\n360\n0\n90\n1\n90\n2\n90\n2\n360\n504\n360\n505\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n{action_extra}330\n502\n360\n0\n90\n1\n90\n2\n90\n2\n{action_list}\ 0\nACDBASSOCDEPENDENCY\n5\n504\n330\n503\n\ - 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n0\n290\n1\n290\n1\n90\n0\n330\n{dep1_target}\n290\n0\n330\n0\n330\n0\n360\n0\n90\n1\n\ + 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n0\n290\n1\n290\n1\n90\n0\n330\n{dep1_target}\n290\n0\n330\n0\n330\n0\n360\n{dep1_body}\n90\n1\n\ 0\nACDBASSOCDEPENDENCY\n5\n505\n330\n503\n\ 100\nAcDbAssocDependency\n90\n2\n90\n0\n290\n1\n290\n1\n290\n1\n290\n1\n90\n0\n330\n{dep2_target}\n290\n0\n330\n0\n330\n0\n360\n506\n90\n2\n\ - 0\nXRECORD\n5\n506\n330\n505\n100\nAcDbXrecord\n280\n1\n1\nDEP_BODY_MARKER\n\ - 0\nENDSEC\n0\nEOF\n" + 0\nXRECORD\n5\n506\n330\n{body_owner}\n100\nAcDbXrecord\n280\n1\n1\nDEP_BODY_MARKER\n\ + {extra_objects}0\nENDSEC\n0\nEOF\n" ) } @@ -103,3 +134,92 @@ fn originally_unbound_assoc_dependency_with_null_target_is_kept() { assert_eq!(deps.len(), 2, "originally unbound dependency should remain kept"); assert!(saved.contains("DEP_BODY_MARKER")); } + +/// The groups of the written action from its `100 AcDbAssocAction` marker on. +fn action_subclass(saved: &str) -> Vec<(String, String)> { + let actions = objects_of(saved, "ACDBASSOCACTION"); + assert_eq!(actions.len(), 1, "one action is written"); + actions[0].iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocAction")).cloned().collect() +} + +/// The dependency count at `at` in an action subclass and the handle groups that follow it. +fn dependency_list(sub: &[(String, String)], at: usize) -> (usize, Vec<(String, String)>) { + assert_eq!(sub[at].0, "90", "the dependency count is a group 90"); + let count: usize = sub[at].1.parse().expect("count"); + let entries = sub[at + 1..].iter().take_while(|(c, _)| c == "330" || c == "360").cloned().collect(); + (count, entries) +} + +fn handle_of(object: &[(String, String)]) -> String { + object.iter().find(|(c, _)| c == "5").map(|(_, v)| v.clone()).expect("handle") +} + +#[test] +fn non_owned_dependency_entry_keeps_its_code_when_its_sibling_is_pruned() { + // acadrust writes a non-owned dependency as a group 330 entry. Dependency 505 is dangling. + let dxf = dxf(&Parts { action_list: "330\n504\n360\n505\n", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_mixed.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 1, "the dangling dependency is dropped, got {deps:?}"); + let (count, entries) = dependency_list(&action_subclass(&saved), 7); + assert!(count < 2, "the count drops below the two read entries"); + assert_eq!(count, entries.len(), "the count matches the written list: {entries:?}"); + assert_eq!(entries, vec![("330".to_string(), handle_of(&deps[0]))], "the surviving entry keeps group 330"); +} + +#[test] +fn null_owner_body_goes_with_its_pruned_hard_owner() { + // XRECORD 506 has owner 0. Only the dangling dependency 505 holds it (group 360). + let dxf = dxf(&Parts { body_owner: "0", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_null_owner.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + assert_eq!(objects_of(&saved, "ACDBASSOCDEPENDENCY").len(), 1, "the dangling dependency is dropped"); + assert!(!saved.contains("DEP_BODY_MARKER"), "a body held only by the dropped dependency is dropped"); +} + +#[test] +fn null_owner_body_stays_while_another_live_object_holds_it() { + // Live dependency 504 also holds XRECORD 506 by group 360. + let dxf = dxf(&Parts { body_owner: "0", dep1_body: "506", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_shared_body.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + assert_eq!(objects_of(&saved, "ACDBASSOCDEPENDENCY").len(), 1, "the dangling dependency is dropped"); + assert!(saved.contains("DEP_BODY_MARKER"), "a body with another live holder stays"); +} + +#[test] +fn dependency_of_an_action_with_an_unknown_header_is_not_pruned() { + // An extra group in the action header hides where its list starts, so the list stays as read. + let dxf = dxf(&Parts { action_extra: "290\n1\n", ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_unknown_action.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 2, "both dependencies stay, got {deps:?}"); + let (count, entries) = dependency_list(&action_subclass(&saved), 8); + assert_eq!(count, entries.len(), "the count matches the written list: {entries:?}"); + let written: Vec = deps.iter().map(|d| handle_of(d)).collect(); + assert!(entries.iter().all(|(_, h)| written.contains(h)), "every entry names a written dependency: {entries:?}"); +} + +#[test] +fn dependency_listed_by_an_action_with_an_unknown_header_is_not_pruned() { + // Known action 503 owns dangling dependency 505. Action 507 has an unknown header and lists 505 by group 330. + let unknown = "0\nACDBASSOCACTION\n5\n507\n330\n502\n\ + 100\nAcDbAssocAction\n90\n1\n90\n0\n290\n1\n330\n502\n360\n0\n90\n2\n90\n0\n90\n1\n330\n505\n"; + let dxf = dxf(&Parts { extra_objects: unknown, ..PARTS }); + let doc = cadcraft_io::read(dxf.as_bytes(), "assoc_unknown_lister.dxf").expect("read DXF"); + let saved = cadcraft_io::write_dxf(&doc); + + let deps = objects_of(&saved, "ACDBASSOCDEPENDENCY"); + assert_eq!(deps.len(), 2, "both dependencies stay, got {deps:?}"); + let written: Vec = deps.iter().map(|d| handle_of(d)).collect(); + let actions = objects_of(&saved, "ACDBASSOCACTION"); + let lister = actions.iter().find(|a| a.iter().any(|(c, _)| c == "290")).expect("the unknown action is written"); + let sub: Vec<(String, String)> = lister.iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbAssocAction")).cloned().collect(); + let (count, entries) = dependency_list(&sub, 8); + assert_eq!(count, entries.len(), "the count matches the written list: {entries:?}"); + assert!(entries.iter().all(|(_, h)| written.contains(h)), "every entry names a written dependency: {entries:?}"); +} From 9f245800ee9871eb292651f2aade629a7282797f Mon Sep 17 00:00:00 2001 From: STE1200 <319441566+STE1200@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:09:35 +0100 Subject: [PATCH 3/3] DXF/DWG: classify unknown assoc actions once The prune guard parsed a dependency owner's action list again for each dependency in each pass. finish now collects the handles of the kept actions of unknown shape once, beside the handles they reference, and the guard tests the owner against that set. The exemption is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index c48648146..37388d550 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -1291,16 +1291,15 @@ pub(crate) fn finish( let entities: HashSet = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect(); // A dependency stays when an action of unknown form names it by group 330 or 360, or is its // owner. That action's list and count stay as read, and only the dangling target becomes null. - let unknown_refs: HashSet = f - .objects + // Each kept action is classified once, here. + let unknown_actions: Vec<&ForeignObject> = f.objects.iter().filter(|o| is_unknown_assoc_action(&o.tags)).collect(); + let unknown_handles: HashSet = unknown_actions.iter().map(|o| o.handle.hex()).collect(); + let unknown_refs: HashSet = unknown_actions .iter() - .filter(|o| is_unknown_assoc_action(&o.tags)) .flat_map(|o| o.tags.iter().take_while(|t| t.code < 1000).filter(|t| matches!(t.code, 330 | 360)).map(|t| norm(&t.value))) .collect(); - let in_unknown_action = |h: &str| { - unknown_refs.contains(h) - || own.get(h).cloned().flatten().and_then(|owner| objs.get(&owner)).is_some_and(|owner| is_unknown_assoc_action(&owner.tags)) - }; + let in_unknown_action = + |h: &str| unknown_refs.contains(h) || own.get(h).and_then(Option::as_deref).is_some_and(|owner| unknown_handles.contains(owner)); // Each pass that changes something drops at least one live object, so the loop ends. loop { let mut changed = false;