sail-solve 0.4.0

Fast, cached Verus verification for Rust: standalone files, projects, watch and agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! `sail fragility`: how fragile are this crate's proofs?
//!
//! ```text
//! sail fragility [--seeds N] [--shuffles K] [--jobs J] [--near-limit F] [--top K]
//!                [--json] [--keep-traces DIR] [--traces DIR] [--z3 PATH]
//!                [--focus] [--output json] [cargo verus verify arguments…]
//! ```
//!
//! Runs `cargo verus verify <arguments>` (or `cargo verus focus`, which
//! partial verification such as `--verify-function` requires: chosen with
//! `--focus`, or automatically when the Verus arguments select part of the
//! crate) once, with `sail-z3` in pure
//! pass-through (no daemon, no cache) and tracing on, so every solver
//! session is exactly what plain Verus sent. It adds `--output-json --time`
//! after `--` (unless already given) to read Verus's per-function
//! breakdown. Then it re-runs every captured session under `N`
//! configurations of the same pinned Z3 (`sail-portfolio`, ADR 0018) and
//! reports per-check fragility: a human summary on stdout, or the whole
//! report as JSON with `--json` (or `--output json`, as `sail verify` and
//! the MCP `fragility` tool spell it).
//!
//! This is an opt-in measurement. It never changes a verdict, and it never
//! reads or writes the cache, so it cannot change the cache keys or answers
//! of `sail verify`. `--traces DIR` measures sessions captured earlier
//! instead of running Verus.

use std::ffi::OsString;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};

use sail_portfolio::fragility::{self, Options, Report};
use sail_portfolio::{Solver, sessions};
use serde::Serialize;
use serde_json::Value;

/// Exit code for a setup or usage failure.
const EXIT_SETUP: u8 = 2;

/// The flags Verus needs for the per-function breakdown.
const VERUS_FLAGS: &[&str] = &["--output-json", "--time"];

/// Parsed command line.
#[derive(Debug, Clone, PartialEq)]
struct Args {
    options: Options,
    top: usize,
    json: bool,
    focus: bool,
    keep_traces: Option<PathBuf>,
    traces: Option<PathBuf>,
    z3: Option<PathBuf>,
    timeout_secs: u64,
    passthrough: Vec<String>,
}

fn parse(args: &[String]) -> Result<Args, String> {
    let mut a = Args {
        options: Options::default(),
        top: 10,
        json: false,
        focus: false,
        keep_traces: None,
        traces: None,
        z3: None,
        timeout_secs: 3600,
        passthrough: Vec::new(),
    };
    let mut it = args.iter();
    while let Some(arg) = it.next() {
        let mut value = || it.next().cloned().ok_or(format!("{arg} needs a value"));
        let number = |v: String| {
            v.parse::<u64>()
                .map_err(|_| format!("{arg} needs a number"))
        };
        match arg.as_str() {
            "--seeds" => a.options.seeds = number(value()?)?,
            "--shuffles" => a.options.shuffles = number(value()?)?,
            "--jobs" => a.options.jobs = usize::try_from(number(value()?)?).unwrap_or(1),
            "--top" => a.top = usize::try_from(number(value()?)?).unwrap_or(0),
            "--timeout-secs" => a.timeout_secs = number(value()?)?,
            "--near-limit" => {
                a.options.near_limit = value()?
                    .parse()
                    .map_err(|_| "--near-limit needs a fraction".to_owned())?;
            }
            "--json" => a.json = true,
            "--output" => {
                let v = value()?;
                if v != "json" {
                    return Err(format!("--output {v}: only `json` is supported"));
                }
                a.json = true;
            }
            "--focus" => a.focus = true,
            "--keep-traces" => a.keep_traces = Some(value()?.into()),
            "--traces" => a.traces = Some(value()?.into()),
            "--z3" => a.z3 = Some(value()?.into()),
            _ => {
                // The first argument sail does not know starts the
                // `cargo verus verify` arguments.
                a.passthrough.push(arg.clone());
                a.passthrough.extend(it.by_ref().cloned());
            }
        }
    }
    if a.options.seeds == 0 || a.options.jobs == 0 || a.timeout_secs == 0 {
        return Err("--seeds, --jobs and --timeout-secs must be at least 1".to_owned());
    }
    Ok(a)
}

/// Verus flags that select part of a crate. `cargo verus` accepts them
/// only under `focus`, so they switch the capture to `cargo verus focus`.
const PARTIAL: &[&str] = &[
    "--verify-module",
    "--verify-only-module",
    "--verify-function",
    "--verify-root",
];

/// Whether the Verus arguments (after `--`) select part of the crate.
fn partial(args: &[String]) -> bool {
    args.iter()
        .skip_while(|a| *a != "--")
        .any(|a| PARTIAL.contains(&a.as_str()))
}

/// `cargo verus verify` arguments with Verus's breakdown flags added after
/// `--` (once).
fn with_verus_flags(args: &[String]) -> Vec<String> {
    let mut out = args.to_vec();
    let after = args.iter().position(|a| a == "--");
    let verus_part = after.map_or(&[][..], |p| args.get(p + 1..).unwrap_or_default());
    let missing: Vec<String> = VERUS_FLAGS
        .iter()
        .filter(|f| !verus_part.iter().any(|a| a == *f))
        .map(|f| (*f).to_owned())
        .collect();
    if !missing.is_empty() {
        if after.is_none() {
            out.push("--".to_owned());
        }
        out.extend(missing);
    }
    out
}

/// One function from Verus's `--time` breakdown.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct VerusFunction {
    function: String,
    success: bool,
    rlimit: u64,
}

/// The functions in every `--output-json` document on `stdout`.
fn verus_functions(stdout: &[u8]) -> Vec<VerusFunction> {
    let mut out = Vec::new();
    let stream = serde_json::Deserializer::from_slice(stdout).into_iter::<Value>();
    for doc in stream.map_while(Result::ok) {
        let modules = doc
            .pointer("/times-ms/smt/smt-run-module-times")
            .and_then(Value::as_array);
        for f in modules
            .into_iter()
            .flatten()
            .filter_map(|m| m.get("function-breakdown")?.as_array())
            .flatten()
        {
            out.push(VerusFunction {
                function: f
                    .get("function")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_owned(),
                success: f.get("success").and_then(Value::as_bool).unwrap_or(false),
                rlimit: f.get("rlimit").and_then(Value::as_u64).unwrap_or(0),
            });
        }
    }
    out
}

/// The JSON document `--json` prints.
#[derive(Serialize)]
struct JsonOutput<'a> {
    /// Format version of this document.
    schema_version: u32,
    /// Always `fragility`: an opt-in measurement, not a verification result.
    mode: &'static str,
    /// Verus's exit code on the capture run (`None` with `--traces`).
    verus_exit_code: Option<i32>,
    /// Verus's per-function breakdown from the capture run.
    verus_functions: &'a [VerusFunction],
    /// Whether any checks have an exact AIR/transcript function mapping.
    attributed: bool,
    /// The fragility report.
    report: &'a Report,
    /// The unchanged baseline verification report, with attributed scores.
    #[serde(skip_serializing_if = "Option::is_none")]
    verification: Option<&'a sail_api::output::Report>,
}

fn fail(err: &mut dyn std::io::Write, code: &str, msg: &str) -> ExitCode {
    let _ = writeln!(err, "error[{code}]: sail fragility: {msg}");
    ExitCode::from(EXIT_SETUP)
}

/// What the capture produced.
struct Captured {
    exit_code: Option<i32>,
    functions: Vec<VerusFunction>,
    logs: Vec<sail_verus::attribution::LogFile>,
    verification: sail_api::output::Report,
}

/// Runs `cargo verus <subcommand>` through the shim with tracing into
/// `dir`.
fn capture(
    cargo_verus: &Path,
    subcommand: &str,
    shim: &Path,
    z3: &Path,
    dir: &Path,
    args: &[String],
) -> Result<Captured, String> {
    let (args, _ownership) = crate::measurement::prepare(args, subcommand == "focus")?;
    let args = args.as_slice();
    let logs_dir = dir.join("logs");
    let unavailable = crate::verify::logs_unavailable(args);
    let output = Command::new(cargo_verus)
        .arg("verus")
        .arg(subcommand)
        .args(
            crate::verify::logged_args(&with_verus_flags(args), unavailable.is_none(), &logs_dir)
                .iter()
                .map(OsString::from),
        )
        .env("VERUS_Z3_PATH", shim)
        .env("SAIL_Z3_PATH", z3)
        .env("SAIL_TRACE_DIR", dir)
        .env("SAIL_SOLVER_MODE", "default")
        .env_remove("SAIL_DAEMON_SOCKET")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .map_err(|e| format!("cannot run {}: {e}", cargo_verus.display()))?;
    let (docs, _) = sail_verus::attribution::json_documents(&output.stdout);
    let logs = sail_verus::attribution::read_logs(&logs_dir).unwrap_or_default();
    let attribution = sail_verus::attribution::attribute(
        &docs,
        Some(&logs),
        &sail_verus::attribution::Provenance::NoCache,
        unavailable.as_deref(),
    );
    let diagnostics = sail_verus::diagnostics::parse(&String::from_utf8_lossy(&output.stderr));
    let verification = crate::report::build(&crate::report::Inputs {
        args,
        exit_code: output.status.code(),
        solver_path: Some(z3.to_string_lossy().into_owned()),
        solver_sha256: crate::verify::file_sha256(z3),
        daemon: false,
        attribution: &attribution,
        diagnostics: &diagnostics,
    });
    let _ = std::io::stderr().write_all(&output.stderr);
    let functions = verus_functions(&output.stdout)
        .into_iter()
        .filter(|f| {
            verification
                .crates
                .iter()
                .flat_map(|c| &c.functions)
                .any(|v| v.function == f.function)
        })
        .collect();
    Ok(Captured {
        logs,
        verification,
        exit_code: output.status.code(),
        functions,
    })
}

/// A fresh trace directory under the sail cache.
fn fresh_trace_dir() -> Result<PathBuf, String> {
    let cache = sail_verus::cache_dir().map_err(|e| e.to_string())?;
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    Ok(cache
        .join("fragility")
        .join(format!("{}-{nanos}", std::process::id())))
}

/// Runs `sail fragility <args>`.
pub fn fragility(
    args: &[String],
    out: &mut dyn std::io::Write,
    err: &mut dyn std::io::Write,
) -> ExitCode {
    let a = match parse(args) {
        Ok(a) => a,
        Err(e) => return fail(err, "SAIL0110", &e),
    };
    let shim = match std::env::current_exe() {
        Ok(me) => crate::verify::shim_for(&me),
        Err(e) => return fail(err, "SAIL0102", &format!("cannot locate sail: {e}")),
    };
    let cargo_verus = crate::verify::cargo_verus();
    let z3 = a.z3.clone().or_else(|| {
        cargo_verus
            .as_deref()
            .ok()
            .and_then(|cv| crate::verify::real_z3(cv, &shim))
    });
    let Some(z3) = z3 else {
        return fail(
            err,
            "SAIL0103",
            "cannot find the Z3 Verus uses (set VERUS_Z3_PATH or pass --z3)",
        );
    };
    let (dir, captured, temporary) = if let Some(dir) = a.traces.clone() {
        (dir, None, false)
    } else {
        let cargo_verus = match cargo_verus {
            Ok(cargo_verus) => cargo_verus,
            Err(message) => return fail(err, "SAIL0101", &message),
        };
        if !shim.is_file() {
            return fail(
                err,
                "SAIL0102",
                &format!("sail-z3 not found next to sail at {}", shim.display()),
            );
        }
        let (dir, temporary) = match a.keep_traces.clone() {
            Some(d) => (d, false),
            None => match fresh_trace_dir() {
                Ok(d) => (d, true),
                Err(e) => return fail(err, "SAIL0104", &e),
            },
        };
        if let Err(e) = std::fs::create_dir_all(&dir) {
            return fail(
                err,
                "SAIL0111",
                &format!("cannot create {}: {e}", dir.display()),
            );
        }
        match capture(
            &cargo_verus,
            if a.focus || partial(&a.passthrough) {
                "focus"
            } else {
                "verify"
            },
            &shim,
            &z3,
            &dir,
            &a.passthrough,
        ) {
            Ok(c) => (dir, Some(c), temporary),
            Err(e) => return fail(err, "SAIL0105", &e),
        }
    };
    let result = measure(&a, &z3, &dir, captured.as_ref());
    if temporary {
        let _ = std::fs::remove_dir_all(&dir);
    }
    match result {
        Ok((report, attributed, verification)) => print(
            &a,
            &report,
            attributed,
            captured.as_ref(),
            verification.as_ref(),
            out,
            err,
        ),
        Err(e) => fail(err, "SAIL0112", &e),
    }
}

/// Prints the result: JSON with `--json`, else a human summary.
fn print(
    a: &Args,
    report: &Report,
    attributed: bool,
    captured: Option<&Captured>,
    verification: Option<&sail_api::output::Report>,
    out: &mut dyn std::io::Write,
    err: &mut dyn std::io::Write,
) -> ExitCode {
    if a.json {
        let doc = JsonOutput {
            schema_version: 1,
            mode: "fragility",
            verus_exit_code: captured.and_then(|c| c.exit_code),
            verus_functions: captured.map(|c| c.functions.as_slice()).unwrap_or_default(),
            attributed,
            report,
            verification,
        };
        match serde_json::to_string_pretty(&doc) {
            Ok(text) => {
                let _ = writeln!(out, "{text}");
            }
            Err(e) => return fail(err, "SAIL0113", &e.to_string()),
        }
    } else {
        if let Some(c) = captured {
            let failed = c.functions.iter().filter(|f| !f.success).count();
            let _ = writeln!(
                out,
                "verus: exit {:?}, {} functions ({} failing); checks attributed to a function: {}",
                c.exit_code,
                c.functions.len(),
                failed,
                if attributed {
                    "yes"
                } else {
                    "no (exact AIR/transcript mapping unavailable)"
                }
            );
        }
        let _ = write!(out, "{}", fragility::render(report, a.top));
    }
    ExitCode::SUCCESS
}

fn measure(
    a: &Args,
    z3: &Path,
    dir: &Path,
    captured: Option<&Captured>,
) -> Result<(Report, bool, Option<sail_api::output::Report>), String> {
    let found = sessions::discover(dir).map_err(|e| e.to_string())?;
    if found.is_empty() {
        return Err(format!(
            "no solver sessions were captured in {}{}",
            dir.display(),
            match captured.and_then(|c| c.exit_code) {
                Some(0) => " (Verus exited 0: Cargo may have found the crate up to date; \
                            change a source file or run `cargo clean -p <crate>`, then retry)"
                    .to_owned(),
                Some(c) => format!(" (Verus exited {c})"),
                None => String::new(),
            }
        ));
    }
    let solver = Solver {
        path: z3.to_path_buf(),
        timeout: std::time::Duration::from_secs(a.timeout_secs),
    };
    let mut report =
        fragility::measure(&solver, &found, &a.options, |_, _| {}).map_err(|e| e.to_string())?;
    let verification = captured.map(|c| {
        let mut verification = c.verification.clone();
        crate::fragility_join::attach(&mut verification, &mut report, &found, &c.logs);
        verification
    });
    let attributed =
        !report.checks.is_empty() && report.checks.iter().all(|c| c.function.is_some());
    Ok((report, attributed, verification))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strings(s: &str) -> Vec<String> {
        s.split_whitespace().map(str::to_owned).collect()
    }

    #[test]
    fn parses_sail_flags_then_passes_the_rest_through() {
        let a = parse(&strings(
            "--seeds 3 --json --focus -p demo -- --verify-function f",
        ));
        let Ok(a) = a else { unreachable!("{a:?}") };
        assert_eq!(a.options.seeds, 3);
        assert!(a.json && a.focus);
        assert_eq!(a.passthrough, strings("-p demo -- --verify-function f"));
        // A sail flag after the first cargo argument belongs to cargo.
        let a = parse(&strings("-p demo --seeds 3"));
        let Ok(a) = a else { unreachable!("{a:?}") };
        assert_eq!(a.options.seeds, 8);
        assert_eq!(a.passthrough, strings("-p demo --seeds 3"));
        assert!(parse(&strings("--seeds 0")).is_err());
        assert!(parse(&strings("--seeds x")).is_err());
        assert!(parse(&strings("--json --seeds")).is_err());
        let a = parse(&strings("--output json -p x"));
        assert!(a.is_ok_and(|a| a.json));
        assert!(parse(&strings("--output text")).is_err());
    }

    #[test]
    fn partial_selectors_need_focus() {
        assert!(partial(&strings(
            "-p x -- --verify-root --verify-function f"
        )));
        assert!(partial(&strings("-- --verify-module m")));
        assert!(!partial(&strings("-p x -- --rlimit 20")));
        // Before `--` they are cargo arguments, not Verus selectors.
        assert!(!partial(&strings("--verify-function f")));
    }

    #[test]
    fn adds_verus_flags_once() {
        assert_eq!(with_verus_flags(&[]), strings("-- --output-json --time"));
        assert_eq!(
            with_verus_flags(&strings("-p x -- --time")),
            strings("-p x -- --time --output-json")
        );
        assert_eq!(
            with_verus_flags(&strings("-- --output-json --time")),
            strings("-- --output-json --time")
        );
    }

    #[test]
    fn reads_the_function_breakdown() {
        let stdout = br#"{"times-ms":{"smt":{"smt-run-module-times":[{"module":"","function-breakdown":[{"function":"m::f","success":true,"rlimit":5},{"function":"m::g","success":false,"rlimit":7}]}]}}}
{"times-ms":{"smt":{"smt-run-module-times":[]}}}"#;
        let fns = verus_functions(stdout);
        assert_eq!(fns.len(), 2);
        assert_eq!(fns[1].function, "m::g");
        assert!(!fns[1].success);
        assert_eq!(verus_functions(b"not json"), vec![]);
    }
}