Skip to main content

seam_atlas/
diff.rs

1use std::collections::BTreeMap;
2
3use crate::model::{Outcome, Pipeline, Pred, Value};
4use crate::partition::{eval_pred_on_box, split_box_for_pred, CoordSpan, TriEval};
5
6/// Canonical equivalence class of inputs whose behavior changed from `old` to `new`.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct DiffClass {
9    pub old_outcome: Outcome,
10    pub old_rule: Option<String>,
11    pub new_outcome: Outcome,
12    pub new_rule: Option<String>,
13    pub region_count: usize,
14    pub point_volume: u128,
15    pub witness: Vec<Value>,
16}
17
18/// Complete behavioral diff report across 100% of the shared input `Schema`.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct DiffReport {
21    pub is_equivalent: bool,
22    pub total_volume: u128,
23    pub unchanged_volume: u128,
24    pub changed_volume: u128,
25    pub classes: Vec<DiffClass>,
26}
27
28/// Computes an exhaustive behavioral diff between `old` and `new` over their shared `Schema`.
29///
30/// Returns `None` if `old.schema != new.schema`.
31pub fn diff_pipelines(old: &Pipeline, new: &Pipeline) -> Option<DiffReport> {
32    if old.schema != new.schema {
33        return None;
34    }
35    let root: Vec<CoordSpan> = old
36        .schema
37        .fields
38        .iter()
39        .map(|f| CoordSpan::full_from_domain(&f.domain))
40        .collect();
41    let old_idx: Vec<usize> = (0..old.rules.len()).collect();
42    let new_idx: Vec<usize> = (0..new.rules.len()).collect();
43
44    let mut acc = DiffAccum::default();
45    co_refine(old, new, root, &old_idx, &new_idx, &mut acc);
46
47    let mut classes: Vec<DiffClass> = acc.classes.into_values().collect();
48    classes.sort_by(|a, b| {
49        b.point_volume
50            .cmp(&a.point_volume)
51            .then_with(|| a.old_outcome.label.cmp(&b.old_outcome.label))
52            .then_with(|| a.new_outcome.label.cmp(&b.new_outcome.label))
53    });
54
55    let total = acc.unchanged_volume.saturating_add(acc.changed_volume);
56    Some(DiffReport {
57        is_equivalent: classes.is_empty(),
58        total_volume: total,
59        unchanged_volume: acc.unchanged_volume,
60        changed_volume: acc.changed_volume,
61        classes,
62    })
63}
64
65type DiffKey = (Outcome, Option<String>, Outcome, Option<String>);
66
67#[derive(Default)]
68struct DiffAccum {
69    unchanged_volume: u128,
70    changed_volume: u128,
71    classes: BTreeMap<DiffKey, DiffClass>,
72}
73
74enum SideStatus<'a> {
75    Resolved(&'a Outcome, Option<&'a str>),
76    Pending {
77        surviving: Vec<usize>,
78        first_pred: &'a Pred,
79    },
80}
81
82fn step_side<'a>(
83    pipeline: &'a Pipeline,
84    spans: &[CoordSpan],
85    candidates: &[usize],
86) -> SideStatus<'a> {
87    let mut surviving = Vec::with_capacity(candidates.len());
88    let mut split_pred: Option<&'a Pred> = None;
89
90    for &idx in candidates {
91        let rule = &pipeline.rules[idx];
92        let mut rule_false = false;
93        let mut first_unresolved: Option<&'a Pred> = None;
94
95        for p in &rule.when_all {
96            match eval_pred_on_box(p, spans) {
97                TriEval::AlwaysTrue => {}
98                TriEval::AlwaysFalse => {
99                    rule_false = true;
100                    break;
101                }
102                TriEval::Split { .. } => {
103                    if first_unresolved.is_none() {
104                        first_unresolved = Some(p);
105                    }
106                }
107            }
108        }
109
110        if rule_false {
111            continue;
112        }
113        if surviving.is_empty() && first_unresolved.is_none() {
114            return SideStatus::Resolved(&rule.outcome, Some(rule.id.as_str()));
115        }
116        if split_pred.is_none() {
117            split_pred = first_unresolved;
118        }
119        surviving.push(idx);
120    }
121
122    match split_pred {
123        Some(pred) => SideStatus::Pending {
124            surviving,
125            first_pred: pred,
126        },
127        None => SideStatus::Resolved(&pipeline.default_outcome, None),
128    }
129}
130
131fn box_volume(spans: &[CoordSpan]) -> u128 {
132    let mut prod = 1u128;
133    for s in spans {
134        prod = prod.saturating_mul(s.cardinality());
135    }
136    prod
137}
138
139fn co_refine(
140    old: &Pipeline,
141    new: &Pipeline,
142    spans: Vec<CoordSpan>,
143    old_candidates: &[usize],
144    new_candidates: &[usize],
145    acc: &mut DiffAccum,
146) {
147    let st_old = step_side(old, &spans, old_candidates);
148    let st_new = step_side(new, &spans, new_candidates);
149
150    match (st_old, st_new) {
151        (SideStatus::Resolved(o_out, o_rule), SideStatus::Resolved(n_out, n_rule)) => {
152            let vol = box_volume(&spans);
153            if o_out == n_out {
154                acc.unchanged_volume = acc.unchanged_volume.saturating_add(vol);
155            } else {
156                acc.changed_volume = acc.changed_volume.saturating_add(vol);
157                let witness: Vec<Value> = spans.iter().map(CoordSpan::witness).collect();
158
159                // Verify the concrete witness directly against both pipelines.
160                let (chk_o, chk_or) = old.eval(&witness);
161                let (chk_n, chk_nr) = new.eval(&witness);
162                debug_assert_eq!(chk_o, o_out);
163                debug_assert_eq!(chk_n, n_out);
164                debug_assert_eq!(chk_or, o_rule);
165                debug_assert_eq!(chk_nr, n_rule);
166
167                let key: DiffKey = (
168                    o_out.clone(),
169                    o_rule.map(str::to_owned),
170                    n_out.clone(),
171                    n_rule.map(str::to_owned),
172                );
173                let entry = acc.classes.entry(key).or_insert_with(|| DiffClass {
174                    old_outcome: o_out.clone(),
175                    old_rule: o_rule.map(str::to_owned),
176                    new_outcome: n_out.clone(),
177                    new_rule: n_rule.map(str::to_owned),
178                    region_count: 0,
179                    point_volume: 0,
180                    witness,
181                });
182                entry.region_count += 1;
183                entry.point_volume = entry.point_volume.saturating_add(vol);
184            }
185        }
186        (
187            SideStatus::Pending {
188                surviving: s_old,
189                first_pred,
190            },
191            SideStatus::Pending {
192                surviving: s_new, ..
193            },
194        ) => {
195            for child in split_box_for_pred(&spans, first_pred) {
196                co_refine(old, new, child, &s_old, &s_new, acc);
197            }
198        }
199        (
200            SideStatus::Pending {
201                surviving: s_old,
202                first_pred,
203            },
204            SideStatus::Resolved(_, _),
205        ) => {
206            for child in split_box_for_pred(&spans, first_pred) {
207                co_refine(old, new, child, &s_old, new_candidates, acc);
208            }
209        }
210        (
211            SideStatus::Resolved(_, _),
212            SideStatus::Pending {
213                surviving: s_new,
214                first_pred,
215            },
216        ) => {
217            for child in split_box_for_pred(&spans, first_pred) {
218                co_refine(old, new, child, old_candidates, &s_new, acc);
219            }
220        }
221    }
222}