Skip to main content

engenho_substrate/
maquina.rs

1//! máquina — typed FSM primitive.
2//!
3//! Per the research brief — MEDIUM-leverage inventive primitive.
4//! The substrate has multiple ad-hoc state machines (Plantio
5//! stage state, Transient lifecycle, `QuorumState` enum, search
6//! Ensaio status) hand-rolled with match statements + bare
7//! enums. máquina folds them into one typed surface.
8//!
9//! ## Surface
10//!
11//!   - `StateMachine` trait — pure step function
12//!     `(state, event) -> (state, effect)`
13//!   - `MachineRunner<M>` — drives steps, holds current state,
14//!     records every transition into a typed history Vec
15//!   - `TransitionRecord<M>` — typed (from, event, to, at: Instant)
16//!     for replay/audit
17//!
18//! ## What this collapses
19//!
20//! Today: every controller hand-rolls its FSM with bespoke enum
21//! matching, scattered transition logic, no transition history.
22//!
23//! Tomorrow: every controller's FSM lifts into a `MachineRunner`,
24//! gains free transition recording + replay + fingerprinting via
25//! the existing trait surfaces.
26//!
27//! ## Composition
28//!
29//!   - `Named` supertrait → every machine has telemetry name
30//!   - `relógio::Instant` for transition timestamps
31//!   - `Fingerprint` over State + Event (caller supplies)
32//!   - `ErrorKind` on `M::Err`
33
34use serde::{Deserialize, Serialize};
35
36use crate::relogio::Instant;
37
38/// Typed finite-state-machine surface. Implementers supply:
39///   - `State`: the machine's state (Clone + Serialize + Eq)
40///   - `Event`: input events (Clone + Serialize)
41///   - `Effect`: side-effects the step requests be performed
42///     by the runner's consumer (telemetry, log line, action)
43///   - `Err`: error type — must implement `ErrorKind`
44///
45/// The step function is PURE — no I/O, no side effects beyond
46/// returning the Effect for the runner to dispatch. This is what
47/// makes replay possible.
48pub trait StateMachine: crate::named::Named + Default + Send + Sync {
49    /// The state type — must be cloneable + comparable + serdeable.
50    type State: Clone + Eq + Serialize + Send + Sync;
51
52    /// The event type — input that drives transitions.
53    type Event: Clone + Serialize + Send + Sync;
54
55    /// The effect type — side-effects the runner's consumer
56    /// dispatches (logging, telemetry, downstream calls).
57    type Effect: Clone + Send + Sync;
58
59    /// The error type — typed step failures (invalid event for
60    /// current state, etc.).
61    type Err: crate::error_kind::ErrorKind + Send + Sync + std::fmt::Debug;
62
63    /// Initial state when the runner spawns.
64    fn initial() -> Self::State;
65
66    /// Pure step: given a state + event, return the next state +
67    /// effect. Pure — no I/O, no side effects.
68    ///
69    /// # Errors
70    /// [`Self::Err`] when the event isn't valid for the current state.
71    fn step(
72        state: &Self::State,
73        event: &Self::Event,
74    ) -> Result<(Self::State, Self::Effect), Self::Err>;
75
76    /// True if `state` is a terminal state. The runner refuses to
77    /// step from a terminal state.
78    fn is_terminal(state: &Self::State) -> bool;
79}
80
81/// One typed record of a transition. Serializable for replay +
82/// fingerprintable for cross-node attestation.
83#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
84pub struct TransitionRecord<S, E> {
85    /// State the machine was in before the event.
86    pub from: S,
87    /// Event that drove the transition.
88    pub event: E,
89    /// State the machine ended up in.
90    pub to: S,
91    /// When the transition happened (clock-injected).
92    pub at: Instant,
93}
94
95/// Runner that owns one machine + drives steps + accumulates
96/// the transition history.
97///
98/// The history is unbounded unless capped with
99/// [`Self::with_history_cap`]. A runner that lives as long as a daemon —
100/// a lifecycle stepping on every retry of a failing boot, for months —
101/// must cap it, or the history is a leak with a clean conscience.
102pub struct MachineRunner<M: StateMachine> {
103    state: M::State,
104    history: Vec<TransitionRecord<M::State, M::Event>>,
105    /// Keep at most this many of the most recent transitions.
106    history_cap: Option<std::num::NonZeroUsize>,
107    /// Every transition ever taken, including those the cap dropped.
108    steps: usize,
109    clock: std::sync::Arc<dyn crate::relogio::Clock>,
110    name: &'static str,
111}
112
113impl<M: StateMachine> MachineRunner<M> {
114    /// New runner with the machine's initial state + a clock
115    /// (operator picks `WallClock` / `FrozenClock` / etc).
116    #[must_use]
117    pub fn new(clock: std::sync::Arc<dyn crate::relogio::Clock>) -> Self {
118        Self {
119            state: M::initial(),
120            history: Vec::new(),
121            history_cap: None,
122            steps: 0,
123            clock,
124            name: <M as MachineNamed>::name_static(),
125        }
126    }
127
128    /// Keep only the `cap` most recent transitions. [`Self::step_count`]
129    /// still counts every transition ever taken.
130    #[must_use]
131    pub fn with_history_cap(mut self, cap: std::num::NonZeroUsize) -> Self {
132        self.history_cap = Some(cap);
133        self.trim_history();
134        self
135    }
136
137    /// Drop the oldest transitions beyond the cap, if any.
138    fn trim_history(&mut self) {
139        if let Some(cap) = self.history_cap {
140            let excess = self.history.len().saturating_sub(cap.get());
141            if excess > 0 {
142                self.history.drain(..excess);
143            }
144        }
145    }
146
147    /// New runner starting from an explicit state. Useful for
148    /// reconstruction / replay tests.
149    #[must_use]
150    pub fn from_state(state: M::State, clock: std::sync::Arc<dyn crate::relogio::Clock>) -> Self {
151        Self {
152            state,
153            history_cap: None,
154            steps: 0,
155            history: Vec::new(),
156            clock,
157            name: <M as MachineNamed>::name_static(),
158        }
159    }
160
161    /// Drive one step. Records the transition + returns the
162    /// effect for the caller to dispatch.
163    ///
164    /// # Errors
165    /// [`MachineError`] wrapping `M::Err` if the step fails OR
166    /// `MachineError::Terminal` if attempted from a terminal state.
167    pub fn step(&mut self, event: M::Event) -> Result<M::Effect, MachineError<M::Err>> {
168        if M::is_terminal(&self.state) {
169            return Err(MachineError::Terminal);
170        }
171        let (next_state, effect) = M::step(&self.state, &event).map_err(MachineError::Step)?;
172        let from = self.state.clone();
173        self.history.push(TransitionRecord {
174            from,
175            event,
176            to: next_state.clone(),
177            at: self.clock.now(),
178        });
179        self.steps += 1;
180        self.trim_history();
181        self.state = next_state;
182        Ok(effect)
183    }
184
185    /// Current state (snapshot).
186    #[must_use]
187    pub fn state(&self) -> &M::State {
188        &self.state
189    }
190
191    /// True when current state is terminal.
192    #[must_use]
193    pub fn is_terminal(&self) -> bool {
194        M::is_terminal(&self.state)
195    }
196
197    /// The recorded transitions, oldest first (cloneable for replay):
198    /// every one, or the most recent [`Self::with_history_cap`] of them.
199    #[must_use]
200    pub fn history(&self) -> &[TransitionRecord<M::State, M::Event>] {
201        &self.history
202    }
203
204    /// Machine's telemetry name.
205    #[must_use]
206    pub fn name(&self) -> &'static str {
207        self.name
208    }
209
210    /// Step count: every transition ever taken, including any the history
211    /// cap has since dropped.
212    #[must_use]
213    pub fn step_count(&self) -> usize {
214        self.steps
215    }
216
217    /// Reset to initial state + clear history. Useful for tests.
218    pub fn reset(&mut self) {
219        self.state = M::initial();
220        self.history.clear();
221        self.steps = 0;
222    }
223}
224
225/// Observable snapshot of a `MachineRunner<M>` — current state +
226/// step count + telemetry name. Plug into a
227/// `mirante::ObservationChannel<MachineSnapshot<M::State>>` for
228/// live dashboards of FSM progress.
229#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
230pub struct MachineSnapshot<S> {
231    /// Machine telemetry name.
232    pub name: &'static str,
233    /// Current FSM state.
234    pub state: S,
235    /// Number of successful transitions to date.
236    pub step_count: usize,
237    /// Whether the current state is terminal.
238    pub is_terminal: bool,
239}
240
241crate::impl_named_field_generic!(MachineRunner, M: StateMachine);
242
243/// Pattern #2 (substrate self-consumption) — `MachineRunner<M>`
244/// is `Observable` so any FSM plugs directly into a mirante
245/// channel without a per-consumer adapter. v0.85 round.
246impl<M: StateMachine> crate::mirante::Observable for MachineRunner<M>
247where
248    M::State: Clone + serde::Serialize + Send + Sync + 'static,
249{
250    type Snapshot = MachineSnapshot<M::State>;
251
252    fn snapshot(&self) -> Self::Snapshot {
253        MachineSnapshot {
254            name: self.name,
255            state: self.state.clone(),
256            step_count: self.steps,
257            is_terminal: M::is_terminal(&self.state),
258        }
259    }
260}
261
262/// Errors a machine runner can surface.
263#[derive(Debug, thiserror::Error)]
264pub enum MachineError<E: crate::error_kind::ErrorKind + std::fmt::Debug> {
265    /// Wrapped step error from the machine's typed err.
266    #[error("step: {0:?}")]
267    Step(E),
268    /// Step attempted from a terminal state.
269    #[error("terminal: machine cannot step from a terminal state")]
270    Terminal,
271}
272
273impl<E: crate::error_kind::ErrorKind + std::fmt::Debug> crate::error_kind::ErrorKind
274    for MachineError<E>
275{
276    fn kind(&self) -> &'static str {
277        match self {
278            Self::Step(_) => "step",
279            Self::Terminal => "terminal",
280        }
281    }
282}
283
284/// Helper trait so `MachineRunner::new` can read the machine's
285/// telemetry name without an instance. Auto-implemented for any
286/// `Named + Default` type.
287pub trait MachineNamed: crate::named::Named {
288    /// Static name lookup — no instance needed.
289    fn name_static() -> &'static str;
290}
291
292impl<T: crate::named::Named + Default> MachineNamed for T {
293    fn name_static() -> &'static str {
294        let instance = Self::default();
295        instance.name()
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::relogio::FrozenClock;
303    use std::sync::Arc;
304    use thiserror::Error;
305
306    // ── Sample machine: door (Open / Closed / Locked) ──────────
307
308    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
309    pub enum DoorState {
310        Open,
311        Closed,
312        Locked,
313    }
314
315    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
316    #[allow(clippy::enum_variant_names)]
317    pub enum DoorEvent {
318        OpenIt,
319        CloseIt,
320        LockIt,
321        UnlockIt,
322    }
323
324    #[derive(Clone, Debug, PartialEq, Eq)]
325    pub enum DoorEffect {
326        Creak,
327        Slam,
328        Click,
329    }
330
331    #[derive(Debug, Clone, Error)]
332    pub enum DoorErr {
333        #[error("invalid transition from {state:?} on {event:?}")]
334        Invalid { state: String, event: String },
335    }
336
337    crate::impl_error_kind! {
338        DoorErr {
339            { Invalid { .. } } => "invalid_transition",
340        }
341    }
342
343    #[derive(Default)]
344    pub struct DoorMachine;
345
346    crate::define_named!(DoorMachine, "door");
347
348    impl StateMachine for DoorMachine {
349        type State = DoorState;
350        type Event = DoorEvent;
351        type Effect = DoorEffect;
352        type Err = DoorErr;
353
354        fn initial() -> DoorState {
355            DoorState::Closed
356        }
357
358        fn step(state: &DoorState, event: &DoorEvent) -> Result<(DoorState, DoorEffect), DoorErr> {
359            match (state, event) {
360                (DoorState::Closed, DoorEvent::OpenIt) => Ok((DoorState::Open, DoorEffect::Creak)),
361                (DoorState::Open, DoorEvent::CloseIt) => Ok((DoorState::Closed, DoorEffect::Slam)),
362                (DoorState::Closed, DoorEvent::LockIt) => {
363                    Ok((DoorState::Locked, DoorEffect::Click))
364                }
365                (DoorState::Locked, DoorEvent::UnlockIt) => {
366                    Ok((DoorState::Closed, DoorEffect::Click))
367                }
368                _ => Err(DoorErr::Invalid {
369                    state: format!("{state:?}"),
370                    event: format!("{event:?}"),
371                }),
372            }
373        }
374
375        fn is_terminal(_state: &DoorState) -> bool {
376            false // door FSM has no terminals
377        }
378    }
379
380    fn make_runner() -> MachineRunner<DoorMachine> {
381        MachineRunner::new(Arc::new(FrozenClock::at(100)))
382    }
383
384    #[test]
385    fn initial_state_is_closed() {
386        let r = make_runner();
387        assert_eq!(r.state(), &DoorState::Closed);
388    }
389
390    #[test]
391    fn step_advances_state() {
392        let mut r = make_runner();
393        let effect = r.step(DoorEvent::OpenIt).unwrap();
394        assert_eq!(effect, DoorEffect::Creak);
395        assert_eq!(r.state(), &DoorState::Open);
396    }
397
398    #[test]
399    fn step_records_transition() {
400        let mut r = make_runner();
401        r.step(DoorEvent::OpenIt).unwrap();
402        assert_eq!(r.step_count(), 1);
403        let h = r.history();
404        assert_eq!(h[0].from, DoorState::Closed);
405        assert_eq!(h[0].event, DoorEvent::OpenIt);
406        assert_eq!(h[0].to, DoorState::Open);
407    }
408
409    #[test]
410    fn invalid_transition_returns_error() {
411        let mut r = make_runner();
412        // Closed + UnlockIt is invalid.
413        let err = r.step(DoorEvent::UnlockIt).unwrap_err();
414        assert!(matches!(err, MachineError::Step(_)), "expected step error");
415        // State unchanged + no history.
416        assert_eq!(r.state(), &DoorState::Closed);
417        assert_eq!(r.step_count(), 0);
418    }
419
420    #[test]
421    fn machine_error_kind_is_stable() {
422        use crate::error_kind::ErrorKind;
423        let e: MachineError<DoorErr> = MachineError::Step(DoorErr::Invalid {
424            state: "x".into(),
425            event: "y".into(),
426        });
427        assert_eq!(e.kind(), "step");
428        let t: MachineError<DoorErr> = MachineError::Terminal;
429        assert_eq!(t.kind(), "terminal");
430    }
431
432    #[test]
433    fn full_state_walk() {
434        let mut r = make_runner();
435        r.step(DoorEvent::OpenIt).unwrap();
436        assert_eq!(r.state(), &DoorState::Open);
437        r.step(DoorEvent::CloseIt).unwrap();
438        assert_eq!(r.state(), &DoorState::Closed);
439        r.step(DoorEvent::LockIt).unwrap();
440        assert_eq!(r.state(), &DoorState::Locked);
441        r.step(DoorEvent::UnlockIt).unwrap();
442        assert_eq!(r.state(), &DoorState::Closed);
443        assert_eq!(r.step_count(), 4);
444    }
445
446    #[test]
447    fn reset_clears_history_and_state() {
448        let mut r = make_runner();
449        r.step(DoorEvent::OpenIt).unwrap();
450        r.step(DoorEvent::CloseIt).unwrap();
451        r.reset();
452        assert_eq!(r.state(), &DoorState::Closed);
453        assert_eq!(r.step_count(), 0);
454    }
455
456    #[test]
457    fn a_capped_history_keeps_the_most_recent_and_still_counts_every_step() {
458        let mut r = make_runner().with_history_cap(std::num::NonZeroUsize::new(2).unwrap());
459        for _ in 0..5 {
460            r.step(DoorEvent::OpenIt).unwrap();
461            r.step(DoorEvent::CloseIt).unwrap();
462        }
463        assert_eq!(r.step_count(), 10, "the count includes dropped transitions");
464        let h = r.history();
465        assert_eq!(h.len(), 2, "only the cap's worth is kept");
466        assert_eq!(h[0].event, DoorEvent::OpenIt, "oldest kept first");
467        assert_eq!(h[1].event, DoorEvent::CloseIt);
468        assert_eq!(h[1].to, DoorState::Closed, "the newest is the last taken");
469    }
470
471    #[test]
472    fn from_state_starts_at_explicit_state() {
473        let r: MachineRunner<DoorMachine> =
474            MachineRunner::from_state(DoorState::Locked, Arc::new(FrozenClock::at(0)));
475        assert_eq!(r.state(), &DoorState::Locked);
476    }
477
478    #[test]
479    fn name_passes_through() {
480        let r = make_runner();
481        assert_eq!(r.name(), "door");
482    }
483
484    #[test]
485    fn frozen_clock_yields_same_instant_for_all_transitions() {
486        let mut r = make_runner();
487        r.step(DoorEvent::OpenIt).unwrap();
488        r.step(DoorEvent::CloseIt).unwrap();
489        let h = r.history();
490        // Same FrozenClock instance → both transitions at the same Instant.
491        assert_eq!(h[0].at, h[1].at);
492    }
493
494    #[test]
495    fn step_with_advancing_clock_records_distinct_instants() {
496        let clock = Arc::new(FrozenClock::at(100));
497        let mut r = MachineRunner::<DoorMachine>::new(clock.clone());
498        r.step(DoorEvent::OpenIt).unwrap();
499        clock.advance(10);
500        r.step(DoorEvent::CloseIt).unwrap();
501        let h = r.history();
502        assert!(h[1].at > h[0].at);
503    }
504
505    // ── Terminal-state machine ──────────────────────────────────
506
507    #[derive(Default)]
508    pub struct OneShotMachine;
509    crate::define_named!(OneShotMachine, "one-shot");
510
511    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
512    pub enum OneShotState {
513        Pending,
514        Done,
515    }
516
517    #[derive(Clone, Debug, Serialize, Deserialize)]
518    pub struct OneShotEvent;
519
520    impl StateMachine for OneShotMachine {
521        type State = OneShotState;
522        type Event = OneShotEvent;
523        type Effect = ();
524        type Err = DoorErr;
525
526        fn initial() -> OneShotState {
527            OneShotState::Pending
528        }
529
530        fn step(
531            _state: &OneShotState,
532            _event: &OneShotEvent,
533        ) -> Result<(OneShotState, ()), DoorErr> {
534            Ok((OneShotState::Done, ()))
535        }
536
537        fn is_terminal(state: &OneShotState) -> bool {
538            matches!(state, OneShotState::Done)
539        }
540    }
541
542    #[test]
543    fn step_from_terminal_returns_terminal_error() {
544        let mut r: MachineRunner<OneShotMachine> = MachineRunner::new(Arc::new(FrozenClock::at(0)));
545        r.step(OneShotEvent).unwrap(); // Pending -> Done
546        assert!(r.is_terminal());
547        let err = r.step(OneShotEvent).unwrap_err();
548        assert!(matches!(err, MachineError::Terminal), "expected Terminal");
549        // No transition recorded for the failed terminal step.
550        assert_eq!(r.step_count(), 1);
551    }
552
553    #[test]
554    fn transition_record_round_trips_via_serde() {
555        let r = TransitionRecord {
556            from: DoorState::Closed,
557            event: DoorEvent::OpenIt,
558            to: DoorState::Open,
559            at: Instant::new(100, 5),
560        };
561        let bytes = serde_json::to_vec(&r).unwrap();
562        let back: TransitionRecord<DoorState, DoorEvent> = serde_json::from_slice(&bytes).unwrap();
563        assert_eq!(back, r);
564    }
565}