Skip to main content

chicago_tdd_tools/testing/
state_machine.rs

1//! Type-Directed State Machine Testing
2//!
3//! Provides type-level state machines for concurrency testing with:
4//! - Phantom-typed states that the compiler enforces
5//! - Transition traits that prevent illegal state transitions
6//! - Automatic schedule generation for concurrent actors
7//! - AUDIT NOTE (W26): loom integration lives in the sibling `concurrency` module, not here
8//!
9//! This brings lightweight model checking into the test suite, purely in Rust,
10//! without external tools. It aligns with the μ-kernel notion of Λ total order
11//! on events/transitions.
12//!
13//! # Architecture
14//!
15//! ```text
16//! StateMachine<S> where S: State
17//!     ↓
18//! Transition<From, To> trait
19//!     ↓
20//! Compiler enforces:
21//!     - Only valid transitions allowed
22//!     - Illegal sequences cannot compile
23//!     - One linear sequence explored (bounded depth); interleaving exploration is not implemented
24//! ```
25
26use std::marker::PhantomData;
27
28/// State marker trait
29///
30/// All states in a state machine must implement this trait.
31/// Use phantom types to represent states at compile time.
32pub trait State: Sized + 'static {
33    /// State name for debugging/logging
34    fn name() -> &'static str;
35}
36
37/// Transition trait: defines valid state transitions
38///
39/// Implement this trait to declare valid transitions between states.
40/// The compiler enforces that only valid transitions can occur.
41///
42/// # Example
43///
44/// ```rust
45/// use chicago_tdd_tools::testing::state_machine::{State, StateMachineError, Transition};
46/// use std::marker::PhantomData;
47///
48/// // Define states
49/// struct Locked;
50/// impl State for Locked {
51///     fn name() -> &'static str { "Locked" }
52/// }
53///
54/// struct Unlocked;
55/// impl State for Unlocked {
56///     fn name() -> &'static str { "Unlocked" }
57/// }
58///
59/// // Define transition
60/// struct Unlock;
61/// impl Transition<Locked, Unlocked> for Unlock {
62///     fn execute() -> Result<(), StateMachineError> {
63///         Ok(())
64///     }
65/// }
66/// ```
67pub trait Transition<From: State, To: State> {
68    /// Execute the transition
69    ///
70    /// Returns Ok(()) if transition succeeds, Err otherwise.
71    ///
72    /// # Errors
73    ///
74    /// Returns error if the transition cannot be executed.
75    fn execute() -> Result<(), StateMachineError>;
76}
77
78/// Typed failure of a state-machine transition or invariant check.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum StateMachineError {
81    /// The transition's `execute` body reported failure.
82    Execution {
83        /// Human-readable failure description from the transition body.
84        message: String,
85    },
86    /// A generated schedule violated the checked invariant.
87    InvariantViolated {
88        /// Zero-based index of the counterexample schedule.
89        schedule_index: usize,
90        /// Number of steps in the counterexample schedule.
91        schedule_length: usize,
92        /// Rendered counterexample schedule.
93        schedule: String,
94    },
95}
96
97impl std::fmt::Display for StateMachineError {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        match self {
100            Self::Execution { message } => write!(f, "{message}"),
101            Self::InvariantViolated {
102                schedule_index,
103                schedule_length,
104                schedule,
105            } => write!(
106                f,
107                "Invariant violated by schedule {schedule_index} (length {schedule_length}): {schedule}"
108            ),
109        }
110    }
111}
112
113impl std::error::Error for StateMachineError {}
114
115/// State machine with phantom-typed state
116///
117/// The state is encoded at the type level, preventing invalid transitions
118/// at compile time.
119pub struct StateMachine<S: State> {
120    _state: PhantomData<S>,
121}
122
123impl<S: State> StateMachine<S> {
124    /// Create a new state machine in the given state
125    #[must_use]
126    pub const fn new() -> Self {
127        Self { _state: PhantomData }
128    }
129
130    /// Transition to a new state
131    ///
132    /// This method is only callable when a valid transition exists.
133    /// The compiler enforces this through the Transition trait bound.
134    ///
135    /// # Errors
136    ///
137    /// Returns error if the transition execution fails.
138    #[allow(clippy::unused_self)] // Consumes self to enforce state machine linearity
139    pub fn transition<To: State, T>(self) -> Result<StateMachine<To>, StateMachineError>
140    where
141        T: Transition<S, To>,
142    {
143        T::execute()?;
144        Ok(StateMachine::<To>::new())
145    }
146
147    /// Get current state name
148    #[must_use]
149    pub fn current_state() -> &'static str {
150        S::name()
151    }
152}
153
154impl<S: State> Default for StateMachine<S> {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159
160/// Concurrent state machine actor
161///
162/// Represents an actor that can perform state transitions concurrently
163/// with other actors. Used for generating concurrent schedules.
164pub struct Actor<S: State> {
165    id: String,
166    state_machine: StateMachine<S>,
167}
168
169impl<S: State> Actor<S> {
170    /// Create a new actor with the given ID
171    #[must_use]
172    pub fn new(id: impl Into<String>) -> Self {
173        Self { id: id.into(), state_machine: StateMachine::new() }
174    }
175
176    /// Get actor ID
177    #[must_use]
178    pub fn id(&self) -> &str {
179        &self.id
180    }
181
182    /// Transition to a new state
183    ///
184    /// # Errors
185    ///
186    /// Returns error if the transition fails.
187    pub fn transition<To: State, T>(self) -> Result<Actor<To>, StateMachineError>
188    where
189        T: Transition<S, To>,
190    {
191        self.state_machine.transition::<To, T>()?;
192        Ok(Actor { id: self.id, state_machine: StateMachine::new() })
193    }
194}
195
196/// Schedule: ordered sequence of actor transitions
197///
198/// Represents a specific interleaving of concurrent operations.
199/// Used for systematic concurrency testing.
200#[derive(Debug, Clone)]
201pub struct Schedule {
202    steps: Vec<ScheduleStep>,
203}
204
205/// Single step in a schedule
206#[derive(Debug, Clone)]
207pub struct ScheduleStep {
208    /// Actor ID
209    pub actor_id: String,
210    /// Transition name
211    pub transition: String,
212    /// From state
213    pub from_state: String,
214    /// To state
215    pub to_state: String,
216}
217
218impl Schedule {
219    /// Create a new empty schedule
220    #[must_use]
221    pub const fn new() -> Self {
222        Self { steps: Vec::new() }
223    }
224
225    /// Add a step to the schedule
226    pub fn add_step(&mut self, step: ScheduleStep) {
227        self.steps.push(step);
228    }
229
230    /// Get all steps
231    #[must_use]
232    pub fn steps(&self) -> &[ScheduleStep] {
233        &self.steps
234    }
235
236    /// Get schedule length
237    #[must_use]
238    pub const fn len(&self) -> usize {
239        self.steps.len()
240    }
241
242    /// Check if schedule is empty
243    #[must_use]
244    pub const fn is_empty(&self) -> bool {
245        self.steps.is_empty()
246    }
247
248    /// Format schedule as string
249    #[must_use]
250    pub fn format(&self) -> String {
251        use std::fmt::Write;
252
253        let mut s = String::from("Schedule:\n");
254        for (i, step) in self.steps.iter().enumerate() {
255            // Writing to a `String` via `fmt::Write` is infallible.
256            writeln!(
257                s,
258                "  {}. Actor {} - {} -> {}: {}",
259                i + 1,
260                step.actor_id,
261                step.from_state,
262                step.to_state,
263                step.transition
264            )
265            .ok();
266        }
267        s
268    }
269}
270
271impl Default for Schedule {
272    fn default() -> Self {
273        Self::new()
274    }
275}
276
277/// Schedule generator (W27 AUDIT NOTE: emits exactly ≤2 hard-coded schedules — empty + one linear path clamped to at most `max_depth` (2); does NOT generate interleavings)
278///
279/// Given a set of concurrent actors and their possible transitions,
280/// emits its fixed ≤2 schedules (bounded by at most two schedules (`max_depth` clamps the linear path); see the module-header note).
281pub struct ScheduleGenerator {
282    max_depth: usize,
283}
284
285impl ScheduleGenerator {
286    /// Create a new schedule generator with maximum depth
287    #[must_use]
288    pub const fn new(max_depth: usize) -> Self {
289        Self { max_depth }
290    }
291
292    /// Get maximum depth
293    #[must_use]
294    pub const fn max_depth(&self) -> usize {
295        self.max_depth
296    }
297
298    /// Generate schedules up to max depth
299    ///
300    /// Generates a base empty schedule plus sequential schedules for the
301    /// canonical Lock state machine (Locked -> Unlocked -> Locked).
302    /// Each schedule represents a linear path through the state machine.
303    #[must_use]
304    pub fn generate(&self) -> Vec<Schedule> {
305        let mut schedules = Vec::new();
306
307        // Always include the empty schedule
308        schedules.push(Schedule::new());
309
310        // Generate sequential schedules for the canonical transitions
311        // up to max_depth steps
312        let canonical_steps = [
313            ScheduleStep {
314                actor_id: "actor0".to_string(),
315                transition: "Unlock".to_string(),
316                from_state: Locked::name().to_string(),
317                to_state: Unlocked::name().to_string(),
318            },
319            ScheduleStep {
320                actor_id: "actor0".to_string(),
321                transition: "Lock".to_string(),
322                from_state: Unlocked::name().to_string(),
323                to_state: Locked::name().to_string(),
324            },
325        ];
326
327        let depth = self.max_depth.min(canonical_steps.len());
328        if depth > 0 {
329            let mut sequential = Schedule::new();
330            for step in canonical_steps.iter().take(depth) {
331                sequential.add_step(step.clone());
332            }
333            schedules.push(sequential);
334        }
335
336        schedules
337    }
338}
339
340/// Model checker: verifies state machine properties
341///
342/// Checks invariants across the same fixed ≤2 generated schedules (W27 AUDIT NOTE: not all interleavings).
343pub struct ModelChecker {
344    generator: ScheduleGenerator,
345}
346
347impl ModelChecker {
348    /// Create a new model checker with bounded depth
349    #[must_use]
350    pub const fn new(max_depth: usize) -> Self {
351        Self { generator: ScheduleGenerator::new(max_depth) }
352    }
353
354    /// Check if an invariant holds for all schedules
355    ///
356    /// Returns Ok(()) if invariant holds, Err with counterexample otherwise.
357    ///
358    /// # Errors
359    ///
360    /// Returns error if invariant is violated by any schedule.
361    pub fn check_invariant<F>(&self, invariant: F) -> Result<(), StateMachineError>
362    where
363        F: Fn(&Schedule) -> bool,
364    {
365        let schedules = self.generator.generate();
366        for (i, schedule) in schedules.iter().enumerate() {
367            if !invariant(schedule) {
368                return Err(StateMachineError::InvariantViolated {
369                    schedule_index: i,
370                    schedule_length: schedule.len(),
371                    schedule: schedule.format(),
372                });
373            }
374        }
375        Ok(())
376    }
377
378    /// Get the schedule generator
379    #[must_use]
380    pub const fn generator(&self) -> &ScheduleGenerator {
381        &self.generator
382    }
383}
384
385// Example: Lock state machine
386
387/// Lock state: Locked
388pub struct Locked;
389
390impl State for Locked {
391    fn name() -> &'static str {
392        "Locked"
393    }
394}
395
396/// Lock state: Unlocked
397pub struct Unlocked;
398
399impl State for Unlocked {
400    fn name() -> &'static str {
401        "Unlocked"
402    }
403}
404
405/// Transition: Unlock
406pub struct Unlock;
407
408impl Transition<Locked, Unlocked> for Unlock {
409    fn execute() -> Result<(), StateMachineError> {
410        // Transition from Locked -> Unlocked: the type system guarantees the
411        // caller held a StateMachine<Locked>, so this transition is always valid.
412        // Returning Ok(()) signals successful unlocking; the new StateMachine<Unlocked>
413        // is constructed by the caller, encoding the unlocked state at the type level.
414        Ok(())
415    }
416}
417
418/// Transition: Lock
419pub struct Lock;
420
421impl Transition<Unlocked, Locked> for Lock {
422    fn execute() -> Result<(), StateMachineError> {
423        // Transition from Unlocked -> Locked: the type system guarantees the
424        // caller held a StateMachine<Unlocked>, so this transition is always valid.
425        // Returning Ok(()) signals successful locking; the new StateMachine<Locked>
426        // is constructed by the caller, encoding the locked state at the type level.
427        Ok(())
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    #[test]
436    fn test_state_machine_transitions() {
437        // Start in Locked state
438        let locked = StateMachine::<Locked>::new();
439        assert_eq!(StateMachine::<Locked>::current_state(), "Locked");
440
441        // Transition to Unlocked
442        let unlocked = locked.transition::<Unlocked, Unlock>();
443        assert!(unlocked.is_ok());
444
445        // Transition back to Locked
446        let locked_again = unlocked.unwrap().transition::<Locked, Lock>();
447        assert!(locked_again.is_ok());
448    }
449
450    #[test]
451    fn test_actor_transitions() {
452        let actor = Actor::<Locked>::new("actor1");
453        assert_eq!(actor.id(), "actor1");
454
455        let actor = actor.transition::<Unlocked, Unlock>();
456        assert!(actor.is_ok());
457
458        let actor = actor.unwrap();
459        assert_eq!(actor.id(), "actor1");
460    }
461
462    #[test]
463    fn test_schedule() {
464        let mut schedule = Schedule::new();
465        assert!(schedule.is_empty());
466
467        schedule.add_step(ScheduleStep {
468            actor_id: "actor1".to_string(),
469            transition: "Unlock".to_string(),
470            from_state: "Locked".to_string(),
471            to_state: "Unlocked".to_string(),
472        });
473
474        assert_eq!(schedule.len(), 1);
475        assert!(!schedule.is_empty());
476
477        let formatted = schedule.format();
478        assert!(formatted.contains("actor1"));
479        assert!(formatted.contains("Unlock"));
480    }
481
482    #[test]
483    fn test_schedule_generator() {
484        let generator = ScheduleGenerator::new(10);
485        assert_eq!(generator.max_depth(), 10);
486
487        let schedules = generator.generate();
488        // Always includes at least the empty schedule
489        assert!(!schedules.is_empty());
490        // First schedule is always the empty schedule
491        assert!(schedules[0].is_empty());
492    }
493
494    #[test]
495    fn test_model_checker() {
496        let checker = ModelChecker::new(10);
497
498        // Check a trivial invariant (always true)
499        let result = checker.check_invariant(|_schedule| true);
500        assert!(result.is_ok());
501    }
502
503    // Example of compile-time enforcement:
504    // This would NOT compile (uncomment to verify):
505    // #[test]
506    // fn test_invalid_transition() {
507    //     let locked = StateMachine::<Locked>::new();
508    //     // Cannot unlock an already unlocked lock!
509    //     // This won't compile because there's no Transition<Unlocked, Unlocked>
510    //     // let still_unlocked = locked.transition::<Unlocked, Unlock>();
511    // }
512}