Skip to main content

soothfast_spec/probe/
baseline.rs

1//! The committed population baseline: `probes.lock`.
2//!
3//! Live market data makes some fields legitimately intermittent
4//! (pre-market prices outside pre-market hours, dividend fields on
5//! non-payers), so the lock records a *class* per field, not a snapshot:
6//!
7//! - `always`: populated in every accepted run; going null fails the gate
8//! - `sometimes`: observed both ways across accepted runs; never gated
9//!
10//! Accepting demotes a flapping `always` field to `sometimes` and keeps it
11//! there: repeated accepts converge on the stable contract instead of
12//! ratcheting on one lucky run. A manifest can pin a field's class when
13//! the operator knows better than the observations.
14//!
15//! Fields the spec declares but no accepted run has ever populated go in
16//! the probe's `uncovered` list: committed debt, visible in review, and
17//! promoted to a real class automatically once data appears. A declared
18//! field in neither place fails the gate: adding a schema field without
19//! wiring data to it is a finding, not a silence.
20
21use std::collections::{BTreeMap, BTreeSet};
22
23use serde_json::{Value, json};
24
25/// A field's population class across accepted runs.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Class {
28    Always,
29    Sometimes,
30}
31
32impl Class {
33    fn as_str(self) -> &'static str {
34        match self {
35            Class::Always => "always",
36            Class::Sometimes => "sometimes",
37        }
38    }
39}
40
41/// One probe's locked state.
42#[derive(Debug, Clone, Default, PartialEq)]
43pub struct ProbeLock {
44    pub fields: BTreeMap<String, Class>,
45    /// Declared by the spec, never yet populated in an accepted run.
46    pub uncovered: BTreeSet<String>,
47}
48
49/// The lock file: probe name → locked state.
50#[derive(Debug, Clone, Default, PartialEq)]
51pub struct Baseline {
52    pub probes: BTreeMap<String, ProbeLock>,
53}
54
55/// One probe's gate findings against the lock.
56#[derive(Debug, Default)]
57pub struct Findings {
58    /// Locked `always`, now null or absent.
59    pub regressed: Vec<String>,
60    /// Populated now, unknown to the lock: the lock is stale.
61    pub new_fields: Vec<String>,
62    /// Declared by the spec, not populated, and not in the accepted
63    /// `uncovered` list: a schema field nobody wired to data.
64    pub uncovered: Vec<String>,
65}
66
67impl Findings {
68    /// Whether the run found nothing to report.
69    pub fn is_clean(&self) -> bool {
70        self.regressed.is_empty() && self.new_fields.is_empty() && self.uncovered.is_empty()
71    }
72}
73
74impl Baseline {
75    /// Read a `probes.lock` document.
76    pub fn parse(text: &str) -> Result<Baseline, String> {
77        let doc: Value =
78            serde_json::from_str(text).map_err(|e| format!("probes.lock is not JSON: {e}"))?;
79        match doc.get("version").and_then(Value::as_u64) {
80            Some(1) => {}
81            other => return Err(format!("probes.lock version {other:?}, expected 1")),
82        }
83        let mut probes = BTreeMap::new();
84        let Some(entries) = doc.get("probes").and_then(Value::as_object) else {
85            return Err("probes.lock has no `probes` table".into());
86        };
87        for (name, entry) in entries {
88            let Some(fields) = entry.get("fields").and_then(Value::as_object) else {
89                return Err(format!("probe `{name}` has no `fields` table"));
90            };
91            let mut lock = ProbeLock::default();
92            for (path, class) in fields {
93                let class = match class.as_str() {
94                    Some("always") => Class::Always,
95                    Some("sometimes") => Class::Sometimes,
96                    other => {
97                        return Err(format!(
98                            "probe `{name}` field `{path}`: bad class {other:?}"
99                        ));
100                    }
101                };
102                lock.fields.insert(path.clone(), class);
103            }
104            if let Some(uncovered) = entry.get("uncovered").and_then(Value::as_array) {
105                lock.uncovered = uncovered
106                    .iter()
107                    .filter_map(Value::as_str)
108                    .map(String::from)
109                    .collect();
110            }
111            probes.insert(name.clone(), lock);
112        }
113        Ok(Baseline { probes })
114    }
115
116    /// The lock as the text `probes.lock` holds.
117    pub fn render(&self) -> String {
118        let probes: BTreeMap<&str, Value> = self
119            .probes
120            .iter()
121            .map(|(name, lock)| {
122                let fields: BTreeMap<&str, &str> = lock
123                    .fields
124                    .iter()
125                    .map(|(path, class)| (path.as_str(), class.as_str()))
126                    .collect();
127                let entry = if lock.uncovered.is_empty() {
128                    json!({ "fields": fields })
129                } else {
130                    json!({ "fields": fields, "uncovered": lock.uncovered })
131                };
132                (name.as_str(), entry)
133            })
134            .collect();
135        let mut out = serde_json::to_string_pretty(&json!({
136            "version": 1,
137            "probes": probes,
138        }))
139        .expect("baseline is plain JSON");
140        out.push('\n');
141        out
142    }
143
144    /// Gate one probe's observed population against its locked classes.
145    /// `pinned_sometimes` are manifest-declared intermittent fields; they
146    /// gate like `sometimes` regardless of the locked class. `declared`
147    /// is the spec's field enumeration when coverage applies.
148    pub fn gate(
149        &self,
150        probe: &str,
151        observed: &BTreeMap<String, bool>,
152        pinned_sometimes: &[String],
153        declared: Option<&BTreeSet<String>>,
154    ) -> Findings {
155        let mut findings = Findings::default();
156        let locked = self.probes.get(probe).cloned().unwrap_or_default();
157        for (path, class) in &locked.fields {
158            if *class == Class::Always
159                && !pinned(pinned_sometimes, path)
160                && observed.get(path) != Some(&true)
161            {
162                findings.regressed.push(path.clone());
163            }
164        }
165        for (path, populated) in observed {
166            if *populated && !locked.fields.contains_key(path) {
167                findings.new_fields.push(path.clone());
168            }
169        }
170        if let Some(declared) = declared {
171            for path in declared {
172                if observed.get(path) != Some(&true)
173                    && !locked.fields.contains_key(path)
174                    && !locked.uncovered.contains(path)
175                    && !pinned(pinned_sometimes, path)
176                {
177                    findings.uncovered.push(path.clone());
178                }
179            }
180        }
181        findings
182    }
183
184    /// Fold one probe's observed population into the lock. First sight of
185    /// a populated field locks it `always`; any accepted run that sees a
186    /// locked field empty demotes it to `sometimes`, permanently. The
187    /// `uncovered` list is recomputed from `declared`: whatever still has
188    /// no class after this run is the probe's accepted coverage debt.
189    pub fn accept(
190        &mut self,
191        probe: &str,
192        observed: &BTreeMap<String, bool>,
193        declared: Option<&BTreeSet<String>>,
194    ) {
195        let lock = self.probes.entry(probe.to_string()).or_default();
196        for (path, populated) in observed {
197            match (lock.fields.get(path), populated) {
198                (None, true) => {
199                    lock.fields.insert(path.clone(), Class::Always);
200                }
201                (None, false) => {}
202                (Some(Class::Always), false) => {
203                    lock.fields.insert(path.clone(), Class::Sometimes);
204                }
205                _ => {}
206            }
207        }
208        // A locked field the response no longer mentions at all is the
209        // same evidence as seeing it empty.
210        let absent: Vec<String> = lock
211            .fields
212            .iter()
213            .filter(|(path, class)| **class == Class::Always && !observed.contains_key(*path))
214            .map(|(path, _)| path.clone())
215            .collect();
216        for path in absent {
217            lock.fields.insert(path, Class::Sometimes);
218        }
219        lock.uncovered = declared
220            .map(|declared| {
221                declared
222                    .iter()
223                    .filter(|path| !lock.fields.contains_key(*path))
224                    .cloned()
225                    .collect()
226            })
227            .unwrap_or_default();
228    }
229
230    /// Drop locked probes the manifest no longer declares. Returns the
231    /// dropped names so the gate can refuse them without `--allow-gone`.
232    pub fn retain_probes(&mut self, declared: &[String]) -> Vec<String> {
233        let gone: Vec<String> = self
234            .probes
235            .keys()
236            .filter(|name| !declared.contains(name))
237            .cloned()
238            .collect();
239        for name in &gone {
240            self.probes.remove(name);
241        }
242        gone
243    }
244}
245
246fn pinned(pins: &[String], path: &str) -> bool {
247    pins.iter().any(|pin| {
248        pin == path
249            || pin
250                .strip_suffix('*')
251                .is_some_and(|prefix| path.starts_with(prefix))
252    })
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    fn observed(pairs: &[(&str, bool)]) -> BTreeMap<String, bool> {
260        pairs
261            .iter()
262            .map(|(path, populated)| (path.to_string(), *populated))
263            .collect()
264    }
265
266    fn declared(paths: &[&str]) -> BTreeSet<String> {
267        paths.iter().map(|p| p.to_string()).collect()
268    }
269
270    #[test]
271    fn lock_round_trips_through_render_and_parse() {
272        let mut baseline = Baseline::default();
273        baseline.accept(
274            "quote",
275            &observed(&[("price", true), ("pe", true)]),
276            Some(&declared(&["price", "pe", "spark"])),
277        );
278        let reparsed = Baseline::parse(&baseline.render()).unwrap();
279        assert_eq!(reparsed, baseline);
280        assert!(baseline.probes["quote"].uncovered.contains("spark"));
281    }
282
283    #[test]
284    fn an_always_field_going_null_regresses() {
285        let mut baseline = Baseline::default();
286        baseline.accept("quote", &observed(&[("pe", true)]), None);
287        let findings = baseline.gate("quote", &observed(&[("pe", false)]), &[], None);
288        assert_eq!(findings.regressed, ["pe"]);
289    }
290
291    #[test]
292    fn accept_demotes_a_flapping_field_for_good() {
293        let mut baseline = Baseline::default();
294        baseline.accept("quote", &observed(&[("preMarket", true)]), None);
295        baseline.accept("quote", &observed(&[("preMarket", false)]), None);
296        baseline.accept("quote", &observed(&[("preMarket", true)]), None);
297        assert_eq!(
298            baseline.probes["quote"].fields["preMarket"],
299            Class::Sometimes
300        );
301        let findings = baseline.gate("quote", &observed(&[("preMarket", false)]), &[], None);
302        assert!(findings.is_clean());
303    }
304
305    #[test]
306    fn a_field_vanishing_entirely_demotes_on_accept_and_regresses_on_gate() {
307        let mut baseline = Baseline::default();
308        baseline.accept("quote", &observed(&[("pe", true)]), None);
309        let findings = baseline.gate("quote", &observed(&[]), &[], None);
310        assert_eq!(findings.regressed, ["pe"]);
311        baseline.accept("quote", &observed(&[]), None);
312        assert_eq!(baseline.probes["quote"].fields["pe"], Class::Sometimes);
313    }
314
315    #[test]
316    fn new_populated_fields_mark_the_lock_stale() {
317        let baseline = Baseline::default();
318        let findings = baseline.gate("quote", &observed(&[("spark", true)]), &[], None);
319        assert_eq!(findings.new_fields, ["spark"]);
320    }
321
322    #[test]
323    fn manifest_pins_silence_the_gate_with_and_without_wildcard() {
324        let mut baseline = Baseline::default();
325        baseline.accept(
326            "quote",
327            &observed(&[("preMarketPrice", true), ("preMarketTime", true)]),
328            None,
329        );
330        let now = observed(&[("preMarketPrice", false), ("preMarketTime", false)]);
331        let findings = baseline.gate("quote", &now, &["preMarket*".to_string()], None);
332        assert!(findings.is_clean());
333        let findings = baseline.gate("quote", &now, &["preMarketPrice".to_string()], None);
334        assert_eq!(findings.regressed, ["preMarketTime"]);
335    }
336
337    #[test]
338    fn gone_probes_are_reported_and_dropped() {
339        let mut baseline = Baseline::default();
340        baseline.accept("quote", &observed(&[("pe", true)]), None);
341        baseline.accept("chart", &observed(&[("meta", true)]), None);
342        let gone = baseline.retain_probes(&["quote".to_string()]);
343        assert_eq!(gone, ["chart"]);
344        assert!(!baseline.probes.contains_key("chart"));
345    }
346
347    #[test]
348    fn a_declared_field_nobody_populates_fails_until_accepted() {
349        let mut baseline = Baseline::default();
350        let spec_fields = declared(&["price", "cvar95"]);
351        let now = observed(&[("price", true)]);
352        baseline.accept("risk", &now, Some(&spec_fields));
353        let findings = baseline.gate("risk", &now, &[], Some(&spec_fields));
354        assert!(findings.is_clean(), "accepted uncovered debt passes");
355
356        let grown = declared(&["price", "cvar95", "omega"]);
357        let findings = baseline.gate("risk", &now, &[], Some(&grown));
358        assert_eq!(findings.uncovered, ["omega"]);
359    }
360
361    #[test]
362    fn covered_fields_drop_off_the_uncovered_list_on_accept() {
363        let mut baseline = Baseline::default();
364        let spec_fields = declared(&["price", "cvar95"]);
365        baseline.accept("risk", &observed(&[("price", true)]), Some(&spec_fields));
366        assert!(baseline.probes["risk"].uncovered.contains("cvar95"));
367        baseline.accept(
368            "risk",
369            &observed(&[("price", true), ("cvar95", true)]),
370            Some(&spec_fields),
371        );
372        assert!(baseline.probes["risk"].uncovered.is_empty());
373        assert_eq!(baseline.probes["risk"].fields["cvar95"], Class::Always);
374    }
375
376    #[test]
377    fn pinned_sometimes_fields_are_not_coverage_findings() {
378        let baseline = Baseline::default();
379        let spec_fields = declared(&["preMarketPrice"]);
380        let findings = baseline.gate(
381            "quote",
382            &observed(&[]),
383            &["preMarket*".to_string()],
384            Some(&spec_fields),
385        );
386        assert!(findings.is_clean());
387    }
388}