BREP_kernel 0.33.0

Rust B-rep CAD kernel (next.BREP.io): a boundary representation (B-rep) geometry kernel for building CAD applications, native and WebAssembly.
Documentation
//! Observation only: what an early cutoff in the history cache would buy, and
//! which scene reads the cache's name scan misses. Nothing here changes a
//! decision the history loop makes.
//!
//! **Shadow early cutoff** (`BREP_HISTORY_EARLY_CUTOFF_SHADOW`, default off).
//! Today a re-run feature puts every name it produced into the run's `changed`
//! set and publishes one version for all of them, so everything downstream
//! re-runs even when the re-run built exactly what it built before. The shadow
//! keeps a second, content-keyed view beside the real one: each produced name
//! carries a STAMP of what a consumer can read through it (a topology name
//! carries its owning solid's stamp, the whole body, since a fillet on one edge
//! reads it), and a consumer is "shadow clean" when its consumed names' stamps
//! are what it was built against. When the real loop re-runs a feature the
//! shadow would have kept, the re-run's full output is compared with the cached
//! one by an independent TRUTH digest (the whole serialized result and solids,
//! not the stamp): equal is a saved re-run, different is a DISAGREEMENT, a case
//! where the cutoff would have shipped stale geometry. The report counts
//! comparisons (zero is not evidence), agreements, disagreements and the
//! milliseconds the agreements spent.
//!
//! **Read trace** (`BREP_HISTORY_READ_TRACE`, default off). The `SceneMap`
//! resolvers note every name a running feature resolves. A read whose producer
//! is not the producer of any name the feature's descriptor names is a GAP: a
//! change there does not re-run the feature. A read of another output of a
//! producer it does name is safe today (one version covers all of a producer's
//! outputs) but is what a per-name version split would have to honour. Reads
//! that bypass the resolvers (direct `scene` field access, the handle registry)
//! are not seen.

use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::hash::{Hash, Hasher};

use super::{FeatureResult, HashMap};

/// Whether the shadow early cutoff runs (`BREP_HISTORY_EARLY_CUTOFF_SHADOW`).
pub(crate) fn shadow_on() -> bool {
    crate::switch!(live "BREP_HISTORY_EARLY_CUTOFF_SHADOW", false)
}

/// Whether the resolvers' reads are traced (`BREP_HISTORY_READ_TRACE`).
pub(crate) fn trace_on() -> bool {
    crate::switch!(live "BREP_HISTORY_READ_TRACE", false)
}

/// A deliberate fault for the shadow's own check: leave the encoded geometry
/// out of the stamps. A shadow that cannot report the disagreements this
/// causes on a geometric edit is not measuring anything.
fn fault_injected() -> bool {
    crate::switch!(live "BREP_HISTORY_EARLY_CUTOFF_FAULT", false)
}

/// Two independent 64-bit SipHash lanes as one 128-bit digest.
struct Digest(std::collections::hash_map::DefaultHasher, std::collections::hash_map::DefaultHasher);

impl Digest {
    fn new(domain: &str) -> Self {
        let mut a = std::collections::hash_map::DefaultHasher::new();
        let mut b = std::collections::hash_map::DefaultHasher::new();
        (domain, 0x9e37_79b9_u32).hash(&mut a);
        (0x85eb_ca6b_u32, domain).hash(&mut b);
        Digest(a, b)
    }
    fn feed(&mut self, value: impl Hash) {
        value.hash(&mut self.0);
        value.hash(&mut self.1);
    }
    fn json(&mut self, value: &impl serde::Serialize) {
        self.feed(serde_json::to_string(value).unwrap_or_default());
    }
    fn finish(self) -> u128 {
        (u128::from(self.0.finish()) << 64) | u128::from(self.1.finish())
    }
}

/// What the shadow keeps on a cache entry: each produced name's stamp, the
/// independent truth digest of the whole result, and the content-keyed input
/// version the entry was built against.
#[derive(Debug, Clone, Default)]
pub(crate) struct ShadowEntry {
    pub(crate) stamps: HashMap<String, u128>,
    pub(crate) truth: u128,
    pub(crate) input_version: u128,
}

/// The stamp of every name `result` produces. A solid and every topology name
/// on it (faces, edges, their groups) carry the SOLID's stamp: its encoded
/// geometry, its own names, its sheet-metal tree and the metadata records of
/// its names. Side channels (profiles, frames, axes, paths, points, ports,
/// components, solid aliases) are stamped by their own value.
pub(crate) fn stamps(result: &FeatureResult) -> HashMap<String, u128> {
    let fault = fault_injected();
    let mut out = HashMap::default();
    for added in &result.added {
        let mut digest = Digest::new("solid");
        match crate::registered_solid_clone(added.handle) {
            Ok(solid) => match crate::encode_solid(&solid) {
                Ok((data, names)) => {
                    if !fault {
                        digest.feed(data.iter().map(|value| value.to_bits()).collect::<Vec<u64>>());
                    }
                    digest.json(&names);
                }
                Err(error) => digest.feed(("encode", error)),
            },
            Err(error) => digest.feed(("registry", error.to_string())),
        }
        digest.feed(&added.name);
        digest.feed(&added.face_names);
        digest.feed(&added.face_groups);
        digest.feed(&added.edge_names);
        digest.feed(&added.edge_groups);
        digest.json(&super::sheet_metal::get_tree(added.handle));
        let names = added_names(added);
        for name in &names {
            digest.json(&super::scene_metadata::own_record(name));
        }
        let stamp = digest.finish();
        for name in names {
            out.insert(name, stamp);
        }
    }
    fn side(out: &mut HashMap<String, u128>, kind: &str, name: &str, value: &dyn erased::Json) {
        let mut digest = Digest::new(kind);
        digest.feed(value.json());
        out.insert(name.to_string(), digest.finish());
    }
    for (name, value) in &result.profiles {
        side(&mut out, "profile", name, value);
    }
    for (name, value) in &result.frames {
        side(&mut out, "frame", name, value);
    }
    for (name, value) in &result.axes {
        side(&mut out, "axis", name, value);
    }
    for (name, value) in &result.paths {
        side(&mut out, "path", name, value);
    }
    for (name, value) in &result.points {
        side(&mut out, "point", name, value);
    }
    for (name, value) in &result.ports {
        side(&mut out, "port", name, value);
    }
    for record in &result.components {
        side(&mut out, "component", &record.id, record);
    }
    // A legacy alias resolves to its canonical solid, so a consumer that names
    // the alias reads that solid: it carries the solid's stamp (found by the
    // edit sweep: a rib named an offset shell by its legacy alias).
    for (legacy, canonical) in &result.solid_aliases {
        let stamp = out.get(canonical).copied();
        match stamp {
            Some(stamp) => {
                out.insert(legacy.clone(), stamp);
            }
            None => side(&mut out, "alias", legacy, canonical),
        }
    }
    out
}

/// Every name an added solid makes resolvable.
fn added_names(added: &super::AddedSolid) -> Vec<String> {
    let mut names = vec![added.name.clone()];
    names.extend(added.face_names.iter().map(|(_, name)| name.clone()));
    names.extend(added.edge_names.iter().map(|(_, name)| name.clone()));
    names.extend(added.face_groups.iter().map(|(name, _)| name.clone()));
    names.extend(added.edge_groups.iter().map(|(name, _)| name.clone()));
    names
}

/// The truth digest: the whole result (handles and the replay flag left out)
/// and every added solid in full. Independent of [`stamps`], so a field the
/// stamps miss still shows up here.
pub(crate) fn truth(result: &FeatureResult) -> u128 {
    let mut digest = Digest::new("truth");
    let mut copy = result.clone();
    copy.reused = false;
    for added in &mut copy.added {
        if let Ok(solid) = crate::registered_solid_clone(added.handle) {
            digest.json(&solid);
        }
        digest.json(&super::sheet_metal::get_tree(added.handle));
        added.handle = 0;
    }
    digest.json(&copy);
    digest.finish()
}

/// The content-keyed input version: the feature's own fingerprint and the
/// stamps of the names it consumes.
pub(crate) fn input_version(fingerprint: u64, consumed: &BTreeSet<String>, stamps: &HashMap<String, u128>) -> u128 {
    let mut digest = Digest::new("input");
    digest.feed(fingerprint);
    for name in consumed {
        digest.feed((name, stamps.get(name)));
    }
    digest.finish()
}

mod erased {
    /// A value hashed by its JSON text (lets the side-channel loop take any
    /// serializable value through one closure).
    pub(super) trait Json {
        fn json(&self) -> String;
    }
    impl<T: serde::Serialize> Json for T {
        fn json(&self) -> String {
            serde_json::to_string(self).unwrap_or_default()
        }
    }
}

/// One run's shadow and trace findings.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ObservationReport {
    /// Features the shadow would have kept that the real loop re-ran and the
    /// truth digest could judge.
    pub comparisons: usize,
    /// Of those, the re-run built exactly what was cached.
    pub agreements: usize,
    /// Of those, the re-run built something else: the cutoff would be wrong.
    pub disagreements: Vec<String>,
    /// Milliseconds the agreeing re-runs spent (what the cutoff would save).
    pub saved_ms: f64,
    /// Features the real loop kept but the shadow would not (should be none).
    pub shadow_stricter: Vec<String>,
    /// A handle in a new cache entry already owned by another live entry.
    pub shared_handles: Vec<String>,
    /// Read-trace gaps: `feature <- name (producer)` read with no consumed
    /// name from that producer.
    pub gaps: Vec<String>,
    /// Reads of an unnamed output of a producer the feature does name.
    pub beyond_named: Vec<String>,
    /// Features traced.
    pub traced: usize,
}

thread_local! {
    static REPORT: RefCell<ObservationReport> = RefCell::new(ObservationReport::default());
    static READS: RefCell<Option<BTreeSet<String>>> = const { RefCell::new(None) };
}

/// Take (and reset) the findings accumulated since the last call.
pub fn take_observation_report() -> ObservationReport {
    REPORT.with(|report| std::mem::take(&mut *report.borrow_mut()))
}

pub(crate) fn record(update: impl FnOnce(&mut ObservationReport)) {
    REPORT.with(|report| update(&mut report.borrow_mut()));
}

/// Note a name a resolver was asked for, while a feature is being traced.
pub(crate) fn note_read(name: &str) {
    READS.with(|reads| {
        if let Some(reads) = reads.borrow_mut().as_mut() {
            reads.insert(name.to_string());
        }
    });
}

/// Start tracing the running feature's reads.
pub(crate) fn begin_trace() {
    READS.with(|reads| *reads.borrow_mut() = Some(BTreeSet::new()));
}

/// Stop tracing and judge the reads against the names the feature consumes:
/// `producer` maps each available name to the feature that last produced it.
pub(crate) fn end_trace(id: &str, consumed: &BTreeSet<String>, producer: &BTreeMap<String, String>) {
    let Some(reads) = READS.with(|reads| reads.borrow_mut().take()) else { return };
    let named: BTreeSet<&String> = consumed.iter().filter_map(|name| producer.get(name)).collect();
    record(|report| {
        report.traced += 1;
        for name in &reads {
            let Some(source) = producer.get(name) else { continue };
            if source == id || consumed.contains(name) {
                continue;
            }
            if named.contains(source) {
                report.beyond_named.push(format!("{id} <- {name} ({source})"));
            } else {
                report.gaps.push(format!("{id} <- {name} ({source})"));
            }
        }
    });
}