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    /// Its obligations; `null` when attribution was unavailable for it.
301    pub obligations: Option<Vec<ObligationReport>>,
302}
303
304/// Summary of answer sources.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
306#[serde(rename_all = "kebab-case")]
307pub enum SourceSummaryName {
308    /// Every check solved fresh by the pinned solver.
309    Fresh,
310    /// Every check served from the cache.
311    Cache,
312    /// Some of each.
313    Mixed,
314    /// Not known for at least one check.
315    Unrecorded,
316}
317
318impl From<SourceSummary> for SourceSummaryName {
319    fn from(s: SourceSummary) -> Self {
320        match s {
321            SourceSummary::Fresh => Self::Fresh,
322            SourceSummary::Cache => Self::Cache,
323            SourceSummary::Mixed => Self::Mixed,
324            SourceSummary::Unrecorded => Self::Unrecorded,
325        }
326    }
327}
328
329/// How a function's answers were established (charter rule 7).
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331pub struct ProvenanceReport {
332    /// The proving configuration in a portfolio attempt.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub configuration: Option<SolverConfiguration>,
335    /// The mode that produced them (`default`, or an opt-in mode's name).
336    pub mode: String,
337    /// Summary of `checks_*`.
338    pub source: SourceSummaryName,
339    /// Checks solved fresh by the pinned solver.
340    pub checks_solved: u64,
341    /// Checks served from the cache (pinned-solver results).
342    pub checks_served: u64,
343    /// Checks with no provenance record.
344    pub checks_unrecorded: u64,
345    /// Source-engine provenance; absent for stock verification.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub engine: Option<EngineProvenance>,
348}
349
350/// Time and effort, as Verus reports them.
351#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
352pub struct Timing {
353    /// Solver time for the function's queries, in microseconds.
354    pub smt_micros: Option<u64>,
355    /// rlimit units.
356    pub rlimit: Option<u64>,
357}
358
359/// Function fragility from complete replay configurations and primary obligations.
360#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
361pub struct Fragility {
362    /// Fraction of runs that did not prove it, from 0 to 1.
363    pub score: f64,
364    /// Replay configurations measured.
365    pub runs: u32,
366    /// Configurations proving every primary obligation together.
367    pub proved: u32,
368}
369
370/// An obligation's outcome.
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
372#[serde(rename_all = "kebab-case")]
373pub enum OutcomeName {
374    /// Proved.
375    Proved,
376    /// Settled failure.
377    Failed,
378    /// Gave up at or near the limit, or no answer recorded.
379    Unknown,
380}
381
382impl From<Outcome> for OutcomeName {
383    fn from(o: Outcome) -> Self {
384        match o {
385            Outcome::Proved => Self::Proved,
386            Outcome::Failed => Self::Failed,
387            Outcome::Unknown => Self::Unknown,
388        }
389    }
390}
391
392/// One obligation: one solver query op.
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394pub struct ObligationReport {
395    /// The stable identity: `<function>#<kind>/<ordinal>` or
396    /// `<function>#<kind>/spinoff-<n>`.
397    pub id: String,
398    /// The op kind (`Function-Def`, `Function-Recommends`, …).
399    pub kind: String,
400    /// Position among the function's in-module ops of this kind (0 for
401    /// spinoffs).
402    pub ordinal: u32,
403    /// Spinoff details, for ops Verus ran in their own process.
404    pub spinoff: Option<SpinoffInfo>,
405    /// Whether its failure is advisory (recommends, expand-errors, profile
406    /// reruns) rather than an error that fails the function.
407    pub advisory: bool,
408    /// Verus's span for the op. Informational; not part of the identity.
409    pub span: Option<SourceSpan>,
410    /// Its outcome.
411    pub outcome: OutcomeName,
412    /// Whether any of its checks is unstable (ADR 0009).
413    pub unstable: bool,
414    /// Its `check-sat` commands, in order.
415    pub checks: Vec<CheckReport>,
416    /// The first model the solver gave for it, if any.
417    pub counterexample: Option<Counterexample>,
418}
419
420/// A spun-off op.
421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
422pub struct SpinoffInfo {
423    /// Verus's spinoff counter for the op (1, 2, …).
424    pub index: u32,
425    /// Why it was spun off (`nonlinear`, `bitvector`, …).
426    pub reason: Option<String>,
427}
428
429/// A span as Verus writes it in its logs: `file:line:col: line:col (#n)`.
430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431pub struct SourceSpan {
432    /// The text, verbatim.
433    pub text: String,
434    /// The file.
435    pub file: Option<String>,
436    /// Start line (1-based).
437    pub line: Option<u64>,
438    /// Start column (1-based).
439    pub column: Option<u64>,
440    /// End line.
441    pub end_line: Option<u64>,
442    /// End column.
443    pub end_column: Option<u64>,
444}
445
446impl SourceSpan {
447    /// Parses Verus's span text; unparsed parts are `None`.
448    #[must_use]
449    pub fn parse(text: &str) -> Self {
450        let mut span = Self {
451            text: text.to_owned(),
452            file: None,
453            line: None,
454            column: None,
455            end_line: None,
456            end_column: None,
457        };
458        let body = text.rsplit_once(" (#").map_or(text, |(b, _)| b);
459        let Some((start, end)) = body.rsplit_once(": ") else {
460            return span;
461        };
462        let mut s = start.rsplitn(3, ':');
463        let (Some(col), Some(line), Some(file)) = (s.next(), s.next(), s.next()) else {
464            return span;
465        };
466        let mut e = end.splitn(2, ':');
467        span.file = Some(file.to_owned());
468        span.line = line.parse().ok();
469        span.column = col.parse().ok();
470        span.end_line = e.next().and_then(|v| v.parse().ok());
471        span.end_column = e.next().and_then(|v| v.parse().ok());
472        span
473    }
474}
475
476/// A `check-sat` answer.
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(rename_all = "kebab-case")]
479pub enum AnswerName {
480    /// `sat`.
481    Sat,
482    /// `unsat`.
483    Unsat,
484    /// `unknown`.
485    Unknown,
486}
487
488impl From<sail_ledger::Answer> for AnswerName {
489    fn from(a: sail_ledger::Answer) -> Self {
490        match a {
491            sail_ledger::Answer::Sat => Self::Sat,
492            sail_ledger::Answer::Unsat => Self::Unsat,
493            sail_ledger::Answer::Unknown => Self::Unknown,
494        }
495    }
496}
497
498/// How one answer was established.
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
500#[serde(rename_all = "kebab-case")]
501pub enum SourceName {
502    /// A fresh pinned-solver run.
503    Solved,
504    /// A cache hit of a pinned-solver result.
505    Cache,
506}
507
508impl From<Source> for SourceName {
509    fn from(s: Source) -> Self {
510        match s {
511            Source::Solved => Self::Solved,
512            Source::Cache => Self::Cache,
513        }
514    }
515}
516
517/// One `check-sat`.
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519pub struct CheckReport {
520    /// Its answer.
521    pub answer: Option<AnswerName>,
522    /// The `:rlimit` in force (0 means unlimited).
523    pub rlimit_limit: Option<u64>,
524    /// rlimit units used.
525    pub rlimit_used: Option<u64>,
526    /// The `reason-unknown` reply, verbatim.
527    pub reason_unknown: Option<String>,
528    /// How it was established; `null` if not recorded.
529    pub source: Option<SourceName>,
530}
531
532/// A counterexample model.
533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
534pub struct Counterexample {
535    /// Index into `checks` of the check that produced it.
536    pub check: u32,
537    /// The `get-model` reply, verbatim.
538    pub model: String,
539    /// Its zero-arity definitions as data.
540    pub assignments: Vec<Assignment>,
541}
542
543/// One constant in a model.
544#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
545pub struct Assignment {
546    /// The SMT name (Verus encodes parameter `x` as `x!`, versions of local
547    /// `i` as `i@0`, `i@1`, …).
548    pub name: String,
549    /// The sort, verbatim.
550    pub sort: String,
551    /// The value, verbatim.
552    pub value: String,
553    /// The value in ITF's value encoding: a rendering of `value`, never a
554    /// replacement for it.
555    pub itf: ItfValue,
556}
557
558/// A model value in the ITF value encoding (Apalache's Informal Trace
559/// Format): a boolean, an integer as `{"#bigint": "[-][0-9]+"}`, or
560/// `{"#unserializable": "<verbatim value>"}` for any value without an ITF
561/// form (uninterpreted sorts, Verus's boxed values, reals and so on).
562///
563/// It is a rendering on top of the solver's exact reply (charter rule 3):
564/// the verbatim `get-model` reply and each verbatim `value` stay alongside
565/// it.
566#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
567#[serde(untagged)]
568pub enum ItfValue {
569    /// An SMT `Bool`.
570    Bool(bool),
571    /// An SMT `Int`, or a bit vector read as an unsigned integer.
572    BigInt {
573        /// Decimal digits with an optional leading `-`.
574        #[serde(rename = "#bigint")]
575        bigint: String,
576    },
577    /// Anything else, verbatim.
578    Unserializable {
579        /// The value, verbatim.
580        #[serde(rename = "#unserializable")]
581        unserializable: String,
582    },
583}
584
585impl ItfValue {
586    /// Renders one zero-arity model constant of `sort` with the verbatim
587    /// `value`. Total: a value it cannot read becomes
588    /// [`ItfValue::Unserializable`].
589    #[must_use]
590    pub fn render(sort: &str, value: &str) -> Self {
591        let v = value.trim();
592        let sort = sort.trim();
593        let read = match sort {
594            "Bool" => match v {
595                "true" => Some(Self::Bool(true)),
596                "false" => Some(Self::Bool(false)),
597                _ => None,
598            },
599            "Int" => smt_int(v).map(|bigint| Self::BigInt { bigint }),
600            _ if sort.starts_with("(_ BitVec ") => smt_bit_vector(v).map(|n| Self::BigInt {
601                bigint: n.to_string(),
602            }),
603            _ => None,
604        };
605        read.unwrap_or_else(|| Self::Unserializable {
606            unserializable: value.to_owned(),
607        })
608    }
609}
610
611/// An SMT-LIB integer value: a numeral, or `(- <numeral>)`.
612fn smt_int(v: &str) -> Option<String> {
613    let numeral = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
614    if numeral(v) {
615        return Some(v.to_owned());
616    }
617    let inner = v.strip_prefix('(')?.strip_suffix(')')?.trim();
618    let digits = inner.strip_prefix('-')?.trim();
619    if !numeral(digits) {
620        return None;
621    }
622    Some(if digits.bytes().all(|b| b == b'0') {
623        "0".to_owned()
624    } else {
625        format!("-{digits}")
626    })
627}
628
629/// An SMT-LIB bit-vector literal (`#x…` or `#b…`) of at most 128 bits, as
630/// an unsigned integer.
631fn smt_bit_vector(v: &str) -> Option<u128> {
632    let (digits, radix) = if let Some(d) = v.strip_prefix("#x") {
633        (d, 16)
634    } else {
635        (v.strip_prefix("#b")?, 2)
636    };
637    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
638        return None;
639    }
640    u128::from_str_radix(digits, radix).ok()
641}
642
643/// A source location in a diagnostic.
644#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
645pub struct DiagnosticSpan {
646    /// The file, as printed.
647    pub file: String,
648    /// 1-based line.
649    pub line: u64,
650    /// 1-based column.
651    pub column: u64,
652    /// Primary (`-->`) or secondary (`:::`).
653    pub primary: bool,
654}
655
656/// One diagnostic from Verus's stderr.
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
658pub struct Diagnostic {
659    /// `error`, `warning`, `note` or `help`.
660    pub level: String,
661    /// The bracketed code, if any.
662    pub code: Option<String>,
663    /// The header's message, verbatim.
664    pub message: String,
665    /// Its locations.
666    pub spans: Vec<DiagnosticSpan>,
667    /// The whole block, verbatim.
668    pub rendered: String,
669}
670
671/// Counts over every function.
672#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
673pub struct Summary {
674    /// Functions.
675    pub functions: u64,
676    /// Verified.
677    pub verified: u64,
678    /// Failed.
679    pub failed: u64,
680    /// Unknown.
681    pub unknown: u64,
682    /// Provisional.
683    pub provisional: u64,
684    /// Unstable (any verdict).
685    pub unstable: u64,
686}
687
688/// A setup failure.
689#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
690pub struct ErrorInfo {
691    /// The stable code (`SAILnnnn`).
692    pub code: String,
693    /// What went wrong.
694    pub message: String,
695}
696
697fn check_report(c: &CheckRecord) -> CheckReport {
698    CheckReport {
699        answer: c.answer.map(AnswerName::from),
700        rlimit_limit: c.effort.limit,
701        rlimit_used: c.effort.used,
702        reason_unknown: c.effort.reason.clone(),
703        source: c.source.map(SourceName::from),
704    }
705}
706
707impl From<&ObligationRecord> for ObligationReport {
708    fn from(o: &ObligationRecord) -> Self {
709        let counterexample = o.checks.iter().enumerate().find_map(|(i, c)| {
710            let model = c.model.as_ref()?;
711            Some(Counterexample {
712                check: u32::try_from(i).unwrap_or(u32::MAX),
713                model: model.text.clone(),
714                assignments: model
715                    .assignments
716                    .iter()
717                    .map(|a| Assignment {
718                        name: a.name.clone(),
719                        sort: a.sort.clone(),
720                        value: a.value.clone(),
721                        itf: ItfValue::render(&a.sort, &a.value),
722                    })
723                    .collect(),
724            })
725        });
726        Self {
727            id: o.id.to_string(),
728            kind: o.id.kind.0.clone(),
729            ordinal: o.id.ordinal,
730            spinoff: o.id.spinoff.map(|index| SpinoffInfo {
731                index,
732                reason: o.spinoff_reason.clone(),
733            }),
734            advisory: !o.id.kind.verdict_bearing(),
735            span: o.span.as_deref().map(SourceSpan::parse),
736            outcome: o.outcome().into(),
737            unstable: o.unstable(),
738            checks: o.checks.iter().map(check_report).collect(),
739            counterexample,
740        }
741    }
742}
743
744impl From<&FunctionRecord> for FunctionReport {
745    fn from(f: &FunctionRecord) -> Self {
746        let sources = f.sources();
747        let verdict = VerdictName::from(f.verdict());
748        let establishment = EstablishmentName::from(f.establishment);
749        Self {
750            function: f.function.clone(),
751            module: f.module.clone(),
752            fn_mode: f.fn_mode.clone(),
753            verdict,
754            establishment,
755            evidence_tier: EvidenceTierName::for_smt(verdict, establishment),
756            unstable: f.unstable(),
757            verus_success: f.verus_success,
758            provenance: ProvenanceReport {
759                configuration: None,
760                mode: f.mode.name().to_owned(),
761                source: sources.summary().into(),
762                checks_solved: sources.solved,
763                checks_served: sources.served,
764                checks_unrecorded: sources.unrecorded,
765                engine: None,
766            },
767            timing: Timing {
768                smt_micros: f.smt_micros,
769                rlimit: f.rlimit,
770            },
771            fragility: None,
772            obligations: f
773                .obligations
774                .as_ref()
775                .map(|os| os.iter().map(ObligationReport::from).collect()),
776        }
777    }
778}
779
780impl Summary {
781    /// Counts the functions in `crates`.
782    #[must_use]
783    pub fn of(crates: &[CrateReport]) -> Self {
784        let mut s = Self::default();
785        for f in crates.iter().flat_map(|c| &c.functions) {
786            s.functions += 1;
787            match f.verdict {
788                VerdictName::Verified => s.verified += 1,
789                VerdictName::Failed => s.failed += 1,
790                VerdictName::Unknown => s.unknown += 1,
791                VerdictName::Provisional => s.provisional += 1,
792            }
793            s.unstable += u64::from(f.unstable);
794        }
795        s
796    }
797}
798
799impl CrateReport {
800    /// How many of this crate's `unknown` functions Verus's own totals clear.
801    ///
802    /// When attribution is incomplete in a failing crate, functions Sail
803    /// cannot confirm one by one are `unknown` (VI-0003, VI-0010). Verus
804    /// counts every failing verification unit in `verus.errors`, bit-vector
805    /// failures included (VI-0003), and each function reported `failed`
806    /// accounts for at least one. So when `errors` equals the number of failed
807    /// functions, no other function had an error, and the `unknown` functions
808    /// passed by Verus's totals. Their verdicts stay `unknown`: this is a
809    /// count from Verus's aggregate, never a per-function proof (charter
810    /// rule 7). Returns 0 whenever the totals cannot clear them.
811    #[must_use]
812    pub fn unknown_passed_by_verus_totals(&self) -> u64 {
813        if self.verus_totals_clear_unknown() {
814            self.count(VerdictName::Unknown)
815        } else {
816            0
817        }
818    }
819
820    /// Whether this crate's `unknown` functions passed by Verus's totals:
821    /// see [`Self::unknown_passed_by_verus_totals`]. The verdicts stay
822    /// `unknown`; this only says Verus's aggregate left no error for them.
823    #[must_use]
824    pub fn verus_totals_clear_unknown(&self) -> bool {
825        let failed = self.count(VerdictName::Failed);
826        failed > 0
827            && self.verus.errors == Some(failed)
828            && self.verus.verified.is_some()
829            && self.verus.encountered_vir_error != Some(true)
830    }
831
832    fn count(&self, verdict: VerdictName) -> u64 {
833        let n = self
834            .functions
835            .iter()
836            .filter(|f| f.verdict == verdict)
837            .count();
838        u64::try_from(n).unwrap_or(u64::MAX)
839    }
840}
841
842impl Report {
843    /// Rules the JSON Schema cannot express. Returns every violation.
844    #[must_use]
845    pub fn invariant_violations(&self) -> Vec<String> {
846        let mut out = Vec::new();
847        if self.schema_version != SCHEMA_VERSION {
848            out.push(format!("schema_version is {}", self.schema_version));
849        }
850        let mut ids = std::collections::BTreeSet::new();
851        for f in self.crates.iter().flat_map(|c| &c.functions) {
852            if f.verdict == VerdictName::Verified && f.establishment != EstablishmentName::Confirmed
853            {
854                out.push(format!("{}: verified but not confirmed", f.function));
855            }
856            if (f.establishment == EstablishmentName::Provisional)
857                != (f.verdict == VerdictName::Provisional)
858            {
859                out.push(format!(
860                    "{}: establishment and verdict disagree",
861                    f.function
862                ));
863            }
864            let settled = matches!(f.verdict, VerdictName::Verified | VerdictName::Failed);
865            if settled != f.evidence_tier.is_some() {
866                out.push(format!(
867                    "{}: evidence tier and verdict disagree",
868                    f.function
869                ));
870            }
871            let p = &f.provenance;
872            let counted = (p.checks_solved, p.checks_served, p.checks_unrecorded);
873            let expected = match p.source {
874                SourceSummaryName::Fresh => counted.0 > 0 && counted.1 == 0 && counted.2 == 0,
875                SourceSummaryName::Cache => counted.0 == 0 && counted.1 > 0 && counted.2 == 0,
876                SourceSummaryName::Mixed => counted.0 > 0 && counted.1 > 0 && counted.2 == 0,
877                SourceSummaryName::Unrecorded => counted.2 > 0 || counted == (0, 0, 0),
878            };
879            if !expected {
880                out.push(format!(
881                    "{}: provenance counts disagree with source",
882                    f.function
883                ));
884            }
885            for o in f.obligations.iter().flatten() {
886                if !ids.insert(o.id.clone()) {
887                    out.push(format!("duplicate obligation id {}", o.id));
888                }
889                if !o.id.starts_with(&format!("{}#", f.function)) {
890                    out.push(format!("obligation {} is not {}'s", o.id, f.function));
891                }
892            }
893        }
894        if self.summary != Summary::of(&self.crates) {
895            out.push("summary does not match the functions".to_owned());
896        }
897        out
898    }
899}
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904
905    #[test]
906    fn spans_parse() {
907        let s = SourceSpan::parse("src/lib.rs:46:1: 46:26 (#0)");
908        assert_eq!(s.file.as_deref(), Some("src/lib.rs"));
909        assert_eq!(
910            (s.line, s.column, s.end_line, s.end_column),
911            (Some(46), Some(1), Some(46), Some(26))
912        );
913        let s = SourceSpan::parse("garbage");
914        assert_eq!((s.file, s.line), (None, None));
915        assert_eq!(s.text, "garbage");
916    }
917    #[test]
918    fn the_example_document_is_valid_v2_with_rendered_itf_values() {
919        let text =
920            include_str!("../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json");
921        let golden: Report =
922            serde_json::from_str(text).unwrap_or_else(|e| unreachable!("fixture: {e}"));
923        let schema: serde_json::Value = serde_json::from_str(JSON_SCHEMA).unwrap_or_default();
924        let value: serde_json::Value = serde_json::from_str(text).unwrap_or_default();
925        assert_eq!(
926            crate::schema::validate(&schema, &value),
927            Vec::<String>::new()
928        );
929        assert_eq!(golden.invariant_violations(), Vec::<String>::new());
930        let mut rendered = 0;
931        for o in golden
932            .crates
933            .iter()
934            .flat_map(|c| &c.functions)
935            .flat_map(|f| f.obligations.iter().flatten())
936        {
937            for a in o.counterexample.iter().flat_map(|c| &c.assignments) {
938                assert_eq!(a.itf, ItfValue::render(&a.sort, &a.value), "{}", a.name);
939                // Every verbatim value is in the verbatim model.
940                assert!(
941                    o.counterexample
942                        .as_ref()
943                        .is_some_and(|c| c.model.contains(&a.value)),
944                    "{}",
945                    a.name
946                );
947                rendered += usize::from(!matches!(a.itf, ItfValue::Unserializable { .. }));
948            }
949        }
950        assert!(rendered > 0);
951    }
952    #[test]
953    fn engine_provenance_is_additive_and_matches_the_schemas() {
954        let stock: Report = serde_json::from_str(include_str!(
955            "../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json"
956        ))
957        .unwrap_or_else(|e| unreachable!("fixture: {e}"));
958        // Stock documents serialize exactly as before: no engine fields.
959        let stock_text = serde_json::to_string(&stock).unwrap_or_default();
960        assert!(!stock_text.contains("\"engine\""));
961        let engine = EngineProvenance {
962            name: "interactive".to_owned(),
963            manifest_sha256: "ab".repeat(32),
964            established_by: EngineEstablishment::StockFallback,
965        };
966        let mut r = stock.clone();
967        r.engine = Some(engine.clone());
968        for f in r.crates.iter_mut().flat_map(|c| &mut c.functions) {
969            f.provenance.engine = Some(engine.clone());
970        }
971        let schema = serde_json::from_str(JSON_SCHEMA).unwrap_or_default();
972        let value = serde_json::to_value(&r).unwrap_or_default();
973        assert_eq!(
974            crate::schema::validate(&schema, &value),
975            Vec::<String>::new()
976        );
977        assert_eq!(value["engine"]["established_by"], "stock-fallback");
978        let mut wrong = value.clone();
979        wrong["engine"]["established_by"] = serde_json::json!("default");
980        assert_ne!(
981            crate::schema::validate(&schema, &wrong),
982            Vec::<String>::new()
983        );
984        let mut wrong = value;
985        if let Some(engine) = wrong["engine"].as_object_mut() {
986            engine.remove("manifest_sha256");
987        }
988        assert_ne!(
989            crate::schema::validate(&schema, &wrong),
990            Vec::<String>::new()
991        );
992        let project: serde_json::Value =
993            serde_json::from_str(include_str!("../schema/project-result-v2.json"))
994                .unwrap_or_default();
995        let identity = crate::project::EngineIdentity {
996            name: "interactive".to_owned(),
997            manifest_sha256: "cd".repeat(32),
998        };
999        let identity = serde_json::to_value(identity).unwrap_or_default();
1000        assert_eq!(
1001            crate::schema::validate(&project["properties"]["engine"], &identity),
1002            Vec::<String>::new()
1003        );
1004        let mut extra = identity;
1005        extra["established_by"] = serde_json::json!("engine");
1006        assert_ne!(
1007            crate::schema::validate(&project["properties"]["engine"], &extra),
1008            Vec::<String>::new()
1009        );
1010    }
1011    #[test]
1012    fn verus_totals_clear_unknown_functions_only_when_every_error_is_accounted_for() {
1013        let golden: Report = serde_json::from_str(include_str!(
1014            "../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json"
1015        ))
1016        .unwrap_or_else(|e| unreachable!("fixture: {e}"));
1017        // The fixture: 8 functions, 2 failed, and Verus reports 2 errors.
1018        let mut krate = golden.crates[0].clone();
1019        assert_eq!(krate.verus.errors, Some(2));
1020        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1021        // Incomplete attribution leaves the 6 successes unknown (VI-0003).
1022        for f in &mut krate.functions {
1023            if f.verdict == VerdictName::Verified {
1024                f.verdict = VerdictName::Unknown;
1025            }
1026        }
1027        assert_eq!(krate.unknown_passed_by_verus_totals(), 6);
1028        // A further Verus error may belong to any unknown function.
1029        krate.verus.errors = Some(3);
1030        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1031        krate.verus.errors = Some(2);
1032        krate.verus.encountered_vir_error = Some(true);
1033        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1034        krate.verus.encountered_vir_error = Some(false);
1035        krate.verus.verified = None;
1036        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1037        // Without a failed function there is nothing to account errors to.
1038        krate.verus.verified = Some(9);
1039        for f in &mut krate.functions {
1040            f.verdict = VerdictName::Unknown;
1041        }
1042        krate.verus.errors = Some(0);
1043        assert_eq!(krate.unknown_passed_by_verus_totals(), 0);
1044    }
1045    #[test]
1046    fn portfolio_evidence_matches_the_schema() {
1047        let mut r: Report = serde_json::from_str(include_str!(
1048            "../resources/crates/sail-cli/tests/fixtures/attr/report.golden.json"
1049        ))
1050        .unwrap_or_else(|e| unreachable!("fixture: {e}"));
1051        let attempt = PortfolioAttempt {
1052            configuration: SolverConfiguration { seed: 4 },
1053            verified: false,
1054            exit_code: Some(1),
1055            wall_ms: 1.0,
1056            error: None,
1057            report: Some(Box::new(r.clone())),
1058            stderr: "original diagnostics".to_owned(),
1059        };
1060        r.mode = "accept-first-proof".to_owned();
1061        r.portfolio = Some(PortfolioReport {
1062            seeds: vec![0, 4],
1063            winner_seed: None,
1064            attempts: vec![attempt],
1065        });
1066        let schema = serde_json::from_str(JSON_SCHEMA).unwrap_or_default();
1067        let value = serde_json::to_value(r).unwrap_or_default();
1068        assert!(
1069            crate::schema::validate(&schema, &value).is_empty(),
1070            "{:?}",
1071            crate::schema::validate(&schema, &value)
1072        );
1073    }
1074}