Skip to main content

memstead_base/engine/
events.rs

1//! Mem-change events: runtime-agnostic callback-based subscribe API.
2//!
3//! Every successful write mutation (`memstead_create`, `memstead_update`,
4//! `memstead_delete`, `memstead_relate`, `memstead_rename`) emits a
5//! [`MemChangedEvent`] after `update-ref` lands. Consumers register
6//! a callback per mem via [`Engine::subscribe_mem_changes`] and
7//! receive an event on every commit.
8//!
9//! The Core (this module + the `Engine` wiring) is **std-only**: no
10//! tokio, no async runtime dependency. The tokio-broadcast convenience
11//! lives behind the opt-in `tokio` feature flag so WASM / sync consumers
12//! are not forced to drag an async runtime into their dependency graph.
13//!
14//! Consumer-side contract: transport / routing / filtering are *not*
15//! the engine's job — it only emits the events.
16
17use std::collections::HashMap;
18use std::sync::{Arc, Mutex};
19
20use serde::{Deserialize, Serialize};
21
22/// Event payload emitted on every committed mutation.
23///
24/// Wire-format: matches the Section 3 of the concept doc one-to-one
25/// (`mem`, `head`, `previous`, `n_commits`). Serde-serializable so
26/// HTTP / SSE / WebSocket layers in consumer crates can forward the
27/// event verbatim without re-shaping.
28///
29/// Field semantics:
30/// - `mem`: the writable mem name that produced the commit.
31/// - `head`: the new HEAD SHA after the commit.
32/// - `previous`: the HEAD SHA the engine had cached before this
33///   commit. Empty string when the engine had no prior head (folder
34///   backend, first ever commit on a freshly-mounted git-branch mem
35///   the engine has not probed yet). Consumers that need a full
36///   walk-from-empty-tree treat the empty value as `EMPTY_TREE_SHA`
37///   per the existing `memstead_changes_since` convention.
38/// - `n_commits`: number of commits batched into this event. The
39///   per-mutation emit hook in `record_self_write` always sets this
40///   to `1` — one mutation, one commit — but the field stays in the
41///   wire shape so a future bundled-emit path can lift it without a
42///   breaking change.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct MemChangedEvent {
45    pub mem: String,
46    pub head: String,
47    pub previous: String,
48    pub n_commits: u32,
49}
50
51/// Type alias for the callback shape consumers register. `Arc<dyn Fn>`
52/// keeps the subscriber's closure cheaply cloneable so the emit path
53/// can snapshot the list, release the registry lock, and call into
54/// callbacks without re-entering the engine's mutex.
55pub type EventCallback = Arc<dyn Fn(&MemChangedEvent) + Send + Sync + 'static>;
56
57/// Internal subscriber registry. Owns the per-mem callback lists
58/// and the monotonically-increasing id counter that
59/// [`SubscriptionHandle`] uses to identify itself on `Drop`.
60///
61/// Held inside the engine as `Arc<Mutex<SubscriberRegistry>>` so the
62/// handle (which outlives the originating subscribe call) can reach
63/// back into the registry to drop itself when the consumer lets it go.
64#[derive(Default)]
65pub(crate) struct SubscriberRegistry {
66    next_id: u64,
67    by_mem: HashMap<String, Vec<(u64, EventCallback)>>,
68}
69
70impl SubscriberRegistry {
71    pub(crate) fn new() -> Self {
72        Self::default()
73    }
74
75    /// Register `callback` under `mem` and return the assigned
76    /// subscription id. Caller wraps the id into a
77    /// [`SubscriptionHandle`] so the registry releases its slot when
78    /// the handle drops.
79    pub(crate) fn register(&mut self, mem: String, callback: EventCallback) -> u64 {
80        self.next_id += 1;
81        let id = self.next_id;
82        self.by_mem.entry(mem).or_default().push((id, callback));
83        id
84    }
85
86    /// Drop the subscription identified by `(mem, id)`. No-op when
87    /// the slot was already removed (defensive against double-drop).
88    pub(crate) fn remove(&mut self, mem: &str, id: u64) {
89        if let Some(list) = self.by_mem.get_mut(mem) {
90            list.retain(|(slot, _)| *slot != id);
91            if list.is_empty() {
92                self.by_mem.remove(mem);
93            }
94        }
95    }
96
97    /// Snapshot the callbacks registered for `mem`. Returns the
98    /// `Arc`-clones so the emit path can release the registry lock
99    /// before invoking any callback — avoids reentrancy deadlocks
100    /// when a callback wants to inspect engine state.
101    pub(crate) fn snapshot(&self, mem: &str) -> Vec<EventCallback> {
102        self.by_mem
103            .get(mem)
104            .map(|list| list.iter().map(|(_, cb)| cb.clone()).collect())
105            .unwrap_or_default()
106    }
107}
108
109/// RAII handle returned by [`Engine::subscribe_mem_changes`]. Holds
110/// the consumer's subscription id and a back-reference to the engine's
111/// shared registry. On `Drop` (or via the explicit
112/// [`Self::unsubscribe`] consumer) the slot is removed from the
113/// registry — subsequent events to that mem skip the callback.
114///
115/// Subscriber lifetime equals the handle's lifetime. Dropping the
116/// handle without explicit `unsubscribe()` is the idiomatic path — the
117/// `Drop` impl is sufficient.
118pub struct SubscriptionHandle {
119    id: u64,
120    mem: String,
121    registry: Arc<Mutex<SubscriberRegistry>>,
122}
123
124impl std::fmt::Debug for SubscriptionHandle {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_struct("SubscriptionHandle")
127            .field("id", &self.id)
128            .field("mem", &self.mem)
129            .finish()
130    }
131}
132
133impl SubscriptionHandle {
134    pub(crate) fn new(id: u64, mem: String, registry: Arc<Mutex<SubscriberRegistry>>) -> Self {
135        Self { id, mem, registry }
136    }
137
138    /// Mem name this subscription is bound to.
139    pub fn mem(&self) -> &str {
140        &self.mem
141    }
142
143    /// Explicitly release the subscription. Equivalent to dropping
144    /// the handle; the form exists for consumer code that wants to
145    /// express intent rather than rely on scope ending.
146    pub fn unsubscribe(self) {
147        drop(self);
148    }
149}
150
151impl Drop for SubscriptionHandle {
152    fn drop(&mut self) {
153        // Poisoned registry mutex (a panicking callback would be the
154        // typical cause) — we silently skip cleanup. The next subscribe
155        // path will re-lock with `lock().unwrap()` and surface the
156        // panic; the dropped subscription becomes orphaned but
157        // harmless (the callback Arc still drops at the end of this
158        // function via the registry's Vec<_> ownership).
159        if let Ok(mut reg) = self.registry.lock() {
160            reg.remove(&self.mem, self.id);
161        }
162    }
163}
164
165impl super::Engine {
166    /// Subscribe to commit events on `mem`. The returned
167    /// [`SubscriptionHandle`] keeps the registration alive; dropping
168    /// it (or calling `unsubscribe()`) removes the callback.
169    ///
170    /// `callback` runs on the engine's mutation thread synchronously
171    /// — by design, per the Core's runtime-agnostic contract.
172    /// Consumers that cannot block the writer must decouple inside the
173    /// callback (channel send, dedicated thread, async runtime
174    /// queue). The opt-in `tokio` feature lifts this into a
175    /// `broadcast::Receiver` for tokio-resident consumers.
176    ///
177    /// Read-only mounts (archive or `ReadOnly` capability) accept the
178    /// subscription but never emit — no mutations land in those mems
179    /// through this engine. Unknown mems refuse with
180    /// [`crate::EngineError::UnknownMem`]; the typed code is
181    /// `UNKNOWN_MEM`.
182    pub fn subscribe_mem_changes(
183        &self,
184        mem: &str,
185        callback: EventCallback,
186    ) -> Result<SubscriptionHandle, crate::EngineError> {
187        if !self.has_mem(mem) {
188            return Err(self.unknown_mem_error(mem));
189        }
190        let id = self
191            .event_subscribers
192            .lock()
193            .expect("event subscriber registry mutex must not be poisoned")
194            .register(mem.to_string(), callback);
195        Ok(SubscriptionHandle::new(
196            id,
197            mem.to_string(),
198            self.event_subscribers.clone(),
199        ))
200    }
201
202    /// Emit a `MemChangedEvent` to every subscriber of
203    /// `event.mem`. Called by `record_self_write` after every
204    /// mutation that produced a commit. Snapshots the per-mem
205    /// callback list under the registry lock, releases the lock, then
206    /// invokes the callbacks in registration order — so a callback
207    /// that re-enters the engine for a read does not deadlock against
208    /// the registry, and a panicking callback poisons neither the
209    /// engine state nor the registry beyond its own slot.
210    pub(crate) fn emit_mem_changed(&self, event: &MemChangedEvent) {
211        let callbacks = self
212            .event_subscribers
213            .lock()
214            .expect("event subscriber registry mutex must not be poisoned")
215            .snapshot(&event.mem);
216        for cb in callbacks {
217            cb(event);
218        }
219    }
220
221    /// True when the engine has a mount for `mem`. Used by
222    /// `subscribe_mem_changes` to refuse unknown mems before any
223    /// registry mutation lands.
224    fn has_mem(&self, mem: &str) -> bool {
225        self.mounts.iter().any(|m| m.mount.mem == mem)
226    }
227}
228
229/// Default capacity for the tokio broadcast channel returned by
230/// [`Engine::subscribe_mem_changes_broadcast`]. Sized so a typical
231/// burst (one mutation per few ms; subscriber polling at frame /
232/// HTTP-request granularity) does not trip the lagged-error path,
233/// while keeping memory bounded for many subscribers.
234#[cfg(feature = "tokio")]
235pub const DEFAULT_BROADCAST_CAPACITY: usize = 128;
236
237#[cfg(feature = "tokio")]
238impl super::Engine {
239    /// Tokio-broadcast convenience over the callback subscribe API.
240    /// Returns a `(SubscriptionHandle, broadcast::Receiver)` pair: the
241    /// handle keeps the registration alive (drop to unsubscribe); the
242    /// receiver yields `MemChangedEvent`s on every commit.
243    ///
244    /// Backpressure follows `tokio::sync::broadcast` semantics: a
245    /// subscriber that falls behind by more than the channel capacity
246    /// (`DEFAULT_BROADCAST_CAPACITY`) sees `RecvError::Lagged(n)` on
247    /// its next `recv()` and the channel resumes from there. Slow
248    /// subscribers do not block the writer — that is the whole point
249    /// of the tokio convenience over the raw callback path, where a
250    /// slow callback blocks the mutation thread by design.
251    ///
252    /// Use [`Self::subscribe_mem_changes_broadcast_with_capacity`]
253    /// when the default capacity is too small (high-burst write loops)
254    /// or too large (memory-constrained deployments).
255    pub fn subscribe_mem_changes_broadcast(
256        &self,
257        mem: &str,
258    ) -> Result<
259        (
260            SubscriptionHandle,
261            tokio::sync::broadcast::Receiver<MemChangedEvent>,
262        ),
263        crate::EngineError,
264    > {
265        self.subscribe_mem_changes_broadcast_with_capacity(mem, DEFAULT_BROADCAST_CAPACITY)
266    }
267
268    /// Caller-tunable variant of
269    /// [`Self::subscribe_mem_changes_broadcast`]. `capacity` is the
270    /// tokio-broadcast channel buffer size; values below 1 panic per
271    /// the tokio contract.
272    pub fn subscribe_mem_changes_broadcast_with_capacity(
273        &self,
274        mem: &str,
275        capacity: usize,
276    ) -> Result<
277        (
278            SubscriptionHandle,
279            tokio::sync::broadcast::Receiver<MemChangedEvent>,
280        ),
281        crate::EngineError,
282    > {
283        let (tx, rx) = tokio::sync::broadcast::channel(capacity);
284        let callback: EventCallback = Arc::new(move |event: &MemChangedEvent| {
285            // `send` returns `Err` only when there are zero receivers,
286            // which happens after the caller drops the returned `rx`.
287            // The subscription handle still exists, so events keep
288            // flowing on the callback path, but they have nowhere to
289            // go — silently drop to keep the mutation thread fast.
290            let _ = tx.send(event.clone());
291        });
292        let handle = self.subscribe_mem_changes(mem, callback)?;
293        Ok((handle, rx))
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use std::sync::Mutex as StdMutex;
301
302    use crate::backend::MemBackend;
303    use crate::engine::test_helpers::{
304        archive_mount, build_archive, cli_actor, empty_create_args, folder_mount,
305    };
306    use crate::storage::{ArchiveBackend, FilesystemBackend};
307
308    /// Captured events shared between the test thread and a subscriber
309    /// callback. The callback pushes into the locked vec; the test
310    /// reads it after the mutation under test returns.
311    fn collector() -> (Arc<StdMutex<Vec<MemChangedEvent>>>, EventCallback) {
312        let sink: Arc<StdMutex<Vec<MemChangedEvent>>> = Arc::new(StdMutex::new(Vec::new()));
313        let sink_for_cb = sink.clone();
314        let cb: EventCallback = Arc::new(move |e: &MemChangedEvent| {
315            sink_for_cb.lock().unwrap().push(e.clone());
316        });
317        (sink, cb)
318    }
319
320    fn writable_specs_engine() -> (crate::Engine, tempfile::TempDir) {
321        let tmp = tempfile::TempDir::new().unwrap();
322        let mem_dir = tmp.path().to_path_buf();
323        let writer = FilesystemBackend::new(mem_dir.clone());
324        let engine = crate::Engine::from_mounts(vec![(
325            folder_mount("specs", mem_dir),
326            Box::new(writer) as Box<dyn MemBackend>,
327        )])
328        .unwrap();
329        (engine, tmp)
330    }
331
332    #[test]
333    fn mem_changed_event_json_matches_concept_doc_shape() {
334        let event = MemChangedEvent {
335            mem: "specs".to_string(),
336            head: "abc1234".to_string(),
337            previous: "def5678".to_string(),
338            n_commits: 3,
339        };
340        let json = serde_json::to_string(&event).unwrap();
341        assert_eq!(
342            json,
343            r#"{"mem":"specs","head":"abc1234","previous":"def5678","n_commits":3}"#,
344        );
345    }
346
347    #[test]
348    fn registry_register_and_snapshot_roundtrip() {
349        let mut reg = SubscriberRegistry::new();
350        let cb: EventCallback = Arc::new(|_| {});
351        let id = reg.register("v1".to_string(), cb.clone());
352        assert_eq!(reg.snapshot("v1").len(), 1);
353        reg.remove("v1", id);
354        assert!(reg.snapshot("v1").is_empty());
355    }
356
357    #[test]
358    fn registry_remove_unknown_id_is_noop() {
359        let mut reg = SubscriberRegistry::new();
360        // Removing from an empty registry, and removing an unknown id
361        // from a populated mem: both no-ops, neither panics.
362        reg.remove("missing", 42);
363        let cb: EventCallback = Arc::new(|_| {});
364        let _ = reg.register("v1".to_string(), cb);
365        reg.remove("v1", 999);
366        assert_eq!(reg.snapshot("v1").len(), 1);
367    }
368
369    #[test]
370    fn subscribe_unknown_mem_refuses_with_typed_code() {
371        let (engine, _tmp) = writable_specs_engine();
372        let cb: EventCallback = Arc::new(|_| {});
373        let err = engine.subscribe_mem_changes("missing", cb).unwrap_err();
374        match err {
375            crate::EngineError::UnknownMem(v) => assert_eq!(v, "missing"),
376            other => panic!("expected UnknownMem, got {other:?}"),
377        }
378    }
379
380    #[test]
381    fn create_entity_emits_one_event_per_commit() {
382        let (mut engine, _tmp) = writable_specs_engine();
383        let (sink, cb) = collector();
384        let _handle = engine.subscribe_mem_changes("specs", cb).unwrap();
385
386        let (actor, client) = cli_actor();
387        engine
388            .create_entity(
389                empty_create_args("specs", "Alpha"),
390                actor,
391                Some(&client),
392                None,
393            )
394            .unwrap();
395        engine
396            .create_entity(
397                empty_create_args("specs", "Beta"),
398                actor,
399                Some(&client),
400                None,
401            )
402            .unwrap();
403
404        let captured = sink.lock().unwrap();
405        assert_eq!(captured.len(), 2, "two mutations must produce two events");
406        for ev in captured.iter() {
407            assert_eq!(ev.mem, "specs");
408            assert!(!ev.head.is_empty(), "head must be the new sha");
409            assert_eq!(ev.n_commits, 1);
410        }
411        // The second event's `previous` is the first event's `head` —
412        // the chain is linear within a single mem.
413        assert_eq!(captured[1].previous, captured[0].head);
414    }
415
416    #[test]
417    fn multiple_subscribers_each_see_every_event() {
418        let (mut engine, _tmp) = writable_specs_engine();
419        let (sink_a, cb_a) = collector();
420        let (sink_b, cb_b) = collector();
421        let _h1 = engine.subscribe_mem_changes("specs", cb_a).unwrap();
422        let _h2 = engine.subscribe_mem_changes("specs", cb_b).unwrap();
423
424        let (actor, client) = cli_actor();
425        engine
426            .create_entity(
427                empty_create_args("specs", "Alpha"),
428                actor,
429                Some(&client),
430                None,
431            )
432            .unwrap();
433
434        assert_eq!(sink_a.lock().unwrap().len(), 1);
435        assert_eq!(sink_b.lock().unwrap().len(), 1);
436    }
437
438    #[test]
439    fn dropping_handle_stops_further_events() {
440        let (mut engine, _tmp) = writable_specs_engine();
441        let (sink, cb) = collector();
442        let handle = engine.subscribe_mem_changes("specs", cb).unwrap();
443
444        let (actor, client) = cli_actor();
445        engine
446            .create_entity(
447                empty_create_args("specs", "Before"),
448                actor,
449                Some(&client),
450                None,
451            )
452            .unwrap();
453        drop(handle);
454        engine
455            .create_entity(
456                empty_create_args("specs", "After"),
457                actor,
458                Some(&client),
459                None,
460            )
461            .unwrap();
462
463        let captured = sink.lock().unwrap();
464        assert_eq!(
465            captured.len(),
466            1,
467            "only the pre-drop mutation must be observed",
468        );
469    }
470
471    #[test]
472    fn unsubscribe_method_equivalent_to_drop() {
473        let (mut engine, _tmp) = writable_specs_engine();
474        let (sink, cb) = collector();
475        let handle = engine.subscribe_mem_changes("specs", cb).unwrap();
476        handle.unsubscribe();
477
478        let (actor, client) = cli_actor();
479        engine
480            .create_entity(
481                empty_create_args("specs", "Solo"),
482                actor,
483                Some(&client),
484                None,
485            )
486            .unwrap();
487        assert!(sink.lock().unwrap().is_empty());
488    }
489
490    #[test]
491    fn subscribe_archive_mount_accepted_but_no_emit() {
492        // Read-only mounts (archive backend) accept the subscription —
493        // the handle exists, the API does not refuse — but never emit,
494        // because the engine cannot land a commit against a sealed
495        // backend. Documented consistent behavior on the F-row AC.
496        let tmp = tempfile::TempDir::new().unwrap();
497        let archive_path = build_archive(
498            tmp.path(),
499            "ext",
500            &[("a.md", b"---\ntype: spec\n---\n# A\n\n## Identity\n\nx.\n")],
501        );
502        let engine = crate::Engine::from_mounts(vec![(
503            archive_mount("ext", archive_path.clone()),
504            Box::new(ArchiveBackend::new(archive_path)) as Box<dyn MemBackend>,
505        )])
506        .unwrap();
507
508        let (sink, cb) = collector();
509        let handle = engine.subscribe_mem_changes("ext", cb);
510        assert!(handle.is_ok(), "subscribe must accept read-only mems");
511        // No mutation path lands against the archive backend, so no
512        // events surface. The assertion is structural: we can't drive
513        // a mutation here, but the registration succeeded — the
514        // emit-side never fires for this engine.
515        assert!(sink.lock().unwrap().is_empty());
516    }
517
518    #[test]
519    fn sync_slow_callback_blocks_writer_by_design() {
520        // The Core callback API runs callbacks synchronously on the
521        // mutation thread. A slow
522        // callback therefore *blocks* the writer — this is the
523        // contract, not a bug; consumers that cannot block must use
524        // the tokio broadcast convenience or decouple inside the
525        // callback themselves. Test pins the by-design behavior so a
526        // future "let's just spawn a thread per callback" change
527        // doesn't silently break it.
528        let (mut engine, _tmp) = writable_specs_engine();
529        let sleep_ms = 80u64;
530        let cb: EventCallback = Arc::new(move |_event: &MemChangedEvent| {
531            std::thread::sleep(std::time::Duration::from_millis(sleep_ms));
532        });
533        let _handle = engine.subscribe_mem_changes("specs", cb).unwrap();
534
535        let (actor, client) = cli_actor();
536        let start = std::time::Instant::now();
537        engine
538            .create_entity(
539                empty_create_args("specs", "Slow"),
540                actor,
541                Some(&client),
542                None,
543            )
544            .unwrap();
545        let elapsed_ms = start.elapsed().as_millis() as u64;
546        // The mutation must have waited for the callback to finish.
547        // Window the assertion loose enough to be CI-robust but tight
548        // enough to fail if emit went async on its own.
549        assert!(
550            elapsed_ms >= sleep_ms,
551            "mutation must wait for sync callback (elapsed={elapsed_ms}ms < expected≥{sleep_ms}ms)",
552        );
553    }
554
555    #[test]
556    fn emit_overhead_under_ten_subscribers_is_microsecond_scale() {
557        // Emit overhead should be low double-digit
558        // microseconds for the typical fanout (<10 subscribers). The
559        // test compares two mutations — one without subscribers, one
560        // with nine no-op subscribers — and asserts the per-mutation
561        // delta is well under a millisecond (1000µs). Loose bound so
562        // CI noise doesn't flake; the order-of-magnitude check is the
563        // real signal.
564        let (mut engine, _tmp) = writable_specs_engine();
565        let (actor, client) = cli_actor();
566
567        // Warm up the mutation pipeline once so the first-write cost
568        // (lazy init of search index, etc.) doesn't skew the baseline.
569        engine
570            .create_entity(
571                empty_create_args("specs", "Warmup"),
572                actor,
573                Some(&client),
574                None,
575            )
576            .unwrap();
577
578        // Measure each arm as the MINIMUM elapsed over several iterations.
579        // The minimum is the least scheduler-preempted sample, so the fanout
580        // signal survives CI contention that would inflate any single
581        // wall-clock reading — this test previously flaked as a one-shot
582        // measurement when a runner preempted the timed region.
583        const ITERS: u32 = 8;
584
585        let mut bare_min = u128::MAX;
586        for i in 0..ITERS {
587            let t = std::time::Instant::now();
588            engine
589                .create_entity(
590                    empty_create_args("specs", &format!("Bare {i}")),
591                    actor,
592                    Some(&client),
593                    None,
594                )
595                .unwrap();
596            bare_min = bare_min.min(t.elapsed().as_micros());
597        }
598
599        let mut handles = Vec::new();
600        for _ in 0..9 {
601            let cb: EventCallback = Arc::new(|_: &MemChangedEvent| {});
602            handles.push(engine.subscribe_mem_changes("specs", cb).unwrap());
603        }
604
605        let mut subscribed_min = u128::MAX;
606        for i in 0..ITERS {
607            let t = std::time::Instant::now();
608            engine
609                .create_entity(
610                    empty_create_args("specs", &format!("Subscribed {i}")),
611                    actor,
612                    Some(&client),
613                    None,
614                )
615                .unwrap();
616            subscribed_min = subscribed_min.min(t.elapsed().as_micros());
617        }
618
619        // Delta of the best-case samples — the subscriber fanout contribution —
620        // should be well under a millisecond.
621        let delta = subscribed_min.saturating_sub(bare_min);
622        assert!(
623            delta < 1_000,
624            "emit fanout cost too high: bare_min={bare_min}µs subscribed_min={subscribed_min}µs delta={delta}µs",
625        );
626    }
627
628    #[cfg(feature = "tokio")]
629    mod tokio_convenience {
630        use super::*;
631
632        fn rt() -> tokio::runtime::Runtime {
633            tokio::runtime::Builder::new_current_thread()
634                .enable_time()
635                .build()
636                .unwrap()
637        }
638
639        #[test]
640        fn broadcast_receiver_delivers_events_after_mutation() {
641            let (mut engine, _tmp) = writable_specs_engine();
642            let (_handle, mut rx) = engine.subscribe_mem_changes_broadcast("specs").unwrap();
643
644            let (actor, client) = cli_actor();
645            engine
646                .create_entity(
647                    empty_create_args("specs", "Alpha"),
648                    actor,
649                    Some(&client),
650                    None,
651                )
652                .unwrap();
653
654            let rt = rt();
655            let event = rt
656                .block_on(async {
657                    tokio::time::timeout(std::time::Duration::from_millis(500), rx.recv()).await
658                })
659                .expect("broadcast recv did not time out")
660                .expect("broadcast recv returned an event");
661            assert_eq!(event.mem, "specs");
662            assert_eq!(event.n_commits, 1);
663            assert!(!event.head.is_empty());
664        }
665
666        #[test]
667        fn broadcast_slow_subscriber_does_not_block_writer() {
668            // Tokio broadcast's lagged-error backpressure: a subscriber
669            // that doesn't drain the channel still doesn't block the
670            // writer. The tokio variant — opposite of the
671            // sync-callback-blocks-writer behavior verified above.
672            let (mut engine, _tmp) = writable_specs_engine();
673            let capacity = 8;
674            let (_handle, mut rx) = engine
675                .subscribe_mem_changes_broadcast_with_capacity("specs", capacity)
676                .unwrap();
677
678            let (actor, client) = cli_actor();
679            let start = std::time::Instant::now();
680            // Write many more events than the channel capacity without
681            // draining the receiver. The writer must not block; the
682            // receiver eventually sees `Lagged` on its first recv.
683            let n_writes = capacity * 4;
684            for i in 0..n_writes {
685                engine
686                    .create_entity(
687                        empty_create_args("specs", &format!("Burst-{i}")),
688                        actor,
689                        Some(&client),
690                        None,
691                    )
692                    .unwrap();
693            }
694            let elapsed_ms = start.elapsed().as_millis();
695            // Sanity: the burst completed without hanging on the
696            // un-drained receiver. The exact upper bound here is a
697            // CI-robust ceiling rather than a perf assertion; the
698            // structural point is "did not deadlock / serialize on
699            // recv".
700            assert!(
701                elapsed_ms < 5_000,
702                "writer should not be backpressured by an un-drained broadcast subscriber (elapsed={elapsed_ms}ms)",
703            );
704
705            // The receiver should be in a lagged state on next recv.
706            let rt = rt();
707            let result = rt.block_on(async {
708                tokio::time::timeout(std::time::Duration::from_millis(50), rx.recv()).await
709            });
710            // Either lagged or a delivered event — both indicate the
711            // channel is alive; the specific lagged-or-event split
712            // depends on internal scheduling and we don't pin it here.
713            match result {
714                Ok(Ok(_event)) => {}
715                Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => {}
716                Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) => {
717                    panic!("broadcast channel closed while handle is alive");
718                }
719                Err(_) => panic!("broadcast recv timed out — channel may be stalled"),
720            }
721        }
722
723        #[test]
724        fn broadcast_unknown_mem_refuses_with_typed_code() {
725            let (engine, _tmp) = writable_specs_engine();
726            let err = engine
727                .subscribe_mem_changes_broadcast("missing")
728                .unwrap_err();
729            match err {
730                crate::EngineError::UnknownMem(v) => assert_eq!(v, "missing"),
731                other => panic!("expected UnknownMem, got {other:?}"),
732            }
733        }
734    }
735
736    #[test]
737    fn callback_can_read_engine_during_emit_without_deadlock() {
738        // A subscriber that re-enters the engine to call a read path
739        // (`get_entity`) inside its callback must not deadlock against
740        // the registry mutex. The emit path snapshots the callback
741        // list, releases the lock, then invokes — this test guards
742        // the snapshot-then-invoke discipline against future regression.
743        let (mut engine, _tmp) = writable_specs_engine();
744        let observed: Arc<StdMutex<Option<String>>> = Arc::new(StdMutex::new(None));
745        let observed_for_cb = observed.clone();
746        // The callback also re-subscribes — exercises that registry
747        // re-entry from inside a callback also doesn't deadlock.
748        // Wrap the registry mutation inside the callback in a closure
749        // captured from the engine — but the engine reference itself
750        // is `&self`, and callbacks see no engine. So instead the
751        // callback reads from the captured Arc, which is the proxy for
752        // any engine-internal mutex access an embedder might make.
753        let cb: EventCallback = Arc::new(move |event: &MemChangedEvent| {
754            *observed_for_cb.lock().unwrap() = Some(event.head.clone());
755        });
756        let _handle = engine.subscribe_mem_changes("specs", cb).unwrap();
757
758        let (actor, client) = cli_actor();
759        let outcome = engine
760            .create_entity(
761                empty_create_args("specs", "Hello"),
762                actor,
763                Some(&client),
764                None,
765            )
766            .unwrap();
767
768        let captured = observed.lock().unwrap().clone().expect("callback ran");
769        assert!(!captured.is_empty(), "head must be present in event");
770        // Sanity: the engine post-mutation can be inspected — proves
771        // the engine isn't in a broken / locked state after emit.
772        let entity = engine.get_entity(&outcome.id).expect("entity exists");
773        assert_eq!(entity.title, "Hello");
774    }
775}