Skip to main content

sail_api/
assurance.rs

1//! Evidence-strength vocabulary and the conservative whole-run proof rules
2//! shared by requirement attribution ([`crate::attribution`], ADR 0104).
3//!
4//! Nothing here runs a verifier. Unknown and incomplete proofs never establish
5//! a tier.
6
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, BTreeSet};
9
10use crate::output::{
11    AnswerName, AttributionStatus, EstablishmentName, FunctionReport, OutcomeName, SolverInfo,
12    VerdictName,
13};
14use crate::project::{Currentness, ProjectResult};
15
16/// Evidence strength, independent of establishment and source currentness.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
18#[serde(rename_all = "kebab-case")]
19pub enum EvidenceTier {
20    /// Observations of executed test cases.
21    Sampled,
22    /// Exhaustive checking within declared finite bounds.
23    Bounded,
24    /// An attributed SMT-backed implementation proof.
25    SmtVerified,
26    /// An independently checked proof certificate.
27    CertificateChecked,
28    /// A proof checked by a trusted proof-assistant kernel.
29    KernelChecked,
30}
31
32/// Mutation observations remain distinct from the underlying proof verdict.
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "kebab-case")]
35pub enum MutationStatus {
36    /// No mutation campaign is established by this source-job result.
37    NotEstablished,
38    /// A reauthenticated bounded campaign, separate from the underlying proof tier.
39    Bounded {
40        /// Exact durable campaign identity.
41        campaign_id: String,
42        /// Versioned admitted mutation policy.
43        policy: String,
44        /// Whole campaign passes only with every candidate conclusively killed.
45        passed: bool,
46        /// Actual target-function conclusive verifier rejections.
47        killed: usize,
48        /// Actual target-function whole proofs.
49        survived: usize,
50        /// Missing, unknown or unexecuted target observations.
51        inconclusive: usize,
52    },
53}
54
55/// Whether the attributed function was proved under its stated preconditions.
56///
57/// `NotProved` covers failed, unknown, incomplete and unattributed evidence; it
58/// is never a refutation of the source.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "kebab-case")]
61pub enum ProofState {
62    /// Every required record is complete and attributed, with no failure or unknown.
63    Proved,
64    /// Anything else.
65    NotProved,
66}
67
68/// Counts of every recorded solver check answer in one backend result.
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
70pub struct CheckCounts {
71    /// Checks answered `unsat`.
72    pub unsat: usize,
73    /// Checks answered `sat`.
74    pub sat: usize,
75    /// Checks answered `unknown`.
76    pub unknown: usize,
77    /// Checks with no recorded answer.
78    pub missing_answer: usize,
79    /// Checks with no recorded source.
80    pub missing_source: usize,
81}
82
83pub(crate) fn digest(bytes: &[u8]) -> String {
84    sail_key::QueryKey(sail_key::sha256(bytes)).to_string()
85}
86
87pub(crate) fn valid_digest(value: &str) -> bool {
88    value.len() == 64
89        && value
90            .bytes()
91            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
92}
93
94/// Every recorded check answer, including advisory obligations and dependency targets.
95pub(crate) fn check_counts(backend: &ProjectResult) -> (CheckCounts, BTreeSet<String>) {
96    let mut checks = CheckCounts::default();
97    let mut reasons = BTreeSet::new();
98    for check in backend
99        .targets
100        .iter()
101        .flat_map(|t| &t.report.crates)
102        .flat_map(|c| &c.functions)
103        .filter_map(|f| f.obligations.as_ref())
104        .flatten()
105        .flat_map(|o| &o.checks)
106    {
107        match check.answer {
108            Some(AnswerName::Unsat) => checks.unsat += 1,
109            Some(AnswerName::Sat) => checks.sat += 1,
110            Some(AnswerName::Unknown) => {
111                checks.unknown += 1;
112                if let Some(reason) = &check.reason_unknown {
113                    reasons.insert(reason.clone());
114                }
115            }
116            None => checks.missing_answer += 1,
117        }
118        checks.missing_source += usize::from(check.source.is_none());
119    }
120    (checks, reasons)
121}
122
123pub(crate) fn requested_targets(backend: &ProjectResult) -> Vec<&crate::project::TargetResult> {
124    backend.targets.iter().filter(|t| t.requested).collect()
125}
126
127/// Whether exactly one requested-target function has this exact name and it is proved.
128pub(crate) fn exactly_one_proved(targets: &[&crate::project::TargetResult], name: &str) -> bool {
129    let matches = targets
130        .iter()
131        .flat_map(|t| &t.report.crates)
132        .flat_map(|c| &c.functions)
133        .filter(|f| f.function == name)
134        .collect::<Vec<_>>();
135    matches.len() == 1 && function_proved(matches[0])
136}
137
138/// Whole-run completeness: one passing function cannot promote an incomplete run.
139pub(crate) fn run_complete(backend: &ProjectResult, checks: &CheckCounts) -> bool {
140    let targets = requested_targets(backend);
141    backend.currentness == Currentness::Current
142        && backend.error.is_none()
143        && backend.no_reuse.is_none()
144        && backend.exit_code == Some(0)
145        && backend.targets.iter().all(|t| {
146            t.complete
147                && t.report.attribution.status == AttributionStatus::Complete
148                && t.report.attribution.unmatched_sessions == 0
149                && t.report.invariant_violations().is_empty()
150        })
151        && !targets.is_empty()
152        && targets.iter().all(|t| {
153            t.complete
154                && t.report.error.is_none()
155                && t.report.exit_code == Some(0)
156                && !t.report.crates.is_empty()
157                && t.report.crates.iter().all(|c| {
158                    c.verus.success == Some(true)
159                        && c.verus.encountered_vir_error == Some(false)
160                        && c.verus.errors == Some(0)
161                })
162        })
163        && checks.unsat > 0
164        && checks.sat == 0
165        && checks.unknown == 0
166        && checks.missing_answer == 0
167        && checks.missing_source == 0
168}
169
170/// Complete actual solver identity across every target, with the sorted distinct identities.
171pub(crate) fn solver_identities(backend: &ProjectResult) -> Result<(bool, Vec<SolverInfo>), ()> {
172    let mut solvers = BTreeMap::new();
173    let mut complete_identity =
174        !backend.targets.is_empty() && valid_digest(&backend.context_sha256);
175    for target in &backend.targets {
176        if let Some(solver) = &target.report.solver {
177            complete_identity &= !solver.name.is_empty()
178                && solver.version.as_ref().is_some_and(|v| !v.is_empty())
179                && solver.sha256.as_deref().is_some_and(valid_digest);
180            solvers.insert(
181                serde_json::to_string(solver).map_err(|_| ())?,
182                solver.clone(),
183            );
184        } else {
185            complete_identity = false;
186        }
187    }
188    Ok((complete_identity, solvers.into_values().collect()))
189}
190
191/// Qualifiers shared by every requirement assurance row, sorted by the caller.
192pub(crate) const SHARED_QUALIFIERS: [&str; 2] = [
193    "contract-to-requirement entailment and required-input feasibility are not established",
194    "mutation assurance and termination are not established by this result",
195];
196
197/// Added when solver identity is incomplete.
198pub(crate) const NO_IDENTITY_QUALIFIER: &str =
199    "complete original solver identity is unavailable; no tier is established";
200
201pub(crate) fn function_proved(function: &FunctionReport) -> bool {
202    if function.verdict != VerdictName::Verified
203        || function.establishment != EstablishmentName::Confirmed
204        || function.unstable
205        || function.verus_success != Some(true)
206        || function.provenance.checks_unrecorded != 0
207    {
208        return false;
209    }
210    let Some(obligations) = &function.obligations else {
211        return false;
212    };
213    let primary = obligations
214        .iter()
215        .filter(|o| !o.advisory)
216        .collect::<Vec<_>>();
217    !primary.is_empty()
218        && primary.iter().all(|o| {
219            o.outcome == OutcomeName::Proved
220                && !o.unstable
221                && !o.checks.is_empty()
222                && o.checks
223                    .iter()
224                    .all(|c| c.answer == Some(AnswerName::Unsat) && c.source.is_some())
225        })
226}