engenho-substrate 0.53.161

engenho-substrate — the substrate leaf: every module a shipped engenho crate references (derivations and caches, receipts, quorum, ledgers, verifiers, rollout gates, freshness, owned tasks), with engenho-substrate-core re-exported whole so every engenho_substrate:: path keeps resolving.
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! máquina — typed FSM primitive.
//!
//! Per the research brief — MEDIUM-leverage inventive primitive.
//! The substrate has multiple ad-hoc state machines (Plantio
//! stage state, Transient lifecycle, QuorumState enum, search
//! Ensaio status) hand-rolled with match statements + bare
//! enums. máquina folds them into one typed surface.
//!
//! ## Surface
//!
//!   - `StateMachine` trait — pure step function
//!     `(state, event) -> (state, effect)`
//!   - `MachineRunner<M>` — drives steps, holds current state,
//!     records every transition into a typed history Vec
//!   - `TransitionRecord<M>` — typed (from, event, to, at: Instant)
//!     for replay/audit
//!
//! ## What this collapses
//!
//! Today: every controller hand-rolls its FSM with bespoke enum
//! matching, scattered transition logic, no transition history.
//!
//! Tomorrow: every controller's FSM lifts into a `MachineRunner`,
//! gains free transition recording + replay + fingerprinting via
//! the existing trait surfaces.
//!
//! ## Composition
//!
//!   - `Named` supertrait → every machine has telemetry name
//!   - `relógio::Instant` for transition timestamps
//!   - `Fingerprint` over State + Event (caller supplies)
//!   - `ErrorKind` on M::Err

use serde::{Deserialize, Serialize};

use crate::relogio::Instant;

/// Typed finite-state-machine surface. Implementers supply:
///   - `State`: the machine's state (Clone + Serialize + Eq)
///   - `Event`: input events (Clone + Serialize)
///   - `Effect`: side-effects the step requests be performed
///     by the runner's consumer (telemetry, log line, action)
///   - `Err`: error type — must implement ErrorKind
///
/// The step function is PURE — no I/O, no side effects beyond
/// returning the Effect for the runner to dispatch. This is what
/// makes replay possible.
pub trait StateMachine: crate::named::Named + Default + Send + Sync {
    /// The state type — must be cloneable + comparable + serdeable.
    type State: Clone + Eq + Serialize + Send + Sync;

    /// The event type — input that drives transitions.
    type Event: Clone + Serialize + Send + Sync;

    /// The effect type — side-effects the runner's consumer
    /// dispatches (logging, telemetry, downstream calls).
    type Effect: Clone + Send + Sync;

    /// The error type — typed step failures (invalid event for
    /// current state, etc.).
    type Err: crate::error_kind::ErrorKind + Send + Sync + std::fmt::Debug;

    /// Initial state when the runner spawns.
    fn initial() -> Self::State;

    /// Pure step: given a state + event, return the next state +
    /// effect. Pure — no I/O, no side effects.
    ///
    /// # Errors
    /// [`Self::Err`] when the event isn't valid for the current state.
    fn step(
        state: &Self::State,
        event: &Self::Event,
    ) -> Result<(Self::State, Self::Effect), Self::Err>;

    /// True if `state` is a terminal state. The runner refuses to
    /// step from a terminal state.
    fn is_terminal(state: &Self::State) -> bool;
}

/// One typed record of a transition. Serializable for replay +
/// fingerprintable for cross-node attestation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionRecord<S, E> {
    /// State the machine was in before the event.
    pub from: S,
    /// Event that drove the transition.
    pub event: E,
    /// State the machine ended up in.
    pub to: S,
    /// When the transition happened (clock-injected).
    pub at: Instant,
}

/// Runner that owns one machine + drives steps + accumulates
/// the transition history.
///
/// The history is unbounded unless capped with
/// [`Self::with_history_cap`]. A runner that lives as long as a daemon —
/// a lifecycle stepping on every retry of a failing boot, for months —
/// must cap it, or the history is a leak with a clean conscience.
pub struct MachineRunner<M: StateMachine> {
    state: M::State,
    history: Vec<TransitionRecord<M::State, M::Event>>,
    /// Keep at most this many of the most recent transitions.
    history_cap: Option<std::num::NonZeroUsize>,
    /// Every transition ever taken, including those the cap dropped.
    steps: usize,
    clock: std::sync::Arc<dyn crate::relogio::Clock>,
    name: &'static str,
}

impl<M: StateMachine> MachineRunner<M> {
    /// New runner with the machine's initial state + a clock
    /// (operator picks `WallClock` / `FrozenClock` / etc).
    #[must_use]
    pub fn new(clock: std::sync::Arc<dyn crate::relogio::Clock>) -> Self {
        Self {
            state: M::initial(),
            history: Vec::new(),
            history_cap: None,
            steps: 0,
            clock,
            name: <M as MachineNamed>::name_static(),
        }
    }

    /// Keep only the `cap` most recent transitions. [`Self::step_count`]
    /// still counts every transition ever taken.
    #[must_use]
    pub fn with_history_cap(mut self, cap: std::num::NonZeroUsize) -> Self {
        self.history_cap = Some(cap);
        self.trim_history();
        self
    }

    /// Drop the oldest transitions beyond the cap, if any.
    fn trim_history(&mut self) {
        if let Some(cap) = self.history_cap {
            let excess = self.history.len().saturating_sub(cap.get());
            if excess > 0 {
                self.history.drain(..excess);
            }
        }
    }

    /// New runner starting from an explicit state. Useful for
    /// reconstruction / replay tests.
    #[must_use]
    pub fn from_state(state: M::State, clock: std::sync::Arc<dyn crate::relogio::Clock>) -> Self {
        Self {
            state,
            history_cap: None,
            steps: 0,
            history: Vec::new(),
            clock,
            name: <M as MachineNamed>::name_static(),
        }
    }

    /// Drive one step. Records the transition + returns the
    /// effect for the caller to dispatch.
    ///
    /// # Errors
    /// [`MachineError`] wrapping `M::Err` if the step fails OR
    /// `MachineError::Terminal` if attempted from a terminal state.
    pub fn step(&mut self, event: M::Event) -> Result<M::Effect, MachineError<M::Err>> {
        if M::is_terminal(&self.state) {
            return Err(MachineError::Terminal);
        }
        let (next_state, effect) = M::step(&self.state, &event).map_err(MachineError::Step)?;
        let from = self.state.clone();
        self.history.push(TransitionRecord {
            from,
            event,
            to: next_state.clone(),
            at: self.clock.now(),
        });
        self.steps += 1;
        self.trim_history();
        self.state = next_state;
        Ok(effect)
    }

    /// Current state (snapshot).
    #[must_use]
    pub fn state(&self) -> &M::State {
        &self.state
    }

    /// True when current state is terminal.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        M::is_terminal(&self.state)
    }

    /// The recorded transitions, oldest first (cloneable for replay):
    /// every one, or the most recent [`Self::with_history_cap`] of them.
    #[must_use]
    pub fn history(&self) -> &[TransitionRecord<M::State, M::Event>] {
        &self.history
    }

    /// Machine's telemetry name.
    #[must_use]
    pub fn name(&self) -> &'static str {
        self.name
    }

    /// Step count: every transition ever taken, including any the history
    /// cap has since dropped.
    #[must_use]
    pub fn step_count(&self) -> usize {
        self.steps
    }

    /// Reset to initial state + clear history. Useful for tests.
    pub fn reset(&mut self) {
        self.state = M::initial();
        self.history.clear();
        self.steps = 0;
    }
}

/// Observable snapshot of a `MachineRunner<M>` — current state +
/// step count + telemetry name. Plug into a
/// `mirante::ObservationChannel<MachineSnapshot<M::State>>` for
/// live dashboards of FSM progress.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct MachineSnapshot<S> {
    /// Machine telemetry name.
    pub name: &'static str,
    /// Current FSM state.
    pub state: S,
    /// Number of successful transitions to date.
    pub step_count: usize,
    /// Whether the current state is terminal.
    pub is_terminal: bool,
}

crate::impl_named_field_generic!(MachineRunner, M: StateMachine);

/// Pattern #2 (substrate self-consumption) — `MachineRunner<M>`
/// is `Observable` so any FSM plugs directly into a mirante
/// channel without a per-consumer adapter. v0.85 round.
impl<M: StateMachine> crate::mirante::Observable for MachineRunner<M>
where
    M::State: Clone + serde::Serialize + Send + Sync + 'static,
{
    type Snapshot = MachineSnapshot<M::State>;

    fn snapshot(&self) -> Self::Snapshot {
        MachineSnapshot {
            name: self.name,
            state: self.state.clone(),
            step_count: self.steps,
            is_terminal: M::is_terminal(&self.state),
        }
    }
}

/// Errors a machine runner can surface.
#[derive(Debug, thiserror::Error)]
pub enum MachineError<E: crate::error_kind::ErrorKind + std::fmt::Debug> {
    /// Wrapped step error from the machine's typed err.
    #[error("step: {0:?}")]
    Step(E),
    /// Step attempted from a terminal state.
    #[error("terminal: machine cannot step from a terminal state")]
    Terminal,
}

impl<E: crate::error_kind::ErrorKind + std::fmt::Debug> crate::error_kind::ErrorKind
    for MachineError<E>
{
    fn kind(&self) -> &'static str {
        match self {
            Self::Step(_) => "step",
            Self::Terminal => "terminal",
        }
    }
}

/// Helper trait so `MachineRunner::new` can read the machine's
/// telemetry name without an instance. Auto-implemented for any
/// `Named + Default` type.
pub trait MachineNamed: crate::named::Named {
    /// Static name lookup — no instance needed.
    fn name_static() -> &'static str;
}

impl<T: crate::named::Named + Default> MachineNamed for T {
    fn name_static() -> &'static str {
        let instance = Self::default();
        instance.name()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::relogio::FrozenClock;
    use std::sync::Arc;
    use thiserror::Error;

    // ── Sample machine: door (Open / Closed / Locked) ──────────

    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    pub enum DoorState {
        Open,
        Closed,
        Locked,
    }

    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    pub enum DoorEvent {
        OpenIt,
        CloseIt,
        LockIt,
        UnlockIt,
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    pub enum DoorEffect {
        Creak,
        Slam,
        Click,
    }

    #[derive(Debug, Clone, Error)]
    pub enum DoorErr {
        #[error("invalid transition from {state:?} on {event:?}")]
        Invalid { state: String, event: String },
    }

    crate::impl_error_kind! {
        DoorErr {
            { Invalid { .. } } => "invalid_transition",
        }
    }

    #[derive(Default)]
    pub struct DoorMachine;

    crate::define_named!(DoorMachine, "door");

    impl StateMachine for DoorMachine {
        type State = DoorState;
        type Event = DoorEvent;
        type Effect = DoorEffect;
        type Err = DoorErr;

        fn initial() -> DoorState {
            DoorState::Closed
        }

        fn step(state: &DoorState, event: &DoorEvent) -> Result<(DoorState, DoorEffect), DoorErr> {
            match (state, event) {
                (DoorState::Closed, DoorEvent::OpenIt) => Ok((DoorState::Open, DoorEffect::Creak)),
                (DoorState::Open, DoorEvent::CloseIt) => Ok((DoorState::Closed, DoorEffect::Slam)),
                (DoorState::Closed, DoorEvent::LockIt) => {
                    Ok((DoorState::Locked, DoorEffect::Click))
                }
                (DoorState::Locked, DoorEvent::UnlockIt) => {
                    Ok((DoorState::Closed, DoorEffect::Click))
                }
                _ => Err(DoorErr::Invalid {
                    state: format!("{state:?}"),
                    event: format!("{event:?}"),
                }),
            }
        }

        fn is_terminal(_state: &DoorState) -> bool {
            false // door FSM has no terminals
        }
    }

    fn make_runner() -> MachineRunner<DoorMachine> {
        MachineRunner::new(Arc::new(FrozenClock::at(100)))
    }

    #[test]
    fn initial_state_is_closed() {
        let r = make_runner();
        assert_eq!(r.state(), &DoorState::Closed);
    }

    #[test]
    fn step_advances_state() {
        let mut r = make_runner();
        let effect = r.step(DoorEvent::OpenIt).unwrap();
        assert_eq!(effect, DoorEffect::Creak);
        assert_eq!(r.state(), &DoorState::Open);
    }

    #[test]
    fn step_records_transition() {
        let mut r = make_runner();
        r.step(DoorEvent::OpenIt).unwrap();
        assert_eq!(r.step_count(), 1);
        let h = r.history();
        assert_eq!(h[0].from, DoorState::Closed);
        assert_eq!(h[0].event, DoorEvent::OpenIt);
        assert_eq!(h[0].to, DoorState::Open);
    }

    #[test]
    fn invalid_transition_returns_error() {
        let mut r = make_runner();
        // Closed + UnlockIt is invalid.
        let err = r.step(DoorEvent::UnlockIt).unwrap_err();
        match err {
            MachineError::Step(_) => {}
            _ => panic!("expected step error"),
        }
        // State unchanged + no history.
        assert_eq!(r.state(), &DoorState::Closed);
        assert_eq!(r.step_count(), 0);
    }

    #[test]
    fn machine_error_kind_is_stable() {
        use crate::error_kind::ErrorKind;
        let e: MachineError<DoorErr> = MachineError::Step(DoorErr::Invalid {
            state: "x".into(),
            event: "y".into(),
        });
        assert_eq!(e.kind(), "step");
        let t: MachineError<DoorErr> = MachineError::Terminal;
        assert_eq!(t.kind(), "terminal");
    }

    #[test]
    fn full_state_walk() {
        let mut r = make_runner();
        r.step(DoorEvent::OpenIt).unwrap();
        assert_eq!(r.state(), &DoorState::Open);
        r.step(DoorEvent::CloseIt).unwrap();
        assert_eq!(r.state(), &DoorState::Closed);
        r.step(DoorEvent::LockIt).unwrap();
        assert_eq!(r.state(), &DoorState::Locked);
        r.step(DoorEvent::UnlockIt).unwrap();
        assert_eq!(r.state(), &DoorState::Closed);
        assert_eq!(r.step_count(), 4);
    }

    #[test]
    fn reset_clears_history_and_state() {
        let mut r = make_runner();
        r.step(DoorEvent::OpenIt).unwrap();
        r.step(DoorEvent::CloseIt).unwrap();
        r.reset();
        assert_eq!(r.state(), &DoorState::Closed);
        assert_eq!(r.step_count(), 0);
    }

    #[test]
    fn a_capped_history_keeps_the_most_recent_and_still_counts_every_step() {
        let mut r = make_runner().with_history_cap(std::num::NonZeroUsize::new(2).unwrap());
        for _ in 0..5 {
            r.step(DoorEvent::OpenIt).unwrap();
            r.step(DoorEvent::CloseIt).unwrap();
        }
        assert_eq!(r.step_count(), 10, "the count includes dropped transitions");
        let h = r.history();
        assert_eq!(h.len(), 2, "only the cap's worth is kept");
        assert_eq!(h[0].event, DoorEvent::OpenIt, "oldest kept first");
        assert_eq!(h[1].event, DoorEvent::CloseIt);
        assert_eq!(h[1].to, DoorState::Closed, "the newest is the last taken");
    }

    #[test]
    fn from_state_starts_at_explicit_state() {
        let r: MachineRunner<DoorMachine> =
            MachineRunner::from_state(DoorState::Locked, Arc::new(FrozenClock::at(0)));
        assert_eq!(r.state(), &DoorState::Locked);
    }

    #[test]
    fn name_passes_through() {
        let r = make_runner();
        assert_eq!(r.name(), "door");
    }

    #[test]
    fn frozen_clock_yields_same_instant_for_all_transitions() {
        let mut r = make_runner();
        r.step(DoorEvent::OpenIt).unwrap();
        r.step(DoorEvent::CloseIt).unwrap();
        let h = r.history();
        // Same FrozenClock instance → both transitions at the same Instant.
        assert_eq!(h[0].at, h[1].at);
    }

    #[test]
    fn step_with_advancing_clock_records_distinct_instants() {
        let clock = Arc::new(FrozenClock::at(100));
        let mut r = MachineRunner::<DoorMachine>::new(clock.clone());
        r.step(DoorEvent::OpenIt).unwrap();
        clock.advance(10);
        r.step(DoorEvent::CloseIt).unwrap();
        let h = r.history();
        assert!(h[1].at > h[0].at);
    }

    // ── Terminal-state machine ──────────────────────────────────

    #[derive(Default)]
    pub struct OneShotMachine;
    crate::define_named!(OneShotMachine, "one-shot");

    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    pub enum OneShotState {
        Pending,
        Done,
    }

    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct OneShotEvent;

    impl StateMachine for OneShotMachine {
        type State = OneShotState;
        type Event = OneShotEvent;
        type Effect = ();
        type Err = DoorErr;

        fn initial() -> OneShotState {
            OneShotState::Pending
        }

        fn step(
            _state: &OneShotState,
            _event: &OneShotEvent,
        ) -> Result<(OneShotState, ()), DoorErr> {
            Ok((OneShotState::Done, ()))
        }

        fn is_terminal(state: &OneShotState) -> bool {
            matches!(state, OneShotState::Done)
        }
    }

    #[test]
    fn step_from_terminal_returns_terminal_error() {
        let mut r: MachineRunner<OneShotMachine> = MachineRunner::new(Arc::new(FrozenClock::at(0)));
        r.step(OneShotEvent).unwrap(); // Pending -> Done
        assert!(r.is_terminal());
        let err = r.step(OneShotEvent).unwrap_err();
        match err {
            MachineError::Terminal => {}
            _ => panic!("expected Terminal"),
        }
        // No transition recorded for the failed terminal step.
        assert_eq!(r.step_count(), 1);
    }

    #[test]
    fn transition_record_round_trips_via_serde() {
        let r = TransitionRecord {
            from: DoorState::Closed,
            event: DoorEvent::OpenIt,
            to: DoorState::Open,
            at: Instant::new(100, 5),
        };
        let bytes = serde_json::to_vec(&r).unwrap();
        let back: TransitionRecord<DoorState, DoorEvent> = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(back, r);
    }
}