Skip to main content

sail_api/
evidence.rs

1//! Explanations, immutable baselines and comparisons of completed evidence.
2//!
3//! These read recorded project results only. They never establish proof of
4//! current inputs or generate proof edits.
5
6use serde::{Deserialize, Serialize};
7
8use crate::output::{Diagnostic, FunctionReport, OutcomeName, VerdictName};
9use crate::project::{Currentness, ProjectResult};
10use crate::proof::Target;
11
12/// Independent evidence contract version.
13pub const VERSION: u32 = 1;
14
15/// Explanation preserving exact verifier evidence instead of generating proof edits.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct Explanation {
18    /// Independent contract version.
19    pub version: u32,
20    /// Complete target identity.
21    pub target: Target,
22    /// Establishing run, including reused historical reports.
23    pub establishing_run: String,
24    /// Currentness of the project evidence.
25    pub currentness: Currentness,
26    /// Complete unchanged function report, with obligations/models/provenance.
27    pub function: FunctionReport,
28    /// Diagnostics with explicit producer attribution, if available.
29    pub attributed_diagnostics: Vec<Diagnostic>,
30    /// Remaining run diagnostics preserved without line-window guesses.
31    pub run_diagnostics: Vec<Diagnostic>,
32    /// Whether diagnostic/function linkage is authoritative.
33    pub diagnostic_attribution_complete: bool,
34    /// Informational limitations, never an invented missing model or verdict.
35    pub notes: Vec<String>,
36}
37
38/// An immutable independently retained baseline snapshot.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct Baseline {
41    /// Independently retained neutral contract snapshot evidence, when present.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub contracts: Option<Box<crate::contracts::Evidence>>,
44    /// Baseline contract version.
45    pub version: u32,
46    /// Owner-selected immutable name.
47    pub name: String,
48    /// Original job identity.
49    pub job_id: String,
50    /// Independently completed evidence, unchanged by later runs or job pruning.
51    pub result: ProjectResult,
52}
53
54/// Classification of one comparison entry.
55///
56/// Function classifications count a function that passed by Verus's totals
57/// (reported `unknown`, not attributed one by one) as verified.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum Change {
61    /// Same reported evidence class.
62    Unchanged,
63    /// A previously verified function now reports a settled failure.
64    Regressed,
65    /// A previously verified function no longer has a confirmed proof.
66    BecameUnknown,
67    /// A previously unproved function now verifies (confirmed, or passed by
68    /// Verus's totals).
69    Recovered,
70    /// Newly observed function.
71    Added,
72    /// No matching evidence: partial scopes do not establish removal.
73    NotObserved,
74    /// Absent from a finalized whole-target function inventory.
75    Removed,
76    /// Scope/runtime/mode differs; compare descriptively, not as a regression.
77    Incomparable,
78    /// Other non-proof transition.
79    Changed,
80}
81
82/// One target/function transition.
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct Difference {
85    /// Target identity including library/binary kind.
86    pub target: Target,
87    /// Exact function identity.
88    pub function: String,
89    /// Earlier reported verdict, absent when not observed or when the
90    /// functions sharing a repeated friendly name report different verdicts.
91    pub before: Option<VerdictName>,
92    /// Later reported verdict, absent when not observed or when the
93    /// functions sharing a repeated friendly name report different verdicts.
94    pub after: Option<VerdictName>,
95    /// Conservative comparison classification.
96    pub change: Change,
97    /// The earlier `unknown` verdict was classified as verified because the
98    /// function passed by Verus's totals (not attributed one by one).
99    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
100    pub before_passed_by_verus_totals: bool,
101    /// The later `unknown` verdict was classified as verified because the
102    /// function passed by Verus's totals (not attributed one by one).
103    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
104    pub after_passed_by_verus_totals: bool,
105    /// Exact attributed obligation IDs; ordinals are not semantically matched.
106    pub obligations: Vec<ObligationDifference>,
107}
108
109/// A comparison of one exact attributed obligation identity.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct ObligationDifference {
112    /// Exact producer identifier, never matched by a source-line heuristic.
113    pub id: String,
114    /// Earlier solver-derived obligation outcome.
115    pub before: Option<OutcomeName>,
116    /// Later solver-derived obligation outcome.
117    pub after: Option<OutcomeName>,
118    /// Whether a failure is advisory in the later or earlier evidence.
119    pub advisory: bool,
120    /// Descriptive transition; an advisory failure is not a function regression.
121    pub change: Change,
122}
123
124/// Comparison of explicit completed evidence; not a new proof of current inputs.
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub struct Comparison {
127    /// Independent contract version.
128    pub version: u32,
129    /// True only when recorded contexts, modes and requested scopes agree.
130    pub compatible: bool,
131    /// Earlier source revision.
132    pub before_revision: String,
133    /// Later source revision.
134    pub after_revision: String,
135    /// Later evidence currentness, never assumed from terminal lifecycle.
136    pub after_currentness: Currentness,
137    /// Differences and unchanged identities.
138    pub differences: Vec<Difference>,
139    /// Why comparisons cannot be interpreted as proof regressions.
140    pub notes: Vec<String>,
141}
142
143/// An explicit earlier evidence source, without guessing a baseline from history.
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
146pub enum Reference {
147    /// Completed durable job identity.
148    Job(String),
149    /// Immutable owner-selected baseline name.
150    Baseline(String),
151}
152
153/// Selects exact evidence without guessing diagnostic ownership or model values.
154///
155/// # Errors
156/// Returns a stable missing/ambiguous target, function, or obligation error.
157pub fn explain(
158    result: &ProjectResult,
159    target: &Target,
160    function: &str,
161    obligation: Option<&str>,
162) -> Result<Explanation, String> {
163    let matches: Vec<_> = result
164        .targets
165        .iter()
166        .filter(|t| {
167            t.package_id == target.package_id && t.target == target.name && t.kind == target.kind
168        })
169        .collect();
170    if matches.len() != 1 {
171        return Err("SAIL0904: exact target is missing or ambiguous".into());
172    }
173    let selected = matches[0];
174    let functions: Vec<_> = selected
175        .report
176        .crates
177        .iter()
178        .flat_map(|c| &c.functions)
179        .filter(|f| f.function == function)
180        .collect();
181    if functions.len() != 1 {
182        return Err("SAIL0904: exact function is missing or ambiguous".into());
183    }
184    let mut report = functions[0].clone();
185    if let Some(id) = obligation {
186        let Some(obligations) = report.obligations.as_mut() else {
187            return Err("SAIL0904: obligation attribution is unavailable".into());
188        };
189        if !obligations.iter().any(|o| o.id == id) {
190            return Err("SAIL0904: exact obligation was not observed".into());
191        }
192        obligations.retain(|o| o.id == id);
193    }
194    Ok(Explanation {
195        version: VERSION, target: target.clone(), establishing_run: selected.establishing_run.clone(),
196        currentness: result.currentness, function: report, attributed_diagnostics: Vec::new(),
197        run_diagnostics: selected.report.diagnostics.clone(), diagnostic_attribution_complete: false,
198        notes: vec!["Run diagnostics are retained; no line-window heuristic establishes their function ownership.".into()],
199    })
200}
201
202/// One recorded function as a comparison sees it.
203#[derive(Debug, Clone, Copy)]
204struct Entry<'a> {
205    report: &'a FunctionReport,
206    /// Reported `unknown` in a crate whose Verus totals clear its unknown
207    /// functions ([`crate::output::CrateReport::verus_totals_clear_unknown`]).
208    by_totals: bool,
209}
210
211impl Entry<'_> {
212    /// The reported verdict (`provisional` for a provisional establishment).
213    fn verdict(self) -> VerdictName {
214        effective(self.report)
215    }
216
217    /// The class a comparison classifies by. A function that passed by
218    /// Verus's totals counts as verified here, as Verus counted it; its
219    /// reported verdict stays `unknown`.
220    fn class(self) -> VerdictName {
221        if self.by_totals {
222            VerdictName::Verified
223        } else {
224            self.verdict()
225        }
226    }
227}
228
229type Records<'a> = std::collections::BTreeMap<(Target, String), Vec<Entry<'a>>>;
230
231fn functions(result: &ProjectResult) -> Records<'_> {
232    let mut records = Records::new();
233    for target in result.targets.iter().filter(|target| target.requested) {
234        let id = Target {
235            package_id: target.package_id.clone(),
236            name: target.target.clone(),
237            kind: target.kind.clone(),
238        };
239        for krate in &target.report.crates {
240            let cleared = krate.verus_totals_clear_unknown();
241            for function in &krate.functions {
242                records
243                    .entry((id.clone(), function.function.clone()))
244                    .or_default()
245                    .push(Entry {
246                        report: function,
247                        by_totals: cleared && effective(function) == VerdictName::Unknown,
248                    });
249            }
250        }
251    }
252    records
253}
254
255fn unique<'a>(entries: &[Entry<'a>]) -> Option<&'a FunctionReport> {
256    match entries {
257        [only] => Some(only.report),
258        _ => None,
259    }
260}
261
262/// One side of a function identity, as classified.
263#[derive(Debug, Default, Clone, Copy)]
264struct Side {
265    /// The reported verdict, when every entry reports the same one.
266    verdict: Option<VerdictName>,
267    /// The comparison class; `None` when not observed.
268    class: Option<VerdictName>,
269    /// Whether the class relies on Verus's totals.
270    by_totals: bool,
271}
272
273/// The entries' common class, or `None` when they disagree.
274fn side(entries: &[Entry<'_>]) -> Option<Side> {
275    let Some(first) = entries.first() else {
276        return Some(Side::default());
277    };
278    entries
279        .iter()
280        .all(|e| e.class() == first.class())
281        .then(|| Side {
282            verdict: entries
283                .iter()
284                .all(|e| e.verdict() == first.verdict())
285                .then(|| first.verdict()),
286            class: Some(first.class()),
287            by_totals: entries.iter().any(|e| e.by_totals),
288        })
289}
290
291/// Resolves one identity on both sides. One entry per side compares
292/// directly. A repeated friendly name (VI-0010) compares only when both sides
293/// hold the same number of entries and every entry on each side has the same
294/// class: every implementation then makes the same transition, whichever is
295/// which. Otherwise `None` (incomparable).
296fn resolve(left: &[Entry<'_>], right: &[Entry<'_>]) -> Option<(Side, Side)> {
297    let repeated = left.len() > 1 || right.len() > 1;
298    if repeated && left.len() != right.len() {
299        return None;
300    }
301    Some((side(left)?, side(right)?))
302}
303
304/// Classifies one transition between comparison classes.
305fn classify(before: Option<VerdictName>, after: Option<VerdictName>, removed: bool) -> Change {
306    match (before, after) {
307        (Some(a), Some(b)) if a == b => Change::Unchanged,
308        (Some(VerdictName::Verified), Some(VerdictName::Failed)) => Change::Regressed,
309        (Some(VerdictName::Verified), Some(VerdictName::Unknown | VerdictName::Provisional)) => {
310            Change::BecameUnknown
311        }
312        (Some(_), Some(VerdictName::Verified)) => Change::Recovered,
313        (None, Some(_)) => Change::Added,
314        (Some(_), None) if removed => Change::Removed,
315        (Some(_), None) => Change::NotObserved,
316        _ => Change::Changed,
317    }
318}
319
320fn scopes(result: &ProjectResult) -> Vec<(Target, String, Vec<String>)> {
321    let mut scopes: Vec<_> = result
322        .targets
323        .iter()
324        .filter(|t| t.requested)
325        .map(|target| {
326            (
327                Target {
328                    package_id: target.package_id.clone(),
329                    name: target.target.clone(),
330                    kind: target.kind.clone(),
331                },
332                target.report.mode.clone(),
333                target.report.command.clone(),
334            )
335        })
336        .collect();
337    scopes.sort();
338    scopes
339}
340
341/// What a comparison's notes report.
342#[derive(Debug, Default)]
343struct Tally {
344    /// Classified functions whose class relies on Verus's totals.
345    by_totals: usize,
346    /// Repeated friendly names compared as uniform groups.
347    repeated_compared: usize,
348    /// Functions holding those names (the larger side).
349    repeated_functions: usize,
350    /// Repeated friendly names left incomparable.
351    repeated_incomparable: usize,
352}
353
354/// Compares recorded evidence only when bound requested contexts/scopes agree.
355/// Runs without proof reuse do not establish a comparable runtime context.
356/// Absent functions remain unobserved; a partial run never proves their removal.
357///
358/// A function reported `unknown` that passed by Verus's totals
359/// ([`crate::output::CrateReport::verus_totals_clear_unknown`]) is classified
360/// as verified on either side, as Verus counted it. Its reported verdict stays
361/// `unknown` in [`Difference::before`] or [`Difference::after`], and the
362/// difference says the class relied on the totals.
363#[must_use]
364pub fn compare(before: &ProjectResult, after: &ProjectResult) -> Comparison {
365    let compatible = before.no_reuse.is_none()
366        && after.no_reuse.is_none()
367        && !before.context_sha256.is_empty()
368        && before.context_sha256 == after.context_sha256
369        && scopes(before) == scopes(after);
370    let after_project = after;
371    let left = functions(before);
372    let right = functions(after);
373    let ids: std::collections::BTreeSet<_> = left.keys().chain(right.keys()).cloned().collect();
374    let mut tally = Tally::default();
375    let differences = ids
376        .into_iter()
377        .map(|(target, function)| {
378            let key = (target.clone(), function.clone());
379            let l = left.get(&key).map_or(&[][..], Vec::as_slice);
380            let r = right.get(&key).map_or(&[][..], Vec::as_slice);
381            let repeated = l.len() > 1 || r.len() > 1;
382            let resolved = resolve(l, r);
383            if repeated && resolved.is_some() {
384                tally.repeated_compared += 1;
385                tally.repeated_functions += l.len().max(r.len());
386            } else if repeated {
387                tally.repeated_incomparable += 1;
388            }
389            let (old, new) = resolved.unwrap_or_default();
390            let change = if compatible && resolved.is_some() {
391                classify(old.class, new.class, inventory(after_project, &target))
392            } else {
393                Change::Incomparable
394            };
395            let classified = change != Change::Incomparable;
396            if classified {
397                let count = |entries: &[Entry<'_>]| entries.iter().filter(|e| e.by_totals).count();
398                tally.by_totals += count(l).max(count(r));
399            }
400            Difference {
401                target,
402                function,
403                before: old.verdict,
404                after: new.verdict,
405                change,
406                before_passed_by_verus_totals: classified && old.by_totals,
407                after_passed_by_verus_totals: classified && new.by_totals,
408                obligations: if repeated {
409                    Vec::new()
410                } else {
411                    obligations(unique(l), unique(r), compatible)
412                },
413            }
414        })
415        .collect();
416    Comparison {
417        version: VERSION,
418        compatible,
419        before_revision: before.input_revision.clone(),
420        after_revision: after.input_revision.clone(),
421        after_currentness: after.currentness,
422        differences,
423        notes: comparison_notes(compatible, &tally),
424    }
425}
426
427fn comparison_notes(compatible: bool, tally: &Tally) -> Vec<String> {
428    let mut notes = Vec::new();
429    if !compatible {
430        notes.push("Requested scope, mode or runtime context differs; transitions are descriptive, not proof regressions.".into());
431    }
432    if tally.by_totals > 0 {
433        notes.push(format!(
434            "{} function(s) reported `unknown` passed by Verus's totals (not attributed one by one); the comparison counts them as passing, as Verus did. Their verdicts stay `unknown`.",
435            tally.by_totals
436        ));
437    }
438    if tally.repeated_compared > 0 {
439        notes.push(format!(
440            "Entries are friendly function names: {} repeated name(s), shared by {} functions (VI-0010), were each compared as a group, since every function sharing the name has the same result on each side.",
441            tally.repeated_compared, tally.repeated_functions
442        ));
443    }
444    if tally.repeated_incomparable > 0 {
445        notes.push(format!(
446            "Repeated friendly function names cannot identify one implementation; {} such name(s) whose functions differ in result or number are incomparable (VI-0010).",
447            tally.repeated_incomparable
448        ));
449    }
450    notes
451}
452
453fn effective(report: &FunctionReport) -> VerdictName {
454    if report.establishment == crate::output::EstablishmentName::Provisional {
455        VerdictName::Provisional
456    } else {
457        report.verdict
458    }
459}
460
461fn inventory(project: &ProjectResult, id: &Target) -> bool {
462    project.error.is_none()
463        && project.exit_code == Some(0)
464        && project.targets.iter().any(|target| {
465            crate::acceptance::complete_target(target).is_some()
466                && target.package_id == id.package_id
467                && target.target == id.name
468                && target.kind == id.kind
469                && target.report.crates.iter().all(|report| {
470                    report.verus.success == Some(true)
471                        && report.verus.encountered_vir_error != Some(true)
472                })
473        })
474}
475
476fn obligations(
477    before: Option<&FunctionReport>,
478    after: Option<&FunctionReport>,
479    compatible: bool,
480) -> Vec<ObligationDifference> {
481    let index = |function: Option<&FunctionReport>| {
482        function
483            .and_then(|f| f.obligations.as_ref())
484            .into_iter()
485            .flatten()
486            .map(|obligation| (obligation.id.clone(), obligation.clone()))
487            .collect::<std::collections::BTreeMap<_, _>>()
488    };
489    let left = index(before);
490    let right = index(after);
491    left.keys()
492        .chain(right.keys())
493        .cloned()
494        .collect::<std::collections::BTreeSet<_>>()
495        .into_iter()
496        .map(|id| {
497            let old = left.get(&id);
498            let new = right.get(&id);
499            let before = old.map(|o| o.outcome);
500            let after = new.map(|o| o.outcome);
501            let advisory = new.or(old).is_some_and(|o| o.advisory);
502            let change = if compatible {
503                match (before, after) {
504                    (Some(a), Some(b)) if a == b => Change::Unchanged,
505                    (Some(OutcomeName::Proved), Some(OutcomeName::Failed)) if !advisory => {
506                        Change::Regressed
507                    }
508                    (Some(OutcomeName::Proved), Some(OutcomeName::Unknown)) => {
509                        Change::BecameUnknown
510                    }
511                    (Some(_), Some(OutcomeName::Proved)) => Change::Recovered,
512                    (None, Some(_)) => Change::Added,
513                    (Some(_), None) => Change::NotObserved,
514                    _ => Change::Changed,
515                }
516            } else {
517                Change::Incomparable
518            };
519            ObligationDifference {
520                id,
521                before,
522                after,
523                advisory,
524                change,
525            }
526        })
527        .collect()
528}