Skip to main content

dive_sim/
statistics.rs

1//! Chosen-action flows from TLC's `SimulationWorkerStatistics.collectPostSuccessor`
2//! and `Simulator.getActionFlowGraphSnapshot(REDUCE)` at tlaplus `94d0c50` (MIT).
3
4use std::collections::BTreeMap;
5
6use dive_ir::actions::ActionName;
7use dive_model::Model;
8
9/// One source-location action group, with parameter contexts combined.
10#[derive(Clone, Debug)]
11pub struct ActionGroup {
12    /// Stable group index in initial/next action order.
13    pub id: usize,
14    /// The first bound action's name.
15    pub name: String,
16    /// The first bound action's source label (including its parameter context).
17    pub label: String,
18    /// Source location used to combine parameter contexts.
19    pub location: dive_ir::Origin,
20    /// Whether the representative is an initial predicate.
21    pub initial: bool,
22    /// Original bound action identities combined into this group.
23    pub bound_action_ids: Vec<usize>,
24}
25
26/// Sparse counts of consecutive chosen actions; no state-space coverage claim.
27#[derive(Clone, Debug)]
28pub struct ActionFlow {
29    /// Source-location groups, including groups never chosen.
30    pub actions: Vec<ActionGroup>,
31    /// Nonzero counts keyed by `(previous group, chosen group)`.
32    pub transitions: BTreeMap<(usize, usize), u64>,
33    groups: BTreeMap<usize, usize>,
34}
35
36impl ActionFlow {
37    /// Builds the source-location inventory for a validated bound model.
38    ///
39    /// # Errors
40    /// Foreign predicates or duplicate bound action identities.
41    pub fn new(model: &Model) -> Result<Self, dive_eval::EvalError> {
42        model
43            .evaluator
44            .validate_model_context(&model.ir, &model.names)?;
45        let mut flow = Self {
46            actions: Vec::new(),
47            transitions: BTreeMap::new(),
48            groups: BTreeMap::new(),
49        };
50        let mut locations = BTreeMap::new();
51        for (action, initial) in model
52            .init_actions
53            .iter()
54            .map(|a| (a, true))
55            .chain(model.actions.iter().map(|a| (a, false)))
56        {
57            model
58                .evaluator
59                .validate_predicate(&action.scope(), action.expr())?;
60            let origin = model.ir.node(action.expr()).origin;
61            let name = match action.name() {
62                ActionName::Def(def) => model
63                    .ir
64                    .defs()
65                    .get(def.index())
66                    .ok_or_else(|| {
67                        dive_eval::EvalError::unsupported(
68                            "basic simulation statistics require a valid action definition ID",
69                        )
70                    })?
71                    .name
72                    .clone(),
73                ActionName::Std(op) => op.name().to_owned(),
74                ActionName::Builtin(name) => name.to_owned(),
75                ActionName::Unnamed => "Action".to_owned(),
76            };
77            // TLC groups Action.getDefinition(), the predicate's source location,
78            // rather than its name or its evaluated parameter values.
79            let key = (origin.file, origin.begin, origin.end);
80            let group = *locations.entry(key).or_insert_with(|| {
81                let id = flow.actions.len();
82                flow.actions.push(ActionGroup {
83                    id,
84                    name,
85                    label: action.label().to_owned(),
86                    location: origin,
87                    initial,
88                    bound_action_ids: Vec::new(),
89                });
90                id
91            });
92            flow.actions[group].bound_action_ids.push(action.id());
93            if flow.groups.insert(action.id(), group).is_some() {
94                return Err(dive_eval::EvalError::unsupported(
95                    "basic simulation statistics require unique bound action IDs",
96                ));
97            }
98        }
99        Ok(flow)
100    }
101
102    /// Records one chosen transition using original bound action identities.
103    ///
104    /// # Errors
105    /// Unknown action identities or counter overflow.
106    pub fn record(&mut self, previous: usize, chosen: usize) -> Result<(), dive_eval::EvalError> {
107        // Init callbacks return an action from model.init_actions; chosen actions
108        // come directly from model.actions. new() maps both vectors and checks
109        // uniqueness. The private map stays unchanged throughout sampling.
110        let from = self.groups.get(&previous).copied().ok_or_else(|| {
111            dive_eval::EvalError::bug("simulation previous action is missing from its flow groups")
112        })?;
113        let to = self.groups.get(&chosen).copied().ok_or_else(|| {
114            dive_eval::EvalError::bug("simulation chosen action is missing from its flow groups")
115        })?;
116        let count = self.transitions.entry((from, to)).or_default();
117        // Each counted edge consumes one retained state, so max_retained bounds
118        // both counts and sparse entries. Still check overflow for public options.
119        *count = count.checked_add(1).ok_or_else(|| {
120            dive_eval::EvalError::resource_limit("simulation action-flow count overflow")
121        })?;
122        Ok(())
123    }
124}