dive_sim/lib.rs
1//! The seeded finite safety simulation contract: its options,
2//! report, static admission and the run host that owns one simulation.
3//!
4//! Core's finite simulation is the backend (`dive-api`), run through
5//! [`Runtime::simulate_with_backend`]. A finished sample is explicitly not a
6//! model-checking proof. Temporal checking, unsupported runtime effects, and
7//! unsupported options refuse by name. The independent trace validator remains
8//! outside this crate.
9#![forbid(unsafe_code)]
10
11mod statistics;
12
13pub use statistics::{ActionFlow, ActionGroup};
14
15use dive_eval::next::StateVals;
16mod host;
17use dive_model::Model;
18use dive_stdlib::random::RandomMode;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicBool, Ordering};
21
22/// A finite simulation request. No unbounded trace count is accepted.
23#[derive(Clone, Debug)]
24pub struct Options {
25 /// Run seed, always recorded by callers.
26 pub seed: i64,
27 /// TLC's `-aril`: skip this many doubles before deriving the worker seed.
28 /// Currently only supported in TLC mode; zero is required in dive mode.
29 pub aril: u64,
30 /// Maximum number of transitions in each trace (TLC's `-depth`).
31 pub depth: usize,
32 /// Number of traces to sample, stopping on the first error.
33 pub traces: u64,
34 /// TLC's worker stream or dive's stable trace identities.
35 pub mode: RandomMode,
36 /// Maximum initial states or candidates retained for one action.
37 pub max_candidates: usize,
38 /// Maximum states retained across all trace documents.
39 pub max_retained: usize,
40 /// Maximum generated states, including discarded candidates.
41 pub max_generated: u64,
42 /// Collect chosen action flows, combining source locations as TLC `stats=basic`.
43 pub action_stats: bool,
44 /// Construct one admitted successor with randomized Next choices instead
45 /// of retaining every successor of a selected action. Sampling is never proof.
46 /// `true` is TLC `-generate num=N`; the default `false` is `-simulate num=N`.
47 pub generation: bool,
48 /// Maximum retained runtime Print/PrintT events (startup output is separate).
49 pub max_output_events: usize,
50 /// Maximum UTF-8 bytes retained in runtime Print/PrintT text. This does not
51 /// bound temporary rendering allocations or total process memory.
52 pub max_output_bytes: usize,
53}
54
55impl Options {
56 /// Bounds with a finite, explicit number of traces and transitions.
57 #[must_use]
58 pub const fn new(seed: i64, mode: RandomMode, depth: usize, traces: u64) -> Self {
59 Self {
60 seed,
61 aril: 0,
62 depth,
63 traces,
64 mode,
65 max_candidates: 1_000_000,
66 max_retained: 1_000_000,
67 max_generated: 10_000_000,
68 action_stats: false,
69 generation: false,
70 max_output_events: 100_000,
71 max_output_bytes: 16 * 1024 * 1024,
72 }
73 }
74}
75
76/// An independently checkable trace of concrete states.
77#[derive(Clone, Debug)]
78pub struct Trace {
79 /// Stable identity, starting at zero.
80 pub id: u64,
81 /// Initial state and chosen transitions; the final state is included.
82 pub states: Vec<StateVals>,
83}
84
85/// The result of a simulation; a sample never proves absence of violations.
86#[derive(Clone, Debug)]
87pub enum Outcome {
88 /// Requested sampling completed without finding an error.
89 Sampled,
90 /// An invariant, action property or deadlock was found.
91 Violation {
92 /// `invariant`, `property`, or `deadlock`.
93 kind: &'static str,
94 /// Configured property name, if any.
95 name: Option<String>,
96 /// TLC's deciding message code.
97 code: u32,
98 /// Index into the report's traces.
99 trace: usize,
100 },
101 /// An assumption or evaluated predicate failed, with a measured class.
102 Error {
103 /// TLC's deciding message code.
104 code: u32,
105 /// Diagnostic detail.
106 message: String,
107 },
108 /// An unimplemented behavior; no simulation conclusion.
109 Unsupported(String),
110 /// A configured resource bound was reached; no conclusion.
111 Limit(String),
112 /// The caller's cancellation checkpoint stopped execution; no conclusion.
113 /// The caller must separately establish its actual resource/stop reason.
114 Cancelled,
115 /// An internal error; no conclusion.
116 Internal(String),
117}
118
119/// A deciding violation observed without retaining its full bounded trace.
120/// This is evidence for diagnosis, not independently certified violation data.
121#[derive(Clone, Debug)]
122pub struct PendingViolation {
123 /// Invariant or action property kind.
124 pub kind: &'static str,
125 /// Configured property name.
126 pub name: Option<String>,
127 /// TLC's deciding message code.
128 pub code: u32,
129}
130
131/// A finite simulation result and complete sampled trace documents.
132#[derive(Clone, Debug)]
133pub struct Report {
134 /// Last reached phase; preflight refusals perform no model evaluation.
135 pub stage: &'static str,
136 /// Result, explicitly distinguishing samples from proofs.
137 pub outcome: Outcome,
138 /// Generated initial states plus all complete successor candidates checked.
139 pub generated: u64,
140 /// Initial candidates collected, including a prefix when enumeration fails.
141 pub initial_candidates: u64,
142 /// Observed violation whose complete trace could not be retained.
143 pub pending_violation: Option<PendingViolation>,
144 /// Traces started, including a trace that ends with a violation.
145 pub traces_started: u64,
146 /// Concrete trace data, retained subject to the request's bound.
147 pub traces: Vec<Trace>,
148 /// Optional chosen-action counts; absent when disabled or preflight refused.
149 pub action_flow: Option<ActionFlow>,
150 /// Actual backend output, separate from binding and independent replay.
151 /// Warning events preserve their existing distinction from Print events.
152 pub runtime_output: Vec<dive_eval::capture::Captured>,
153}
154
155/// Owns one simulation's host from source binding through execution.
156///
157/// Install [`Self::host`] in `dive_model::BindOptions` before binding, then
158/// execute with this same runtime. Startup and reached random operations share
159/// one stream; the simulator never restarts a caller's partially consumed RNG.
160/// A runtime admits one execution, including failed/cancelled executions.
161/// Run execution on a thread with [`dive_eval::RECOMMENDED_STACK`].
162///
163/// ```
164/// use dive_sim::{Options, Runtime};
165/// use dive_stdlib::random::RandomMode;
166/// let runtime = Runtime::new(Options::new(7, RandomMode::Dive, 100, 10));
167/// let binding = dive_model::BindOptions { host: Some(runtime.host()), ..Default::default() };
168/// assert!(binding.host.is_some());
169/// // Bind the source with `binding`, then run a backend with
170/// // `runtime.simulate_with_backend`.
171/// ```
172#[derive(Debug)]
173pub struct Runtime {
174 options: Options,
175 host: Arc<host::SimulationHost>,
176 used: AtomicBool,
177}
178
179impl Runtime {
180 /// Creates the run context before source binding or startup evaluation.
181 #[must_use]
182 pub fn new(options: Options) -> Self {
183 let host = host::SimulationHost::new(&options);
184 host.binding(true);
185 Self {
186 host,
187 options,
188 used: AtomicBool::new(false),
189 }
190 }
191
192 /// The owned host to install in the source binder.
193 #[must_use]
194 pub fn host(&self) -> Arc<dyn dive_eval::Host> {
195 self.host.clone()
196 }
197
198 /// Supplies the actual bound configuration after startup binding finishes.
199 /// Configuration remains unavailable during binding, as in ordinary TLC.
200 pub fn set_config(&self, config: Option<dive_eval::RunConfig>) {
201 self.host.set_config(config);
202 }
203
204 /// Runs an alternate finite backend under this same binding/runtime host.
205 /// The callback receives the remaining retained-output allowance.
206 #[must_use]
207 pub fn simulate_with_backend(
208 &self,
209 model: &Model,
210 driver: impl FnOnce(&dyn Fn() -> (usize, usize)) -> Report,
211 ) -> Report {
212 self.run(model, |host| driver(&|| host.remaining_output()))
213 }
214
215 fn run(&self, model: &Model, driver: impl FnOnce(&host::SimulationHost) -> Report) -> Report {
216 if self.used.swap(true, Ordering::AcqRel) {
217 return refused_runtime("simulation runtime was already used");
218 }
219 self.host.binding(false);
220 with_host(model, &self.options, &self.host, driver)
221 }
222}
223
224fn refused_runtime(reason: &str) -> Report {
225 Report {
226 stage: "preflight",
227 outcome: Outcome::Unsupported(reason.to_owned()),
228 generated: 0,
229 initial_candidates: 0,
230 pending_violation: None,
231 traces_started: 0,
232 traces: Vec::new(),
233 action_flow: None,
234 runtime_output: Vec::new(),
235 }
236}
237
238fn with_host(
239 model: &Model,
240 opts: &Options,
241 host: &Arc<host::SimulationHost>,
242 driver: impl FnOnce(&host::SimulationHost) -> Report,
243) -> Report {
244 if let Some(outcome) = preflight(model, opts) {
245 return Report {
246 stage: "preflight",
247 outcome,
248 generated: 0,
249 initial_candidates: 0,
250 pending_violation: None,
251 traces_started: 0,
252 traces: Vec::new(),
253 action_flow: None,
254 runtime_output: Vec::new(),
255 };
256 }
257 // Declared before HostRestore so reverse drop order restores the original
258 // host before releasing shared-core simulation ownership, on every return.
259 let Some(_lease) = model.evaluator.try_simulation_lease() else {
260 return Report {
261 stage: "preflight",
262 outcome: Outcome::Unsupported(
263 "concurrent or reentrant simulation on the same evaluator".to_owned(),
264 ),
265 generated: 0,
266 initial_candidates: 0,
267 pending_violation: None,
268 traces_started: 0,
269 traces: Vec::new(),
270 action_flow: None,
271 runtime_output: Vec::new(),
272 };
273 };
274 let _restore = host::HostRestore::install(&model.evaluator, host);
275 let capture = dive_eval::capture::PrintCapture::start();
276 let mut report = driver(host);
277 let mut output = model.evaluator.filter_captured_warnings(capture.take());
278 output.append(&mut report.runtime_output);
279 report.runtime_output = output;
280 if let Some(reason) = host.limit() {
281 report.outcome = Outcome::Limit(reason.to_owned());
282 } else if let Some(reason) = host.denied() {
283 report.outcome = Outcome::Unsupported(reason);
284 }
285 report
286}
287
288/// Checks finite-mode options and statically unsupported combinations without evaluation.
289#[must_use]
290pub fn preflight(model: &Model, opts: &Options) -> Option<Outcome> {
291 let refusal = |s: &str| Some(Outcome::Unsupported(s.to_owned()));
292 if opts.traces == 0 {
293 return refusal("simulation requires a positive finite trace count");
294 }
295 if opts.aril > 1_000_000 {
296 return Some(Outcome::Limit("simulation aril skip bound".to_owned()));
297 }
298 if opts.mode == RandomMode::Dive && opts.aril != 0 {
299 return refusal("nonzero aril outside TLC simulation mode");
300 }
301 if model.runtime_name_order {
302 return refusal(
303 "simulation runtime string encounter order requires independent namespace provenance",
304 );
305 }
306 // A temporal property's binding refusal names the liveness backend, which
307 // simulation never uses; the simulation-specific refusal below names it.
308 if let Some(u) = model
309 .unsupported
310 .iter()
311 .find(|u| u.kind != dive_model::UnsupportedKind::TemporalProperty)
312 {
313 return refusal(&u.feature);
314 }
315 // Fairness (`model.temporals`) constrains only infinite behaviors and is
316 // inert for the finite safety prefixes simulation checks.
317 // Simulation does not check temporal properties on its traces yet.
318 if !model.implied_temporals.is_empty() {
319 let names: Vec<&str> = model
320 .implied_temporals
321 .iter()
322 .map(|n| n.name.as_str())
323 .collect();
324 return refusal(&format!(
325 "simulation temporal properties: {}",
326 names.join(", ")
327 ));
328 }
329 if !model.implied_inits.is_empty() {
330 return refusal(
331 "simulation implied initial properties require a separate validation contract",
332 );
333 }
334 if !model.implied_actions.is_empty()
335 && (!model.constraints.is_empty() || !model.action_constraints.is_empty())
336 {
337 return refusal(
338 "simulation implied action properties with state/action constraints require a separate validation contract",
339 );
340 }
341 if model.symmetry.is_some() {
342 return refusal("simulation SYMMETRY declarations");
343 }
344 if model.view.is_some() {
345 return refusal("simulation VIEW declarations");
346 }
347 // ALIAS only projects printed traces; as in checking, the report shows
348 // the states themselves and says so (`dive_api::simulate`). A failed
349 // lookup is TLC's error when it prints a trace, which is not reproduced.
350 if matches!(model.alias, Some(Err(_))) {
351 return refusal("simulation ALIAS whose definition lookup fails");
352 }
353 if !matches!(&model.postconditions, Ok(p) if p.is_empty()) {
354 return refusal("simulation POSTCONDITION");
355 }
356 if model.actions.len() > i32::MAX as usize {
357 return Some(Outcome::Limit(
358 "simulation action count exceeds TLC integer indexing".to_owned(),
359 ));
360 }
361 None
362}