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