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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
//! Experimental bounded Kani checks, separate from Verus jobs and Verus receipts.
//!
//! One exact `--harness` keeps the original single-harness run and result
//! document. Several `--harness` options, none, or `--jobs` run one original
//! driver over the whole selection with `-j` (ADR 0186). Cargo selection,
//! admitted `-Z` features, `--solver` and `--harness-timeout` pass through to
//! the driver in order, as `cargo kani` takes them (ADR 0184). Every CBMC
//! process runs under the integrity supervisor installed beside `sail`
//! (ADR 0182). A `cbmc` call whose exact GOTO bytes, argv and tools match a
//! stored clean run replays that run's exact bytes and exit status from the
//! machine's result store instead of running (ADR 0188); `--no-store` turns
//! the store off for a run and `--store-max` bounds its size.
//! A run whose input closure is unchanged can also replay a local
//! `kani-v1` receipt (ADR 0189). Use `--no-receipts` or
//! `SAIL_KANI_RECEIPTS=off` to run the Kani driver.
use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;

#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
mod health;

/// Longest admitted child-process budget, in milliseconds (24 hours).
const MAX_TIMEOUT_MS: u64 = 86_400_000;
/// The result store's default size bound (ADR 0188).
const DEFAULT_STORE_MAX: u64 = 4 << 30;

#[derive(Debug, PartialEq)]
struct Options {
    project: PathBuf,
    cargo_home: PathBuf,
    harnesses: Vec<String>,
    unwind: Option<u32>,
    jobs: Option<u32>,
    arguments: Vec<sail_kani::arguments::Argument>,
    solver_policy: sail_kani::SolverPolicy,
    timeout_ms: u64,
    memory_max: Option<u64>,
    harness_memory_max: Option<u64>,
    /// The result store's size bound; `None` with `--no-store`.
    store_max: Option<u64>,
    json: bool,
    receipts: bool,
}

impl Options {
    /// The original single-harness shape: one exact harness, no `--jobs`.
    #[cfg(any(
        test,
        any(
            all(target_os = "linux", target_arch = "x86_64"),
            all(target_os = "macos", target_arch = "aarch64")
        )
    ))]
    fn single(&self) -> bool {
        self.harnesses.len() == 1 && self.jobs.is_none()
    }
}

/// Parse one pass-through option (ADR 0184) into `arguments`; `false` when
/// `flag` is not one.
fn pass_through<'a>(
    flag: &str,
    tokens: &mut impl Iterator<Item = &'a String>,
    arguments: &mut Vec<sail_kani::arguments::Argument>,
) -> Result<bool, String> {
    use sail_kani::arguments::Argument;
    let takes_value = Argument::takes_value(flag);
    if !takes_value
        && !matches!(
            flag,
            "--all-features" | "--no-default-features" | "--workspace" | "--randomize-layout"
        )
    {
        return Ok(false);
    }
    let value = if takes_value {
        Some(
            tokens
                .next()
                .ok_or_else(|| format!("missing value for `{flag}`"))?
                .as_str(),
        )
    } else {
        None
    };
    let argument = Argument::parse(flag, value).map_err(|error| error.to_string())?;
    let repeatable = matches!(
        argument,
        Argument::Unstable(_) | Argument::Package(_) | Argument::Features(_)
    );
    if !repeatable
        && arguments
            .iter()
            .any(|seen| std::mem::discriminant(seen) == std::mem::discriminant(&argument))
    {
        return Err(format!("duplicate Kani option `{flag}`"));
    }
    arguments.push(argument);
    Ok(true)
}

/// Add one exact `--harness` name to the selection.
fn push_harness(harnesses: &mut Vec<String>, value: &str) -> Result<(), String> {
    if value.is_empty()
        || value.starts_with('-')
        || value.chars().any(char::is_control)
        || value.len() > 4096
    {
        return Err("use the exact hand-written harness name reported by Kani".into());
    }
    if harnesses.iter().any(|seen| seen == value) {
        return Err(format!("duplicate harness `{value}`"));
    }
    harnesses.push(value.to_owned());
    Ok(())
}

fn parse(args: &[String]) -> Result<Options, String> {
    use sail_kani::arguments::Argument;
    let mut values = std::collections::BTreeMap::new();
    let mut harnesses = Vec::new();
    let mut arguments: Vec<Argument> = Vec::new();
    let mut tokens = args.iter();
    let mut no_store = false;
    let mut receipts = std::env::var("SAIL_KANI_RECEIPTS").map_or(true, |value| value != "off");
    while let Some(flag) = tokens.next() {
        if pass_through(flag, &mut tokens, &mut arguments)? {
            continue;
        }
        if reuse_control(flag, &mut no_store, &mut receipts)? {
            continue;
        }
        if !matches!(
            flag.as_str(),
            "--backend"
                | "--project"
                | "--cargo-home"
                | "--harness"
                | "--unwind"
                | "--jobs"
                | "--timeout-ms"
                | "--memory-max"
                | "--harness-memory-max"
                | "--store-max"
                | "--solver-policy"
                | "--output"
        ) {
            return Err(format!("unsupported Kani option `{flag}`"));
        }
        let value = tokens
            .next()
            .filter(|value| !value.starts_with("--"))
            .ok_or_else(|| format!("missing value for `{flag}`"))?;
        if flag == "--harness" {
            push_harness(&mut harnesses, value)?;
            continue;
        }
        if values.insert(flag.as_str(), value.as_str()).is_some() {
            return Err(format!("duplicate Kani option `{flag}`"));
        }
    }
    if values.get("--backend") != Some(&"kani") {
        return Err("expected --backend kani".into());
    }
    let positive = |name: &str| -> Result<Option<u32>, String> {
        values
            .get(name)
            .map(|value| {
                value
                    .parse::<u32>()
                    .ok()
                    .filter(|value| *value > 0)
                    .ok_or_else(|| format!("{} must be a positive integer", &name[2..]))
            })
            .transpose()
    };
    let unwind = positive("--unwind")?;
    let jobs = positive("--jobs")?;
    let timeout_ms = values
        .get("--timeout-ms")
        .unwrap_or(&"600000")
        .parse::<u64>()
        .map_err(|_| "timeout-ms must be an integer")?;
    if !(1..=MAX_TIMEOUT_MS).contains(&timeout_ms) {
        return Err(format!("timeout-ms must be 1..={MAX_TIMEOUT_MS}"));
    }
    let [memory_max, harness_memory_max] =
        ["--memory-max", "--harness-memory-max"].map(|name| size(&values, name));
    let (memory_max, harness_memory_max) = (memory_max?, harness_memory_max?);
    let store_max = store_max(no_store, values.get("--store-max").copied())?;
    let solver_policy = solver_policy(values.get("--solver-policy").copied())?;
    let json = match values.get("--output") {
        None => false,
        Some(&"json") => true,
        _ => return Err("expected --output json".into()),
    };
    let cargo_home = values
        .get("--cargo-home")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("CARGO_HOME").map(PathBuf::from))
        .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cargo")))
        .ok_or("specify a prepared --cargo-home directory")?;
    Ok(Options {
        project: PathBuf::from(values.get("--project").unwrap_or(&".")),
        cargo_home,
        harnesses,
        unwind,
        jobs,
        arguments,
        solver_policy,
        timeout_ms,
        memory_max,
        harness_memory_max,
        store_max,
        json,
        receipts,
    })
}

fn solver_policy(value: Option<&str>) -> Result<sail_kani::SolverPolicy, String> {
    match value {
        None => Ok(sail_kani::SolverPolicy::Original),
        Some("remembered-best") => Ok(sail_kani::SolverPolicy::RememberedBest),
        _ => Err("SAIL6380: expected --solver-policy remembered-best".into()),
    }
}

fn reuse_control(flag: &str, no_store: &mut bool, receipts: &mut bool) -> Result<bool, String> {
    match flag {
        "--no-store" => {
            if std::mem::replace(no_store, true) {
                return Err(format!("duplicate Kani option `{flag}`"));
            }
        }
        "--no-receipts" => *receipts = false,
        _ => return Ok(false),
    }
    Ok(true)
}

/// A memory size option's value.
fn size(
    values: &std::collections::BTreeMap<&str, &str>,
    name: &str,
) -> Result<Option<u64>, String> {
    values
        .get(name)
        .map(|value| {
            sail_kani_size(value).map_err(|error| format!("SAIL6343: {}: {error}", &name[2..]))
        })
        .transpose()
}

/// The result store's bound from `--no-store` and `--store-max`.
fn store_max(no_store: bool, value: Option<&str>) -> Result<Option<u64>, String> {
    match (no_store, value) {
        (true, Some(_)) => Err("SAIL6350: --store-max and --no-store cannot be combined".into()),
        (true, None) => Ok(None),
        (false, None) => Ok(Some(DEFAULT_STORE_MAX)),
        (false, Some(value)) => sail_kani_size(value)
            .map(Some)
            .map_err(|error| format!("SAIL6350: store-max: {error}")),
    }
}

#[cfg(unix)]
fn sail_kani_size(text: &str) -> Result<u64, String> {
    sail_kani::supervise::parse_size(text)
}

#[cfg(not(unix))]
fn sail_kani_size(_text: &str) -> Result<u64, String> {
    Err("memory limits need a Unix host".into())
}

pub(crate) fn requested(args: &[String]) -> bool {
    args.iter()
        .take_while(|arg| arg.as_str() != "--")
        .any(|arg| arg == "--backend" || arg.starts_with("--backend="))
}

pub(crate) fn verify(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> ExitCode {
    let result = parse(args).and_then(|options| execute(&options, out));
    match result {
        Ok(code) => ExitCode::from(code),
        Err(error) if error.starts_with("error[") => {
            let _ = writeln!(err, "{error}");
            ExitCode::from(2)
        }
        Err(error) => {
            let _ = writeln!(err, "error[SAIL6306]: experimental Kani check: {error}");
            ExitCode::from(2)
        }
    }
}

/// The report's tier for one harness, in the vocabulary of a Verus function
/// report's `evidence_tier`: `bounded` exactly when the bounded-evidence
/// record carries the tier (a supervised success or counterexample), `null`
/// for every no-claim and tierless result.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn evidence_tier(
    evidence: &sail_api::bounded::Evidence,
) -> Option<sail_api::output::EvidenceTierName> {
    evidence.tier.map(Into::into)
}

#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn outcome_name(outcome: sail_kani::Outcome) -> &'static str {
    match outcome {
        sail_kani::Outcome::BoundedSuccess => "bounded_success",
        sail_kani::Outcome::Counterexample => "counterexample",
        sail_kani::Outcome::BoundInsufficient => "bound_insufficient",
        sail_kani::Outcome::ExpectedPanicMissing => "expected_panic_missing",
        sail_kani::Outcome::Unsupported => "unsupported",
    }
}

/// The sealed tool stage, checked per call by metadata. A missing, stale or
/// contradicted manifest falls back to full authentication and a new seal.
/// Either way the stage is confirmed when this returns.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn stage(root: &std::path::Path) -> Result<(sail_kani::tools::Stage, PathBuf), String> {
    use sail_kani::tools::{Stage, Tools};
    let release = sail_kani::tools::RUNTIME_RELEASE;
    let suffix = sail_kani::host::SUFFIX;
    let runtime = root.join(format!("{release}-{suffix}"));
    let (bundle, rust) = (runtime.join("bundle"), runtime.join("rust"));
    let stage_path = root.join(format!("stage-{release}-{suffix}"));
    let manifest = root.join(format!("stage-{release}-{suffix}.manifest.json"));
    if let Ok(stage) = Stage::open(&stage_path, &bundle, &rust, &manifest) {
        return Ok((stage, manifest));
    }
    let tools = Tools::authenticate(&bundle, &rust)
        .map_err(|error| format!("{error}; run `sail engine install --backend kani`"))?;
    let stage = if std::fs::symlink_metadata(&stage_path).is_ok() {
        tools.inspect_stage(&stage_path)
    } else {
        tools.stage(&stage_path)
    }
    .map_err(|error| error.to_string())?;
    stage.seal(&manifest).map_err(|error| error.to_string())?;
    Ok((stage, manifest))
}

/// The run's cancellation flag: set on SIGINT, and at the end of stdin when
/// the `sail mcp` server that started the run asks for that (see
/// [`cancel_at_end_of`]).
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn cancellation() -> Result<std::sync::Arc<std::sync::atomic::AtomicBool>, String> {
    use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};
    let cancel = Arc::new(AtomicBool::new(false));
    let signal = Arc::clone(&cancel);
    ctrlc::set_handler(move || signal.store(true, Ordering::SeqCst))
        .map_err(|error| format!("cannot install cancellation handler: {error}"))?;
    if std::env::var_os(sail_mcp::KANI_STOP_ON_STDIN_EOF).is_some_and(|value| value == "1") {
        cancel_at_end_of(std::io::stdin(), Arc::clone(&cancel));
    }
    Ok(cancel)
}

/// Cancels, as SIGINT does, once `input` ends or fails. `sail mcp` sets
/// [`sail_mcp::KANI_STOP_ON_STDIN_EOF`] and holds the only write end of this
/// run's stdin, so a server that exits or is killed stops its Kani runs.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn cancel_at_end_of(
    mut input: impl std::io::Read + Send + 'static,
    cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        let _ = std::io::copy(&mut input, &mut std::io::sink());
        cancel.store(true, std::sync::atomic::Ordering::SeqCst);
    })
}

#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn execute(options: &Options, out: &mut dyn Write) -> Result<u8, String> {
    use sail_kani::execution::{Check, Jobs, Request, Target};
    use std::time::Duration;
    let project = options
        .project
        .canonicalize()
        .map_err(|error| format!("project: {error}"))?;
    let cargo_home = options
        .cargo_home
        .canonicalize()
        .map_err(|error| format!("Cargo home: {error}"))?;
    let root = crate::kani_setup::root()?;
    let cancel = cancellation()?;
    // Installed beside `sail`, as `sail-runtime-worker` is.
    let supervisor = std::env::current_exe()
        .map_err(|error| format!("cannot locate sail: {error}"))?
        .with_file_name(sail_kani::supervise::BINARY);
    if options.receipts && options.solver_policy == sail_kani::SolverPolicy::Original {
        // A receipt key binds the supervisor's digest; hash it beside the
        // stage check instead of after it.
        sail_kani::receipts::prefetch_file_sha256(&supervisor);
    }
    let targets = root.join("targets");
    {
        use std::os::unix::fs::DirBuilderExt as _;
        match std::fs::DirBuilder::new().mode(0o700).create(&targets) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(error) => return Err(format!("kept targets: {error}")),
        }
    }
    let limit = Duration::from_millis(options.timeout_ms);
    let target = Target::acquire(
        &targets,
        &project,
        &sail_kani::tools::identity(),
        limit,
        &cancel,
    )
    .map_err(|error| error.to_string())?;
    // Probe delegation beside the stage check; nothing staged runs before
    // the check passes.
    sail_kani::execution::prefetch_delegation(&target, &supervisor);
    let (stage, manifest) = stage(&root)?;
    let attempt = crate::kani_setup::private_attempt(&root)?;
    let (store, unavailable) = receipts(options, &root);
    let jobs = (!options.single()).then(|| {
        options
            .jobs
            .and_then(std::num::NonZeroU32::new)
            .map_or(Jobs::Default, Jobs::Count)
    });
    let store_root = root.join("cbmc-store");
    let request = Request {
        project: &project,
        cargo_home: &cargo_home,
        harnesses: &options.harnesses,
        unwind: options.unwind,
        jobs,
        arguments: &options.arguments,
        solver_policy: options.solver_policy,
        process_limit: limit,
        supervisor: sail_kani::execution::Supervisor {
            binary: &supervisor,
            budget: options.memory_max,
            harness_memory_max: options.harness_memory_max,
            store: options
                .store_max
                .map(|max_bytes| sail_kani::execution::StoreRequest {
                    root: &store_root,
                    max_bytes,
                }),
        },
        receipts: store.as_ref(),
    };
    let check = Check::Opened(&manifest);
    if options.single() {
        let capture = sail_kani::execution::run(
            &stage,
            check,
            &target,
            &request,
            &attempt.join("capture"),
            &cancel,
        )
        .map_err(|error| error.to_string())?;
        let mut capture = capture;
        if let Some(status) = unavailable {
            capture.receipt = status;
        }
        return single(options, &capture, out);
    }
    let batch = sail_kani::execution::run_batch(
        &stage,
        check,
        &target,
        &request,
        &attempt.join("capture"),
        &cancel,
    )
    .map_err(|error| error.to_string())?;
    let mut batch = batch;
    if let Some(status) = unavailable {
        batch.receipt = status;
    }
    report(options, &batch, target.directory(), out)
}

/// The receipt store (ADR 0189), unless receipts are off. A store problem
/// only turns them off, with the reason.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn receipts(
    options: &Options,
    root: &std::path::Path,
) -> (
    Option<sail_kani::receipts::Store>,
    Option<sail_kani::receipts::Status>,
) {
    if !options.receipts || options.solver_policy != sail_kani::SolverPolicy::Original {
        return (None, None);
    }
    match sail_kani::receipts::Store::open(root) {
        Ok(store) => (Some(store.with_ci_environment()), None),
        Err(error) => (
            None,
            Some(sail_kani::receipts::Status::NotStored {
                code: "SAIL6360".into(),
                reason: error.to_string(),
                replay_refused: None,
            }),
        ),
    }
}

/// A line saying memory was not supervised, when it was not.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn memory_note(cgroup: Option<&sail_kani::supervise::Cgroup>) -> String {
    match cgroup {
        Some(
            sail_kani::supervise::Cgroup::Delegated { .. }
            | sail_kani::supervise::Cgroup::Sampled { .. },
        ) => String::new(),
        Some(sail_kani::supervise::Cgroup::Unavailable { reason }) => format!(
            "warning[SAIL6342]: memory supervision unavailable ({reason}); exit, signal, output and deadline were supervised\n"
        ),
        None => "warning[SAIL6342]: memory supervision state not recorded\n".into(),
    }
}

/// The JSON result document of a batch.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn batch_document(
    options: &Options,
    batch: &sail_kani::execution::Batch,
    target: &std::path::Path,
    counts: &std::collections::BTreeMap<&str, usize>,
    harnesses: &[serde_json::Value],
) -> serde_json::Value {
    let selection = if options.harnesses.is_empty() {
        serde_json::json!("all")
    } else {
        serde_json::json!(options.harnesses)
    };
    serde_json::json!({
        "kind": "sail-kani-bounded-batch", "version": 1, "backend": "kani",
        "experimental": true, "selection": selection, "unwind": options.unwind,
        "arguments": options.arguments,
        "jobs": options.jobs.map_or_else(|| serde_json::json!("default"), |jobs| serde_json::json!(jobs)),
        "counts": counts, "harnesses": harnesses,
        "capture": batch.directory, "target": target,
        "memory_supervision": batch.cgroup, "scope_leftovers": batch.scope_leftovers,
        "discovered_from": batch.discovered.files,
        "result_store": batch.store,
        "input_closure_authenticated": batch.receipt.hit(), "proof_authority": false,
        "currentness_authority": false,
        "cache_reused": batch.receipt.hit() || batch.store.replayed > 0,
        "receipt": batch.receipt,
    })
}

/// A line saying what the result store did, when the run used it.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn store_note(store: &sail_kani::execution::StoreSummary, receipt_hit: bool) -> String {
    if store.used {
        let label = if receipt_hit {
            "Original result store"
        } else {
            "Result store"
        };
        format!(
            "{label}: {} cbmc runs replayed, {} stored.\n",
            store.replayed, store.stored
        )
    } else {
        String::new()
    }
}

#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn harness_document(
    options: &Options,
    checked: &sail_kani::execution::Checked,
    receipt_hit: bool,
) -> Result<(&'static str, serde_json::Value), String> {
    let harness = &checked.decoded;
    let evidence = checked
        .bounded_evidence()
        .map_err(|error| error.to_string())?;
    let outcome = checked
        .admitted()
        .map(|observation| outcome_name(observation.outcome()));
    let health = health::harness(
        &evidence,
        &checked.supervision,
        checked.admitted(),
        harness.duration_ms,
        harness.native_exit_status.as_deref(),
        receipt_hit,
        &options.arguments,
    );
    let document = serde_json::json!({
        "harness": harness.name,
        "crate": harness.crate_name,
        "backend": "kani",
        "evidence_tier": evidence_tier(&evidence),
        "outcome": outcome,
        "native_status": harness.native_status,
        "native_exit_status": harness.native_exit_status,
        "duration_ms": harness.duration_ms,
        "attributes": checked.attributes,
        "solver": checked.admitted().and_then(|observation| {
            checked
                .attributes
                .as_ref()
                .map(|attributes| solver(&options.arguments, attributes, observation.mode(), checked.supervision.solver_choice()))
        }),
        "observation": checked.admitted(),
        "refusal": checked.refusal(),
        "supervision": checked.supervision,
        "health": health,
        "evidence": evidence,
    });
    Ok((outcome.unwrap_or("refused"), document))
}

/// Print a batch and choose its exit: 0 when every harness is a bounded
/// success, 2 when any harness has no admitted observation, otherwise 1.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn report(
    options: &Options,
    batch: &sail_kani::execution::Batch,
    target: &std::path::Path,
    out: &mut dyn Write,
) -> Result<u8, String> {
    let mut counts = std::collections::BTreeMap::from([
        ("bounded_success", 0_usize),
        ("counterexample", 0),
        ("bound_insufficient", 0),
        ("expected_panic_missing", 0),
        ("unsupported", 0),
        ("refused", 0),
    ]);
    let mut harnesses = Vec::new();
    for checked in &batch.harnesses {
        let (outcome, document) = harness_document(options, checked, batch.receipt.hit())?;
        *counts.entry(outcome).or_insert(0) += 1;
        harnesses.push(document);
    }
    let code = if counts["refused"] > 0 {
        2
    } else {
        u8::from(counts["bounded_success"] != batch.harnesses.len())
    };
    if options.json {
        let mut result = batch_document(options, batch, target, &counts, &harnesses);
        label_solver_policy(&mut result, options.solver_policy);
        serde_json::to_writer(&mut *out, &result).map_err(|error| error.to_string())?;
        writeln!(out).map_err(|error| error.to_string())?;
    } else {
        // A name two selected crates share is shown with its crate.
        let mut named = std::collections::BTreeMap::new();
        for checked in &batch.harnesses {
            *named
                .entry(checked.decoded.name.as_str())
                .or_insert(0_usize) += 1;
        }
        for checked in &batch.harnesses {
            let harness = &checked.decoded;
            let label = if named[harness.name.as_str()] > 1 {
                harness.id().to_string()
            } else {
                harness.name.clone()
            };
            match (checked.admitted(), checked.refusal()) {
                (Some(observation), _) => writeln!(
                    out,
                    "experimental kani: {} for {label}",
                    outcome_name(observation.outcome()),
                ),
                (None, refusal) => writeln!(
                    out,
                    "experimental kani: no admitted result for {label} (native {}): {}",
                    harness.native_status,
                    refusal.unwrap_or_default()
                ),
            }
            .map_err(|error| error.to_string())?;
            if let Some(choice) = checked.supervision.solver_choice() {
                writeln!(out, "  SAT solver {} (remembered-best)", choice.name)
                    .map_err(|error| error.to_string())?;
            }
        }
        write!(
            out,
            "{}{}",
            memory_note(batch.cgroup.as_ref()),
            store_note(&batch.store, batch.receipt.hit())
        )
        .map_err(|error| error.to_string())?;
        writeln!(
            out,
            "{} harnesses: {} bounded_success, {} counterexample, {} bound_insufficient, {} expected_panic_missing, {} unsupported, {} without an admitted result\nOriginal captures: {}\n{}",
            batch.harnesses.len(),
            counts["bounded_success"],
            counts["counterexample"],
            counts["bound_insufficient"],
            counts["expected_panic_missing"],
            counts["unsupported"],
            counts["refused"],
            batch.directory.display(),
            authority(&batch.receipt)
        )
        .map_err(|error| error.to_string())?;
    }
    Ok(code)
}

#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn single(
    options: &Options,
    capture: &sail_kani::execution::Captured,
    out: &mut dyn Write,
) -> Result<u8, String> {
    let success = capture.observation.outcome() == sail_kani::Outcome::BoundedSuccess;
    let evidence = capture
        .bounded_evidence()
        .map_err(|error| error.to_string())?;
    if options.json {
        let health = health::harness(
            &evidence,
            &capture.supervision,
            Some(&capture.observation),
            None,
            None,
            capture.receipt.hit(),
            &options.arguments,
        );
        let mut result = serde_json::json!({
            "kind": "sail-kani-bounded-result", "version": 1, "backend": "kani",
            "experimental": true, "harness": options.harnesses[0],
            "crate": capture.observation.crate_name(), "unwind": options.unwind,
            "arguments": options.arguments,
            "observation": capture.observation, "attributes": capture.attributes,
            "solver": solver(&options.arguments, &capture.attributes, capture.observation.mode(), capture.supervision.solver_choice()),
            "evidence_tier": evidence_tier(&evidence),
            "evidence": evidence, "capture": capture.directory, "health": health,
            "supervision": capture.supervision, "memory_supervision": capture.cgroup,
            "result_store": capture.store,
            "input_closure_authenticated": capture.receipt.hit(), "proof_authority": false,
            "currentness_authority": false,
            "cache_reused": capture.receipt.hit() || capture.store.replayed > 0,
            "receipt": capture.receipt,
        });
        label_solver_policy(&mut result, options.solver_policy);
        serde_json::to_writer(&mut *out, &result).map_err(|error| error.to_string())?;
        writeln!(out).map_err(|error| error.to_string())?;
    } else {
        let unwind = options.unwind.map_or_else(
            || "bounds as declared".to_owned(),
            |unwind| format!("unwind {unwind}"),
        );
        if let Some(choice) = capture.supervision.solver_choice() {
            writeln!(out, "SAT solver {} (remembered-best)", choice.name)
                .map_err(|error| error.to_string())?;
        }
        writeln!(
            out,
            "experimental kani: {} for {} ({unwind})\n{}{}Original captures: {}\n{}",
            outcome_name(capture.observation.outcome()),
            options.harnesses[0],
            memory_note(capture.cgroup.as_ref()),
            store_note(&capture.store, capture.receipt.hit()),
            capture.directory.display(),
            authority(&capture.receipt)
        )
        .map_err(|error| error.to_string())?;
    }
    Ok(u8::from(!success))
}

#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn label_solver_policy(result: &mut serde_json::Value, policy: sail_kani::SolverPolicy) {
    if policy == sail_kani::SolverPolicy::RememberedBest {
        result["solver_policy"] = serde_json::json!("remembered-best");
    }
}

/// The last line of a text report: what the results may be used for.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn authority(receipt: &sail_kani::receipts::Status) -> std::borrow::Cow<'static, str> {
    if let Some(signer) = receipt.signer() {
        format!("Replayed from a signed CI receipt for the exact request and source closure (signer {signer}).").into()
    } else if receipt.hit() {
        "Replayed from a local kani-v1 receipt: nothing in the input closure changed since the run that produced these results.".into()
    } else {
        "No reusable proof or source-currentness authority.".into()
    }
}

/// The solver CBMC ran and what chose it, by Kani's precedence: `--solver`
/// over `#[kani::solver]` over the default, `CaDiCaL`. Kissat is the bundle's
/// external `bin/kissat`; `CaDiCaL` and `MiniSat` are built into CBMC.
#[cfg(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
))]
fn solver(
    arguments: &[sail_kani::arguments::Argument],
    attributes: &sail_kani::Attributes,
    mode: &sail_kani::Mode,
    choice: Option<&sail_kani::supervise::SolverChoice>,
) -> serde_json::Value {
    let argued = arguments
        .iter()
        .any(|argument| matches!(argument, sail_kani::arguments::Argument::Solver(_)));
    let source = if choice.is_some() {
        "remembered_best"
    } else if argued {
        "argument"
    } else if attributes.solver.is_some() {
        "annotation"
    } else {
        "tool_default"
    };
    let binary = (mode.solver == "kissat").then_some("bin/kissat");
    let mut solver = serde_json::json!({
        "name": mode.solver, "version": mode.solver_version, "source": source,
        "binary": binary,
        "binary_sha256": binary.and_then(sail_kani::tools::bundle_file_sha256),
    });
    if let Some(choice) = choice {
        solver["selection"] = serde_json::json!(choice);
    }
    solver
}

#[cfg(not(any(
    all(target_os = "linux", target_arch = "x86_64"),
    all(target_os = "macos", target_arch = "aarch64")
)))]
fn execute(_options: &Options, _out: &mut dyn Write) -> Result<u8, String> {
    Err("the pinned experimental Kani backend supports native Linux x86-64 and macOS arm64".into())
}

#[cfg(test)]
mod tests {
    use super::{parse, requested};
    fn args(text: &str) -> Vec<String> {
        text.split_whitespace().map(str::to_owned).collect()
    }

    /// The MCP lifeline: the run is cancelled only once its stdin ends.
    #[cfg(any(
        all(target_os = "linux", target_arch = "x86_64"),
        all(target_os = "macos", target_arch = "aarch64")
    ))]
    #[test]
    fn end_of_stdin_cancels_the_run() -> std::io::Result<()> {
        use std::io::Write as _;
        use std::sync::{Arc, atomic::AtomicBool, atomic::Ordering};
        let (reader, mut writer) = std::io::pipe()?;
        let cancel = Arc::new(AtomicBool::new(false));
        let watcher = super::cancel_at_end_of(reader, Arc::clone(&cancel));
        writer.write_all(b"ignored")?;
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert!(
            !cancel.load(Ordering::SeqCst),
            "cancelled while stdin was open"
        );
        drop(writer);
        assert!(watcher.join().is_ok());
        assert!(
            cancel.load(Ordering::SeqCst),
            "not cancelled at end of stdin"
        );
        Ok(())
    }
    #[test]
    fn bounds_identity_and_mode_boundaries_are_explicit() {
        let valid = "--backend kani --harness pilot::proof --unwind 6 --cargo-home prepared";
        let result = parse(&args(valid));
        assert!(result.is_ok(), "{result:?}");
        assert!(result.is_ok_and(|options| options.single()));
        for suffix in [
            " --unwind 8",
            " --harness pilot::proof",
            " --output xml",
            " --background",
            " -- --engine interactive",
            " --timeout-ms 0",
            " --timeout-ms 86400001",
            " --jobs 0",
            " --jobs x",
            " --memory-max 0",
            " --memory-max 3X",
            " --harness-memory-max -1",
        ] {
            assert!(
                parse(&args(&format!("{valid}{suffix}"))).is_err(),
                "{suffix}"
            );
        }
        for text in [
            "--backend other --harness pilot::proof --unwind 6",
            "--backend kani --harness pilot::proof --unwind 0",
            "--backend kani --harness -x",
        ] {
            assert!(parse(&args(text)).is_err(), "{text}");
        }
        assert!(
            parse(&args(
                "--backend kani --harness proof --unwind 6 --cargo-home prepared"
            ))
            .is_ok()
        );
        assert!(requested(&args(valid)));
        assert!(!requested(&args("-- --backend kani")));
        assert!(requested(&args("--backend=kani")));
    }

    #[test]
    fn batch_selection_jobs_and_optional_unwind() -> Result<(), String> {
        let all = parse(&args("--backend kani --cargo-home prepared"))?;
        assert!(all.harnesses.is_empty() && !all.single());
        assert_eq!(
            (all.unwind, all.jobs, all.timeout_ms),
            (None, None, 600_000)
        );
        let several = parse(&args(
            "--backend kani --harness a::p --harness b::q --jobs 8 --cargo-home prepared",
        ))?;
        assert_eq!(several.harnesses, ["a::p", "b::q"]);
        assert_eq!(several.jobs, Some(8));
        assert!(!several.single());
        let one_parallel = parse(&args(
            "--backend kani --harness a::p --jobs 2 --cargo-home prepared",
        ))?;
        assert!(!one_parallel.single());
        let unbounded = parse(&args("--backend kani --harness a::p --cargo-home prepared"))?;
        assert!(unbounded.single() && unbounded.unwind.is_none());
        assert!(parse(&args("--backend kani --timeout-ms 86400000 --cargo-home p")).is_ok());
        let capped = parse(&args(
            "--backend kani --memory-max 32G --harness-memory-max 1536M --cargo-home p",
        ))?;
        assert_eq!(
            (capped.memory_max, capped.harness_memory_max),
            (Some(32 << 30), Some(1536 << 20))
        );
        Ok(())
    }

    #[test]
    fn the_result_store_is_on_by_default_and_can_be_bounded_or_turned_off() -> Result<(), String> {
        let default = parse(&args("--backend kani --cargo-home p"))?;
        assert_eq!(default.store_max, Some(super::DEFAULT_STORE_MAX));
        let bounded = parse(&args("--backend kani --cargo-home p --store-max 512M"))?;
        assert_eq!(bounded.store_max, Some(512 << 20));
        let off = parse(&args("--backend kani --no-store --cargo-home p"))?;
        assert_eq!(off.store_max, None);
        for text in [
            "--backend kani --cargo-home p --no-store --store-max 1G",
            "--backend kani --cargo-home p --no-store --no-store",
            "--backend kani --cargo-home p --store-max 0",
            "--backend kani --cargo-home p --store-max x",
        ] {
            assert!(parse(&args(text)).is_err(), "{text}");
        }
        Ok(())
    }

    #[test]
    fn the_two_reuse_controls_compose_independently() -> Result<(), String> {
        let store_only = parse(&args(
            "--backend kani --cargo-home p --no-receipts --store-max 64M",
        ))?;
        assert!(!store_only.receipts);
        assert_eq!(store_only.store_max, Some(64 << 20));
        let both_off = parse(&args(
            "--backend kani --cargo-home p --no-store --no-receipts",
        ))?;
        assert!(!both_off.receipts);
        assert_eq!(both_off.store_max, None);
        Ok(())
    }

    #[test]
    fn remembered_best_is_explicit_and_can_record_an_explicit_solver() -> Result<(), String> {
        let original = parse(&args("--backend kani --cargo-home p"))?;
        assert_eq!(original.solver_policy, sail_kani::SolverPolicy::Original);
        let training = parse(&args(
            "--backend kani --cargo-home p --solver-policy remembered-best --solver minisat",
        ))?;
        assert_eq!(
            training.solver_policy,
            sail_kani::SolverPolicy::RememberedBest
        );
        assert_eq!(
            training.arguments,
            [sail_kani::arguments::Argument::Solver("minisat".into())]
        );
        assert!(parse(&args("--backend kani --cargo-home p --solver-policy race")).is_err());
        Ok(())
    }

    #[test]
    fn cargo_selection_and_kani_options_pass_through_in_order() -> Result<(), String> {
        let options = parse(&args(
            "--backend kani --cargo-home p -Z stubbing --all-features -p vmm --features a,b \
             --workspace --solver kissat --harness-timeout 40m -Z function-contracts \
             --no-default-features --package utils",
        ))?;
        let rendered: Vec<String> = options
            .arguments
            .iter()
            .flat_map(sail_kani::arguments::Argument::render)
            .collect();
        assert_eq!(
            rendered,
            [
                "-Z",
                "stubbing",
                "--all-features",
                "--package",
                "vmm",
                "--features",
                "a,b",
                "--workspace",
                "--solver",
                "kissat",
                "--harness-timeout",
                "40m",
                "-Z",
                "function-contracts",
                "--no-default-features",
                "--package",
                "utils"
            ]
        );
        for text in [
            "-Z autoharness",
            "-Z",
            "--solver z3",
            "--solver kissat --solver cadical",
            "--workspace --workspace",
            "--all-features --all-features",
            "--harness-timeout 1s --harness-timeout 2s",
            "--cbmc-args --unwind",
            "--output-format old",
        ] {
            let parsed = parse(&args(&format!("--backend kani --cargo-home p {text}")));
            assert!(parsed.is_err(), "{text}");
        }
        let refused = parse(&args("--backend kani --cargo-home p -Z autoharness"));
        assert!(refused.is_err_and(|error| error.starts_with("error[SAIL6330]")));
        Ok(())
    }
}