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