Skip to main content

sail_api/
output.rs

1//! The `sail verify --output json` document, schema version 2.
2//!
3//! The schema is documented in `docs/output-schema.md`; the JSON Schema is
4//! [`JSON_SCHEMA`] (`crates/sail-api/schema/verify-output-v2.json`). The
5//! types ignore unknown fields when read back, as consumers must; the JSON
6//! Schema is strict, and tests check that it requires every field the types
7//! write and allows no other.
8//!
9//! Compatibility: within schema version 2, fields are only ever added
10//! (consumers must ignore fields they do not know); a field is never
11//! removed, renamed or given a different meaning. Any such change bumps
12//! [`SCHEMA_VERSION`].
13
14use serde::{Deserialize, Serialize};
15
16use sail_ledger::{
17    CheckRecord, Establishment, FunctionRecord, ObligationRecord, Outcome, Source, SourceSummary,
18    Verdict,
19};
20
21/// The schema version this module writes.
22pub const SCHEMA_VERSION: u32 = 2;
23
24/// The JSON Schema (draft 2020-12) for schema version 2.
25pub const JSON_SCHEMA: &str = include_str!("../schema/verify-output-v2.json");
26
27/// The whole document.
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct Report {
30    /// Complete-run seed portfolio evidence, only when explicitly requested.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub portfolio: Option<PortfolioReport>,
33    /// Always [`SCHEMA_VERSION`].
34    pub schema_version: u32,
35    /// The `sail` version that wrote it.
36    pub sail_version: String,
37    /// The verification mode: `default`, or a named opt-in mode.
38    pub mode: String,
39    /// The arguments passed through to `cargo verus verify`.
40    pub command: Vec<String>,
41    /// `cargo verus verify`'s exit code (`None` if it was killed by a signal
42    /// or never ran).
43    pub exit_code: Option<i32>,
44    /// The solver every answer came from.
45    pub solver: Option<SolverInfo>,
46    /// Cache use.
47    pub cache: CacheInfo,
48    /// How completely solver queries were attributed to functions.
49    pub attribution: AttributionInfo,
50    /// One entry per crate Verus verified, in the order Verus finished them.
51    pub crates: Vec<CrateReport>,
52    /// Verus's diagnostics, in order, as data and verbatim.
53    pub diagnostics: Vec<Diagnostic>,
54    /// Counts over every function in every crate.
55    pub summary: Summary,
56    /// Set when `sail verify` itself could not run Verus.
57    pub error: Option<ErrorInfo>,
58    /// Source-engine provenance, present only for an explicitly selected
59    /// engine (ADR 0027). Stock reports omit it.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub engine: Option<EngineProvenance>,
62}
63
64/// How an explicitly selected source engine established a report or function
65/// (charter rule 7, ADR 0027). Absent for stock verification.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct EngineProvenance {
68    /// The engine name (`interactive`).
69    pub name: String,
70    /// SHA-256 of the validated engine build manifest, as lowercase hex.
71    pub manifest_sha256: String,
72    /// Whether the engine or the stock fallback produced the evidence.
73    pub established_by: EngineEstablishment,
74}
75
76/// Which verifier produced the evidence of an engine-requested report.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "kebab-case")]
79pub enum EngineEstablishment {
80    /// The engine's complete, sealed full-phase output.
81    Engine,
82    /// The engine faulted; the exact stock Verus invocation's output is
83    /// reported instead, and it never yields a proof receipt or accepted repair.
84    StockFallback,
85}
86
87/// A solver configuration establishing a complete portfolio attempt.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89pub struct SolverConfiguration {
90    /// Both Z3 random seeds (zero represents the unchanged default baseline).
91    pub seed: u32,
92}
93
94/// One independent Verus attempt in a sequential portfolio.
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
96pub struct PortfolioAttempt {
97    /// The configuration this attempt used.
98    pub configuration: SolverConfiguration,
99    /// Whether complete verification was established.
100    pub verified: bool,
101    /// Its process exit code; absent for cancellation or startup failure.
102    pub exit_code: Option<i32>,
103    /// Wall time including compilation and verification.
104    pub wall_ms: f64,
105    /// Infrastructure failure, never a solver answer.
106    pub error: Option<String>,
107    /// The attempt's complete verification report, when available.
108    pub report: Option<Box<Report>>,
109    /// Its stderr, retained verbatim.
110    pub stderr: String,
111}
112
113/// Evidence for the explicitly selected complete-run portfolio.
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115pub struct PortfolioReport {
116    /// Ordered configurations, including the unchanged baseline.
117    pub seeds: Vec<u32>,
118    /// The first configuration establishing a complete verification.
119    pub winner_seed: Option<u32>,
120    /// Every completed or failed attempt, in order.
121    pub attempts: Vec<PortfolioAttempt>,
122}
123
124/// The solver's identity.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct SolverInfo {
127    /// Solver family (`z3`).
128    pub name: String,
129    /// The version it reported.
130    pub version: Option<String>,
131    /// Its path.
132    pub path: Option<String>,
133    /// SHA-256 of the binary, as lowercase hex.
134    pub sha256: Option<String>,
135}
136
137/// Cache use.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
139pub struct CacheInfo {
140    /// Whether solver sessions could be served from the cache daemon.
141    pub daemon: bool,
142}
143
144/// Attribution coverage.
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(rename_all = "kebab-case")]
147pub enum AttributionStatus {
148    /// Every solver process was attributed.
149    Complete,
150    /// Some were not; see `notes`.
151    Partial,
152    /// None were; see `notes`. Function verdicts are still reported.
153    Unavailable,
154}
155
156/// How completely solver queries were attributed to functions.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct AttributionInfo {
159    /// Coverage.
160    pub status: AttributionStatus,
161    /// Why coverage is not complete, in plain words.
162    pub notes: Vec<String>,
163    /// Solver sessions that matched no Verus log.
164    pub unmatched_sessions: u64,
165}
166
167/// One crate.
168#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169pub struct CrateReport {
170    /// The crate name, if Verus reported any function for it.
171    pub name: Option<String>,
172    /// Verus's own crate-level counts.
173    pub verus: VerusResults,
174    /// Its functions, sorted by name.
175    pub functions: Vec<FunctionReport>,
176}
177
178/// Verus's `verification-results` for a crate.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
180pub struct VerusResults {
181    /// `verified`.
182    pub verified: Option<u64>,
183    /// `errors`.
184    pub errors: Option<u64>,
185    /// `success` (only for whole-crate runs).
186    pub success: Option<bool>,
187    /// `encountered-vir-error`.
188    pub encountered_vir_error: Option<bool>,
189}
190
191/// The reported verdict.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "kebab-case")]
194pub enum VerdictName {
195    /// Confirmed and proved.
196    Verified,
197    /// Confirmed and failed.
198    Failed,
199    /// Confirmed, not proved, and not a settled failure.
200    Unknown,
201    /// Not yet established by the pinned solver; never verified.
202    Provisional,
203}
204
205impl From<Verdict> for VerdictName {
206    fn from(v: Verdict) -> Self {
207        match v {
208            Verdict::Verified => Self::Verified,
209            Verdict::Failed => Self::Failed,
210            Verdict::Unknown => Self::Unknown,
211            Verdict::Provisional => Self::Provisional,
212        }
213    }
214}
215
216/// How a result was established (charter rule 7): the establishment axis.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
218#[serde(rename_all = "snake_case")]
219pub enum EstablishmentName {
220    /// Not yet established by the pinned solver.
221    Provisional,
222    /// Established by the pinned solver: fresh, or a cached pinned result.
223    Confirmed,
224}
225
226impl From<Establishment> for EstablishmentName {
227    fn from(t: Establishment) -> Self {
228        match t {
229            Establishment::Provisional => Self::Provisional,
230            Establishment::Confirmed => Self::Confirmed,
231        }
232    }
233}
234
235/// How strong a settled verdict's evidence is: the evidence-tier axis,
236/// ordered from weakest to strongest (`docs/scope/verification-runtime.md`).
237///
238/// Every verdict `sail verify` settles today comes from the pinned SMT
239/// solver through Verus, so it is [`EvidenceTierName::SmtVerified`]. The
240/// other tiers are reserved for the verification runtime, which extends
241/// schema version 2 rather than breaking it.
242#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
243#[serde(rename_all = "snake_case")]
244pub enum EvidenceTierName {
245    /// Runtime-checked contracts under property tests.
246    Sampled,
247    /// Checked within declared bounds.
248    Bounded,
249    /// Settled by an SMT solver.
250    SmtVerified,
251    /// Solver proof certificates checked independently.
252    CertificateChecked,
253    /// Checked by a proof assistant's kernel.
254    KernelChecked,
255}
256
257impl EvidenceTierName {
258    /// The evidence tier of an SMT-backed result reported with `verdict`
259    /// and `establishment`: [`EvidenceTierName::SmtVerified`] for a
260    /// confirmed `verified` or `failed` verdict, and `None` for anything
261    /// not settled (`unknown`, or provisional).
262    #[must_use]
263    pub fn for_smt(verdict: VerdictName, establishment: EstablishmentName) -> Option<Self> {
264        match (verdict, establishment) {
265            (VerdictName::Verified | VerdictName::Failed, EstablishmentName::Confirmed) => {
266                Some(Self::SmtVerified)
267            }
268            _ => None,
269        }
270    }
271}
272
273/// One function.
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
275pub struct FunctionReport {
276    /// The function, as Verus names it.
277    pub function: String,
278    /// Its module, as Verus reports it (`""` for the crate root).
279    pub module: String,
280    /// Verus's mode for it (`exec`, `proof`, `spec`).
281    pub fn_mode: Option<String>,
282    /// The verdict. Never `verified` unless `establishment` is `confirmed`.
283    pub verdict: VerdictName,
284    /// How it was established: `confirmed` or `provisional`.
285    pub establishment: EstablishmentName,
286    /// How strong the evidence for a settled verdict is; `null` when the
287    /// verdict is not settled (`unknown` or `provisional`).
288    pub evidence_tier: Option<EvidenceTierName>,
289    /// Whether any answer finished near its limit or gave up from resource
290    /// exhaustion (ADR 0009).
291    pub unstable: bool,
292    /// Verus's own `success` for it (incomplete for bit-vector queries).
293    pub verus_success: Option<bool>,
294    /// How its answers were established.
295    pub provenance: ProvenanceReport,
296    /// Time and effort, as Verus reports them.
297    pub timing: Timing,
298    /// Explicit replay measurement; `null` without complete attribution and replay.
299    pub fragility: Option<Fragility>,
300    /// Original per-check effort measurements; absent in older schema-v2 reports.
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub health: Option<crate::health::FunctionHealth>,
303    /// Its obligations; `null` when attribution was unavailable for it.
304    pub obligations: Option<Vec<ObligationReport>>,
305}
306
307/// Summary of answer sources.
308#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
309#[serde(rename_all = "kebab-case")]
310pub enum SourceSummaryName {
311    /// Every check solved fresh by the pinned solver.
312    Fresh,
313    /// Every check served from the cache.
314    Cache,
315    /// Some of each.
316    Mixed,
317    /// Not known for at least one check.
318    Unrecorded,
319}
320
321impl From<SourceSummary> for SourceSummaryName {
322    fn from(s: SourceSummary) -> Self {
323        match s {
324            SourceSummary::Fresh => Self::Fresh,
325            SourceSummary::Cache => Self::Cache,
326            SourceSummary::Mixed => Self::Mixed,
327            SourceSummary::Unrecorded => Self::Unrecorded,
328        }
329    }
330}
331
332/// How a function's answers were established (charter rule 7).
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
334pub struct ProvenanceReport {
335    /// The proving configuration in a portfolio attempt.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub configuration: Option<SolverConfiguration>,
338    /// The mode that produced them (`default`, or an opt-in mode's name).
339    pub mode: String,
340    /// Summary of `checks_*`.
341    pub source: SourceSummaryName,
342    /// Checks solved fresh by the pinned solver.
343    pub checks_solved: u64,
344    /// Checks served from the cache (pinned-solver results).
345    pub checks_served: u64,
346    /// Checks with no provenance record.
347    pub checks_unrecorded: u64,
348    /// Source-engine provenance; absent for stock verification.
349    #[serde(default, skip_serializing_if = "Option::is_none")]
350    pub engine: Option<EngineProvenance>,
351}
352
353/// Time and effort, as Verus reports them.
354#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
355pub struct Timing {
356    /// Solver time for the function's queries, in microseconds.
357    pub smt_micros: Option<u64>,
358    /// rlimit units.
359    pub rlimit: Option<u64>,
360}
361
362/// Function fragility from complete replay configurations and primary obligations.
363#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
364pub struct Fragility {
365    /// Fraction of runs that did not prove it, from 0 to 1.
366    pub score: f64,
367    /// Replay configurations measured.
368    pub runs: u32,
369    /// Configurations proving every primary obligation together.
370    pub proved: u32,
371}
372
373/// An obligation's outcome.
374#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "kebab-case")]
376pub enum OutcomeName {
377    /// Proved.
378    Proved,
379    /// Settled failure.
380    Failed,
381    /// Gave up at or near the limit, or no answer recorded.
382    Unknown,
383}
384
385impl From<Outcome> for OutcomeName {
386    fn from(o: Outcome) -> Self {
387        match o {
388            Outcome::Proved => Self::Proved,
389            Outcome::Failed => Self::Failed,
390            Outcome::Unknown => Self::Unknown,
391        }
392    }
393}
394
395/// One obligation: one solver query op.
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct ObligationReport {
398    /// The stable identity: `<function>#<kind>/<ordinal>` or
399    /// `<function>#<kind>/spinoff-<n>`.
400    pub id: String,
401    /// The op kind (`Function-Def`, `Function-Recommends`, …).
402    pub kind: String,
403    /// Position among the function's in-module ops of this kind (0 for
404    /// spinoffs).
405    pub ordinal: u32,
406    /// Spinoff details, for ops Verus ran in their own process.
407    pub spinoff: Option<SpinoffInfo>,
408    /// Whether its failure is advisory (recommends, expand-errors, profile
409    /// reruns) rather than an error that fails the function.
410    pub advisory: bool,
411    /// Verus's span for the op. Informational; not part of the identity.
412    pub span: Option<SourceSpan>,
413    /// Its outcome.
414    pub outcome: OutcomeName,
415    /// Whether any of its checks is unstable (ADR 0009).
416    pub unstable: bool,
417    /// Its `check-sat` commands, in order.
418    pub checks: Vec<CheckReport>,
419    /// The first model the solver gave for it, if any.
420    pub counterexample: Option<Counterexample>,
421}
422
423/// A spun-off op.
424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
425pub struct SpinoffInfo {
426    /// Verus's spinoff counter for the op (1, 2, …).
427    pub index: u32,
428    /// Why it was spun off (`nonlinear`, `bitvector`, …).
429    pub reason: Option<String>,
430}
431
432/// A span as Verus writes it in its logs: `file:line:col: line:col (#n)`.
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
434pub struct SourceSpan {
435    /// The text, verbatim.
436    pub text: String,
437    /// The file.
438    pub file: Option<String>,
439    /// Start line (1-based).
440    pub line: Option<u64>,
441    /// Start column (1-based).
442    pub column: Option<u64>,
443    /// End line.
444    pub end_line: Option<u64>,
445    /// End column.
446    pub end_column: Option<u64>,
447}
448
449impl SourceSpan {
450    /// Parses Verus's span text; unparsed parts are `None`.
451    #[must_use]
452    pub fn parse(text: &str) -> Self {
453        let mut span = Self {
454            text: text.to_owned(),
455            file: None,
456            line: None,
457            column: None,
458            end_line: None,
459            end_column: None,
460        };
461        let body = text.rsplit_once(" (#").map_or(text, |(b, _)| b);
462        let Some((start, end)) = body.rsplit_once(": ") else {
463            return span;
464        };
465        let mut s = start.rsplitn(3, ':');
466        let (Some(col), Some(line), Some(file)) = (s.next(), s.next(), s.next()) else {
467            return span;
468        };
469        let mut e = end.splitn(2, ':');
470        span.file = Some(file.to_owned());
471        span.line = line.parse().ok();
472        span.column = col.parse().ok();
473        span.end_line = e.next().and_then(|v| v.parse().ok());
474        span.end_column = e.next().and_then(|v| v.parse().ok());
475        span
476    }
477}
478
479/// A `check-sat` answer.
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
481#[serde(rename_all = "kebab-case")]
482pub enum AnswerName {
483    /// `sat`.
484    Sat,
485    /// `unsat`.
486    Unsat,
487    /// `unknown`.
488    Unknown,
489}
490
491impl From<sail_ledger::Answer> for AnswerName {
492    fn from(a: sail_ledger::Answer) -> Self {
493        match a {
494            sail_ledger::Answer::Sat => Self::Sat,
495            sail_ledger::Answer::Unsat => Self::Unsat,
496            sail_ledger::Answer::Unknown => Self::Unknown,
497        }
498    }
499}
500
501/// How one answer was established.
502#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
503#[serde(rename_all = "kebab-case")]
504pub enum SourceName {
505    /// A fresh pinned-solver run.
506    Solved,
507    /// A cache hit of a pinned-solver result.
508    Cache,
509}
510
511impl From<Source> for SourceName {
512    fn from(s: Source) -> Self {
513        match s {
514            Source::Solved => Self::Solved,
515            Source::Cache => Self::Cache,
516        }
517    }
518}
519
520/// One `check-sat`.
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522pub struct CheckReport {
523    /// Its answer.
524    pub answer: Option<AnswerName>,
525    /// The `:rlimit` in force (0 means unlimited).
526    pub rlimit_limit: Option<u64>,
527    /// rlimit units used.
528    pub rlimit_used: Option<u64>,
529    /// The `reason-unknown` reply, verbatim.
530    pub reason_unknown: Option<String>,
531    /// How it was established; `null` if not recorded.
532    pub source: Option<SourceName>,
533}
534
535/// A counterexample model.
536#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
537pub struct Counterexample {
538    /// Index into `checks` of the check that produced it.
539    pub check: u32,
540    /// The `get-model` reply, verbatim.
541    pub model: String,
542    /// Its zero-arity definitions as data.
543    pub assignments: Vec<Assignment>,
544}
545
546/// One constant in a model.
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
548pub struct Assignment {
549    /// The SMT name (Verus encodes parameter `x` as `x!`, versions of local
550    /// `i` as `i@0`, `i@1`, …).
551    pub name: String,
552    /// The sort, verbatim.
553    pub sort: String,
554    /// The value, verbatim.
555    pub value: String,
556    /// The value in ITF's value encoding: a rendering of `value`, never a
557    /// replacement for it.
558    pub itf: ItfValue,
559}
560
561/// A model value in the ITF value encoding (Apalache's Informal Trace
562/// Format): a boolean, an integer as `{"#bigint": "[-][0-9]+"}`, or
563/// `{"#unserializable": "<verbatim value>"}` for any value without an ITF
564/// form (uninterpreted sorts, Verus's boxed values, reals and so on).
565///
566/// It is a rendering on top of the solver's exact reply (charter rule 3):
567/// the verbatim `get-model` reply and each verbatim `value` stay alongside
568/// it.
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
570#[serde(untagged)]
571pub enum ItfValue {
572    /// An SMT `Bool`.
573    Bool(bool),
574    /// An SMT `Int`, or a bit vector read as an unsigned integer.
575    BigInt {
576        /// Decimal digits with an optional leading `-`.
577        #[serde(rename = "#bigint")]
578        bigint: String,
579    },
580    /// Anything else, verbatim.
581    Unserializable {
582        /// The value, verbatim.
583        #[serde(rename = "#unserializable")]
584        unserializable: String,
585    },
586}
587
588impl ItfValue {
589    /// Renders one zero-arity model constant of `sort` with the verbatim
590    /// `value`. Total: a value it cannot read becomes
591    /// [`ItfValue::Unserializable`].
592    #[must_use]
593    pub fn render(sort: &str, value: &str) -> Self {
594        let v = value.trim();
595        let sort = sort.trim();
596        let read = match sort {
597            "Bool" => match v {
598                "true" => Some(Self::Bool(true)),
599                "false" => Some(Self::Bool(false)),
600                _ => None,
601            },
602            "Int" => smt_int(v).map(|bigint| Self::BigInt { bigint }),
603            _ if sort.starts_with("(_ BitVec ") => smt_bit_vector(v).map(|n| Self::BigInt {
604                bigint: n.to_string(),
605            }),
606            _ => None,
607        };
608        read.unwrap_or_else(|| Self::Unserializable {
609            unserializable: value.to_owned(),
610        })
611    }
612}
613
614/// An SMT-LIB integer value: a numeral, or `(- <numeral>)`.
615fn smt_int(v: &str) -> Option<String> {
616    let numeral = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
617    if numeral(v) {
618        return Some(v.to_owned());
619    }
620    let inner = v.strip_prefix('(')?.strip_suffix(')')?.trim();
621    let digits = inner.strip_prefix('-')?.trim();
622    if !numeral(digits) {
623        return None;
624    }
625    Some(if digits.bytes().all(|b| b == b'0') {
626        "0".to_owned()
627    } else {
628        format!("-{digits}")
629    })
630}
631
632/// An SMT-LIB bit-vector literal (`#x…` or `#b…`) of at most 128 bits, as
633/// an unsigned integer.
634fn smt_bit_vector(v: &str) -> Option<u128> {
635    let (digits, radix) = if let Some(d) = v.strip_prefix("#x") {
636        (d, 16)
637    } else {
638        (v.strip_prefix("#b")?, 2)
639    };
640    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
641        return None;
642    }
643    u128::from_str_radix(digits, radix).ok()
644}
645
646/// A source location in a diagnostic.
647#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
648pub struct DiagnosticSpan {
649    /// The file, as printed.
650    pub file: String,
651    /// 1-based line.
652    pub line: u64,
653    /// 1-based column.
654    pub column: u64,
655    /// Primary (`-->`) or secondary (`:::`).
656    pub primary: bool,
657}
658
659/// One diagnostic from Verus's stderr.
660#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
661pub struct Diagnostic {
662    /// `error`, `warning`, `note` or `help`.
663    pub level: String,
664    /// The bracketed code, if any.
665    pub code: Option<String>,
666    /// The header's message, verbatim.
667    pub message: String,
668    /// Its locations.
669    pub spans: Vec<DiagnosticSpan>,
670    /// The whole block, verbatim.
671    pub rendered: String,
672}
673
674/// Counts over every function.
675#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
676pub struct Summary {
677    /// Functions.
678    pub functions: u64,
679    /// Verified.
680    pub verified: u64,
681    /// Failed.
682    pub failed: u64,
683    /// Unknown.
684    pub unknown: u64,
685    /// Provisional.
686    pub provisional: u64,
687    /// Unstable (any verdict).
688    pub unstable: u64,
689}
690
691/// A setup failure.
692#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
693pub struct ErrorInfo {
694    /// The stable code (`SAILnnnn`).
695    pub code: String,
696    /// What went wrong.
697    pub message: String,
698}
699
700fn check_report(c: &CheckRecord) -> CheckReport {
701    CheckReport {
702        answer: c.answer.map(AnswerName::from),
703        rlimit_limit: c.effort.limit,
704        rlimit_used: c.effort.used,
705        reason_unknown: c.effort.reason.clone(),
706        source: c.source.map(SourceName::from),
707    }
708}
709
710impl From<&ObligationRecord> for ObligationReport {
711    fn from(o: &ObligationRecord) -> Self {
712        let counterexample = o.checks.iter().enumerate().find_map(|(i, c)| {
713            let model = c.model.as_ref()?;
714            Some(Counterexample {
715                check: u32::try_from(i).unwrap_or(u32::MAX),
716                model: model.text.clone(),
717                assignments: model
718                    .assignments
719                    .iter()
720                    .map(|a| Assignment {
721                        name: a.name.clone(),
722                        sort: a.sort.clone(),
723                        value: a.value.clone(),
724                        itf: ItfValue::render(&a.sort, &a.value),
725                    })
726                    .collect(),
727            })
728        });
729        Self {
730            id: o.id.to_string(),
731            kind: o.id.kind.0.clone(),
732            ordinal: o.id.ordinal,
733            spinoff: o.id.spinoff.map(|index| SpinoffInfo {
734                index,
735                reason: o.spinoff_reason.clone(),
736            }),
737            advisory: !o.id.kind.verdict_bearing(),
738            span: o.span.as_deref().map(SourceSpan::parse),
739            outcome: o.outcome().into(),
740            unstable: o.unstable(),
741            checks: o.checks.iter().map(check_report).collect(),
742            counterexample,
743        }
744    }
745}
746
747impl From<&FunctionRecord> for FunctionReport {
748    fn from(f: &FunctionRecord) -> Self {
749        let sources = f.sources();
750        let verdict = VerdictName::from(f.verdict());
751        let establishment = EstablishmentName::from(f.establishment);
752        let obligations: Option<Vec<_>> = f
753            .obligations
754            .as_ref()
755            .map(|obligations| obligations.iter().map(ObligationReport::from).collect());
756        let health = crate::health::FunctionHealth::from_obligations(obligations.as_deref());
757        Self {
758            function: f.function.clone(),
759            module: f.module.clone(),
760            fn_mode: f.fn_mode.clone(),
761            verdict,
762            establishment,
763            evidence_tier: EvidenceTierName::for_smt(verdict, establishment),
764            unstable: f.unstable(),
765            verus_success: f.verus_success,
766            provenance: ProvenanceReport {
767                configuration: None,
768                mode: f.mode.name().to_owned(),
769                source: sources.summary().into(),
770                checks_solved: sources.solved,
771                checks_served: sources.served,
772                checks_unrecorded: sources.unrecorded,
773                engine: None,
774            },
775            timing: Timing {
776                smt_micros: f.smt_micros,
777                rlimit: f.rlimit,
778            },
779            fragility: None,
780            health: Some(health),
781            obligations,
782        }
783    }
784}
785
786impl Summary {
787    /// Counts the functions in `crates`.
788    #[must_use]
789    pub fn of(crates: &[CrateReport]) -> Self {
790        let mut s = Self::default();
791        for f in crates.iter().flat_map(|c| &c.functions) {
792            s.functions += 1;
793            match f.verdict {
794                VerdictName::Verified => s.verified += 1,
795                VerdictName::Failed => s.failed += 1,
796                VerdictName::Unknown => s.unknown += 1,
797                VerdictName::Provisional => s.provisional += 1,
798            }
799            s.unstable += u64::from(f.unstable);
800        }
801        s
802    }
803}
804
805impl CrateReport {
806    /// How many of this crate's `unknown` functions Verus's own totals clear.
807    ///
808    /// When attribution is incomplete in a failing crate, functions Sail
809    /// cannot confirm one by one are `unknown` (VI-0003, VI-0010). Verus
810    /// counts every failing verification unit in `verus.errors`, bit-vector
811    /// failures included (VI-0003), and each function reported `failed`
812    /// accounts for at least one. So when `errors` equals the number of failed
813    /// functions, no other function had an error, and the `unknown` functions
814    /// passed by Verus's totals. Their verdicts stay `unknown`: this is a
815    /// count from Verus's aggregate, never a per-function proof (charter
816    /// rule 7). Returns 0 whenever the totals cannot clear them.
817    #[must_use]
818    pub fn unknown_passed_by_verus_totals(&self) -> u64 {
819        if self.verus_totals_clear_unknown() {
820            self.count(VerdictName::Unknown)
821        } else {
822            0
823        }
824    }
825
826    /// Whether this crate's `unknown` functions passed by Verus's totals:
827    /// see [`Self::unknown_passed_by_verus_totals`]. The verdicts stay
828    /// `unknown`; this only says Verus's aggregate left no error for them.
829    #[must_use]
830    pub fn verus_totals_clear_unknown(&self) -> bool {
831        let failed = self.count(VerdictName::Failed);
832        failed > 0
833            && self.verus.errors == Some(failed)
834            && self.verus.verified.is_some()
835            && self.verus.encountered_vir_error != Some(true)
836    }
837
838    fn count(&self, verdict: VerdictName) -> u64 {
839        let n = self
840            .functions
841            .iter()
842            .filter(|f| f.verdict == verdict)
843            .count();
844        u64::try_from(n).unwrap_or(u64::MAX)
845    }
846}
847
848impl Report {
849    /// Rules the JSON Schema cannot express. Returns every violation.
850    #[must_use]
851    pub fn invariant_violations(&self) -> Vec<String> {
852        let mut out = Vec::new();
853        if self.schema_version != SCHEMA_VERSION {
854            out.push(format!("schema_version is {}", self.schema_version));
855        }
856        let mut ids = std::collections::BTreeSet::new();
857        for f in self.crates.iter().flat_map(|c| &c.functions) {
858            if f.verdict == VerdictName::Verified && f.establishment != EstablishmentName::Confirmed
859            {
860                out.push(format!("{}: verified but not confirmed", f.function));
861            }
862            if (f.establishment == EstablishmentName::Provisional)
863                != (f.verdict == VerdictName::Provisional)
864            {
865                out.push(format!(
866                    "{}: establishment and verdict disagree",
867                    f.function
868                ));
869            }
870            let settled = matches!(f.verdict, VerdictName::Verified | VerdictName::Failed);
871            if settled != f.evidence_tier.is_some() {
872                out.push(format!(
873                    "{}: evidence tier and verdict disagree",
874                    f.function
875                ));
876            }
877            let p = &f.provenance;
878            let counted = (p.checks_solved, p.checks_served, p.checks_unrecorded);
879            let expected = match p.source {
880                SourceSummaryName::Fresh => counted.0 > 0 && counted.1 == 0 && counted.2 == 0,
881                SourceSummaryName::Cache => counted.0 == 0 && counted.1 > 0 && counted.2 == 0,
882                SourceSummaryName::Mixed => counted.0 > 0 && counted.1 > 0 && counted.2 == 0,
883                SourceSummaryName::Unrecorded => counted.2 > 0 || counted == (0, 0, 0),
884            };
885            if !expected {
886                out.push(format!(
887                    "{}: provenance counts disagree with source",
888                    f.function
889                ));
890            }
891            for o in f.obligations.iter().flatten() {
892                if !ids.insert(o.id.clone()) {
893                    out.push(format!("duplicate obligation id {}", o.id));
894                }
895                if !o.id.starts_with(&format!("{}#", f.function)) {
896                    out.push(format!("obligation {} is not {}'s", o.id, f.function));
897                }
898            }
899        }
900        if self.summary != Summary::of(&self.crates) {
901            out.push("summary does not match the functions".to_owned());
902        }
903        out
904    }
905}
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910
911    #[test]
912    fn spans_parse() {
913        let s = SourceSpan::parse("src/lib.rs:46:1: 46:26 (#0)");
914        assert_eq!(s.file.as_deref(), Some("src/lib.rs"));
915        assert_eq!(
916            (s.line, s.column, s.end_line, s.end_column),
917            (Some(46), Some(1), Some(46), Some(26))
918        );
919        let s = SourceSpan::parse("garbage");
920        assert_eq!((s.file, s.line), (None, None));
921        assert_eq!(s.text, "garbage");
922    }
923    #[test]
924    fn the_example_document_is_valid_v2_with_rendered_itf_values() {
925        let text =
926            include_str!("../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json");
927        let golden: Report =
928            serde_json::from_str(text).unwrap_or_else(|e| unreachable!("fixture: {e}"));
929        let schema: serde_json::Value = serde_json::from_str(JSON_SCHEMA).unwrap_or_default();
930        let value: serde_json::Value = serde_json::from_str(text).unwrap_or_default();
931        assert_eq!(
932            crate::schema::validate(&schema, &value),
933            Vec::<String>::new()
934        );
935        assert_eq!(golden.invariant_violations(), Vec::<String>::new());
936        let mut rendered = 0;
937        for o in golden
938            .crates
939            .iter()
940            .flat_map(|c| &c.functions)
941            .flat_map(|f| f.obligations.iter().flatten())
942        {
943            for a in o.counterexample.iter().flat_map(|c| &c.assignments) {
944                assert_eq!(a.itf, ItfValue::render(&a.sort, &a.value), "{}", a.name);
945                // Every verbatim value is in the verbatim model.
946                assert!(
947                    o.counterexample
948                        .as_ref()
949                        .is_some_and(|c| c.model.contains(&a.value)),
950                    "{}",
951                    a.name
952                );
953                rendered += usize::from(!matches!(a.itf, ItfValue::Unserializable { .. }));
954            }
955        }
956        assert!(rendered > 0);
957    }
958    #[test]
959    fn engine_provenance_is_additive_and_matches_the_schemas() {
960        let stock: Report = serde_json::from_str(include_str!(
961            "../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json"
962        ))
963        .unwrap_or_else(|e| unreachable!("fixture: {e}"));
964        // Stock documents serialize exactly as before: no engine fields.
965        let stock_text = serde_json::to_string(&stock).unwrap_or_default();
966        assert!(!stock_text.contains("\"engine\""));
967        let engine = EngineProvenance {
968            name: "interactive".to_owned(),
969            manifest_sha256: "ab".repeat(32),
970            established_by: EngineEstablishment::StockFallback,
971        };
972        let mut r = stock.clone();
973        r.engine = Some(engine.clone());
974        for f in r.crates.iter_mut().flat_map(|c| &mut c.functions) {
975            f.provenance.engine = Some(engine.clone());
976        }
977        let schema = serde_json::from_str(JSON_SCHEMA).unwrap_or_default();
978        let value = serde_json::to_value(&r).unwrap_or_default();
979        assert_eq!(
980            crate::schema::validate(&schema, &value),
981            Vec::<String>::new()
982        );
983        assert_eq!(value["engine"]["established_by"], "stock-fallback");
984        let mut wrong = value.clone();
985        wrong["engine"]["established_by"] = serde_json::json!("default");
986        assert_ne!(
987            crate::schema::validate(&schema, &wrong),
988            Vec::<String>::new()
989        );
990        let mut wrong = value;
991        if let Some(engine) = wrong["engine"].as_object_mut() {
992            engine.remove("manifest_sha256");
993        }
994        assert_ne!(
995            crate::schema::validate(&schema, &wrong),
996            Vec::<String>::new()
997        );
998        let project: serde_json::Value =
999            serde_json::from_str(include_str!("../schema/project-result-v2.json"))
1000                .unwrap_or_default();
1001        let identity = crate::project::EngineIdentity {
1002            name: "interactive".to_owned(),
1003            manifest_sha256: "cd".repeat(32),
1004        };
1005        let identity = serde_json::to_value(identity).unwrap_or_default();
1006        assert_eq!(
1007            crate::schema::validate(&project["properties"]["engine"], &identity),
1008            Vec::<String>::new()
1009        );
1010        let mut extra = identity;
1011        extra["established_by"] = serde_json::json!("engine");
1012        assert_ne!(
1013            crate::schema::validate(&project["properties"]["engine"], &extra),
1014            Vec::<String>::new()
1015        );
1016    }
1017    #[test]
1018    fn verus_totals_clear_unknown_functions_only_when_every_error_is_accounted_for() {
1019        let golden: Report = serde_json::from_str(include_str!(
1020            "../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json"
1021        ))
1022        .unwrap_or_else(|e| unreachable!("fixture: {e}"));
1023        // The fixture: 8 functions, 2 failed, and Verus reports 2 errors.
1024        let mut krate = golden.crates[0].clone();
1025        assert_eq!(krate.verus.errors, Some(2));
1026        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1027        // Incomplete attribution leaves the 6 successes unknown (VI-0003).
1028        for f in &mut krate.functions {
1029            if f.verdict == VerdictName::Verified {
1030                f.verdict = VerdictName::Unknown;
1031            }
1032        }
1033        assert_eq!(krate.unknown_passed_by_verus_totals(), 6);
1034        // A further Verus error may belong to any unknown function.
1035        krate.verus.errors = Some(3);
1036        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1037        krate.verus.errors = Some(2);
1038        krate.verus.encountered_vir_error = Some(true);
1039        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1040        krate.verus.encountered_vir_error = Some(false);
1041        krate.verus.verified = None;
1042        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1043        // Without a failed function there is nothing to account errors to.
1044        krate.verus.verified = Some(9);
1045        for f in &mut krate.functions {
1046            f.verdict = VerdictName::Unknown;
1047        }
1048        krate.verus.errors = Some(0);
1049        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1050    }
1051    #[test]
1052    fn portfolio_evidence_matches_the_schema() {
1053        let mut r: Report = serde_json::from_str(include_str!(
1054            "../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json"
1055        ))
1056        .unwrap_or_else(|e| unreachable!("fixture: {e}"));
1057        let attempt = PortfolioAttempt {
1058            configuration: SolverConfiguration { seed: 4 },
1059            verified: false,
1060            exit_code: Some(1),
1061            wall_ms: 1.0,
1062            error: None,
1063            report: Some(Box::new(r.clone())),
1064            stderr: "original diagnostics".to_owned(),
1065        };
1066        r.mode = "accept-first-proof".to_owned();
1067        r.portfolio = Some(PortfolioReport {
1068            seeds: vec![0, 4],
1069            winner_seed: None,
1070            attempts: vec![attempt],
1071        });
1072        let schema = serde_json::from_str(JSON_SCHEMA).unwrap_or_default();
1073        let value = serde_json::to_value(r).unwrap_or_default();
1074        assert!(
1075            crate::schema::validate(&schema, &value).is_empty(),
1076            "{:?}",
1077            crate::schema::validate(&schema, &value)
1078        );
1079    }
1080}