Skip to main content

sail_api/
assurance.rs

1//! Requirement-aware views derived from authenticated neutral source-job evidence.
2//!
3//! This interface describes the submitted immutable source snapshot. A client must
4//! separately establish that its live source still matches, and establish any
5//! contract-to-requirement entailment. Reading a view never runs a verifier.
6
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, BTreeSet};
9
10use crate::contracts::{CheckCounts, ContractProof, LoweringManifest, ProofState};
11use crate::jobs::{Lifecycle, ResultDocument};
12use crate::output::{
13    AnswerName, AttributionStatus, EstablishmentName, FunctionReport, OutcomeName, SolverInfo,
14    VerdictName,
15};
16use crate::project::{Currentness, ProjectResult};
17
18/// Requirement assurance view contract version.
19pub const VERSION: u32 = 2;
20
21/// Evidence strength, independent of establishment and source currentness.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum EvidenceTier {
25    /// Observations of executed test cases.
26    Sampled,
27    /// Exhaustive checking within declared finite bounds.
28    Bounded,
29    /// An attributed SMT-backed implementation proof.
30    SmtVerified,
31    /// An independently checked proof certificate.
32    CertificateChecked,
33    /// A proof checked by a trusted proof-assistant kernel.
34    KernelChecked,
35}
36
37/// Established relationship; matching requirement identities cannot add one.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum Relationship {
41    /// Exact submitted implementation satisfies its stated neutral contract.
42    ContractToCode,
43}
44
45/// Evidence applies to a sealed source snapshot, not implicitly to live files.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "kebab-case")]
48pub enum Scope {
49    /// The source whose exact bytes were submitted and authenticated by Sail.
50    SourceSnapshot,
51}
52
53/// Mutation observations remain distinct from the underlying proof verdict.
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(rename_all = "kebab-case")]
56pub enum MutationStatus {
57    /// No mutation campaign is established by this source-job result.
58    NotEstablished,
59    /// A reauthenticated bounded campaign, separate from the underlying proof tier.
60    Bounded {
61        /// Exact durable campaign identity.
62        campaign_id: String,
63        /// Versioned admitted mutation policy.
64        policy: String,
65        /// Whole campaign passes only with every candidate conclusively killed.
66        passed: bool,
67        /// Actual target-function conclusive verifier rejections.
68        killed: usize,
69        /// Actual target-function whole proofs.
70        survived: usize,
71        /// Missing, unknown or unexecuted target observations.
72        inconclusive: usize,
73    },
74}
75
76/// One exact guarantee, its implementation proof and retained provenance.
77#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
78pub struct Evidence {
79    /// Content-derived identity, independent of source line numbering.
80    pub obligation_id: String,
81    /// The relationship this evidence actually checks.
82    pub relationship: Relationship,
83    /// Exact original qualified function name.
84    pub function: String,
85    /// Exact source snapshot digest.
86    pub source_sha256: String,
87    /// Exact guarantee syntax digest from the authenticated lowering manifest.
88    pub guarantee_sha256: String,
89    /// Exact generated shadow digest.
90    pub lowered_sha256: String,
91    /// Original backend report digest, not an invented verifier receipt.
92    pub backend_sha256: String,
93    /// The conservative whole-job proof outcome, never a source refutation.
94    pub outcome: ProofState,
95    /// Present only for complete confirmed evidence with actual tool identity.
96    pub establishment: Option<EstablishmentName>,
97    /// Present only when that strength has actually been established.
98    pub tier: Option<EvidenceTier>,
99    /// Scope of the proof; live source matching is a client responsibility.
100    pub scope: Scope,
101    /// All actual distinct solver identities, sorted canonically.
102    pub solvers: Vec<SolverInfo>,
103    /// Explicit assumptions, trust and missing relationships.
104    pub qualifiers: Vec<String>,
105    /// Mutation establishment is never inferred from a passing proof.
106    pub mutation: MutationStatus,
107}
108
109/// Evidence grouped by stable requirement identity.
110#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
111pub struct Requirement {
112    /// Original owner-selected identity carried by a neutral contract.
113    pub requirement_id: String,
114    /// Sorted exact function/guarantee relationships for this identity.
115    pub evidence: Vec<Evidence>,
116}
117
118/// Versioned read-only view over one authenticated neutral source job.
119#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
120pub struct View {
121    /// Equals [`VERSION`].
122    pub version: u32,
123    /// Exact retained job identity.
124    pub job_id: String,
125    /// Currentness of caller files is unknown to a source-snapshot service.
126    pub currentness: Currentness,
127    /// Requirement groups sorted by stable identity.
128    pub requirements: Vec<Requirement>,
129}
130
131fn digest(bytes: &[u8]) -> String {
132    sail_key::QueryKey(sail_key::sha256(bytes)).to_string()
133}
134
135fn valid_digest(value: &str) -> bool {
136    value.len() == 64
137        && value
138            .bytes()
139            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
140}
141
142/// Project an already authenticated source-job result, checking its raw proof
143/// projection again. The daemon authenticates source and stored output seals
144/// before calling this function; caller-created documents are not authentication.
145///
146/// # Errors
147/// Refuses unfinished jobs, missing evidence, mismatched attribution and invalid
148/// content identities. Unknown and incomplete proofs retain no established tier.
149#[allow(
150    clippy::too_many_lines,
151    reason = "One projection checks all attribution before constructing any assurance row."
152)]
153pub fn from_contract_result(document: &ResultDocument) -> Result<View, String> {
154    let invalid = || "SAIL3143: invalid or incomplete neutral assurance evidence".to_owned();
155    let contracts = document.contracts.as_deref().ok_or_else(invalid)?;
156    let backend: ProjectResult =
157        serde_json::from_value(document.result.clone().ok_or_else(invalid)?)
158            .map_err(|_| invalid())?;
159    let manifest = &contracts.manifest;
160    if document.job.version != crate::jobs::VERSION
161        || document.job.state != Lifecycle::Completed
162        || document.job.id.is_empty()
163        || document.job.error.is_some()
164        || document.repair.is_some()
165        || contracts.version != crate::contracts::VERSION
166        || !matches!(
167            (manifest.version, manifest.contract_version),
168            (1 | 2, 1) | (3, 2)
169        )
170        || manifest.bindings.is_empty()
171        || document.job.input_revision.as_deref() != Some(manifest.original_sha256.as_str())
172        || !valid_digest(&manifest.original_sha256)
173        || !valid_digest(&manifest.lowered_sha256)
174        || !valid_digest(&contracts.translation_trust.source_policy_sha256)
175        || !valid_digest(&contracts.translation_trust.metadata_sha256)
176        || !valid_digest(&contracts.translation_trust.cargo_lock_sha256)
177        || backend.kind != "sail-project-result"
178        || backend.schema_version != crate::project::SCHEMA_VERSION
179        || document.job.exit_code.is_none()
180        || document.job.exit_code != backend.exit_code
181        || contracts.proof != observed_contract_proof(manifest, &backend)
182    {
183        return Err(invalid());
184    }
185    let mut seen = BTreeSet::new();
186    for binding in &manifest.bindings {
187        if binding.requirement_id.is_empty()
188            || binding.function.is_empty()
189            || binding.lowered_function.is_empty()
190            || !valid_digest(&binding.guarantee_sha256)
191            || !seen.insert((&binding.requirement_id, &binding.function))
192        {
193            return Err(invalid());
194        }
195    }
196    let backend_sha256 = digest(&serde_json::to_vec(&backend).map_err(|_| invalid())?);
197    let mut solvers = BTreeMap::new();
198    let mut complete_identity =
199        !backend.targets.is_empty() && valid_digest(&backend.context_sha256);
200    for target in &backend.targets {
201        if let Some(solver) = &target.report.solver {
202            complete_identity &= !solver.name.is_empty()
203                && solver.version.as_ref().is_some_and(|v| !v.is_empty())
204                && solver.sha256.as_deref().is_some_and(valid_digest);
205            solvers.insert(
206                serde_json::to_string(solver).map_err(|_| invalid())?,
207                solver.clone(),
208            );
209        } else {
210            complete_identity = false;
211        }
212    }
213    let confirmed = contracts.proof.state == ProofState::Proved && complete_identity;
214    let mut grouped: BTreeMap<String, Vec<Evidence>> = BTreeMap::new();
215    for binding in &manifest.bindings {
216        let mut qualifiers = vec![
217            "applies to the exact submitted source snapshot under its stated preconditions".into(),
218            format!(
219                "neutral lowering version {}: {}",
220                manifest.version, manifest.arithmetic
221            ),
222            "neutral source translation and the pinned Verus/SMT toolchain are trusted".into(),
223            "contract-to-requirement entailment and required-input feasibility are not established"
224                .into(),
225            "mutation assurance and termination are not established by this result".into(),
226        ];
227        if !complete_identity {
228            qualifiers.push(
229                "complete original solver identity is unavailable; no tier is established".into(),
230            );
231        }
232        qualifiers.sort();
233        let identity = serde_json::to_vec(&(
234            &manifest.original_sha256,
235            &binding.function,
236            &binding.guarantee_sha256,
237            &backend.context_sha256,
238        ))
239        .map_err(|_| invalid())?;
240        grouped
241            .entry(binding.requirement_id.clone())
242            .or_default()
243            .push(Evidence {
244                obligation_id: format!("neutral:{}", digest(&identity)),
245                relationship: Relationship::ContractToCode,
246                function: binding.function.clone(),
247                source_sha256: manifest.original_sha256.clone(),
248                guarantee_sha256: binding.guarantee_sha256.clone(),
249                lowered_sha256: manifest.lowered_sha256.clone(),
250                backend_sha256: backend_sha256.clone(),
251                outcome: contracts.proof.state,
252                establishment: confirmed.then_some(EstablishmentName::Confirmed),
253                tier: confirmed.then_some(EvidenceTier::SmtVerified),
254                scope: Scope::SourceSnapshot,
255                solvers: solvers.values().cloned().collect(),
256                qualifiers,
257                mutation: MutationStatus::NotEstablished,
258            });
259    }
260    let requirements = grouped
261        .into_iter()
262        .map(|(requirement_id, mut evidence)| {
263            evidence.sort_by(|a, b| a.obligation_id.cmp(&b.obligation_id));
264            Requirement {
265                requirement_id,
266                evidence,
267            }
268        })
269        .collect();
270    Ok(View {
271        version: VERSION,
272        job_id: document.job.id.clone(),
273        currentness: Currentness::Unknown,
274        requirements,
275    })
276}
277
278/// Recompute the conservative neutral proof projection from original backend records.
279///
280/// This is shared by source-job validation and assurance views.
281#[must_use]
282pub fn observed_contract_proof(
283    manifest: &LoweringManifest,
284    backend: &ProjectResult,
285) -> ContractProof {
286    let mut checks = CheckCounts::default();
287    let mut reasons = BTreeSet::new();
288    for check in backend
289        .targets
290        .iter()
291        .flat_map(|t| &t.report.crates)
292        .flat_map(|c| &c.functions)
293        .filter_map(|f| f.obligations.as_ref())
294        .flatten()
295        .flat_map(|o| &o.checks)
296    {
297        match check.answer {
298            Some(AnswerName::Unsat) => checks.unsat += 1,
299            Some(AnswerName::Sat) => checks.sat += 1,
300            Some(AnswerName::Unknown) => {
301                checks.unknown += 1;
302                if let Some(reason) = &check.reason_unknown {
303                    reasons.insert(reason.clone());
304                }
305            }
306            None => checks.missing_answer += 1,
307        }
308        checks.missing_source += usize::from(check.source.is_none());
309    }
310    let targets = backend
311        .targets
312        .iter()
313        .filter(|t| t.requested)
314        .collect::<Vec<_>>();
315    let mut proved = BTreeSet::new();
316    for binding in &manifest.bindings {
317        let matches = targets
318            .iter()
319            .flat_map(|t| &t.report.crates)
320            .flat_map(|c| &c.functions)
321            .filter(|f| f.function == binding.lowered_function)
322            .collect::<Vec<_>>();
323        if matches.len() == 1 && function_proved(matches[0]) {
324            proved.insert(binding.lowered_function.clone());
325        }
326    }
327    let complete = backend.currentness == Currentness::Current
328        && backend.error.is_none()
329        && backend.no_reuse.is_none()
330        && backend.exit_code == Some(0)
331        && backend.targets.iter().all(|t| {
332            t.complete
333                && t.report.attribution.status == AttributionStatus::Complete
334                && t.report.attribution.unmatched_sessions == 0
335                && t.report.invariant_violations().is_empty()
336        })
337        && !targets.is_empty()
338        && targets.iter().all(|t| {
339            t.complete
340                && t.report.error.is_none()
341                && t.report.exit_code == Some(0)
342                && !t.report.crates.is_empty()
343                && t.report.crates.iter().all(|c| {
344                    c.verus.success == Some(true)
345                        && c.verus.encountered_vir_error == Some(false)
346                        && c.verus.errors == Some(0)
347                })
348        })
349        && !manifest.bindings.is_empty()
350        && manifest
351            .bindings
352            .iter()
353            .all(|b| proved.contains(&b.lowered_function))
354        && checks.unsat > 0
355        && checks.sat == 0
356        && checks.unknown == 0
357        && checks.missing_answer == 0
358        && checks.missing_source == 0;
359    ContractProof {
360        state: if complete {
361            ProofState::Proved
362        } else {
363            ProofState::NotProved
364        },
365        checks,
366        unknown_reasons: reasons.into_iter().collect(),
367        proved_functions: proved.into_iter().collect(),
368    }
369}
370
371fn function_proved(function: &FunctionReport) -> bool {
372    if function.verdict != VerdictName::Verified
373        || function.establishment != EstablishmentName::Confirmed
374        || function.unstable
375        || function.verus_success != Some(true)
376        || function.provenance.checks_unrecorded != 0
377    {
378        return false;
379    }
380    let Some(obligations) = &function.obligations else {
381        return false;
382    };
383    let primary = obligations
384        .iter()
385        .filter(|o| !o.advisory)
386        .collect::<Vec<_>>();
387    !primary.is_empty()
388        && primary.iter().all(|o| {
389            o.outcome == OutcomeName::Proved
390                && !o.unstable
391                && !o.checks.is_empty()
392                && o.checks
393                    .iter()
394                    .all(|c| c.answer == Some(AnswerName::Unsat) && c.source.is_some())
395        })
396}