Skip to main content

brep_kernel/feature_pipeline/
parts_library.rs

1//! The per-document PARTS LIBRARY.
2//!
3//! Each unique part is stored ONCE per document: `{ sourceKey, sourceSignature,
4//! document (the embedded full sub-part history JSON), snapshot (the io/snapshot
5//! exact-BREP payload) }`, keyed by a document-unique part name. ACOMP instance
6//! features (`features/assembly_component.rs`) reference entries by name and
7//! carry NO payload of their own.
8//!
9//! # Residency and round-trip
10//!
11//! The library is KERNEL-RESIDENT state (thread-local, like the history cache):
12//! it is seeded through [`ingest`] (the `partsLibrary` block of a history
13//! request) or [`install_parts_library`] (the app → runner channel), mutated
14//! through [`add_part_to_library`] / [`refresh_library_entry`], and serialized
15//! for SAVE via [`parts_library_json`] — save must serialize THIS, never echo
16//! the loaded block, or healed snapshots and refreshes are lost. It clears
17//! with `clear_history_cache` (document-switch semantics).
18//!
19//! Ingest rule (stale request blocks must never undo kernel-side state): a
20//! RESIDENT entry always wins — a request echoing the block the document
21//! LOADED with predates any heal/refresh, so the block only FILLS names
22//! missing from the store.
23//!
24//! # Two seeding doors, and why they differ
25//!
26//! [`ingest`] is fill-only because it is fed by a *possibly stale echo*. The
27//! app's history runner runs OFF the caller's thread (a native thread or a
28//! browser worker), so it owns a SEPARATE store that must be kept in step with
29//! the app's — and re-sending the whole block on every run is what made a
30//! large assembly freeze the browser UI (each run stringified megabytes of
31//! payload on the main thread). The app therefore sends the library only when
32//! it CHANGES, over [`install_parts_library`], which is a *replace by content
33//! identity*: it may drop and replace, not merely fill. Two guards keep that
34//! safe — [`parts_library_revision`] tells the sender when to re-send, and
35//! [`missing_library_parts`] lets the receiver refuse a run whose parts it
36//! cannot resolve (the orphan GC below can drop entries the sender still
37//! believes are resident).
38//!
39//! # Orphan GC
40//!
41//! At the end of every `execute_history` run, entries whose part name is
42//! referenced by NO ACOMP feature in the request are dropped — orphaned
43//! payloads never accumulate in the file. (The insert flow must therefore add
44//! the ACOMP feature to the history before triggering another rebuild.)
45//!
46//! # Isolated sub-part execution
47//!
48//! [`rebuild_snapshot`] executes an embedded part document HEADLESSLY to
49//! (re)produce its snapshot — the [`add_part_to_library`] insert path and the
50//! ACOMP self-heal lane. It deliberately does NOT recurse into
51//! `execute_history`: the history cache's `retain(request_ids)` prologue would
52//! free every PARENT feature's cached handles mid-run. Instead it walks the
53//! sub-document's features through `execute_feature` with a local scene,
54//! brackets the scene-metadata store (the sub-part's un-namespaced records must
55//! never touch the parent document's), pushes the sub-document's OWN
56//! `partsLibrary` as the active library (parent and child libraries are
57//! independent), and frees every handle it registered before returning.
58
59use serde::{Deserialize, Serialize};
60use std::cell::RefCell;
61use std::collections::BTreeMap;
62
63use crate::feature_pipeline::component::NestedConstraint;
64use crate::feature_pipeline::{
65    execute_feature, scene_metadata, sheet_metal, Env, FeatureDescriptor, HistoryRequest,
66    PortRecord, SceneMap,
67};
68use crate::BrepSolid;
69use wasm_bindgen::prelude::*;
70
71// ===========================================================================
72// The entry + the resident stores
73// ===========================================================================
74
75/// One unique part payload. `dirty` is RESIDENT-ONLY state: set by
76/// [`refresh_library_entry`] (edit-in-context / update-components) when the
77/// new document builds differently, it forces the ACOMP self-heal lane on the
78/// next run even with a readable snapshot, and clears when the heal rewrites
79/// the snapshot.
80#[derive(Debug, Clone, Default, Serialize, Deserialize)]
81pub struct PartsLibraryEntry {
82    #[serde(rename = "sourceKey", default)]
83    pub source_key: String,
84    #[serde(rename = "sourceSignature", default)]
85    pub source_signature: String,
86    /// The embedded full sub-part history JSON — the durable source the
87    /// self-heal lane re-executes when the snapshot cache fails.
88    #[serde(default)]
89    pub document: serde_json::Value,
90    /// The evaluated part as an `io/snapshot` payload (the fast lane).
91    #[serde(default)]
92    pub snapshot: String,
93    /// The kernel build that produced `snapshot` ([`kernel_source_stamp`]).
94    ///
95    /// A snapshot is a CACHE of evaluated geometry, and it is only as current as
96    /// the code that evaluated it. Before this stamp an entry was served for as
97    /// long as it decoded, so a document kept the geometry of whichever kernel
98    /// first inserted the part, whatever the kernel had learned since: the
99    /// `AssemblyTest` fixture decoded 1859.122725 where a rebuild of its own
100    /// document gives 1859.151146, and the stale body failed the shell
101    /// vector-area bar at 4.7x. An entry whose stamp differs from the running
102    /// build — including one with no stamp — is rebuilt by the ACOMP lane.
103    /// Carried beside the snapshot rather than inside the `BREPSNAP` container,
104    /// whose layout is a durable format (see `io/snapshot.rs`).
105    #[serde(rename = "snapshotProducer", default, skip_serializing_if = "String::is_empty")]
106    pub snapshot_producer: String,
107    /// The part's harness ports (part-local id -> record, part-local pose),
108    /// captured from the same run as the snapshot. Derived like the snapshot:
109    /// an entry whose document declares a PORT but carries none is healed.
110    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
111    pub ports: BTreeMap<String, PortRecord>,
112    #[serde(skip)]
113    pub dirty: bool,
114    /// The statuses of the part's own assembly constraints and of every
115    /// sub-assembly below it, from the run that made `snapshot` (see
116    /// `NestedConstraint`). `None` means no run has happened in this session:
117    /// the rows are not saved, so an entry whose document carries constraints
118    /// is rebuilt once after a load (`needs_constraint_rows`) — the parent
119    /// must report how its sub-assembly's mates ended, not assume they solved.
120    #[serde(skip)]
121    pub nested_constraints: Option<Vec<NestedConstraint>>,
122    /// The solved occurrence poses of the same run, part-local frame (see
123    /// [`crate::feature_pipeline::ComponentRecord::nested_poses`]); kept and
124    /// cleared with `nested_constraints`.
125    #[serde(skip)]
126    pub nested_poses: BTreeMap<String, crate::AffineTransform>,
127    /// `nested_constraints` and `nested_poses` as SAVED beside the snapshot
128    /// (`SavedRows`): a loaded entry adopts them only under the snapshot's
129    /// own rule, so reopening a saved assembly takes the snapshot lane instead
130    /// of rebuilding every sub-assembly with mates to learn its rows again.
131    #[serde(rename = "nestedRows", default, skip_serializing_if = "Option::is_none")]
132    pub nested_rows: Option<SavedRows>,
133    /// Stable content hash of `document`, precomputed at insert/refresh/ingest
134    /// so the per-feature cache hook never re-hashes a large document.
135    #[serde(skip)]
136    pub doc_hash: u64,
137}
138
139/// The constraint rows and solved poses of the run that made an entry's
140/// snapshot, saved with it. Valid exactly when the snapshot is: the same
141/// `producer` (the kernel build that ran it, as `snapshot_producer`) and the
142/// same `document` (the stable hash, hex, of the entry's document then). An
143/// entry whose document was edited since, or that a different build snapshot,
144/// rebuilds as before. Additive and defaulted: an older file has none and
145/// rebuilds once, as before; an older build ignores the field.
146#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
147pub struct SavedRows {
148    pub producer: String,
149    pub document: String,
150    #[serde(default)]
151    pub constraints: Vec<NestedConstraint>,
152    /// Occurrence path -> part-local pose, row-major 4x4, each element as
153    /// its IEEE bits in hex: the parse here is not round-trip exact
154    /// (`serde_json` without `float_roundtrip` can land a 17-digit value one
155    /// ulp off), and a pose must come back bit for bit.
156    #[serde(default)]
157    pub poses: BTreeMap<String, Vec<String>>,
158}
159
160fn document_stamp(document: &serde_json::Value) -> String {
161    format!("{:016x}", stable_json_hash(document))
162}
163
164impl PartsLibraryEntry {
165    /// The rows of the run that just made this entry's snapshot, to save.
166    fn save_rows(&mut self) {
167        self.nested_rows = self.nested_constraints.as_ref().map(|constraints| SavedRows {
168            producer: self.snapshot_producer.clone(),
169            document: document_stamp(&self.document),
170            constraints: constraints.clone(),
171            poses: self
172                .nested_poses
173                .iter()
174                .map(|(path, pose)| (path.clone(), pose.elements.iter().map(|e| format!("{:016x}", e.to_bits())).collect()))
175                .collect(),
176        });
177    }
178
179    /// Take the saved rows of a loaded entry when they are still its
180    /// snapshot's: same producer as the snapshot and as this build, and the
181    /// document they were taken from.
182    fn adopt_saved_rows(&mut self) {
183        if self.nested_constraints.is_some() || self.snapshot.is_empty() {
184            return;
185        }
186        let Some(rows) = &self.nested_rows else { return };
187        // An unstamped build cannot tell one solver from another: rows it
188        // saved are rebuilt rather than trusted.
189        let same_build = !rows.producer.is_empty()
190            && rows.producer == self.snapshot_producer
191            && kernel_source_stamp().is_none_or(|stamp| stamp == rows.producer);
192        // `doc_hash` is the stable hash of `document`: every load door sets
193        // it just before adopting.
194        if !same_build || rows.document != format!("{:016x}", self.doc_hash) {
195            return;
196        }
197        let mut poses = BTreeMap::new();
198        for (path, hex) in &rows.poses {
199            let bits: Option<Vec<f64>> =
200                hex.iter().map(|h| u64::from_str_radix(h, 16).ok().map(f64::from_bits)).collect();
201            let Some(Ok(elements)) = bits.map(|b| <[f64; 16]>::try_from(b)) else { return };
202            let Ok(pose) = crate::AffineTransform::new(elements) else { return };
203            poses.insert(path.clone(), pose);
204        }
205        self.nested_constraints = Some(rows.constraints.clone());
206        self.nested_poses = poses;
207    }
208
209    /// Invalidate derived data when the document builds a different part.
210    /// `dirty` alone cannot carry this across a save or runner transfer: it is
211    /// serde-skipped, and a fresh receiver has no previous document to compare.
212    /// A blank snapshot makes that receiver take the self-heal lane too.
213    fn invalidate_snapshot(&mut self) {
214        self.snapshot.clear();
215        self.snapshot_producer.clear();
216        self.ports.clear();
217        self.dirty = true;
218        self.nested_constraints = None;
219        self.nested_poses.clear();
220        self.nested_rows = None;
221    }
222}
223
224/// The library map shape as it travels in the history request / save file.
225pub type PartsLibraryMap = BTreeMap<String, PartsLibraryEntry>;
226
227/// This build's identity for [`PartsLibraryEntry::snapshot_producer`]: the hash
228/// of the kernel source that `build.rs` computes. `None` when the build could
229/// not compute it, which disables stale-snapshot invalidation rather than
230/// making every snapshot look stale on every run.
231pub fn kernel_source_stamp() -> Option<&'static str> {
232    static STAMP: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
233    STAMP.get_or_init(|| crate::combined_source_stamp(crate::KERNEL_SOURCE_HASHES)).as_deref()
234}
235
236/// Whether `entry`'s snapshot was made by another kernel build (and its
237/// document has not changed since: a dirty entry rebuilds for that reason).
238pub(crate) fn snapshot_is_stale(entry: &PartsLibraryEntry) -> bool {
239    !entry.dirty && kernel_source_stamp().is_some_and(|stamp| entry.snapshot_producer != stamp)
240}
241
242thread_local! {
243    /// The run in progress shows a stale part from its stored snapshot
244    /// instead of rebuilding it ([`HistoryRequest::defer_stale_parts`]). Set
245    /// for a whole top-level run, so the isolated part runs inside it (which
246    /// never re-enter `execute_history`) follow the same rule.
247    static DEFER_STALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
248    /// The parts the run in progress showed from a stale snapshot.
249    static STALE_SHOWN: RefCell<std::collections::BTreeSet<String>> = const { RefCell::new(std::collections::BTreeSet::new()) };
250}
251
252/// The deferred-stale mode for one top-level run: set on entry, put back on
253/// drop; the parts it showed stale are read by [`Self::finish`].
254pub(crate) struct DeferStaleScope {
255    previous: bool,
256}
257
258impl DeferStaleScope {
259    pub(crate) fn enter(defer: bool) -> Self {
260        STALE_SHOWN.with(|shown| shown.borrow_mut().clear());
261        Self { previous: DEFER_STALE.with(|flag| flag.replace(defer)) }
262    }
263
264    /// The parts this run showed from a snapshot of another kernel build.
265    pub(crate) fn finish(&self) -> Vec<String> {
266        STALE_SHOWN.with(|shown| std::mem::take(&mut *shown.borrow_mut()).into_iter().collect())
267    }
268}
269
270impl Drop for DeferStaleScope {
271    fn drop(&mut self) {
272        DEFER_STALE.with(|flag| flag.set(self.previous));
273    }
274}
275
276/// Whether the run in progress defers stale parts (see [`DeferStaleScope`]).
277pub(crate) fn defer_stale() -> bool {
278    DEFER_STALE.with(std::cell::Cell::get)
279}
280
281/// Record that the run showed `part_name` from a stale snapshot.
282pub(crate) fn note_stale_shown(part_name: &str) {
283    STALE_SHOWN.with(|shown| {
284        shown.borrow_mut().insert(part_name.to_string());
285    });
286}
287
288/// The constraint rows and poses saved with a stale snapshot, taken although
289/// another build made them, when they still describe the entry's document: a
290/// stale part shown as it was stored shows the rows stored with it. Empty
291/// otherwise (the revalidating run solves them).
292pub(crate) fn stale_saved_rows(
293    entry: &PartsLibraryEntry,
294) -> (Vec<NestedConstraint>, BTreeMap<String, crate::AffineTransform>) {
295    let Some(rows) = &entry.nested_rows else { return Default::default() };
296    if rows.document != format!("{:016x}", entry.doc_hash) {
297        return Default::default();
298    }
299    let mut poses = BTreeMap::new();
300    for (path, hex) in &rows.poses {
301        let bits: Option<Vec<f64>> = hex.iter().map(|h| u64::from_str_radix(h, 16).ok().map(f64::from_bits)).collect();
302        let Some(Ok(elements)) = bits.map(|b| <[f64; 16]>::try_from(b)) else { return Default::default() };
303        let Ok(pose) = crate::AffineTransform::new(elements) else { return Default::default() };
304        poses.insert(path.clone(), pose);
305    }
306    (rows.constraints.clone(), poses)
307}
308
309thread_local! {
310    /// The open document's library (the ROOT store).
311    static ROOT: RefCell<PartsLibraryMap> = RefCell::new(BTreeMap::new());
312    /// Active-library stack for isolated sub-document runs: a nested ACOMP
313    /// resolves against ITS document's library, never the parent's.
314    static STACK: RefCell<Vec<PartsLibraryMap>> = const { RefCell::new(Vec::new()) };
315    /// Monotonic REVISION of the ROOT store, bumped by every mutation that
316    /// actually CHANGES it (insert, refresh, heal, GC drop, install, clear).
317    /// The app polls it to decide whether a background runner's resident copy
318    /// is stale — the library no longer rides on every history request, so
319    /// this counter is what tells the app when to re-send it. Thread-local
320    /// like the store itself: main and each runner count their own store.
321    static REVISION: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
322}
323
324/// Record that the ROOT store changed. Call it from EVERY mutation that
325/// actually alters content — never speculatively: `ingest` and
326/// `gc_after_rebuild` run on every history run, so an unconditional bump there
327/// would make the app re-send the whole library every edit, which is the cost
328/// this counter exists to avoid.
329fn bump_revision() {
330    REVISION.with(|revision| revision.set(revision.get().wrapping_add(1)));
331}
332
333/// The ROOT store's current revision (see `REVISION`). Two reads that differ
334/// mean the library changed in between; two that agree mean it did not.
335pub fn parts_library_revision() -> u64 {
336    REVISION.with(std::cell::Cell::get)
337}
338
339/// Stable content hash of a JSON value: sorted-key walk (never trusts a
340/// serializer's map ordering), string leaves verbatim.
341pub fn stable_json_hash(value: &serde_json::Value) -> u64 {
342    use std::hash::{Hash, Hasher};
343    fn walk(value: &serde_json::Value, hasher: &mut impl Hasher) {
344        match value {
345            serde_json::Value::Null => 0u8.hash(hasher),
346            serde_json::Value::Bool(flag) => {
347                1u8.hash(hasher);
348                flag.hash(hasher);
349            }
350            serde_json::Value::Number(number) => {
351                2u8.hash(hasher);
352                number.to_string().hash(hasher);
353            }
354            serde_json::Value::String(text) => {
355                3u8.hash(hasher);
356                text.hash(hasher);
357            }
358            serde_json::Value::Array(items) => {
359                4u8.hash(hasher);
360                for item in items {
361                    walk(item, hasher);
362                }
363            }
364            serde_json::Value::Object(map) => {
365                5u8.hash(hasher);
366                let mut keys: Vec<&String> = map.keys().collect();
367                keys.sort();
368                for key in keys {
369                    key.hash(hasher);
370                    walk(&map[key], hasher);
371                }
372            }
373        }
374    }
375    let mut hasher = std::collections::hash_map::DefaultHasher::new();
376    walk(value, &mut hasher);
377    hasher.finish()
378}
379
380/// Read the entry for a part name from the ACTIVE library: the innermost
381/// isolated-run library when one is pushed, else the root store.
382pub(crate) fn active_entry(part_name: &str) -> Option<PartsLibraryEntry> {
383    STACK.with(|stack| {
384        let stack = stack.borrow();
385        if let Some(top) = stack.last() {
386            return top.get(part_name).cloned();
387        }
388        ROOT.with(|root| root.borrow().get(part_name).cloned())
389    })
390}
391
392/// Write a healed snapshot back into the ACTIVE library entry and clear its
393/// dirty flag. A heal inside an isolated run updates the pushed (temporary)
394/// library only — the parent entry's embedded document is NOT rewritten (its
395/// re-snapshot bakes the healed geometry anyway; the stale inner snapshot heals
396/// again on the next full sub-document run).
397pub(crate) fn heal_entry(part_name: &str, rebuilt: &RebuiltPart) {
398    let heal = |map: &mut PartsLibraryMap| {
399        if let Some(entry) = map.get_mut(part_name) {
400            entry.snapshot = rebuilt.snapshot.clone();
401            entry.snapshot_producer = kernel_source_stamp().unwrap_or_default().to_string();
402            entry.ports = rebuilt.ports.clone();
403            entry.nested_constraints = Some(rebuilt.nested_constraints.clone());
404            entry.nested_poses = rebuilt.nested_poses.clone();
405            entry.save_rows();
406            entry.dirty = false;
407        }
408    };
409    STACK.with(|stack| {
410        let mut stack = stack.borrow_mut();
411        if let Some(top) = stack.last_mut() {
412            heal(top);
413        } else {
414            ROOT.with(|root| heal(&mut root.borrow_mut()));
415            // A heal rewrites a ROOT entry's snapshot, so the store changed.
416            // (It does NOT change the entry's content IDENTITY — see
417            // `install` — so re-sending a healed library never clobbers a
418            // runner's own, independently-derived heal.)
419            bump_revision();
420        }
421    });
422}
423
424/// Drop the whole library (document switch — wired into `clear_history_cache`).
425pub(crate) fn clear_all() {
426    let had_entries = ROOT.with(|root| {
427        let mut root = root.borrow_mut();
428        let had = !root.is_empty();
429        root.clear();
430        had
431    });
432    STACK.with(|stack| stack.borrow_mut().clear());
433    if had_entries {
434        bump_revision();
435    }
436}
437
438// ===========================================================================
439// execute_history hooks: ingest, cache fingerprint, GC
440// ===========================================================================
441
442/// The ACOMP dispatch predicate — shared by the fingerprint hook, the GC scan,
443/// and (as adjacent literals) the `execute_feature` match arm, so they can
444/// never disagree on what counts as a component instance.
445pub(crate) fn is_acomp_type(feature_type: &str) -> bool {
446    matches!(feature_type, "ACOMP" | "ASSEMBLY COMPONENT")
447}
448
449/// Merge a request's `partsLibrary` block into the root store (start of every
450/// `execute_history` run — this is how a LOADED document seeds the library).
451/// A RESIDENT entry always wins: mid-session the kernel store is the source of
452/// truth (it carries heals, refreshes, and pending-dirty state the request's
453/// echo of the loaded block predates); the block only ever FILLS missing names
454/// (document load starts from an empty store, cleared by `clear_history_cache`).
455pub(crate) fn ingest(request_map: &PartsLibraryMap) {
456    if request_map.is_empty() {
457        return;
458    }
459    let seeded = ROOT.with(|root| {
460        let mut root = root.borrow_mut();
461        let mut seeded = false;
462        for (name, incoming) in request_map {
463            if root.contains_key(name) {
464                continue;
465            }
466            let mut entry = incoming.clone();
467            // A loaded block's entry gets the same stamp as an inserted one, so a
468            // document saved before per-loop ids existed picks them up on open.
469            stamp_document_loop_ids(&mut entry.document);
470            entry.doc_hash = stable_json_hash(&entry.document);
471            // A document saved before parts carried their ports heals once.
472            entry.dirty = needs_port_heal(&entry);
473            entry.adopt_saved_rows();
474            root.insert(name.clone(), entry);
475            seeded = true;
476        }
477        seeded
478    });
479    if seeded {
480        bump_revision();
481    }
482}
483
484/// Whether an entry must heal to pick up its connection points: its document
485/// declares some (at any depth — a nested assembly's parts count) but the entry
486/// carries no records, i.e. it was captured before they existed.
487fn needs_port_heal(entry: &PartsLibraryEntry) -> bool {
488    entry.ports.is_empty() && document_declares_ports(&entry.document)
489}
490
491/// Whether an entry must be rebuilt for its constraint rows: its document — or
492/// a sub-assembly it embeds — carries assembly constraints, and no run in this
493/// session has reported them ([`PartsLibraryEntry::nested_constraints`]).
494pub(crate) fn needs_constraint_rows(entry: &PartsLibraryEntry) -> bool {
495    entry.nested_constraints.is_none() && document_has_constraints(&entry.document)
496}
497
498/// Whether `document`, or a library entry it embeds at any depth, has a
499/// non-empty `assembly.constraints` list.
500fn document_has_constraints(document: &serde_json::Value) -> bool {
501    let own = document
502        .get("assembly")
503        .and_then(|block| block.get("constraints"))
504        .and_then(serde_json::Value::as_array)
505        .is_some_and(|constraints| !constraints.is_empty());
506    own || document
507        .get("partsLibrary")
508        .and_then(serde_json::Value::as_object)
509        .is_some_and(|library| {
510            library
511                .values()
512                .filter_map(|entry| entry.get("document"))
513                .any(document_has_constraints)
514        })
515}
516
517/// Whether `document` — or a library entry it embeds — declares a connection
518/// point or a WAYPOINT, the two things that put a record in `scene.ports`.
519fn document_declares_ports(document: &serde_json::Value) -> bool {
520    match document {
521        serde_json::Value::Object(map) => {
522            map.get(crate::feature_pipeline::ports::PORTS_BLOCK)
523                .and_then(serde_json::Value::as_array)
524                .is_some_and(|block| !block.is_empty())
525                || matches!(
526                    map.get("type").and_then(serde_json::Value::as_str),
527                    Some("WP" | "WAYPOINT")
528                )
529                || map.values().any(document_declares_ports)
530        }
531        serde_json::Value::Array(items) => items.iter().any(document_declares_ports),
532        _ => false,
533    }
534}
535
536/// The CONTENT IDENTITY of an entry: what makes two entries the same PART.
537/// `snapshot` is deliberately excluded — a heal re-derives the snapshot from
538/// the same `document`, so it must not read as a different part. This is the
539/// same identity [`mix_descriptor_fingerprint`] mixes into an ACOMP's cache
540/// fingerprint, so "install kept the resident entry" and "the instance
541/// replayed from cache" can never disagree.
542fn identity(entry: &PartsLibraryEntry) -> (&str, &str, u64) {
543    (&entry.source_key, &entry.source_signature, entry.doc_hash)
544}
545
546/// INSTALL a library wholesale — the app → history-runner channel (the runner
547/// owns its own thread-local store, and the per-run request no longer carries
548/// the block, so this is how a background thread/worker learns the library).
549///
550/// Unlike `ingest` (fill-only, resident-wins) this makes the store MATCH
551/// `incoming` BY CONTENT IDENTITY, which is what a cache channel needs:
552///
553/// * a name missing from the store is inserted (stamped + hashed like ingest);
554/// * a name whose resident entry has the SAME identity is KEPT VERBATIM — that
555///   is what protects a runner-side heal, whose only trace is a rewritten
556///   `snapshot`, from being clobbered by a re-send;
557/// * a name whose resident entry has a DIFFERENT identity but the SAME build
558///   ([`same_build`]: only the symbol, pads or BOM attributes moved) is
559///   REPLACED with the resident snapshot and ports carried over — they still
560///   describe the part, so nothing is rebuilt;
561/// * a name whose resident entry builds DIFFERENTLY is REPLACED and marked
562///   `dirty`, so the ACOMP self-heal lane re-derives every instance (`dirty` is
563///   `#[serde(skip)]` and cannot ride the wire — it is derived HERE, from the
564///   mismatch);
565/// * a resident name ABSENT from `incoming` is dropped.
566///
567/// Returns whether anything changed (and bumps the revision if so).
568pub fn install_parts_library(incoming: &PartsLibraryMap) -> bool {
569    let mut changed = false;
570    ROOT.with(|root| {
571        let mut root = root.borrow_mut();
572        root.retain(|name, _| {
573            let keep = incoming.contains_key(name);
574            changed |= !keep;
575            keep
576        });
577        for (name, entry) in incoming {
578            let mut document = entry.document.clone();
579            stamp_document_loop_ids(&mut document);
580            let doc_hash = stable_json_hash(&document);
581            // Same part: keep the RESIDENT copy — it may carry a heal this
582            // side derived and the sender never saw. Decided on the document
583            // alone, so a kept entry is neither cloned nor derived.
584            if root.get(name).is_some_and(|resident| {
585                identity(resident) == (entry.source_key.as_str(), entry.source_signature.as_str(), doc_hash)
586            }) {
587                continue;
588            }
589            let mut entry = PartsLibraryEntry { document, doc_hash, ..entry.clone() };
590            entry.dirty = needs_port_heal(&entry);
591            entry.adopt_saved_rows();
592            match root.get(name) {
593                // A new version that builds the same (a symbol, pads or BOM
594                // attribute edit): take its document and signature, but the
595                // resident snapshot and ports still describe it — keep them, and
596                // any heal they carry, rather than rebuilding the part.
597                Some(resident) if same_stamped_build(&resident.document, &entry.document) => {
598                    entry.snapshot = resident.snapshot.clone();
599                    entry.snapshot_producer = resident.snapshot_producer.clone();
600                    entry.ports = resident.ports.clone();
601                    // The resident's rows, else the ones this entry just adopted.
602                    if resident.nested_constraints.is_some() {
603                        entry.nested_constraints = resident.nested_constraints.clone();
604                        entry.nested_poses = resident.nested_poses.clone();
605                    }
606                    // The same build of a new document: the rows still describe it.
607                    entry.save_rows();
608                    entry.dirty = resident.dirty || needs_port_heal(&entry);
609                }
610                // Genuinely different content: replace, and force the self-heal
611                // lane so every instance follows the new document.
612                Some(_) => entry.invalidate_snapshot(),
613                None => {}
614            }
615            root.insert(name.clone(), entry);
616            changed = true;
617        }
618    });
619    if changed {
620        bump_revision();
621    }
622    changed
623}
624
625/// A CLONE of the root store — what the app hands a runner through
626/// [`install_parts_library`]. (`parts_library_json` is the SAVE door; this is
627/// the in-process one, with no JSON round trip on the native paths.)
628pub fn parts_library_map() -> PartsLibraryMap {
629    ROOT.with(|root| root.borrow().clone())
630}
631
632/// The PREFLIGHT for a run: every part name the request's ACOMP features
633/// reference that the root store cannot resolve, in request order.
634///
635/// A background runner calls this BEFORE executing a run and refuses the run
636/// when it is non-empty. That is the drift-proof half of the library channel:
637/// the orphan GC at the end of every run can legitimately drop entries the
638/// sender still believes are resident (undo to zero components GCs the runner's
639/// store while the sender's store, which never ran, keeps them), and no
640/// revision bookkeeping can see that. Missing CONTENT is observable; that is
641/// what this checks.
642pub fn missing_library_parts(request: &HistoryRequest) -> Vec<String> {
643    let mut missing = Vec::new();
644    ROOT.with(|root| {
645        let root = root.borrow();
646        for descriptor in &request.features {
647            if !is_acomp_type(&descriptor.feature_type) {
648                continue;
649            }
650            let Some(name) = descriptor
651                .input_params
652                .get("partName")
653                .and_then(|value| value.as_str())
654                .map(str::trim)
655                .filter(|name| !name.is_empty())
656            else {
657                continue;
658            };
659            if !root.contains_key(name) && !missing.iter().any(|seen| seen == name) {
660                missing.push(name.to_string());
661            }
662        }
663    });
664    missing
665}
666
667/// The history-cache hook for one descriptor: mix the referenced library
668/// entry's CONTENT identity (source key/signature/document hash — snapshot
669/// deliberately excluded, a heal must not dirty the instance) into the
670/// feature fingerprint, and report whether a DIRTY entry forces re-execution.
671/// Non-ACOMP descriptors pass through untouched.
672pub(crate) fn mix_descriptor_fingerprint(
673    descriptor: &FeatureDescriptor,
674    fingerprint: u64,
675) -> (u64, bool) {
676    if !is_acomp_type(&descriptor.feature_type) {
677        return (fingerprint, false);
678    }
679    use std::hash::{Hash, Hasher};
680    let mut hasher = std::collections::hash_map::DefaultHasher::new();
681    fingerprint.hash(&mut hasher);
682    let part_name = descriptor
683        .input_params
684        .get("partName")
685        .and_then(|value| value.as_str())
686        .unwrap_or("");
687    part_name.hash(&mut hasher);
688    let mut force_dirty = false;
689    match active_entry(part_name) {
690        Some(entry) => {
691            1u8.hash(&mut hasher);
692            entry.source_key.hash(&mut hasher);
693            entry.source_signature.hash(&mut hasher);
694            entry.doc_hash.hash(&mut hasher);
695            force_dirty = entry.dirty || super::extension::document_uses_extensions(&entry.document);
696            // A stale part shown from its snapshot is not what a rebuild
697            // makes: the run that revalidates it must not replay this entry.
698            // Mixed only then (an entry with no snapshot is rebuilt in this
699            // very run), so every other fingerprint is unchanged.
700            if defer_stale() && snapshot_is_stale(&entry) && !entry.snapshot.is_empty() {
701                "stale-shown".hash(&mut hasher);
702            }
703        }
704        None => 0u8.hash(&mut hasher),
705    }
706    (hasher.finish(), force_dirty)
707}
708
709/// Orphan GC (end of every `execute_history` run): retain only entries some
710/// ACOMP feature in the REQUEST references (the request always carries the full
711/// feature list — editor stop points truncate execution, not the list).
712pub(crate) fn gc_after_rebuild(request: &HistoryRequest) {
713    let referenced: std::collections::BTreeSet<String> = request
714        .features
715        .iter()
716        .filter(|descriptor| is_acomp_type(&descriptor.feature_type))
717        .filter_map(|descriptor| {
718            descriptor
719                .input_params
720                .get("partName")
721                .and_then(|value| value.as_str())
722                .map(|name| name.trim().to_string())
723        })
724        .collect();
725    let dropped = ROOT.with(|root| {
726        let mut root = root.borrow_mut();
727        let before = root.len();
728        root.retain(|name, _| referenced.contains(name));
729        before != root.len()
730    });
731    if dropped {
732        bump_revision();
733    }
734}
735
736// ===========================================================================
737// Isolated sub-part execution (the self-heal / insert lane)
738// ===========================================================================
739
740/// Execute an embedded part document headlessly and return its surviving
741/// solids as PART-LOCAL `(scene name, owned BREP)` pairs in history order.
742/// Never touches the history cache or the parent scene; every handle it
743/// registers is freed before returning. See the module doc for why this must
744/// not recurse into `execute_history`.
745fn run_isolated_document(
746    document: &serde_json::Value,
747    pmi: Option<&mut Option<crate::feature_pipeline::pmi::PmiReport>>,
748) -> Result<IsolatedRun, String> {
749    let mut request: HistoryRequest = serde_json::from_value(document.clone())
750        .map_err(|error| format!("embedded part document does not parse: {error}"))?;
751    // A stale editor stop point saved into a library part must not silently
752    // truncate the part on every heal.
753    request.stop_at_id = None;
754    request.stop_before_id = None;
755
756    // The sub-document's own library is the active one for this run (a nested
757    // assembly's ACOMPs resolve against it; missing entries are clean errors,
758    // never a fallback to the parent's library). Its entries arrive raw from
759    // the JSON, so the port heal is decided here as `ingest` decides it for a
760    // loaded document — an inner part saved before parts carried their ports
761    // must not take the fast lane and publish none.
762    STACK.with(|stack| {
763        let mut library = std::mem::take(&mut request.parts_library);
764        for entry in library.values_mut() {
765            entry.dirty = needs_port_heal(entry);
766        }
767        stack.borrow_mut().push(library);
768    });
769    let electronics_part = ["symbol", "pads"]
770        .iter()
771        .any(|key| document.get(*key).is_some_and(serde_json::Value::is_object))
772        || !request.ports.is_empty();
773    let outcome = run_isolated_features(
774        &request,
775        pmi,
776        electronics_part,
777        crate::feature_pipeline::ports::document_is_boundary(document),
778    );
779    STACK.with(|stack| {
780        stack.borrow_mut().pop();
781    });
782    outcome
783}
784
785/// The feature walk of [`run_isolated_document`], separated so the library
786/// stack push/pop brackets every exit path.
787/// What an isolated part run yields: the surviving solids (part-local names,
788/// history order), the part's ports (part-local ids, part-local pose) and the
789/// statuses of its assembly constraints (part-local ids, every level below
790/// included) and the solved pose of every occurrence it places, at any depth
791/// (part-local frame).
792type IsolatedRun = (
793    Vec<(String, BrepSolid)>,
794    BTreeMap<String, PortRecord>,
795    Vec<NestedConstraint>,
796    BTreeMap<String, crate::AffineTransform>,
797);
798
799fn run_isolated_features(
800    request: &HistoryRequest,
801    pmi: Option<&mut Option<crate::feature_pipeline::pmi::PmiReport>>,
802    electronics_part: bool,
803    boundary: bool,
804) -> Result<IsolatedRun, String> {
805    let _plugin_scope = super::extension::enter(&request.plugins);
806    let env = Env::build(&request.expressions, &request.configurator).unwrap_or_else(Env::poisoned);
807    let mut scene = SceneMap::default();
808    // The same pre-walk seed `execute_history` does (see `ports.rs`): a part's
809    // own spline must attach to its own connection point on this lane too.
810    // Nothing here caches, so the versions are dropped.
811    crate::feature_pipeline::ports::seed_history_run(request, &mut scene, &env);
812    let mut results = Vec::with_capacity(request.features.len());
813    let mut all_handles: Vec<u32> = Vec::new();
814    let mut error: Option<String> = None;
815    for descriptor in &request.features {
816        let result = execute_feature(descriptor, &env, &scene);
817        scene.apply(&result);
818        all_handles.extend(result.added.iter().map(|added| added.handle));
819        // Replicate the loop's producer stamp so the snapshot carries the same
820        // topology metadata a real history run would have written.
821        if !result.id.is_empty() {
822            let mut seed = serde_json::Map::new();
823            seed.insert(
824                "sourceFeatureId".into(),
825                serde_json::Value::String(result.id.clone()),
826            );
827            for added in &result.added {
828                for (_, face_name) in &added.face_names {
829                    scene_metadata::merge_record(face_name, &seed, false);
830                }
831                for (_, edge_name) in &added.edge_names {
832                    scene_metadata::merge_record(edge_name, &seed, false);
833                }
834            }
835        }
836        if let Some(message) = &result.error {
837            error = Some(format!("feature '{}': {message}", result.id));
838            break;
839        }
840        results.push(result);
841    }
842
843    // A sub-assembly is RIGID to its parent: its own constraints solve here,
844    // inside its own run, so the snapshot bakes the solved poses and the
845    // parent's mates then place it as one body (the NX / SolidWorks default).
846    // Same lifecycle `execute_history` runs, NOT its `finish_history_run`,
847    // which would replace the live assembly session in the middle of the
848    // parent's run. It re-poses members under their existing handles, so it
849    // has to run before the survivors are cloned out of the registry, and
850    // before the ports tail so the declared points follow the solved poses.
851    let mut nested_constraints = Vec::new();
852    let mut nested_poses = BTreeMap::new();
853    if error.is_none() {
854        if let Some(state) = request.assembly.as_ref().filter(|state| !state.constraints.is_empty()) {
855            let weld_poses = super::capture_weld_poses(request, &results, &scene);
856            let mut state = state.clone();
857            crate::feature_pipeline::assembly::lifecycle::run_constraints(&mut state, &mut scene, &env);
858            // A weld rebuilt after the solve frees its old bead and owns a new
859            // one: the free loop below must follow the swap.
860            let weld_handles = |results: &[super::FeatureResult]| -> Vec<u32> {
861                results.iter().filter(|result| result.feature_type == "WELD")
862                    .flat_map(|result| result.added.iter().map(|added| added.handle)).collect()
863            };
864            let before = weld_handles(&results);
865            super::pose_weld_outputs(request, &env, &mut results, &mut scene, weld_poses);
866            let after = weld_handles(&results);
867            all_handles.retain(|handle| !before.contains(handle) || after.contains(handle));
868            all_handles.extend(after.iter().filter(|handle| !before.contains(handle)));
869            if let Some(failed) = results.iter().find(|result| result.error.is_some()) {
870                error = Some(format!("feature '{}': {}", failed.id, failed.error.as_deref().unwrap()));
871            }
872            nested_constraints.extend(state.constraints.iter().map(NestedConstraint::from_entry));
873        }
874        // Every level below arrives on the component records, namespaced by
875        // the ACOMP that placed it.
876        for record in scene.components.values() {
877            nested_constraints.extend(record.nested_constraints.iter().cloned());
878            // Where every occurrence ended up, in THIS document's frame: the
879            // solved record pose, and each deeper occurrence composed onto it.
880            nested_poses.insert(record.id.clone(), record.transform);
881            // (No `?`: the registered handles are freed below on every path;
882            // both poses are rigid, so the compose cannot fail.)
883            for (path, pose) in &record.nested_poses {
884                if let Ok(posed) = crate::feature_pipeline::component::compose(&record.transform, pose) {
885                    nested_poses.insert(crate::feature_pipeline::component::namespaced(&record.id, path), posed);
886                }
887            }
888        }
889    }
890
891    // Survivors: added solids still scene-resident under their own name, in
892    // history order (a consumed/superseded solid's name no longer maps to it).
893    let mut members = Vec::new();
894    if error.is_none() {
895        for result in &results {
896            for added in &result.added {
897                if scene.resolve_solid(&added.name) == Some(added.handle) {
898                    let solid =
899                        crate::with_registered_solid_str(added.handle, |solid| Ok(solid.clone()))?;
900                    members.push((added.name.clone(), solid));
901                }
902            }
903        }
904    }
905    // The document's own PMI, resolved while its solids are still RESIDENT —
906    // every reference resolves through the registry, so the tail has to run
907    // before the free loop below. Plugin annotations must also resolve during
908    // snapshot rebuild: unavailable providers cannot silently pass as fresh parts.
909    let has_plugin_annotations = request.pmi.as_ref().is_some_and(|state|
910        state.views.iter().flat_map(|v| &v.annotations).any(|a| a.enabled && a.kind.contains('/')));
911    if pmi.is_some() || has_plugin_annotations {
912        let report = crate::feature_pipeline::pmi::finish_history_run(request, &scene, &env);
913        if let Some(row) = report.as_ref().into_iter().flat_map(|r| &r.views)
914            .flat_map(|v| &v.annotations)
915            .find(|a| a.enabled && a.kind.contains('/') && a.status == crate::feature_pipeline::pmi::PmiStatus::Error)
916        {
917            if error.is_none() { error = Some(format!("annotation '{}': {}", row.id, row.message)); }
918        }
919        if let Some(out) = pmi { *out = report; }
920    }
921    // The document's own declared ports, resolved here for the same reason the
922    // PMI is: a point may reference the part's geometry, and the geometry is
923    // only resident until the free loop below. This is the one place a part's
924    // connection points are captured, so the tail HAS to run on this lane too —
925    // without it every placed part would arrive with an empty port map.
926    let declared: Vec<String> = crate::feature_pipeline::ports::finish_history_run(
927        request,
928        &mut scene,
929        &env,
930    )
931    .report
932    .map(|report| report.points.into_iter().map(|row| row.address).collect())
933    .unwrap_or_default();
934    for handle in all_handles {
935        sheet_metal::remove_tree(handle);
936        crate::free_registered_solid(handle);
937    }
938    // The part's connection points: every record the run left in the scene (a
939    // nested assembly's component points are already namespaced by its ACOMPs),
940    // through the ENCAPSULATION filter. A boundary part — a PCB, or anything
941    // flagged one — exports only what it declares itself, so a parent can reach
942    // its connectors and nothing inside it. See `ports::export_ports`.
943    let scene_ports: BTreeMap<String, PortRecord> = scene
944        .ports
945        .iter()
946        .map(|(id, port)| (id.clone(), port.clone()))
947        .collect();
948    let ports = crate::feature_pipeline::ports::export_ports(&scene_ports, &declared, boundary);
949    match error {
950        Some(message) => Err(message),
951        // An electronics part may have a symbol and ports before a 3D model is
952        // available. Keep the occurrence and its endpoints without inventing a
953        // solid. A generic empty modeling document remains an error.
954        None if members.is_empty() && !electronics_part =>
955            Err("embedded part document produced no solids".into()),
956        None => Ok((members, ports, nested_constraints, nested_poses)),
957    }
958}
959
960/// Execute an embedded part document and snapshot the result — the ONE
961/// snapshot-(re)build lane ([`add_part_to_library`] insert + ACOMP self-heal).
962/// The scene-metadata store is bracketed around the run: the sub-part's
963/// un-namespaced records feed the snapshot capture and are then discarded, so
964/// the parent document's store is byte-identical afterwards on every path.
965pub(crate) fn rebuild_snapshot(
966    document: &serde_json::Value,
967) -> Result<(String, BTreeMap<String, PortRecord>), String> {
968    rebuild_part(document).map(|rebuilt| (rebuilt.snapshot, rebuilt.ports))
969}
970
971/// What [`rebuild_part`] makes of a part document: the snapshot, the ports and
972/// the constraint rows of the one run, which the library entry keeps together.
973#[derive(Debug, Clone)]
974pub(crate) struct RebuiltPart {
975    pub snapshot: String,
976    pub ports: BTreeMap<String, PortRecord>,
977    pub nested_constraints: Vec<NestedConstraint>,
978    pub nested_poses: BTreeMap<String, crate::AffineTransform>,
979}
980
981/// How many rebuilt documents [`rebuild_part`] keeps.
982const REBUILT_MEMO_LEN: usize = 32;
983
984thread_local! {
985    /// Documents [`rebuild_part`] executed on this thread, most recent first,
986    /// with what they built: `(content hash, the document, the result)`. One
987    /// definition placed by several sub-assemblies (on l500 every module
988    /// places the same cells) is a copy per placing library, identical in
989    /// content: an edit used to rebuild it once per copy. A hit needs the
990    /// SAME document, compared in full, so a stale hit is impossible; the
991    /// isolated run reads nothing else (its own library rides inside the
992    /// document, and the scene-metadata store is bracketed around it). The
993    /// one outside input is the plugin provider, so a document that uses
994    /// extensions is never kept: it replays against the active provider.
995    static REBUILT: RefCell<Vec<(u64, serde_json::Value, RebuiltPart)>> = const { RefCell::new(Vec::new()) };
996}
997
998
999/// Forget every memoized rebuild (with the history cache).
1000pub(crate) fn clear_rebuilt_memo() {
1001    REBUILT.with(|memo| memo.borrow_mut().clear());
1002}
1003
1004/// [`rebuild_snapshot`] with the run's constraint rows and solved poses.
1005pub(crate) fn rebuild_part(document: &serde_json::Value) -> Result<RebuiltPart, String> {
1006    let hash = stable_json_hash(document);
1007    let memoized = !super::extension::document_uses_extensions(document);
1008    let hit = REBUILT.with(|memo| {
1009        let mut memo = memo.borrow_mut();
1010        let index = memo.iter().position(|(h, d, _)| memoized && *h == hash && d == document)?;
1011        let entry = memo.remove(index);
1012        let rebuilt = entry.2.clone();
1013        memo.insert(0, entry);
1014        Some(rebuilt)
1015    });
1016    if let Some(rebuilt) = hit {
1017        return Ok(rebuilt);
1018    }
1019    let outcome = rebuild_part_uncached(document);
1020    match &outcome {
1021        Ok(rebuilt) if memoized => REBUILT.with(|memo| {
1022            let mut memo = memo.borrow_mut();
1023            memo.insert(0, (hash, document.clone(), rebuilt.clone()));
1024            memo.truncate(REBUILT_MEMO_LEN);
1025        }),
1026        _ => {}
1027    }
1028    outcome
1029}
1030
1031fn rebuild_part_uncached(document: &serde_json::Value) -> Result<RebuiltPart, String> {
1032    let saved = scene_metadata::take_store();
1033    let outcome = run_isolated_document(document, None).and_then(|(members, ports, nested_constraints, nested_poses)| {
1034        let refs: Vec<(&str, &BrepSolid)> = members
1035            .iter()
1036            .map(|(name, solid)| (name.as_str(), solid))
1037            .collect();
1038        crate::snapshot_solids(&refs).map(|snapshot| RebuiltPart {
1039            snapshot,
1040            ports,
1041            nested_constraints,
1042            nested_poses,
1043        })
1044    });
1045    scene_metadata::restore_store(saved);
1046    outcome
1047}
1048
1049/// Whether an isolated part run is in progress (a library is pushed). Its
1050/// component ids are the SUB-document's, and collide with the parent's.
1051pub(crate) fn in_isolated_run() -> bool {
1052    STACK.with(|stack| !stack.borrow().is_empty())
1053}
1054
1055/// An embedded part document's OWN PMI, resolved against the geometry the
1056/// document builds — the pair the STEP writer needs to put a part's
1057/// annotations into the part's own `PRODUCT` rather than into the assembly
1058/// that places it (`io/step/assembly.rs`).
1059///
1060/// `None` when the document carries no PMI block, when it does not run, or
1061/// when nothing resolved. The scene-metadata store is bracketed exactly as
1062/// [`rebuild_snapshot`] brackets it, so the caller's store is byte-identical
1063/// afterwards on every path.
1064pub(crate) fn document_pmi(
1065    document: &serde_json::Value,
1066) -> Option<(crate::feature_pipeline::pmi::PmiState, crate::feature_pipeline::pmi::PmiReport)> {
1067    let state: crate::feature_pipeline::pmi::PmiState = serde_json::from_value(document.get("pmi")?.clone()).ok()?;
1068    if state.views.is_empty() {
1069        return None;
1070    }
1071    let saved = scene_metadata::take_store();
1072    let mut report = None;
1073    let outcome = run_isolated_document(document, Some(&mut report));
1074    scene_metadata::restore_store(saved);
1075    outcome.ok()?;
1076    report.map(|report| (state, report))
1077}
1078
1079// ===========================================================================
1080// The app-facing insert / update / save surface
1081// ===========================================================================
1082
1083/// A part name not yet used in the root store: `requested`, else
1084/// `requested-2`, `requested-3`, …
1085fn unique_name(root: &PartsLibraryMap, requested: &str) -> String {
1086    if !root.contains_key(requested) {
1087        return requested.to_string();
1088    }
1089    for counter in 2.. {
1090        let candidate = format!("{requested}-{counter}");
1091        if !root.contains_key(&candidate) {
1092            return candidate;
1093        }
1094    }
1095    unreachable!("counter loop is unbounded")
1096}
1097
1098/// Stamp per-loop sketch ids onto an entry's document, in place — run at EVERY
1099/// door into the library (insert, refresh, and the loaded-block seeding), so a
1100/// part gets durable loop ids no matter how it arrived.
1101///
1102/// The engine also stamps a document on LOAD
1103/// (`EngineState::set_history_json`), but a part inserted or refreshed through
1104/// the assembly lanes never passes through that: `add_part_to_library` and
1105/// `refresh_library_entry` take a document STRING straight from a caller (the
1106/// file panel inserts a saved `.nbrep`; update-components commits an edited
1107/// one). Stamping here rather than at those call sites means a future lane that
1108/// installs a document cannot silently skip it.
1109///
1110/// This renames nothing — the kernel derives the same loop ids every run. What
1111/// it adds is durability: a stored id survives deleting the edge it was derived
1112/// from, which derivation alone cannot. See `features/sketch/loop_ids`.
1113fn stamp_document_loop_ids(document: &mut serde_json::Value) {
1114    let Some(features) = document
1115        .get_mut("features")
1116        .and_then(serde_json::Value::as_array_mut)
1117    else {
1118        return;
1119    };
1120    for feature in features {
1121        if feature.get("type").and_then(serde_json::Value::as_str) != Some("S") {
1122            continue;
1123        }
1124        let Some(sketch) = feature
1125            .get_mut("persistentData")
1126            .and_then(|data| data.get_mut("sketch"))
1127        else {
1128            continue;
1129        };
1130        crate::feature_pipeline::assign_sketch_loop_ids(sketch);
1131    }
1132}
1133
1134/// INSERT: hand the opened sub-part document over to the library. Executes the
1135/// document once, snapshots, stores the entry, and returns the EFFECTIVE part
1136/// name (the ACOMP `partName` the app must reference):
1137///
1138/// - a live entry with the same `sourceKey` AND `sourceSignature` is reused
1139///   verbatim (no re-execution, instant re-insert);
1140/// - same `sourceKey` but a DIFFERENT signature gets a fresh entry under a
1141///   disambiguated name (existing instances keep their version; the explicit
1142///   refresh lane is [`refresh_library_entry`]);
1143/// - a requested name taken by different content is disambiguated (`name-2`).
1144///
1145/// The wasm export. A NATIVE caller must call [`add_part_to_library_impl`]:
1146/// building a `JsValue` off wasm32 panics inside a frame that cannot unwind,
1147/// so an error returned through this door aborts the whole app (the audit's
1148/// Insert component crash).
1149#[wasm_bindgen]
1150pub fn add_part_to_library(
1151    name: &str,
1152    source_key: &str,
1153    source_signature: &str,
1154    document_json: &str,
1155) -> Result<String, JsValue> {
1156    add_part_to_library_impl(name, source_key, source_signature, document_json)
1157        .map_err(|error| JsValue::from_str(&error))
1158}
1159
1160/// [`add_part_to_library`] for native callers: the same insert, its error as
1161/// text.
1162pub fn add_part_to_library_impl(
1163    name: &str,
1164    source_key: &str,
1165    source_signature: &str,
1166    document_json: &str,
1167) -> Result<String, String> {
1168    let requested = name.trim();
1169    if requested.is_empty() {
1170        return Err("add_part_to_library: empty part name".to_string());
1171    }
1172    let reused = ROOT.with(|root| {
1173        root.borrow().iter().find_map(|(entry_name, entry)| {
1174            (entry.source_key == source_key && entry.source_signature == source_signature)
1175                .then(|| entry_name.clone())
1176        })
1177    });
1178    if let Some(entry_name) = reused {
1179        return Ok(entry_name);
1180    }
1181    let mut document: serde_json::Value = serde_json::from_str(document_json)
1182        .map_err(|error| format!("add_part_to_library: {error}"))?;
1183    // Stamp BEFORE the hash and the snapshot so both describe the stored form —
1184    // a later re-stamp then finds nothing to change and cannot dirty the entry.
1185    stamp_document_loop_ids(&mut document);
1186    let RebuiltPart { snapshot, ports, nested_constraints, nested_poses } = rebuild_part(&document)
1187        .map_err(|error| format!("add_part_to_library: {error}"))?;
1188    let mut entry = PartsLibraryEntry {
1189        source_key: source_key.to_string(),
1190        source_signature: source_signature.to_string(),
1191        doc_hash: stable_json_hash(&document),
1192        document,
1193        snapshot,
1194        snapshot_producer: kernel_source_stamp().unwrap_or_default().to_string(),
1195        ports,
1196        dirty: false,
1197        nested_constraints: Some(nested_constraints),
1198        nested_poses,
1199        nested_rows: None,
1200    };
1201    entry.save_rows();
1202    let final_name = ROOT.with(|root| {
1203        let mut root = root.borrow_mut();
1204        let final_name = unique_name(&root, requested);
1205        root.insert(final_name.clone(), entry);
1206        final_name
1207    });
1208    bump_revision();
1209    Ok(final_name)
1210}
1211
1212/// UPDATE (update-components / edit-in-place commit): replace an existing
1213/// entry's document + signature. When the new document BUILDS differently
1214/// ([`same_build`]) the entry is marked DIRTY: the next history run's ACOMP
1215/// self-heal lane re-executes the document, re-snapshots, and every instance
1216/// of the part follows. When it builds the same — only its symbol, pads or BOM
1217/// attributes moved — the snapshot and ports still describe it and are kept,
1218/// so the part is not rebuilt for an edit that changed no geometry.
1219///
1220/// The wasm export; a NATIVE caller must call [`refresh_library_entry_impl`],
1221/// for the reason [`add_part_to_library`] gives.
1222#[wasm_bindgen]
1223pub fn refresh_library_entry(
1224    name: &str,
1225    source_signature: &str,
1226    document_json: &str,
1227) -> Result<(), JsValue> {
1228    refresh_library_entry_impl(name, source_signature, document_json)
1229        .map_err(|error| JsValue::from_str(&error))
1230}
1231
1232/// [`refresh_library_entry`] for native callers: its error as text.
1233pub fn refresh_library_entry_impl(
1234    name: &str,
1235    source_signature: &str,
1236    document_json: &str,
1237) -> Result<(), String> {
1238    let mut document: serde_json::Value = serde_json::from_str(document_json)
1239        .map_err(|error| format!("refresh_library_entry: {error}"))?;
1240    // Stamped before the hash, as in `add_part_to_library`.
1241    stamp_document_loop_ids(&mut document);
1242    ROOT.with(|root| {
1243        let mut root = root.borrow_mut();
1244        let Some(entry) = root.get_mut(name) else {
1245            return Err(format!(
1246                "refresh_library_entry: no parts-library entry named '{name}'"
1247            ));
1248        };
1249        let rebuild = !same_stamped_build(&entry.document, &document);
1250        entry.source_signature = source_signature.to_string();
1251        entry.doc_hash = stable_json_hash(&document);
1252        entry.document = document;
1253        if rebuild {
1254            entry.invalidate_snapshot();
1255        } else {
1256            // The same build: the snapshot and its rows still describe the new
1257            // document, so the saved rows follow it (else a reopen refuses them).
1258            entry.save_rows();
1259        }
1260        Ok(())
1261    })?;
1262    bump_revision();
1263    Ok(())
1264}
1265
1266/// Whether two part documents build the same solids and ports, so that one's
1267/// snapshot serves the other.
1268///
1269/// A snapshot is what `run_isolated_document` makes of a document: the
1270/// document read as a [`HistoryRequest`] with its editor stop points cleared.
1271/// Everything that request does not read — the eCAD `symbol` and `pads`
1272/// blocks, the BOM `partAttributes`, drawing `sheets` — cannot change what the
1273/// part builds, so two documents that read as the same request build the same
1274/// part. The comparison is of that request, not of a list of keys that do or
1275/// do not matter, so a block the request learns to read later counts at once.
1276///
1277/// Sketch loop ids are stamped on both sides first, as every library door
1278/// stamps them. A document that does not read as a request is never the same
1279/// build as anything: it has to heal.
1280pub fn same_build(a: &serde_json::Value, b: &serde_json::Value) -> bool {
1281    let stamped = |document: &serde_json::Value| {
1282        let mut document = document.clone();
1283        stamp_document_loop_ids(&mut document);
1284        document
1285    };
1286    same_stamped_build(&stamped(a), &stamped(b))
1287}
1288
1289/// The rows rule of [`refresh_library_entry_impl`] for a door that rewrites an
1290/// entry's `document` in the `partsLibrary` block itself (the app's Update
1291/// components): that block is what Save writes. Rows taken from `old` follow
1292/// the same build of `new`; any other rows are dropped, as no reopen could
1293/// take them.
1294pub fn follow_saved_rows(entry: &mut serde_json::Value, old: &serde_json::Value, new: &serde_json::Value) {
1295    follow_rows(entry, old, new, || same_build(old, new));
1296}
1297
1298/// [`follow_saved_rows`] for a caller that has already asked
1299/// [`same_build`]`(old, new)`: it is not asked again (each asks parses both
1300/// whole documents as requests, ~5 ms for an l500 module).
1301pub fn follow_saved_rows_known(
1302    entry: &mut serde_json::Value,
1303    old: &serde_json::Value,
1304    new: &serde_json::Value,
1305    same_build: bool,
1306) {
1307    follow_rows(entry, old, new, || same_build);
1308}
1309
1310fn follow_rows(
1311    entry: &mut serde_json::Value,
1312    old: &serde_json::Value,
1313    new: &serde_json::Value,
1314    same_build: impl FnOnce() -> bool,
1315) {
1316    let stamp = |document: &serde_json::Value| {
1317        let mut document = document.clone();
1318        stamp_document_loop_ids(&mut document);
1319        document_stamp(&document)
1320    };
1321    let Some(object) = entry.as_object_mut() else { return };
1322    let taken_from_old = object
1323        .get("nestedRows")
1324        .and_then(|rows| rows.get("document"))
1325        .and_then(serde_json::Value::as_str)
1326        .is_some_and(|document| document == stamp(old));
1327    if taken_from_old && same_build() {
1328        object["nestedRows"]["document"] = serde_json::Value::String(stamp(new));
1329    } else {
1330        object.remove("nestedRows");
1331    }
1332}
1333
1334/// [`same_build`] for two documents a library door has already stamped.
1335fn same_stamped_build(a: &serde_json::Value, b: &serde_json::Value) -> bool {
1336    matches!((build_identity(a), build_identity(b)), (Some(a), Some(b)) if a == b)
1337}
1338
1339/// The hash of `document` as [`run_isolated_document`] reads it; `None` when it
1340/// does not read as a request.
1341fn build_identity(document: &serde_json::Value) -> Option<u64> {
1342    let mut request = <HistoryRequest as serde::Deserialize>::deserialize(document).ok()?;
1343    request.stop_at_id = None;
1344    request.stop_before_id = None;
1345    Some(stable_json_hash(&serde_json::to_value(&request).ok()?))
1346}
1347
1348/// The current library in the `partsLibrary` block shape — what
1349/// SAVE must serialize into the document (never the loaded block: this copy
1350/// carries healed snapshots, refreshes, and GC).
1351#[wasm_bindgen]
1352pub fn parts_library_json() -> String {
1353    ROOT.with(|root| {
1354        serde_json::to_string(&*root.borrow()).unwrap_or_else(|_| "{}".to_string())
1355    })
1356}
1357
1358