engenho-substrate 0.53.141

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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! mirante — typed live-state observation channel.
//!
//! Per the research brief — operator-dashboard primitive.
//! Different from `BroadcastLedger` (event-stream, every event
//! delivered). Different from logs (typed S, not text).
//!
//! Every substrate primitive that has observable state publishes
//! a typed `Snapshot` via `ObservationChannel`. Operators wire one
//! channel per primitive; a single `Mirante` registry surfaces them
//! all for dashboards / TUIs / health-check endpoints.
//!
//! ## Surface
//!
//!   - `Observable` trait — `fn snapshot(&self) -> Self::Snapshot`
//!   - `ObservationChannel<S>` — typed `watch::Sender` wrapper
//!   - `Mirante` registry — keyed by `&'static str` name
//!
//! ## Composition
//!
//!   - `Named` supertrait on Observable
//!   - `Fingerprint` over Snapshot for cross-node attestation
//!   - `relógio::Instant` for last-changed timestamps
//!   - `Serialize` on Snapshot so registry can render to JSON

use std::collections::BTreeMap;
use std::sync::Arc;

use serde::Serialize;
use tokio::sync::{RwLock, watch};

use crate::named::Named;
use crate::relogio::{Clock, Instant};

/// Canonical snapshot shape for substrate wrappers that own a
/// broadcast channel — captures the operator-facing observability
/// (name + currently-active subscribers). Third-site extraction
/// (v0.87 TSR): `BroadcastLedger`, `WatchedCache`, `FakeGossipTransport`
/// all return this from their `Observable::snapshot()`.
///
/// If a future subscriber-having primitive needs more fields, add
/// them here (every consumer benefits) rather than forking a new
/// shape.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SubscriberSnapshot {
    /// Telemetry name of the underlying wrapper.
    pub name: &'static str,
    /// Currently-active subscribers on the broadcast channel.
    pub subscriber_count: usize,
}

/// Canonical snapshot for substrate wrappers that compose N
/// children — captures name + child count. Third-site extraction
/// (v0.91 TSR): `TieredCache`, `CompositeShapeRenderer`,
/// `ChainedVerifier` all return this from `Observable::snapshot()`.
///
/// Sibling to [`SubscriberSnapshot`]; both standardize the
/// wrapper-with-N pattern at the snapshot layer.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ChildCountSnapshot {
    /// Telemetry name of the wrapper.
    pub name: &'static str,
    /// Number of children currently composed.
    pub child_count: usize,
}

/// Generate an `impl Observable for $Type` that builds a
/// [`SubscriberSnapshot`] inline by calling `self.subscriber_count()`.
/// Third-site extraction (v0.95 TSR): `BroadcastLedger`,
/// `WatchedCache`, `FakeGossipTransport` all shared this exact shape.
///
/// Required: `$type` already impls `Named` + has an inherent
/// `subscriber_count(&self) -> usize` method.
///
/// ## Usage
///
/// ```ignore
/// use engenho_substrate::impl_observable_subscriber;
///
/// impl Foo {
///     pub fn subscriber_count(&self) -> usize { ... }
/// }
///
/// impl_observable_subscriber!(Foo, "foo");
/// ```
#[macro_export]
macro_rules! impl_observable_subscriber {
    ($type:ty, $name:literal) => {
        impl $crate::mirante::Observable for $type {
            type Snapshot = $crate::mirante::SubscriberSnapshot;
            fn snapshot(&self) -> Self::Snapshot {
                $crate::mirante::SubscriberSnapshot {
                    name: $name,
                    subscriber_count: self.subscriber_count(),
                }
            }
        }
    };
}

/// Generate an `impl Observable for $Type` that delegates to the
/// type's inherent `snapshot()` method. Pattern #1 (TSR) extraction
/// v0.92 — `Budget`, `TieredCache`, `CompositeShapeRenderer`,
/// `ChainedVerifier` all shared the exact same 5-line delegation
/// shape.
///
/// ## Usage
///
/// ```ignore
/// use engenho_substrate::impl_observable;
///
/// impl Foo {
///     pub fn snapshot(&self) -> FooSnapshot { ... }
/// }
///
/// impl_observable!(Foo, FooSnapshot);
/// ```
///
/// Expands to:
///
/// ```ignore
/// impl engenho_substrate::mirante::Observable for Foo {
///     type Snapshot = FooSnapshot;
///     fn snapshot(&self) -> Self::Snapshot {
///         Self::snapshot(self)
///     }
/// }
/// ```
///
/// Requires the type to already impl `Named` + have an inherent
/// `snapshot()` method. Generic types (e.g. `MachineRunner<M>`) +
/// types that build the snapshot inline (e.g. `Mirante`,
/// `SubscriberSnapshot`-returning wrappers) keep their hand-rolled
/// impls.
#[macro_export]
macro_rules! impl_observable {
    ($type:ty, $snapshot:ty) => {
        impl $crate::mirante::Observable for $type {
            type Snapshot = $snapshot;
            fn snapshot(&self) -> Self::Snapshot {
                Self::snapshot(self)
            }
        }
    };
}

/// Universal observable surface. Every substrate primitive that
/// has live state worth observing implements this trait.
pub trait Observable: Named + Send + Sync {
    /// The snapshot type — must be cloneable + serializable +
    /// shareable across tasks.
    type Snapshot: Clone + Serialize + Send + Sync + 'static;

    /// Capture the current state (cheap; no I/O). Operators call
    /// this once per channel publish.
    fn snapshot(&self) -> Self::Snapshot;
}

/// Typed live-state channel. Wraps `tokio::sync::watch` + tracks
/// the last-changed Instant.
pub struct ObservationChannel<S: Clone + Send + Sync + 'static> {
    tx: watch::Sender<S>,
    rx: watch::Receiver<S>,
    last_changed: Arc<RwLock<Instant>>,
    clock: Arc<dyn Clock>,
}

impl<S: Clone + Send + Sync + 'static> ObservationChannel<S> {
    /// New channel with an initial snapshot + clock for timestamps.
    #[must_use]
    pub fn new(initial: S, clock: Arc<dyn Clock>) -> Self {
        let (tx, rx) = watch::channel(initial);
        let last_changed = Arc::new(RwLock::new(clock.now()));
        Self {
            tx,
            rx,
            last_changed,
            clock,
        }
    }

    /// Publish a new snapshot. The current value is replaced (last-
    /// value-only — older snapshots are NOT queued).
    pub fn publish(&self, next: S) {
        let _ = self.tx.send(next);
        let now = self.clock.now();
        if let Ok(mut guard) = self.last_changed.try_write() {
            *guard = now;
        }
    }

    /// Current snapshot (cheap; reads `watch::Receiver::borrow()`).
    #[must_use]
    pub fn current(&self) -> S {
        self.rx.borrow().clone()
    }

    /// Subscribe to changes — every publish wakes the receiver.
    /// (Last-value-only: a slow subscriber sees the LATEST value,
    /// not every intermediate.)
    #[must_use]
    pub fn subscribe(&self) -> watch::Receiver<S> {
        self.rx.clone()
    }

    /// When the channel was last published.
    pub async fn last_changed(&self) -> Instant {
        *self.last_changed.read().await
    }

    /// Currently-active subscriber count.
    #[must_use]
    pub fn subscriber_count(&self) -> usize {
        self.tx.receiver_count()
    }
}

/// ObservationChannel impl Named + Observable (v1.04 SSC) —
/// completes the SubscriberSnapshot family by exposing the
/// channel itself as observable. Joins BroadcastLedger +
/// WatchedCache + FakeGossipTransport as the 4th SubscriberSnapshot
/// consumer.
///
/// Hand-rolled (not `define_named!` / `impl_observable_subscriber!`)
/// because S has multi-bound generic shape (`Clone + Send + Sync +
/// '`static`) that the existing macros don't fit. 2nd site of
/// "literal-name multi-bound generic" — TSR clock at 2/3.
impl<S: Clone + Send + Sync + 'static> Named for ObservationChannel<S> {
    fn name(&self) -> &'static str {
        "observation-channel"
    }
}

impl<S: Clone + Send + Sync + 'static> Observable for ObservationChannel<S> {
    type Snapshot = SubscriberSnapshot;

    fn snapshot(&self) -> Self::Snapshot {
        SubscriberSnapshot {
            name: "observation-channel",
            subscriber_count: self.subscriber_count(),
        }
    }
}

/// Type-erased view onto an `ObservationChannel<S>` for the
/// `Mirante` registry. Operators reach for the concrete channel
/// when they know the type; the registry exposes the universal
/// "current snapshot as JSON" surface.
pub trait AnyChannel: Send + Sync {
    /// Channel name (telemetry identifier).
    fn name(&self) -> &'static str;

    /// Current snapshot rendered as JSON. Used by the registry's
    /// `snapshot_all()` for dashboard rendering.
    fn current_json(&self) -> serde_json::Value;

    /// Last-changed Instant (cheap).
    fn last_changed_packed(&self) -> u64;
}

impl<S: Clone + Serialize + Send + Sync + 'static> AnyChannel
    for (&'static str, Arc<ObservationChannel<S>>)
{
    fn name(&self) -> &'static str {
        self.0
    }

    fn current_json(&self) -> serde_json::Value {
        serde_json::to_value(self.1.current()).unwrap_or(serde_json::Value::Null)
    }

    fn last_changed_packed(&self) -> u64 {
        // Use try_read to avoid blocking from sync context.
        match self.1.last_changed.try_read() {
            Ok(guard) => guard.to_packed(),
            Err(_) => 0,
        }
    }
}

/// The mirante registry — operator wires one per process. Every
/// observable primitive registers its channel; dashboards iterate
/// the registry to render live state.
#[derive(Default)]
pub struct Mirante {
    channels: BTreeMap<&'static str, Arc<dyn AnyChannel>>,
}

impl Mirante {
    /// Fresh empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a typed channel under `name`. Replaces any prior
    /// channel with the same name.
    pub fn register<S: Clone + Serialize + Send + Sync + 'static>(
        &mut self,
        name: &'static str,
        channel: Arc<ObservationChannel<S>>,
    ) {
        let any: Arc<dyn AnyChannel> = Arc::new((name, channel));
        self.channels.insert(name, any);
    }

    /// Names of all registered channels.
    #[must_use]
    pub fn list(&self) -> Vec<&'static str> {
        self.channels.keys().copied().collect()
    }

    /// Count of registered channels.
    #[must_use]
    pub fn len(&self) -> usize {
        self.channels.len()
    }

    /// True if no channels registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.channels.is_empty()
    }

    /// Snapshot every channel as JSON. Useful for one-shot
    /// dashboard rendering.
    #[must_use]
    pub fn snapshot_all(&self) -> BTreeMap<String, serde_json::Value> {
        self.channels
            .iter()
            .map(|(name, ch)| ((*name).to_string(), ch.current_json()))
            .collect()
    }

    /// Last-changed timestamps for every channel.
    #[must_use]
    pub fn last_changed_all(&self) -> BTreeMap<String, u64> {
        self.channels
            .iter()
            .map(|(name, ch)| ((*name).to_string(), ch.last_changed_packed()))
            .collect()
    }
}

/// Observable snapshot of a `Mirante` registry — channel count +
/// channel names. Pattern #2 (substrate self-consumption, v0.90):
/// the mirante registry now observes ITSELF. A meta-Mirante can
/// register the primary registry and report on registry-level
/// liveness alongside per-channel state.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MiranteSnapshot {
    /// Telemetry name ("mirante").
    pub name: &'static str,
    /// Number of registered channels.
    pub channel_count: usize,
    /// Names of registered channels (sorted by BTreeMap iteration).
    pub channel_names: Vec<String>,
}

crate::define_named!(Mirante, "mirante");

impl Observable for Mirante {
    type Snapshot = MiranteSnapshot;

    fn snapshot(&self) -> Self::Snapshot {
        MiranteSnapshot {
            name: "mirante",
            channel_count: self.len(),
            channel_names: self.channels.keys().map(|s| (*s).to_string()).collect(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::relogio::FrozenClock;
    use serde::Deserialize;

    #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
    pub struct CacheStats {
        hits: u64,
        misses: u64,
    }

    fn frozen_clock(t: u64) -> Arc<dyn Clock> {
        Arc::new(FrozenClock::at(t))
    }

    // v1.06: contract tests for `impl_observable!` (v0.92) +
    // `impl_observable_subscriber!` (v0.95). Synthetic types prove
    // each macro generates the expected Observable impl.

    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    pub struct FooSnapshot {
        pub name: &'static str,
        pub answer: u32,
    }

    pub struct Foo {
        pub answer: u32,
    }
    crate::define_named!(Foo, "foo");
    impl Foo {
        pub fn snapshot(&self) -> FooSnapshot {
            FooSnapshot {
                name: "foo",
                answer: self.answer,
            }
        }
    }
    crate::impl_observable!(Foo, FooSnapshot);

    pub struct BarBroadcast {
        sender: tokio::sync::broadcast::Sender<u32>,
    }
    impl BarBroadcast {
        pub fn new() -> Self {
            let (sender, _) = tokio::sync::broadcast::channel(8);
            Self { sender }
        }
        pub fn subscriber_count(&self) -> usize {
            self.sender.receiver_count()
        }
    }
    crate::define_named!(BarBroadcast, "bar-broadcast");
    crate::impl_observable_subscriber!(BarBroadcast, "bar-broadcast");

    #[test]
    fn impl_observable_macro_delegates_to_inherent() {
        let f = Foo { answer: 42 };
        // Inherent snapshot
        let inh = Foo::snapshot(&f);
        // Trait snapshot
        let via_trait = Observable::snapshot(&f);
        assert_eq!(inh, via_trait);
        assert_eq!(via_trait.name, "foo");
        assert_eq!(via_trait.answer, 42);
    }

    #[test]
    fn impl_observable_subscriber_macro_returns_subscriber_snapshot() {
        let b = BarBroadcast::new();
        let snap0 = Observable::snapshot(&b);
        assert_eq!(snap0.name, "bar-broadcast");
        assert_eq!(snap0.subscriber_count, 0);
        let _rx1 = b.sender.subscribe();
        let _rx2 = b.sender.subscribe();
        let snap2 = Observable::snapshot(&b);
        assert_eq!(snap2.subscriber_count, 2);
    }

    #[tokio::test]
    async fn channel_publish_and_current_round_trip() {
        let ch = ObservationChannel::new(CacheStats { hits: 0, misses: 0 }, frozen_clock(100));
        assert_eq!(ch.current(), CacheStats { hits: 0, misses: 0 });
        ch.publish(CacheStats {
            hits: 10,
            misses: 1,
        });
        assert_eq!(
            ch.current(),
            CacheStats {
                hits: 10,
                misses: 1
            }
        );
    }

    #[tokio::test]
    async fn channel_subscribe_receives_latest() {
        let ch = ObservationChannel::new(0u32, frozen_clock(0));
        let mut rx = ch.subscribe();
        ch.publish(42);
        rx.changed().await.unwrap();
        assert_eq!(*rx.borrow(), 42);
    }

    #[tokio::test]
    async fn channel_subscriber_count_tracks_lifetimes() {
        let ch = ObservationChannel::new(0u32, frozen_clock(0));
        assert_eq!(ch.subscriber_count(), 1); // internal rx counts
        let _rx2 = ch.subscribe();
        assert_eq!(ch.subscriber_count(), 2);
        drop(_rx2);
        assert_eq!(ch.subscriber_count(), 1);
    }

    #[tokio::test]
    async fn channel_last_changed_advances_on_publish() {
        let clock = Arc::new(FrozenClock::at(100));
        let ch = ObservationChannel::new(0u32, clock.clone());
        let t0 = ch.last_changed().await;
        clock.advance(50);
        ch.publish(1);
        // Allow a tick for write lock acquisition.
        tokio::task::yield_now().await;
        let t1 = ch.last_changed().await;
        assert!(t1 > t0);
    }

    #[tokio::test]
    async fn channel_publishes_are_last_value_only() {
        let ch = ObservationChannel::new(0u32, frozen_clock(0));
        ch.publish(1);
        ch.publish(2);
        ch.publish(3);
        // No queue — only the latest matters.
        assert_eq!(ch.current(), 3);
    }

    // ── Mirante registry ───────────────────────────────────────

    #[tokio::test]
    async fn mirante_register_and_list() {
        let mut m = Mirante::new();
        let cache_ch = Arc::new(ObservationChannel::new(
            CacheStats { hits: 0, misses: 0 },
            frozen_clock(0),
        ));
        let count_ch = Arc::new(ObservationChannel::new(0u32, frozen_clock(0)));
        m.register("cache", cache_ch);
        m.register("count", count_ch);
        let names = m.list();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"cache"));
        assert!(names.contains(&"count"));
        assert_eq!(m.len(), 2);
        assert!(!m.is_empty());
    }

    #[tokio::test]
    async fn mirante_register_replaces_by_name() {
        let mut m = Mirante::new();
        m.register(
            "x",
            Arc::new(ObservationChannel::new(0u32, frozen_clock(0))),
        );
        m.register(
            "x",
            Arc::new(ObservationChannel::new(99u32, frozen_clock(0))),
        );
        let snap = m.snapshot_all();
        assert_eq!(snap["x"], serde_json::json!(99));
    }

    #[tokio::test]
    async fn mirante_snapshot_all_returns_json() {
        let mut m = Mirante::new();
        let cache_ch = Arc::new(ObservationChannel::new(
            CacheStats {
                hits: 10,
                misses: 2,
            },
            frozen_clock(0),
        ));
        m.register("cache", cache_ch);
        let snap = m.snapshot_all();
        assert_eq!(snap["cache"]["hits"], 10);
        assert_eq!(snap["cache"]["misses"], 2);
    }

    #[tokio::test]
    async fn mirante_reflects_publish_after_register() {
        let mut m = Mirante::new();
        let ch = Arc::new(ObservationChannel::new(0u32, frozen_clock(0)));
        m.register("x", ch.clone());
        ch.publish(42);
        let snap = m.snapshot_all();
        assert_eq!(snap["x"], serde_json::json!(42));
    }

    #[tokio::test]
    async fn mirante_empty_default() {
        let m = Mirante::new();
        assert!(m.is_empty());
        assert_eq!(m.len(), 0);
        assert!(m.list().is_empty());
        assert!(m.snapshot_all().is_empty());
    }

    #[tokio::test]
    async fn mirante_last_changed_all_returns_packed() {
        let clock = Arc::new(FrozenClock::at(100));
        let ch = Arc::new(ObservationChannel::new(0u32, clock.clone()));
        let mut m = Mirante::new();
        m.register("x", ch.clone());
        clock.advance(50);
        ch.publish(1);
        tokio::task::yield_now().await;
        let lc = m.last_changed_all();
        assert!(lc["x"] > 0);
    }

    // ── Observable trait via newtype ───────────────────────────

    #[derive(Default)]
    pub struct FakeCache {
        stats: std::sync::Mutex<CacheStats>,
    }

    crate::define_named!(FakeCache, "fake-cache");

    impl Observable for FakeCache {
        type Snapshot = CacheStats;
        fn snapshot(&self) -> CacheStats {
            self.stats.lock().unwrap().clone()
        }
    }

    #[tokio::test]
    async fn observable_implementer_returns_snapshot() {
        let cache = FakeCache::default();
        cache.stats.lock().unwrap().hits = 5;
        let snap = cache.snapshot();
        assert_eq!(snap.hits, 5);
        assert_eq!(cache.name(), "fake-cache");
    }
}