Skip to main content

brep_kernel/feature_pipeline/
early_cutoff.rs

1//! Observation only: what an early cutoff in the history cache would buy, and
2//! which scene reads the cache's name scan misses. Nothing here changes a
3//! decision the history loop makes.
4//!
5//! **Shadow early cutoff** (`BREP_HISTORY_EARLY_CUTOFF_SHADOW`, default off).
6//! Today a re-run feature puts every name it produced into the run's `changed`
7//! set and publishes one version for all of them, so everything downstream
8//! re-runs even when the re-run built exactly what it built before. The shadow
9//! keeps a second, content-keyed view beside the real one: each produced name
10//! carries a STAMP of what a consumer can read through it (a topology name
11//! carries its owning solid's stamp, the whole body, since a fillet on one edge
12//! reads it), and a consumer is "shadow clean" when its consumed names' stamps
13//! are what it was built against. When the real loop re-runs a feature the
14//! shadow would have kept, the re-run's full output is compared with the cached
15//! one by an independent TRUTH digest (the whole serialized result and solids,
16//! not the stamp): equal is a saved re-run, different is a DISAGREEMENT, a case
17//! where the cutoff would have shipped stale geometry. The report counts
18//! comparisons (zero is not evidence), agreements, disagreements and the
19//! milliseconds the agreements spent.
20//!
21//! **Read trace** (`BREP_HISTORY_READ_TRACE`, default off). The `SceneMap`
22//! resolvers note every name a running feature resolves. A read whose producer
23//! is not the producer of any name the feature's descriptor names is a GAP: a
24//! change there does not re-run the feature. A read of another output of a
25//! producer it does name is safe today (one version covers all of a producer's
26//! outputs) but is what a per-name version split would have to honour. Reads
27//! that bypass the resolvers (direct `scene` field access, the handle registry)
28//! are not seen.
29
30use std::cell::RefCell;
31use std::collections::{BTreeMap, BTreeSet};
32use std::hash::{Hash, Hasher};
33
34use super::{FeatureResult, HashMap};
35
36/// Whether the shadow early cutoff runs (`BREP_HISTORY_EARLY_CUTOFF_SHADOW`).
37pub(crate) fn shadow_on() -> bool {
38    crate::switch!(live "BREP_HISTORY_EARLY_CUTOFF_SHADOW", false)
39}
40
41/// Whether the resolvers' reads are traced (`BREP_HISTORY_READ_TRACE`).
42pub(crate) fn trace_on() -> bool {
43    crate::switch!(live "BREP_HISTORY_READ_TRACE", false)
44}
45
46/// A deliberate fault for the shadow's own check: leave the encoded geometry
47/// out of the stamps. A shadow that cannot report the disagreements this
48/// causes on a geometric edit is not measuring anything.
49fn fault_injected() -> bool {
50    crate::switch!(live "BREP_HISTORY_EARLY_CUTOFF_FAULT", false)
51}
52
53/// Two independent 64-bit SipHash lanes as one 128-bit digest.
54struct Digest(std::collections::hash_map::DefaultHasher, std::collections::hash_map::DefaultHasher);
55
56impl Digest {
57    fn new(domain: &str) -> Self {
58        let mut a = std::collections::hash_map::DefaultHasher::new();
59        let mut b = std::collections::hash_map::DefaultHasher::new();
60        (domain, 0x9e37_79b9_u32).hash(&mut a);
61        (0x85eb_ca6b_u32, domain).hash(&mut b);
62        Digest(a, b)
63    }
64    fn feed(&mut self, value: impl Hash) {
65        value.hash(&mut self.0);
66        value.hash(&mut self.1);
67    }
68    fn json(&mut self, value: &impl serde::Serialize) {
69        self.feed(serde_json::to_string(value).unwrap_or_default());
70    }
71    fn finish(self) -> u128 {
72        (u128::from(self.0.finish()) << 64) | u128::from(self.1.finish())
73    }
74}
75
76/// What the shadow keeps on a cache entry: each produced name's stamp, the
77/// independent truth digest of the whole result, and the content-keyed input
78/// version the entry was built against.
79#[derive(Debug, Clone, Default)]
80pub(crate) struct ShadowEntry {
81    pub(crate) stamps: HashMap<String, u128>,
82    pub(crate) truth: u128,
83    pub(crate) input_version: u128,
84}
85
86/// The stamp of every name `result` produces. A solid and every topology name
87/// on it (faces, edges, their groups) carry the SOLID's stamp: its encoded
88/// geometry, its own names, its sheet-metal tree and the metadata records of
89/// its names. Side channels (profiles, frames, axes, paths, points, ports,
90/// components, solid aliases) are stamped by their own value.
91pub(crate) fn stamps(result: &FeatureResult) -> HashMap<String, u128> {
92    let fault = fault_injected();
93    let mut out = HashMap::default();
94    for added in &result.added {
95        let mut digest = Digest::new("solid");
96        match crate::registered_solid_clone(added.handle) {
97            Ok(solid) => match crate::encode_solid(&solid) {
98                Ok((data, names)) => {
99                    if !fault {
100                        digest.feed(data.iter().map(|value| value.to_bits()).collect::<Vec<u64>>());
101                    }
102                    digest.json(&names);
103                }
104                Err(error) => digest.feed(("encode", error)),
105            },
106            Err(error) => digest.feed(("registry", error.to_string())),
107        }
108        digest.feed(&added.name);
109        digest.feed(&added.face_names);
110        digest.feed(&added.face_groups);
111        digest.feed(&added.edge_names);
112        digest.feed(&added.edge_groups);
113        digest.json(&super::sheet_metal::get_tree(added.handle));
114        let names = added_names(added);
115        for name in &names {
116            digest.json(&super::scene_metadata::own_record(name));
117        }
118        let stamp = digest.finish();
119        for name in names {
120            out.insert(name, stamp);
121        }
122    }
123    fn side(out: &mut HashMap<String, u128>, kind: &str, name: &str, value: &dyn erased::Json) {
124        let mut digest = Digest::new(kind);
125        digest.feed(value.json());
126        out.insert(name.to_string(), digest.finish());
127    }
128    for (name, value) in &result.profiles {
129        side(&mut out, "profile", name, value);
130    }
131    for (name, value) in &result.frames {
132        side(&mut out, "frame", name, value);
133    }
134    for (name, value) in &result.axes {
135        side(&mut out, "axis", name, value);
136    }
137    for (name, value) in &result.paths {
138        side(&mut out, "path", name, value);
139    }
140    for (name, value) in &result.points {
141        side(&mut out, "point", name, value);
142    }
143    for (name, value) in &result.ports {
144        side(&mut out, "port", name, value);
145    }
146    for record in &result.components {
147        side(&mut out, "component", &record.id, record);
148    }
149    // A legacy alias resolves to its canonical solid, so a consumer that names
150    // the alias reads that solid: it carries the solid's stamp (found by the
151    // edit sweep: a rib named an offset shell by its legacy alias).
152    for (legacy, canonical) in &result.solid_aliases {
153        let stamp = out.get(canonical).copied();
154        match stamp {
155            Some(stamp) => {
156                out.insert(legacy.clone(), stamp);
157            }
158            None => side(&mut out, "alias", legacy, canonical),
159        }
160    }
161    out
162}
163
164/// Every name an added solid makes resolvable.
165fn added_names(added: &super::AddedSolid) -> Vec<String> {
166    let mut names = vec![added.name.clone()];
167    names.extend(added.face_names.iter().map(|(_, name)| name.clone()));
168    names.extend(added.edge_names.iter().map(|(_, name)| name.clone()));
169    names.extend(added.face_groups.iter().map(|(name, _)| name.clone()));
170    names.extend(added.edge_groups.iter().map(|(name, _)| name.clone()));
171    names
172}
173
174/// The truth digest: the whole result (handles and the replay flag left out)
175/// and every added solid in full. Independent of [`stamps`], so a field the
176/// stamps miss still shows up here.
177pub(crate) fn truth(result: &FeatureResult) -> u128 {
178    let mut digest = Digest::new("truth");
179    let mut copy = result.clone();
180    copy.reused = false;
181    for added in &mut copy.added {
182        if let Ok(solid) = crate::registered_solid_clone(added.handle) {
183            digest.json(&solid);
184        }
185        digest.json(&super::sheet_metal::get_tree(added.handle));
186        added.handle = 0;
187    }
188    digest.json(&copy);
189    digest.finish()
190}
191
192/// The content-keyed input version: the feature's own fingerprint and the
193/// stamps of the names it consumes.
194pub(crate) fn input_version(fingerprint: u64, consumed: &BTreeSet<String>, stamps: &HashMap<String, u128>) -> u128 {
195    let mut digest = Digest::new("input");
196    digest.feed(fingerprint);
197    for name in consumed {
198        digest.feed((name, stamps.get(name)));
199    }
200    digest.finish()
201}
202
203mod erased {
204    /// A value hashed by its JSON text (lets the side-channel loop take any
205    /// serializable value through one closure).
206    pub(super) trait Json {
207        fn json(&self) -> String;
208    }
209    impl<T: serde::Serialize> Json for T {
210        fn json(&self) -> String {
211            serde_json::to_string(self).unwrap_or_default()
212        }
213    }
214}
215
216/// One run's shadow and trace findings.
217#[derive(Debug, Clone, Default, serde::Serialize)]
218pub struct ObservationReport {
219    /// Features the shadow would have kept that the real loop re-ran and the
220    /// truth digest could judge.
221    pub comparisons: usize,
222    /// Of those, the re-run built exactly what was cached.
223    pub agreements: usize,
224    /// Of those, the re-run built something else: the cutoff would be wrong.
225    pub disagreements: Vec<String>,
226    /// Milliseconds the agreeing re-runs spent (what the cutoff would save).
227    pub saved_ms: f64,
228    /// Features the real loop kept but the shadow would not (should be none).
229    pub shadow_stricter: Vec<String>,
230    /// A handle in a new cache entry already owned by another live entry.
231    pub shared_handles: Vec<String>,
232    /// Read-trace gaps: `feature <- name (producer)` read with no consumed
233    /// name from that producer.
234    pub gaps: Vec<String>,
235    /// Reads of an unnamed output of a producer the feature does name.
236    pub beyond_named: Vec<String>,
237    /// Features traced.
238    pub traced: usize,
239}
240
241thread_local! {
242    static REPORT: RefCell<ObservationReport> = RefCell::new(ObservationReport::default());
243    static READS: RefCell<Option<BTreeSet<String>>> = const { RefCell::new(None) };
244}
245
246/// Take (and reset) the findings accumulated since the last call.
247pub fn take_observation_report() -> ObservationReport {
248    REPORT.with(|report| std::mem::take(&mut *report.borrow_mut()))
249}
250
251pub(crate) fn record(update: impl FnOnce(&mut ObservationReport)) {
252    REPORT.with(|report| update(&mut report.borrow_mut()));
253}
254
255/// Note a name a resolver was asked for, while a feature is being traced.
256pub(crate) fn note_read(name: &str) {
257    READS.with(|reads| {
258        if let Some(reads) = reads.borrow_mut().as_mut() {
259            reads.insert(name.to_string());
260        }
261    });
262}
263
264/// Start tracing the running feature's reads.
265pub(crate) fn begin_trace() {
266    READS.with(|reads| *reads.borrow_mut() = Some(BTreeSet::new()));
267}
268
269/// Stop tracing and judge the reads against the names the feature consumes:
270/// `producer` maps each available name to the feature that last produced it.
271pub(crate) fn end_trace(id: &str, consumed: &BTreeSet<String>, producer: &BTreeMap<String, String>) {
272    let Some(reads) = READS.with(|reads| reads.borrow_mut().take()) else { return };
273    let named: BTreeSet<&String> = consumed.iter().filter_map(|name| producer.get(name)).collect();
274    record(|report| {
275        report.traced += 1;
276        for name in &reads {
277            let Some(source) = producer.get(name) else { continue };
278            if source == id || consumed.contains(name) {
279                continue;
280            }
281            if named.contains(source) {
282                report.beyond_named.push(format!("{id} <- {name} ({source})"));
283            } else {
284                report.gaps.push(format!("{id} <- {name} ({source})"));
285            }
286        }
287    });
288}
289