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