dive-model 0.1.0

Binding a TLA+ specification to its TLC model configuration
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
//! The bound model: what the checker, simulator and trace validator consume.

use std::sync::Arc;

use dive_eval::{AssumptionOutcome, Evaluator, Scope, St};
use dive_ir::{DefId, ExprId, Ir};
use dive_value::{Interner, Value};

use crate::error::{BindError, Message};

/// A predicate or expression TLC evaluates for a role, with the context it
/// is evaluated in: TLC's `tlc2.tool.Action` (`pred`, `con`).
#[derive(Clone, Debug)]
pub struct Pred {
    /// The expression.
    pub expr: ExprId,
    /// Where it is evaluated (operator parameters, split `\E` variables,
    /// instance substitutions).
    pub scope: Scope,
    /// The node TLC reports the role's location from: the expression, or the
    /// outermost instance substitution TLC wrapped around it
    /// (`Specs.addSubsts`).
    pub location: ExprId,
}

impl Pred {
    /// A predicate evaluated in its own definition's frame.
    #[must_use]
    pub fn new(expr: ExprId, scope: Scope) -> Self {
        Self {
            expr,
            scope,
            location: expr,
        }
    }
}

/// A role with the name TLC reports it under.
#[derive(Clone, Debug)]
pub struct Named {
    /// The name: the configuration's name for `INVARIANT` and the
    /// constraints, TLC's derived name for parts of a `PROPERTY`.
    pub name: String,
    /// The predicate.
    pub pred: Pred,
}

/// An initial predicate (`getInitStateSpec`).
#[derive(Clone, Debug)]
pub struct Init {
    /// The predicate.
    pub pred: Pred,
    /// The definition it came from, if any (`INIT Init`, or a conjunct of a
    /// `SPECIFICATION` that is a use of a definition).
    pub def: Option<DefId>,
}

/// The `-deadlock` and `CHECK_DEADLOCK` outcome and other run settings.
#[derive(Clone, Debug)]
pub struct Settings {
    /// Whether deadlock is checked: `CHECK_DEADLOCK` and TLC's `-deadlock`
    /// flag together.
    pub check_deadlock: bool,
}

/// Why the model cannot yet receive a complete checking verdict.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnsupportedKind {
    /// A temporal property requires the liveness backend.
    TemporalProperty,
    /// Another unimplemented feature, which graph capture cannot defer.
    Feature,
}

/// A feature of the model that dive does not check yet. The checker refuses
/// the model as `unsupported`, naming it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unsupported {
    /// The structured reason, never inferred from diagnostic text.
    pub kind: UnsupportedKind,
    /// The feature, by name.
    pub feature: String,
}

/// A specification bound to its configuration.
#[derive(Clone, Debug)]
pub struct Model {
    /// The lowered specification.
    pub ir: Arc<Ir>,
    /// The evaluator, with the constants bound and the start-up values
    /// computed. Clones share them.
    pub evaluator: Evaluator,
    /// The run's names, in TLC's encounter order.
    pub names: Arc<Interner>,
    /// What TLC prints while it processes the model, before it checks the
    /// assumptions: `Print` output of constant definitions and warnings.
    pub output: Vec<Message>,
    /// Initial predicates, in TLC's order.
    pub init: Vec<Init>,
    /// The next-state relation as TLC holds it before splitting
    /// (`getNextStateSpec`), if any.
    pub next: Option<Pred>,
    /// The initial predicates as the successor generator's actions
    /// (`Evaluator::init_states`), numbered from 0.
    pub init_actions: Vec<dive_eval::next::Action>,
    /// The next-state relation split into TLC's actions, with TLC's labels,
    /// numbered after the initial predicates (`Evaluator::successors`).
    pub actions: Vec<dive_eval::next::Action>,
    /// Invariants: `INVARIANT`s, then the state predicates `[]P` of
    /// `PROPERTY`s.
    pub invariants: Vec<Named>,
    /// Implied initial predicates: state-level parts of `PROPERTY`s.
    pub implied_inits: Vec<Named>,
    /// Implied actions: the `[A]_v` of `[][A]_v` in `PROPERTY`s.
    pub implied_actions: Vec<Named>,
    /// Temporal formulas of the behavior specification (fairness), named as
    /// TLC names them. Inert for safety checking.
    pub temporals: Vec<Named>,
    /// Temporal properties to check (liveness).
    pub implied_temporals: Vec<Named>,
    /// Binder-recorded original names of TLC implied-temporal Actions.
    pub(crate) implied_temporal_action_names: Vec<String>,
    /// Original configured PROPERTY formulas, before TLC's role splitting.
    /// These retain configuration names for complete counterexample claims;
    /// the role vectors above keep TLC's evaluation/checking order unchanged.
    pub configured_properties: Vec<Named>,
    /// `CONSTRAINT`s.
    pub constraints: Vec<Named>,
    /// `ACTION_CONSTRAINT`s.
    pub action_constraints: Vec<Named>,
    /// `VIEW`.
    pub view: Option<Named>,
    /// `ALIAS`. TLC looks it up only when it prints a trace
    /// (`Spec.getAliasSpec`), so a lookup error is reported then, not at
    /// start-up.
    pub alias: Option<Result<Named, BindError>>,
    /// `POSTCONDITION`s. TLC looks them up after checking
    /// (`Spec.getPostConditionSpecs`), stopping at the first error, which it
    /// reports then.
    pub postconditions: Result<Vec<Named>, BindError>,
    /// `SYMMETRY`, by name.
    pub symmetry: Option<String>,
    pub(crate) symmetry_liveness: crate::SymmetryLivenessResolution,
    /// Prepared safety reduction. Concrete states remain unmodified.
    pub symmetry_reduction: Option<Arc<crate::symmetry::Reduction>>,
    /// Pre-constant-evaluation lookup, retained only for the configured declaration.
    pub(crate) symmetry_definition: Option<crate::tables::Look>,
    /// Run settings.
    pub settings: Settings,
    /// The root module's assumptions TLC checks (not `AXIOM`s), in order.
    pub assumptions: Vec<DefId>,
    /// Features this model uses that dive does not check yet.
    pub unsupported: Vec<Unsupported>,
    /// Why the model must be checked in sequential mode, with one logical
    /// worker evaluating in TLC's order; empty when a parallel
    /// search gives the same results. Each entry names the feature.
    pub sequential: Vec<String>,
    /// The only sequential restriction is preserving runtime name encounter
    /// order. This is not an I/O, random-stream or live-checker-state effect.
    /// This conservative source inventory remains available to checkpoint
    /// admission after a proof discharges the corresponding worker restriction.
    pub sequential_names_only: bool,
    /// Checking may create runtime names whose encounter order is observable
    /// under the selected value or exploration order. Remains true when other
    /// sequential effects are also reachable.
    /// This is a conservative source feature flag; a worker-selection proof
    /// can remove a scheduling reason without changing replay's inventory.
    pub runtime_name_order: bool,
    pub(crate) stateful_checking: Option<String>,
    /// Pure constant-level definitions whose start-up evaluation was left to
    /// Core ([`crate::bind_deferring_constants`]); empty
    /// otherwise. The evaluator evaluates them lazily.
    pub deferred_constants: std::collections::BTreeSet<dive_ir::DefId>,
    /// The root module's pure `ASSUME`s, in order, that Core
    /// evaluates when it compiles its plan
    /// ([`crate::bind_deferring_constants`]); empty otherwise. Their value
    /// is a function of the start-up values alone, so one the core finds
    /// `TRUE` need not be checked again
    /// ([`Model::check_assumptions_except`]).
    pub deferred_assumptions: Vec<DefId>,
}

impl Model {
    /// A reachable stateful checking restriction, if any, from model binding.
    ///
    /// Runtime-name encounter order and TLC composition accounting are separate
    /// sequential requirements. Their presence alone does not return a reason
    /// here. This classification does not establish support: each backend must
    /// still apply its remaining checks and evaluate the actual model.
    ///
    /// ```
    /// # fn explain(model: &dive_model::Model) {
    /// if let Some(reason) = model.stateful_checking() {
    ///     eprintln!("stateful checking: {reason}");
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn stateful_checking(&self) -> Option<&str> {
        self.stateful_checking.as_deref()
    }

    /// Records every name interned so far as a start-up name
    /// ([`dive_eval::Evaluator::seal_startup_names`]). Call it only after
    /// interning names TLC interns before it evaluates any `ASSUME` or state.
    pub fn seal_startup_names(&self) {
        self.evaluator.seal_startup_names();
    }

    /// Whether a name was interned after start-up
    /// ([`dive_eval::Evaluator::startup_names`])
    /// and string order follows encounter order (TLC's value or exploration
    /// order), so that the name's position relative to the others depends
    /// on evaluations outside a given trace.
    #[must_use]
    pub fn has_runtime_names(&self) -> bool {
        let opts = self.evaluator.options();
        (opts.ctx.order == dive_value::ValueOrder::Tlc
            || opts.exploration == dive_eval::ExplorationOrder::Tlc)
            && self.names.len() > self.evaluator.startup_names()
    }

    /// The immutable original declaration and policy after actual role binding.
    /// This is not exploration or witness evidence.
    ///
    /// ```
    /// # fn example(model: &dive_model::Model) {
    /// let requested = model.symmetry_liveness().requested();
    /// assert!(["unreduced", "refuse", "tlc"].contains(&requested.as_str()));
    /// # }
    /// ```
    #[must_use]
    pub const fn symmetry_liveness(&self) -> &crate::SymmetryLivenessResolution {
        &self.symmetry_liveness
    }

    /// Whether this model uses full concrete identities for temporal checking.
    /// Public role/declaration changes or an installed reduction invalidate it.
    ///
    /// ```
    /// # fn example(model: &dive_model::Model) {
    /// if model.unreduced_symmetry_liveness() {
    ///     assert!(model.symmetry_reduction.is_none());
    ///     assert!(!model.implied_temporals.is_empty());
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn unreduced_symmetry_liveness(&self) -> bool {
        self.symmetry_liveness.unreduced()
            && self.symmetry.as_deref() == self.symmetry_liveness.declared()
            && !self.implied_temporals.is_empty()
            && self.symmetry_reduction.is_none()
    }

    /// Admits public bound-model metadata before backend startup or host effects.
    /// Checks evaluator ownership and every predicate/action scope without
    /// evaluating expressions or forcing captured values.
    ///
    /// # Errors
    /// A named malformed/foreign context or bounded admission refusal.
    pub fn validate_context(&self) -> dive_eval::Result<()> {
        self.evaluator
            .validate_model_context(&self.ir, &self.names)?;
        let check = |pred: &Pred| {
            if self.ir.nodes().get(pred.location.index()).is_none() {
                return Err(dive_eval::EvalError::unsupported(
                    "invalid model predicate location (DIVE-EVAL-C001)",
                ));
            }
            self.evaluator.validate_predicate(&pred.scope, pred.expr)
        };
        for init in &self.init {
            if init
                .def
                .is_some_and(|d| self.ir.defs().get(d.index()).is_none())
            {
                return Err(dive_eval::EvalError::unsupported(
                    "invalid initial definition (DIVE-EVAL-C001)",
                ));
            }
            check(&init.pred)?;
        }
        if let Some(next) = &self.next {
            check(next)?;
        }
        for named in self
            .invariants
            .iter()
            .chain(&self.implied_inits)
            .chain(&self.implied_actions)
            .chain(&self.temporals)
            .chain(&self.implied_temporals)
            .chain(&self.configured_properties)
            .chain(&self.constraints)
            .chain(&self.action_constraints)
            .chain(self.view.iter())
            .chain(self.alias.as_ref().and_then(|a| a.as_ref().ok()))
            .chain(self.postconditions.as_ref().into_iter().flatten())
        {
            check(&named.pred)?;
        }
        if self
            .assumptions
            .iter()
            .any(|d| self.ir.defs().get(d.index()).is_none())
        {
            return Err(dive_eval::EvalError::unsupported(
                "invalid assumption definition (DIVE-EVAL-C001)",
            ));
        }
        for action in self.init_actions.iter().chain(&self.actions) {
            self.evaluator
                .validate_predicate(&action.scope(), action.expr())?;
        }
        if self.implied_temporal_action_names.len() != self.implied_temporals.len() {
            return Err(dive_eval::EvalError::unsupported(
                "invalid temporal property-origin metadata (DIVE-EVAL-C001)",
            ));
        }
        Ok(())
    }

    /// Original configuration names on TLC's expanded implied-temporal Actions,
    /// recorded in role order by the binder. A conjunctive `P` can yield
    /// `P;P`; these are distinct from configured claims and derived labels.
    /// Rebind caller-edited role vectors before using this binding snapshot.
    #[must_use]
    pub fn implied_temporal_action_names(&self) -> &[String] {
        &self.implied_temporal_action_names
    }

    /// Original configured property claims, or the temporal roles for a model
    /// without retained originals. A quantified conjunction must be attributed
    /// as one configured property, not as ambiguous identically named roles.
    #[must_use]
    pub fn property_claims(&self) -> &[Named] {
        if self.configured_properties.is_empty() {
            &self.implied_temporals
        } else {
            &self.configured_properties
        }
    }

    /// Evaluates a role's predicate.
    ///
    /// # Errors
    /// Any evaluation error, refusal or resource limit.
    pub fn eval(&self, pred: &Pred, st: &St) -> dive_eval::Result<Value> {
        self.evaluator
            .validate_model_context(&self.ir, &self.names)?;
        self.evaluator.eval_scoped(&pred.scope, pred.expr, st)
    }

    /// Evaluates a configured Boolean role with TLC's `Tool.isValid` boundary.
    /// A returned non-Boolean value raises the tool's source-qualified 2215;
    /// an error inside the expression retains its original constructor/source.
    ///
    /// ```no_run
    /// # fn check(model: &dive_model::Model, pred: &dive_model::Pred, state: &dive_eval::St) -> dive_eval::Result<()> {
    /// let holds = model.eval_boolean(pred, state)?;
    /// # let _ = holds; Ok(()) }
    /// ```
    ///
    /// # Errors
    /// The original evaluation failure, or the actual non-Boolean role failure.
    pub fn eval_boolean(&self, pred: &Pred, st: &St) -> dive_eval::Result<bool> {
        match self.eval(pred, st)? {
            Value::Bool(value) => Ok(value),
            _ => Err(dive_eval::EvalError::coded(
                dive_eval::Ec::ExpectedValue,
                format!(
                    "TLC expected a boolean value, but did not find one. {}",
                    self.evaluator.location(pred.location)
                ),
            )
            .at(pred.location)),
        }
    }

    /// TLC's `Tool.checkAssumptions`: the assumptions in order, `AXIOM`s
    /// skipped, stopping at the first that is not `TRUE`.
    #[must_use]
    pub fn check_assumptions(&self) -> AssumptionOutcome {
        self.check_assumptions_except(&[])
    }

    /// [`Self::check_assumptions`], skipping `proved`: pure assumptions
    /// (among [`Self::deferred_assumptions`]) another evaluator found
    /// `TRUE`. Skipping one is unobservable: TLC's evaluation of it has no
    /// effect and does not stop the check.
    #[must_use]
    pub fn check_assumptions_except(&self, proved: &[DefId]) -> AssumptionOutcome {
        if let Err(error) = self.evaluator.validate_model_context(&self.ir, &self.names) {
            return AssumptionOutcome::Error {
                def: DefId(u32::MAX),
                message: error.to_string(),
                error: error.into(),
            };
        }
        let axioms: Vec<DefId> = {
            let root = self.ir.module(self.ir.root());
            root.assumptions
                .iter()
                .zip(&root.axioms)
                .filter(|(_, ax)| **ax)
                .map(|(d, _)| *d)
                .collect()
        };
        self.evaluator
            .check_assumptions(|d| axioms.contains(&d) || proved.contains(&d))
    }

    /// The `Print` output collected since the last call (the evaluator's
    /// default sink).
    #[must_use]
    pub fn take_output(&self) -> Vec<String> {
        self.evaluator.take_output()
    }

    /// The location TLC prints for a role's predicate (`getLocation()`).
    #[must_use]
    pub fn location(&self, pred: &Pred) -> String {
        self.ir.location(&self.ir.node(pred.location).origin)
    }
}