Skip to main content

dive_runtime/
lib.rs

1//! `dive-runtime`: the run contract every checking engine shares.
2//!
3//! The execution core and temporal analysis (`dive-liveness`) agree on these
4//! pieces, so neither needs the other's search runtime:
5//!
6//! - [`CheckOptions`] and the [`CheckResult`] it produces, with its
7//!   [`Verdict`], statistics, counterexample and storage evidence;
8//! - TLC's error classes ([`classify`]) and human rendering;
9//! - time and memory budgets and evaluation control ([`budget`]);
10//! - behavior-graph capture types, evidence and admission ([`capture`]);
11//! - native checkpoint framing, requests and Core's archive identity
12//!   ([`checkpoint`]);
13//! - the run host's configuration and counters ([`run`]) and pure model
14//!   admission analysis ([`admission`]).
15//!
16//! The searches themselves belong to the execution core.
17//!
18//! # Example
19//!
20//! ```
21//! use dive_runtime::{CheckOptions, Verdict};
22//! let opts = CheckOptions::tlc(0, 7);
23//! assert_eq!(opts.seed, 7);
24//! assert!(Verdict::Success.is_verdict());
25//! ```
26#![forbid(unsafe_code)]
27
28pub mod admission;
29pub mod budget;
30pub mod capture;
31pub mod checkpoint;
32#[doc(hidden)]
33pub mod class;
34pub mod classify;
35#[doc(hidden)]
36pub mod diagnostic;
37mod options;
38mod render;
39mod result;
40pub mod run;
41pub mod usage;
42
43use dive_ir::Ir;
44use dive_model::{BindError, ErrorKind, Message};
45
46pub use options::CheckOptions;
47pub use render::{format_trace_state, render_human};
48pub use result::{
49    CheckResult, Collision, Counterexample, DiagnosticWitness, ErrorSite, PartialState,
50    PredecessorUsage, Stats, TlcClass, TraceState, Verdict, Workers, tlc_exit_status,
51};
52pub use usage::{FrontierUsage, SeenFailure, SeenOptions, SeenPhase, SeenReplay, SeenUsage};
53
54impl From<&BindError> for Verdict {
55    fn from(e: &BindError) -> Self {
56        match &e.kind {
57            ErrorKind::Tlc(ec) => Verdict::ModelError {
58                code: ec.code(),
59                name: ec.name().to_owned(),
60                message: e.message.clone(),
61            },
62            ErrorKind::Eval { code } => Verdict::ModelError {
63                code: *code,
64                name: eval_code_name(*code).to_owned(),
65                message: e.message.clone(),
66            },
67            ErrorKind::Unsupported { feature } => Verdict::Unsupported {
68                feature: feature.clone(),
69            },
70            ErrorKind::Bug => Verdict::InternalError {
71                message: e.message.clone(),
72            },
73        }
74    }
75}
76
77/// The `EC` name of an evaluation error code `dive-eval` raises.
78#[doc(hidden)]
79#[must_use]
80pub fn eval_code_name(code: u32) -> &'static str {
81    match code {
82        2215 => "TLC_EXPECTED_VALUE",
83        2184 => "TLC_MODULE_APPLY_EMPTY_SEQ",
84        2283 => "TLC_MODULE_ONE_ARGUMENT_ERROR",
85        2169 => "TLC_MODULE_ARGUMENT_ERROR",
86        2266 => "TLC_MODULE_ARGUMENT_ERROR_AN",
87        2182 => "TLC_MODULE_EVALUATING",
88        2183 => "TLC_MODULE_ARGUMENT_NOT_IN_DOMAIN",
89        2181 => "TLC_MODULE_COMPUTING_CARDINALITY",
90        2132 => "TLC_VALUE_ASSERT_FAILED",
91        2280 => "TLC_CONFIG_UNDEFINED_OR_NO_OPERATOR",
92        2261 => "TLC_ENCOUNTERED_FORMULA_IN_PREDICATE",
93        2179 => "TLC_MODULE_DIVISION_BY_ZERO",
94        2178 => "TLC_MODULE_OVERFLOW",
95        2180 => "TLC_MODULE_NULL_POWER_NULL",
96        2265 => "TLC_INTEGER_TOO_BIG",
97        2158 => "TLC_MODULE_CHECK_MEMBER_OF",
98        2155 => "TLC_MODULE_COMPARE_VALUE",
99        2154 => "TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE",
100        2244 => "TLC_CANT_HANDLE_REAL_NUMBERS",
101        2170 => "TLC_ARGUMENT_MISMATCH",
102        2176 => "TLC_MODULE_APPLYING_TO_WRONG_VALUE",
103        2247 => "TLC_EXPECTED_EXPRESSION_IN_COMPUTING",
104        2248 => "TLC_EXPECTED_EXPRESSION_IN_COMPUTING2",
105        _ => "GENERAL",
106    }
107}
108
109/// A result with `verdict` and no search: the run's metadata only.
110#[doc(hidden)]
111#[must_use]
112pub fn bare(verdict: Verdict, opts: &CheckOptions, ir: &Ir) -> CheckResult {
113    // Refusal/panic reporting also receives untrusted public arenas. Preserve
114    // valid concrete metadata, but never index an invalid declaration/order or
115    // create a partial variable mapping that could be mistaken for a valid one.
116    let names: Option<Vec<_>> = ir
117        .vars()
118        .iter()
119        .enumerate()
120        .map(|(i, d)| {
121            ir.decls()
122                .get(d.index())
123                .filter(|decl| decl.var.is_some_and(|v| v.index() == i))
124                .map(|decl| decl.name.clone())
125        })
126        .collect();
127    let order: Vec<_> = ir.tlc_var_order().iter().map(|v| v.index()).collect();
128    let valid_order = order.len() == ir.vars().len()
129        && order.iter().all(|&i| i < ir.vars().len())
130        && order
131            .iter()
132            .copied()
133            .collect::<std::collections::BTreeSet<_>>()
134            .len()
135            == order.len();
136    let (var_names, tlc_var_order) = match names {
137        Some(names) if valid_order => (names, order),
138        _ => (Vec::new(), Vec::new()),
139    };
140    CheckResult {
141        symmetry_liveness: None,
142        frontier: crate::FrontierUsage {
143            memory_bytes_per_queue: opts.frontier_memory_bytes,
144            max_record_bytes: opts
145                .frontier_memory_bytes
146                .map(|_| dive_store::spill::MAX_RECORD_BYTES),
147            ..crate::FrontierUsage::default()
148        },
149        seen: None,
150        predecessor: crate::PredecessorUsage::default(),
151        verdict,
152        binding_model_error: false,
153        stats: None,
154        tlc_prints_stats: false,
155        counterexample: None,
156        diagnostic_witness: None,
157        collision: None,
158        store: opts.store,
159        fp_index: (opts.store == dive_store::StoreMode::Fingerprint).then_some(opts.fp_index),
160        tlc_fingerprints: opts.tlc_fingerprints,
161        var_names,
162        tlc_var_order,
163        output: Vec::new(),
164        warnings: Vec::new(),
165        notes: Vec::new(),
166        // No search has run yet.
167        workers: Workers {
168            requested: opts.workers.max(1),
169            used: 0,
170            sequential: false,
171            reason: None,
172        },
173        elapsed: std::time::Duration::ZERO,
174    }
175}
176
177/// Appends binding output and warnings to `r`.
178#[doc(hidden)]
179pub fn messages(out: &[Message], r: &mut CheckResult) {
180    for m in out {
181        match m {
182            Message::Print(line) => r.output.push(line.clone()),
183            Message::Warning { code, message } => r.warnings.push((code.code(), message.clone())),
184        }
185    }
186}
187
188/// Shared default-profile qualification for an observed safety stop.
189#[doc(hidden)]
190pub fn note_canonical_stop(opts: &CheckOptions, verdict: &Verdict, notes: &mut Vec<String>) {
191    if opts.profile == dive_eval::Profile::Dive
192        && verdict.is_verdict()
193        && *verdict != Verdict::Success
194    {
195        // Canonical exploration can stop at a different event than
196        // TLC's order. Detecting whether it did is not implemented yet, so
197        // every stop says so.
198        notes.push(
199            "The default profile explores sets in canonical order. When several violations are reachable at the same depth, which one is reported, and the counts at the stop, may differ under --compat=tlc; dive does not yet detect whether the order mattered in this run.".to_owned(),
200        );
201    }
202}
203
204#[cfg(test)]
205#[allow(
206    clippy::expect_used,
207    reason = "malformed public metadata regression controls"
208)]
209mod metadata_controls {
210    use super::*;
211
212    #[test]
213    fn panic_and_early_refusal_metadata_do_not_index_invalid_public_ids() {
214        let a = dive_sema::analyze_source(
215            "M.tla",
216            "---- MODULE M ----\nVARIABLE x\nInit == x = TRUE\n====\n",
217            &dive_sema::Options::default(),
218        );
219        let ir = dive_ir::lower(&a).expect("IR");
220        for field in ["vars", "tlc_vars"] {
221            let mut json = serde_json::to_value(&ir).expect("serialize");
222            json[field] = serde_json::json!([u32::MAX]);
223            let bad: Ir = serde_json::from_value(json).expect("deserialize");
224            for verdict in [
225                Verdict::InternalError {
226                    message: "original panic".into(),
227                },
228                Verdict::Unsupported {
229                    feature: "original option refusal".into(),
230                },
231            ] {
232                let result = bare(verdict.clone(), &CheckOptions::tlc(0, 7), &bad);
233                assert_eq!(result.verdict, verdict);
234                assert!(result.var_names.is_empty() && result.tlc_var_order.is_empty());
235                assert_eq!(result.workers.used, 0);
236                assert!(result.stats.is_none() && result.output.is_empty());
237            }
238        }
239    }
240}