Skip to main content

ftui_runtime/
subscription.rs

1#![forbid(unsafe_code)]
2
3//! Subscription system for continuous event sources.
4//!
5//! Subscriptions provide a declarative way to receive events from external
6//! sources like timers, file watchers, or network connections. The runtime
7//! manages subscription lifecycles automatically based on what the model
8//! declares as active.
9//!
10//! # How it works
11//!
12//! 1. `Model::subscriptions()` returns the set of active subscriptions
13//! 2. After each `update()`, the runtime compares active vs previous subscriptions
14//! 3. New subscriptions are started, removed ones are stopped
15//! 4. Subscription messages are routed through `Model::update()`
16
17use crate::cancellation::{CancellationSource, CancellationToken};
18use std::collections::HashSet;
19use std::path::{Path, PathBuf};
20use std::sync::mpsc;
21use std::thread;
22use web_time::{Duration, Instant};
23
24/// A unique identifier for a subscription.
25///
26/// Used by the runtime to track which subscriptions are active and
27/// to deduplicate subscriptions across update cycles.
28pub type SubId = u64;
29
30/// A subscription produces messages from an external event source.
31///
32/// Subscriptions run on background threads and send messages through
33/// the provided channel. The runtime manages their lifecycle.
34pub trait Subscription<M: Send + 'static>: Send {
35    /// Unique identifier for deduplication.
36    ///
37    /// Subscriptions with the same ID are considered identical.
38    /// The runtime uses this to avoid restarting unchanged subscriptions.
39    fn id(&self) -> SubId;
40
41    /// Start the subscription, sending messages through the channel.
42    ///
43    /// This is called on a background thread. Implementations should
44    /// loop and send messages until the channel is disconnected (receiver dropped)
45    /// or the stop signal is received.
46    fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal);
47}
48
49/// Signal for stopping a subscription.
50///
51/// When the runtime stops a subscription, it sets this signal. The subscription
52/// should check it periodically and exit its run loop when set.
53///
54/// Backed by [`CancellationToken`] for structured cancellation.
55#[derive(Clone)]
56pub struct StopSignal {
57    token: CancellationToken,
58}
59
60impl StopSignal {
61    /// Create a new stop signal pair (signal, trigger).
62    pub(crate) fn new() -> (Self, StopTrigger) {
63        let source = CancellationSource::new();
64        let signal = Self {
65            token: source.token(),
66        };
67        let trigger = StopTrigger { source };
68        (signal, trigger)
69    }
70
71    /// Check if the stop signal has been triggered.
72    pub fn is_stopped(&self) -> bool {
73        self.token.is_cancelled()
74    }
75
76    /// Wait for either the stop signal or a timeout.
77    ///
78    /// Returns `true` if stopped, `false` if timed out.
79    /// Blocks the thread efficiently using a condition variable.
80    /// Handles spurious wakeups by looping until condition met or timeout expired.
81    pub fn wait_timeout(&self, duration: Duration) -> bool {
82        self.token.wait_timeout(duration)
83    }
84
85    /// Access the underlying cancellation token.
86    ///
87    /// This enables integration with Asupersync-style structured cancellation
88    /// while preserving backwards compatibility with the `StopSignal` API.
89    pub fn cancellation_token(&self) -> &CancellationToken {
90        &self.token
91    }
92}
93
94/// Trigger to stop a subscription from the runtime side.
95///
96/// Backed by [`CancellationSource`] for structured cancellation.
97pub(crate) struct StopTrigger {
98    source: CancellationSource,
99}
100
101impl StopTrigger {
102    /// Signal the subscription to stop.
103    pub(crate) fn stop(&self) {
104        self.source.cancel();
105    }
106}
107
108/// A running subscription handle.
109pub(crate) struct RunningSubscription {
110    pub(crate) id: SubId,
111    trigger: StopTrigger,
112    thread: Option<thread::JoinHandle<()>>,
113    /// Tracks whether the subscription thread panicked (set by the catch_unwind wrapper).
114    panicked: std::sync::Arc<std::sync::atomic::AtomicBool>,
115}
116
117/// A background subscription failure waiting to be reported to the model.
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub(crate) struct SubscriptionFailure {
120    pub(crate) id: SubId,
121    pub(crate) error: String,
122}
123
124const SUBSCRIPTION_STOP_JOIN_TIMEOUT: Duration = Duration::from_millis(250);
125/// Poll interval for bounded subscription thread joins (bd-1f2aw).
126///
127/// Same rationale as the executor shutdown polls: `JoinHandle` has no
128/// `join_timeout` in stable Rust, so we poll `is_finished()` with a short
129/// sleep. 1ms minimizes stop latency while avoiding spin.
130const SUBSCRIPTION_STOP_JOIN_POLL: Duration = Duration::from_millis(1);
131
132impl RunningSubscription {
133    /// Returns true if the subscription thread panicked.
134    pub(crate) fn has_panicked(&self) -> bool {
135        self.panicked.load(std::sync::atomic::Ordering::Acquire)
136    }
137
138    /// Signal the subscription to stop (phase 1 of two-phase shutdown).
139    ///
140    /// Does NOT join the thread — call [`join_bounded`] after signalling all
141    /// subscriptions to allow parallel wind-down (bd-1f2aw).
142    pub(crate) fn signal_stop(&self) {
143        self.trigger.stop();
144    }
145
146    /// Join the subscription thread with a bounded timeout (phase 2).
147    ///
148    /// Returns the join handle if the thread did not finish within the timeout,
149    /// allowing callers to log and move on without blocking indefinitely.
150    pub(crate) fn join_bounded(mut self) -> Option<thread::JoinHandle<()>> {
151        let handle = self.thread.take()?;
152        let start = Instant::now();
153
154        // Fast path: subscription already finished (common for short-lived subs).
155        if handle.is_finished() {
156            let _ = handle.join();
157            tracing::trace!(
158                sub_id = self.id,
159                panicked = self.has_panicked(),
160                elapsed_us = start.elapsed().as_micros() as u64,
161                "subscription join (fast path)"
162            );
163            return None;
164        }
165
166        // Slow path: bounded poll loop (bd-1f2aw).
167        while !handle.is_finished() {
168            if start.elapsed() >= SUBSCRIPTION_STOP_JOIN_TIMEOUT {
169                tracing::warn!(
170                    sub_id = self.id,
171                    panicked = self.has_panicked(),
172                    timeout_ms = SUBSCRIPTION_STOP_JOIN_TIMEOUT.as_millis() as u64,
173                    "subscription join timed out, detaching thread"
174                );
175                return Some(handle);
176            }
177            thread::sleep(SUBSCRIPTION_STOP_JOIN_POLL);
178        }
179
180        let _ = handle.join();
181        tracing::trace!(
182            sub_id = self.id,
183            panicked = self.has_panicked(),
184            elapsed_us = start.elapsed().as_micros() as u64,
185            "subscription join (slow path)"
186        );
187        None
188    }
189
190    /// Stop the subscription and join its thread if it exits promptly.
191    ///
192    /// Convenience method combining signal + join for single-subscription stops.
193    /// Used by tests and external callers that stop a single subscription.
194    #[cfg_attr(not(test), allow(dead_code))]
195    pub(crate) fn stop(mut self) {
196        self.trigger.stop();
197        if let Some(handle) = self.thread.take() {
198            let start = Instant::now();
199            // Fast path: subscription already finished (common for short-lived subs).
200            if handle.is_finished() {
201                let _ = handle.join();
202                tracing::trace!(
203                    sub_id = self.id,
204                    panicked = self.has_panicked(),
205                    elapsed_us = start.elapsed().as_micros() as u64,
206                    "subscription stop (fast path)"
207                );
208                return;
209            }
210            // Slow path: bounded poll loop (bd-1f2aw).
211            while !handle.is_finished() {
212                if start.elapsed() >= SUBSCRIPTION_STOP_JOIN_TIMEOUT {
213                    tracing::warn!(
214                        sub_id = self.id,
215                        panicked = self.has_panicked(),
216                        timeout_ms = SUBSCRIPTION_STOP_JOIN_TIMEOUT.as_millis() as u64,
217                        "subscription did not stop within timeout; detaching thread"
218                    );
219                    return;
220                }
221                thread::sleep(SUBSCRIPTION_STOP_JOIN_POLL);
222            }
223            let _ = handle.join();
224            tracing::trace!(
225                sub_id = self.id,
226                panicked = self.has_panicked(),
227                elapsed_us = start.elapsed().as_micros() as u64,
228                "subscription stop (slow path)"
229            );
230        }
231    }
232}
233
234impl Drop for RunningSubscription {
235    fn drop(&mut self) {
236        self.trigger.stop();
237        // Don't join in drop to avoid blocking
238    }
239}
240
241/// Manages the lifecycle of subscriptions for a program.
242pub(crate) struct SubscriptionManager<M: Send + 'static> {
243    active: Vec<RunningSubscription>,
244    sender: mpsc::Sender<M>,
245    receiver: mpsc::Receiver<M>,
246    failure_sender: mpsc::Sender<SubscriptionFailure>,
247    failure_receiver: mpsc::Receiver<SubscriptionFailure>,
248}
249
250impl<M: Send + 'static> SubscriptionManager<M> {
251    pub(crate) fn new() -> Self {
252        let (sender, receiver) = mpsc::channel();
253        let (failure_sender, failure_receiver) = mpsc::channel();
254        Self {
255            active: Vec::new(),
256            sender,
257            receiver,
258            failure_sender,
259            failure_receiver,
260        }
261    }
262
263    /// Update the set of active subscriptions.
264    ///
265    /// Compares the new set against currently running subscriptions:
266    /// - Starts subscriptions that are new (ID not in active set)
267    /// - Stops subscriptions that are no longer declared (ID not in new set)
268    /// - Leaves unchanged subscriptions running
269    pub(crate) fn reconcile(&mut self, subscriptions: Vec<Box<dyn Subscription<M>>>) {
270        let reconcile_start = Instant::now();
271        let new_ids: HashSet<SubId> = subscriptions.iter().map(|s| s.id()).collect();
272        let active_count_before = self.active.len();
273
274        crate::debug_trace!(
275            "reconcile: new_ids={:?}, active_before={}",
276            new_ids,
277            active_count_before
278        );
279        tracing::trace!(
280            new_id_count = new_ids.len(),
281            active_before = active_count_before,
282            new_ids = ?new_ids,
283            "subscription reconcile starting"
284        );
285
286        // Stop subscriptions that are no longer active (two-phase: bd-1f2aw).
287        let mut remaining = Vec::new();
288        let mut to_stop = Vec::new();
289        for running in self.active.drain(..) {
290            if new_ids.contains(&running.id) {
291                remaining.push(running);
292            } else {
293                crate::debug_trace!("stopping subscription: id={}", running.id);
294                tracing::debug!(sub_id = running.id, "Stopping subscription");
295                crate::effect_system::record_subscription_stop("subscription", running.id, 0);
296                crate::effect_system::record_dynamics_sub_stop();
297                to_stop.push(running);
298            }
299        }
300        // Phase 1: Signal all removals.
301        for running in &to_stop {
302            running.signal_stop();
303        }
304        let stopped_count = to_stop.len();
305        // Phase 2: Join with bounded timeout.
306        for running in to_stop {
307            let _ = running.join_bounded();
308        }
309        self.active = remaining;
310
311        // Start new subscriptions
312        let mut started_count = 0usize;
313        let mut active_ids: HashSet<SubId> = self.active.iter().map(|r| r.id).collect();
314        for sub in subscriptions {
315            let id = sub.id();
316            if !active_ids.insert(id) {
317                continue;
318            }
319            started_count += 1;
320
321            crate::debug_trace!("starting subscription: id={}", id);
322            tracing::debug!(sub_id = id, "Starting subscription");
323            crate::effect_system::record_subscription_start("subscription", id);
324            crate::effect_system::record_dynamics_sub_start();
325            let (signal, trigger) = StopSignal::new();
326            let sender = self.sender.clone();
327            let panicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
328            let panicked_flag = panicked.clone();
329            let sub_id_for_thread = id;
330            let failure_sender = self.failure_sender.clone();
331
332            let thread = thread::spawn(move || {
333                // Recoverable boundary: a panicking subscription is recorded
334                // and the program continues. Suppress the terminal panic
335                // hook so it doesn't tear down live terminal state mid-run.
336                let result = ftui_core::with_panic_cleanup_suppressed(|| {
337                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
338                        sub.run(sender, signal);
339                    }))
340                });
341                if let Err(payload) = result {
342                    panicked_flag.store(true, std::sync::atomic::Ordering::Release);
343                    crate::effect_system::record_dynamics_sub_panic();
344                    let panic_msg = match payload.downcast_ref::<&str>() {
345                        Some(s) => (*s).to_string(),
346                        None => match payload.downcast_ref::<String>() {
347                            Some(s) => s.clone(),
348                            None => "unknown panic payload".to_string(),
349                        },
350                    };
351                    crate::effect_system::error_effect_panic(
352                        "subscription",
353                        &format!("sub_id={sub_id_for_thread}: {panic_msg}"),
354                    );
355                    let _ = failure_sender.send(SubscriptionFailure {
356                        id: sub_id_for_thread,
357                        error: panic_msg,
358                    });
359                }
360            });
361
362            self.active.push(RunningSubscription {
363                id,
364                trigger,
365                thread: Some(thread),
366                panicked,
367            });
368        }
369
370        let active_count_after = self.active.len();
371        let reconcile_elapsed_us = reconcile_start.elapsed().as_micros() as u64;
372        crate::effect_system::record_dynamics_reconcile(reconcile_elapsed_us);
373        crate::debug_trace!("reconcile complete: active_after={}", active_count_after);
374        tracing::trace!(
375            active_before = active_count_before,
376            active_after = active_count_after,
377            started = started_count,
378            stopped = stopped_count,
379            reconcile_us = reconcile_elapsed_us,
380            "subscription reconcile complete"
381        );
382    }
383
384    /// Drain pending messages from subscriptions.
385    pub(crate) fn drain_messages(&self) -> Vec<M> {
386        let mut messages = Vec::new();
387        while let Ok(msg) = self.receiver.try_recv() {
388            messages.push(msg);
389        }
390        messages
391    }
392
393    /// Drain subscription failures that have not yet been reported to the model.
394    pub(crate) fn drain_failures(&self) -> Vec<SubscriptionFailure> {
395        let mut failures = Vec::new();
396        while let Ok(failure) = self.failure_receiver.try_recv() {
397            failures.push(failure);
398        }
399        failures
400    }
401
402    /// Return the number of active subscriptions.
403    #[inline]
404    pub(crate) fn active_count(&self) -> usize {
405        self.active.len()
406    }
407
408    /// Stop all running subscriptions using two-phase parallel shutdown (bd-1f2aw).
409    ///
410    /// Phase 1: Signal all subscriptions to stop (non-blocking).
411    /// Phase 2: Join all threads with bounded timeout.
412    ///
413    /// This is significantly faster than sequential stop when multiple
414    /// subscriptions are active, because all threads begin winding down
415    /// simultaneously rather than waiting for each to finish in turn.
416    pub(crate) fn stop_all(&mut self) {
417        let count = self.active.len();
418        if count == 0 {
419            return;
420        }
421        let start = Instant::now();
422
423        // Phase 1: Signal all subscriptions to stop (parallel).
424        for running in &self.active {
425            running.signal_stop();
426        }
427
428        let signal_elapsed_us = start.elapsed().as_micros() as u64;
429        tracing::trace!(
430            target: crate::telemetry_schema::TARGET_RUNTIME,
431            count,
432            signal_elapsed_us,
433            "subscription stop_all phase 1 (signal) complete"
434        );
435
436        // Phase 2: Join all threads with bounded timeout.
437        let mut panicked_count = 0_usize;
438        let mut timed_out_count = 0_usize;
439        for running in self.active.drain(..) {
440            if running.has_panicked() {
441                panicked_count += 1;
442            }
443            if running.join_bounded().is_some() {
444                timed_out_count += 1;
445            }
446        }
447
448        let shutdown_elapsed_us = start.elapsed().as_micros() as u64;
449        crate::effect_system::record_dynamics_shutdown(shutdown_elapsed_us, timed_out_count as u64);
450        tracing::debug!(
451            target: crate::telemetry_schema::TARGET_RUNTIME,
452            count,
453            panicked_count,
454            timed_out_count,
455            elapsed_us = shutdown_elapsed_us,
456            "subscription stop_all complete"
457        );
458    }
459}
460
461impl<M: Send + 'static> Drop for SubscriptionManager<M> {
462    fn drop(&mut self) {
463        self.stop_all();
464    }
465}
466
467// --- Built-in subscriptions ---
468
469/// A subscription that fires at a fixed interval.
470///
471/// # Example
472///
473/// ```ignore
474/// fn subscriptions(&self) -> Vec<Box<dyn Subscription<MyMsg>>> {
475///     vec![Box::new(Every::new(Duration::from_secs(1), || MyMsg::Tick))]
476/// }
477/// ```
478pub struct Every<M: Send + 'static> {
479    id: SubId,
480    interval: Duration,
481    make_msg: Box<dyn Fn() -> M + Send + Sync>,
482}
483
484impl<M: Send + 'static> Every<M> {
485    /// Create a tick subscription with the given interval and message factory.
486    pub fn new(interval: Duration, make_msg: impl Fn() -> M + Send + Sync + 'static) -> Self {
487        // Generate a stable ID from the interval to allow deduplication
488        let id = interval.as_nanos() as u64 ^ 0x5449_434B; // "TICK" magic
489        Self {
490            id,
491            interval,
492            make_msg: Box::new(make_msg),
493        }
494    }
495
496    /// Create a tick subscription with an explicit ID.
497    pub fn with_id(
498        id: SubId,
499        interval: Duration,
500        make_msg: impl Fn() -> M + Send + Sync + 'static,
501    ) -> Self {
502        Self {
503            id,
504            interval,
505            make_msg: Box::new(make_msg),
506        }
507    }
508}
509
510/// Boxed tick subscription: the one-liner for `subscriptions()`.
511///
512/// Equivalent to `Box::new(Every::new(interval, make_msg))`.
513///
514/// # Example
515///
516/// ```ignore
517/// fn subscriptions(&self) -> Vec<Box<dyn Subscription<MyMsg>>> {
518///     vec![tick_every(Duration::from_millis(16), || MyMsg::Tick)]
519/// }
520/// ```
521pub fn tick_every<M: Send + 'static>(
522    interval: Duration,
523    make_msg: impl Fn() -> M + Send + Sync + 'static,
524) -> Box<dyn Subscription<M>> {
525    Box::new(Every::new(interval, make_msg))
526}
527
528/// What a [`FileWatcher`] observed between two polls of its path.
529#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
530pub enum FileEvent {
531    /// The path exists now and did not at the previous poll.
532    Created,
533    /// The path still exists and its modification time or size changed.
534    Modified,
535    /// The path existed at the previous poll and is gone now.
536    Removed,
537}
538
539/// Metadata fingerprint compared between polls.
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541struct FileFingerprint {
542    modified: Option<std::time::SystemTime>,
543    len: u64,
544}
545
546fn file_fingerprint(path: &Path) -> Option<FileFingerprint> {
547    std::fs::metadata(path).ok().map(|meta| FileFingerprint {
548        modified: meta.modified().ok(),
549        len: meta.len(),
550    })
551}
552
553/// Stable subscription id for a watched path: the same path yields the same
554/// id on every frame, so the runtime keeps one watcher running instead of
555/// restarting it whenever `subscriptions()` is re-evaluated.
556fn file_watcher_id(path: &Path) -> SubId {
557    // FNV-1a over the path bytes; the magic keeps it out of `Every`'s id space.
558    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
559    for byte in path.as_os_str().as_encoded_bytes() {
560        hash ^= u64::from(*byte);
561        hash = hash.wrapping_mul(0x0100_0000_01b3);
562    }
563    hash ^ 0x4653_5754 // "FSWT" magic
564}
565
566/// A subscription that reports changes to one filesystem path.
567///
568/// The watcher polls the path's metadata (modification time and size) every
569/// `interval` (250 ms by default) and sends one message per observed
570/// transition: [`FileEvent::Created`], [`FileEvent::Modified`] or
571/// [`FileEvent::Removed`]. Polling keeps the runtime free of platform
572/// watcher dependencies and behaves the same everywhere; the trade-offs are
573/// latency bounded by the interval and that an edit which leaves both size
574/// and modification time unchanged within one interval is not reported (a
575/// same-length rewrite on a filesystem with coarse timestamps). Watching a
576/// directory reports changes to the directory entry itself (entries added
577/// or removed), not edits inside nested files.
578///
579/// # Example
580///
581/// ```ignore
582/// fn subscriptions(&self) -> Vec<Box<dyn Subscription<MyMsg>>> {
583///     vec![file_watcher("config.toml", MyMsg::ConfigChanged)]
584/// }
585/// ```
586pub struct FileWatcher<M: Send + 'static> {
587    id: SubId,
588    path: PathBuf,
589    interval: Duration,
590    make_msg: Box<dyn Fn(FileEvent) -> M + Send + Sync>,
591}
592
593impl<M: Send + 'static> FileWatcher<M> {
594    /// Default poll interval.
595    pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(250);
596
597    /// Watch `path`, turning each observed [`FileEvent`] into a message.
598    pub fn new(
599        path: impl Into<PathBuf>,
600        make_msg: impl Fn(FileEvent) -> M + Send + Sync + 'static,
601    ) -> Self {
602        let path = path.into();
603        Self {
604            id: file_watcher_id(&path),
605            path,
606            interval: Self::DEFAULT_INTERVAL,
607            make_msg: Box::new(make_msg),
608        }
609    }
610
611    /// Set the poll interval (clamped to at least 1 ms).
612    #[must_use]
613    pub fn with_interval(mut self, interval: Duration) -> Self {
614        self.interval = interval.max(Duration::from_millis(1));
615        self
616    }
617
618    /// The watched path.
619    #[must_use]
620    pub fn path(&self) -> &Path {
621        &self.path
622    }
623
624    /// The poll interval.
625    #[must_use]
626    pub fn interval(&self) -> Duration {
627        self.interval
628    }
629}
630
631/// Boxed file watcher: the one-liner for `subscriptions()`.
632///
633/// Equivalent to `Box::new(FileWatcher::new(path, make_msg))` with the
634/// default 250 ms poll interval.
635pub fn file_watcher<M: Send + 'static>(
636    path: impl Into<PathBuf>,
637    make_msg: impl Fn(FileEvent) -> M + Send + Sync + 'static,
638) -> Box<dyn Subscription<M>> {
639    Box::new(FileWatcher::new(path, make_msg))
640}
641
642impl<M: Send + 'static> Subscription<M> for FileWatcher<M> {
643    fn id(&self) -> SubId {
644        self.id
645    }
646
647    fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal) {
648        let mut last = file_fingerprint(&self.path);
649        let mut sent: u64 = 0;
650        crate::debug_trace!(
651            "FileWatcher started: id={}, path={}, interval={:?}",
652            self.id,
653            self.path.display(),
654            self.interval
655        );
656        loop {
657            if stop.wait_timeout(self.interval) {
658                crate::debug_trace!("FileWatcher stopped: id={}, sent {} events", self.id, sent);
659                break;
660            }
661            let now = file_fingerprint(&self.path);
662            let event = match (last, now) {
663                (None, Some(_)) => Some(FileEvent::Created),
664                (Some(_), None) => Some(FileEvent::Removed),
665                (Some(prev), Some(cur)) if prev != cur => Some(FileEvent::Modified),
666                _ => None,
667            };
668            last = now;
669            if let Some(event) = event {
670                sent += 1;
671                if sender.send((self.make_msg)(event)).is_err() {
672                    crate::debug_trace!(
673                        "FileWatcher channel closed: id={}, sent {} events",
674                        self.id,
675                        sent
676                    );
677                    break;
678                }
679            }
680        }
681    }
682}
683
684impl<M: Send + 'static> Subscription<M> for Every<M> {
685    fn id(&self) -> SubId {
686        self.id
687    }
688
689    fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal) {
690        let mut tick_count: u64 = 0;
691        crate::debug_trace!(
692            "Every subscription started: id={}, interval={:?}",
693            self.id,
694            self.interval
695        );
696        loop {
697            if stop.wait_timeout(self.interval) {
698                crate::debug_trace!(
699                    "Every subscription stopped: id={}, sent {} ticks",
700                    self.id,
701                    tick_count
702                );
703                break;
704            }
705            tick_count += 1;
706            let msg = (self.make_msg)();
707            if sender.send(msg).is_err() {
708                crate::debug_trace!(
709                    "Every subscription channel closed: id={}, sent {} ticks",
710                    self.id,
711                    tick_count
712                );
713                break;
714            }
715        }
716    }
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[derive(Debug, Clone, PartialEq)]
724    enum TestMsg {
725        Tick,
726        Value(i32),
727        File(FileEvent),
728    }
729
730    struct ChannelSubscription<M: Send + 'static> {
731        id: SubId,
732        receiver: mpsc::Receiver<M>,
733        poll: Duration,
734    }
735
736    impl<M: Send + 'static> ChannelSubscription<M> {
737        fn new(id: SubId, receiver: mpsc::Receiver<M>) -> Self {
738            Self {
739                id,
740                receiver,
741                poll: Duration::from_millis(5),
742            }
743        }
744    }
745
746    impl<M: Send + 'static> Subscription<M> for ChannelSubscription<M> {
747        fn id(&self) -> SubId {
748            self.id
749        }
750
751        fn run(&self, sender: mpsc::Sender<M>, stop: StopSignal) {
752            loop {
753                if stop.is_stopped() {
754                    break;
755                }
756                match self.receiver.recv_timeout(self.poll) {
757                    Ok(msg) => {
758                        if sender.send(msg).is_err() {
759                            break;
760                        }
761                    }
762                    Err(mpsc::RecvTimeoutError::Timeout) => {}
763                    Err(mpsc::RecvTimeoutError::Disconnected) => break,
764                }
765            }
766        }
767    }
768
769    fn channel_subscription(id: SubId) -> (ChannelSubscription<TestMsg>, mpsc::Sender<TestMsg>) {
770        let (tx, rx) = mpsc::channel();
771        (ChannelSubscription::new(id, rx), tx)
772    }
773
774    #[test]
775    fn stop_signal_starts_false() {
776        let (signal, _trigger) = StopSignal::new();
777        assert!(!signal.is_stopped());
778    }
779
780    #[test]
781    fn stop_signal_becomes_true_after_trigger() {
782        let (signal, trigger) = StopSignal::new();
783        trigger.stop();
784        assert!(signal.is_stopped());
785    }
786
787    #[test]
788    fn stop_signal_wait_returns_true_when_stopped() {
789        let (signal, trigger) = StopSignal::new();
790        trigger.stop();
791        assert!(signal.wait_timeout(Duration::from_millis(100)));
792    }
793
794    #[test]
795    fn stop_signal_wait_returns_false_on_timeout() {
796        let (signal, _trigger) = StopSignal::new();
797        assert!(!signal.wait_timeout(Duration::from_millis(10)));
798    }
799
800    #[test]
801    fn channel_subscription_forwards_messages() {
802        let (sub, event_tx) = channel_subscription(1);
803        let (tx, rx) = mpsc::channel();
804        let (signal, trigger) = StopSignal::new();
805
806        let handle = thread::spawn(move || {
807            sub.run(tx, signal);
808        });
809
810        event_tx.send(TestMsg::Value(1)).unwrap();
811        event_tx.send(TestMsg::Value(2)).unwrap();
812        thread::sleep(Duration::from_millis(10));
813        trigger.stop();
814        handle.join().unwrap();
815
816        let msgs: Vec<_> = rx.try_iter().collect();
817        assert_eq!(msgs, vec![TestMsg::Value(1), TestMsg::Value(2)]);
818    }
819
820    #[test]
821    fn every_subscription_fires() {
822        let sub = Every::new(Duration::from_millis(10), || TestMsg::Tick);
823        let (tx, rx) = mpsc::channel();
824        let (signal, trigger) = StopSignal::new();
825
826        let handle = thread::spawn(move || {
827            sub.run(tx, signal);
828        });
829
830        // Wait for a few ticks
831        thread::sleep(Duration::from_millis(50));
832        trigger.stop();
833        handle.join().unwrap();
834
835        let msgs: Vec<_> = rx.try_iter().collect();
836        assert!(!msgs.is_empty(), "Should have received at least one tick");
837        assert!(msgs.iter().all(|m| *m == TestMsg::Tick));
838    }
839
840    #[test]
841    fn tick_every_is_a_boxed_every_with_the_same_id() {
842        let boxed: Box<dyn Subscription<TestMsg>> =
843            tick_every(Duration::from_millis(10), || TestMsg::Tick);
844        let plain = Every::new(Duration::from_millis(10), || TestMsg::Tick);
845        assert_eq!(
846            boxed.id(),
847            plain.id(),
848            "the helper must not change subscription identity (diffing relies on it)"
849        );
850
851        let (tx, rx) = mpsc::channel();
852        let (signal, trigger) = StopSignal::new();
853        let handle = thread::spawn(move || boxed.run(tx, signal));
854        thread::sleep(Duration::from_millis(50));
855        trigger.stop();
856        handle.join().unwrap();
857
858        let msgs: Vec<_> = rx.try_iter().collect();
859        assert!(!msgs.is_empty(), "boxed tick subscription must fire");
860        assert!(msgs.iter().all(|m| *m == TestMsg::Tick));
861    }
862
863    #[test]
864    fn file_watcher_id_is_stable_per_path_and_distinct_from_ticks() {
865        let a1 = FileWatcher::new("/tmp/a.toml", TestMsg::File);
866        let a2 = FileWatcher::new("/tmp/a.toml", TestMsg::File);
867        let b = FileWatcher::new("/tmp/b.toml", TestMsg::File);
868        assert_eq!(a1.id(), a2.id(), "same path must dedupe across frames");
869        assert_ne!(
870            a1.id(),
871            b.id(),
872            "different paths are different subscriptions"
873        );
874        let tick = Every::new(Duration::from_millis(250), || TestMsg::Tick);
875        assert_ne!(a1.id(), tick.id());
876        assert_eq!(a1.interval(), FileWatcher::<TestMsg>::DEFAULT_INTERVAL);
877        assert_eq!(
878            a1.with_interval(Duration::ZERO).interval(),
879            Duration::from_millis(1),
880            "interval is clamped so the poll loop can never spin"
881        );
882    }
883
884    /// Create, modify and remove a real file and expect exactly those three
885    /// transitions in order, with nothing reported while the file is idle.
886    #[test]
887    fn file_watcher_reports_create_modify_remove() {
888        let dir = tempfile::tempdir().expect("temp dir");
889        let path = dir.path().join("watched.toml");
890        let sub = FileWatcher::new(&path, TestMsg::File).with_interval(Duration::from_millis(5));
891        assert_eq!(sub.path(), path.as_path());
892        let (tx, rx) = mpsc::channel();
893        let (signal, trigger) = StopSignal::new();
894        let handle = thread::spawn(move || sub.run(tx, signal));
895        let wait = Duration::from_secs(10);
896        // Let the watcher take its baseline (path absent) and prove it stays quiet.
897        thread::sleep(Duration::from_millis(40));
898        assert!(rx.try_recv().is_err(), "no event before anything happens");
899
900        std::fs::write(&path, b"a = 1\n").expect("create file");
901        assert_eq!(
902            rx.recv_timeout(wait).expect("created"),
903            TestMsg::File(FileEvent::Created)
904        );
905        // A create followed by the content write can straddle two polls and
906        // yield an extra Modified; drain it so the next assertion is exact.
907        thread::sleep(Duration::from_millis(40));
908        let _ = rx.try_iter().count();
909
910        // Growing the file changes the size, which every filesystem reports
911        // even when its timestamp granularity is coarse.
912        std::fs::write(&path, b"a = 1\nb = 22\n").expect("modify file");
913        assert_eq!(
914            rx.recv_timeout(wait).expect("modified"),
915            TestMsg::File(FileEvent::Modified)
916        );
917        thread::sleep(Duration::from_millis(40));
918        let _ = rx.try_iter().count();
919
920        std::fs::remove_file(&path).expect("remove file");
921        assert_eq!(
922            rx.recv_timeout(wait).expect("removed"),
923            TestMsg::File(FileEvent::Removed)
924        );
925        thread::sleep(Duration::from_millis(40));
926        assert!(rx.try_recv().is_err(), "nothing after removal");
927
928        trigger.stop();
929        handle.join().unwrap();
930    }
931
932    /// The boxed helper is the same subscription as the struct.
933    #[test]
934    fn file_watcher_helper_boxes_the_same_subscription() {
935        let boxed: Box<dyn Subscription<TestMsg>> = file_watcher("/tmp/x.toml", TestMsg::File);
936        assert_eq!(
937            boxed.id(),
938            FileWatcher::new("/tmp/x.toml", TestMsg::File).id()
939        );
940    }
941
942    #[test]
943    fn every_subscription_uses_stable_id() {
944        let sub1 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
945        let sub2 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
946        assert_eq!(sub1.id(), sub2.id());
947    }
948
949    #[test]
950    fn every_subscription_different_intervals_different_ids() {
951        let sub1 = Every::<TestMsg>::new(Duration::from_secs(1), || TestMsg::Tick);
952        let sub2 = Every::<TestMsg>::new(Duration::from_secs(2), || TestMsg::Tick);
953        assert_ne!(sub1.id(), sub2.id());
954    }
955
956    #[test]
957    fn subscription_manager_starts_subscriptions() {
958        let mut mgr = SubscriptionManager::<TestMsg>::new();
959        let (sub, event_tx) = channel_subscription(1);
960        let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub)];
961
962        mgr.reconcile(subs);
963        event_tx.send(TestMsg::Value(42)).unwrap();
964
965        // Give the thread a moment to send
966        thread::sleep(Duration::from_millis(20));
967
968        let msgs = mgr.drain_messages();
969        assert_eq!(msgs, vec![TestMsg::Value(42)]);
970    }
971
972    #[test]
973    fn subscription_manager_dedupes_duplicate_ids() {
974        let mut mgr = SubscriptionManager::<TestMsg>::new();
975        let (sub_a, tx_a) = channel_subscription(7);
976        let (sub_b, tx_b) = channel_subscription(7);
977        let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub_a), Box::new(sub_b)];
978
979        mgr.reconcile(subs);
980
981        tx_a.send(TestMsg::Value(1)).unwrap();
982        assert!(
983            tx_b.send(TestMsg::Value(2)).is_err(),
984            "Duplicate subscription should be dropped"
985        );
986
987        thread::sleep(Duration::from_millis(20));
988        let msgs = mgr.drain_messages();
989        assert_eq!(msgs, vec![TestMsg::Value(1)]);
990    }
991
992    #[test]
993    fn subscription_manager_stops_removed() {
994        let mut mgr = SubscriptionManager::<TestMsg>::new();
995
996        // Start with one subscription
997        mgr.reconcile(vec![Box::new(Every::with_id(
998            99,
999            Duration::from_millis(5),
1000            || TestMsg::Tick,
1001        ))]);
1002
1003        thread::sleep(Duration::from_millis(20));
1004        let msgs_before = mgr.drain_messages();
1005        assert!(!msgs_before.is_empty());
1006
1007        // Remove it
1008        mgr.reconcile(vec![]);
1009
1010        // Drain any remaining buffered messages
1011        thread::sleep(Duration::from_millis(20));
1012        let _ = mgr.drain_messages();
1013
1014        // After stopping, no more messages should arrive
1015        thread::sleep(Duration::from_millis(30));
1016        let msgs_after = mgr.drain_messages();
1017        assert!(
1018            msgs_after.is_empty(),
1019            "Should stop receiving after reconcile with empty set"
1020        );
1021    }
1022
1023    #[test]
1024    fn subscription_manager_keeps_unchanged() {
1025        let mut mgr = SubscriptionManager::<TestMsg>::new();
1026
1027        // Start subscription
1028        mgr.reconcile(vec![Box::new(Every::with_id(
1029            50,
1030            Duration::from_millis(10),
1031            || TestMsg::Tick,
1032        ))]);
1033
1034        thread::sleep(Duration::from_millis(30));
1035        let _ = mgr.drain_messages();
1036
1037        // Reconcile with same ID - should keep running
1038        mgr.reconcile(vec![Box::new(Every::with_id(
1039            50,
1040            Duration::from_millis(10),
1041            || TestMsg::Tick,
1042        ))]);
1043
1044        thread::sleep(Duration::from_millis(30));
1045        let msgs = mgr.drain_messages();
1046        assert!(!msgs.is_empty(), "Subscription should still be running");
1047    }
1048
1049    #[test]
1050    fn subscription_manager_stop_all() {
1051        let mut mgr = SubscriptionManager::<TestMsg>::new();
1052
1053        mgr.reconcile(vec![
1054            Box::new(Every::with_id(1, Duration::from_millis(5), || {
1055                TestMsg::Value(1)
1056            })),
1057            Box::new(Every::with_id(2, Duration::from_millis(5), || {
1058                TestMsg::Value(2)
1059            })),
1060        ]);
1061
1062        thread::sleep(Duration::from_millis(20));
1063        mgr.stop_all();
1064
1065        thread::sleep(Duration::from_millis(20));
1066        let _ = mgr.drain_messages();
1067        thread::sleep(Duration::from_millis(30));
1068        let msgs = mgr.drain_messages();
1069        assert!(msgs.is_empty());
1070    }
1071
1072    // =========================================================================
1073    // ADDITIONAL TESTS - Cmd sequencing + Subscriptions (bd-2nu8.10.2)
1074    // =========================================================================
1075
1076    #[test]
1077    fn stop_signal_is_cloneable() {
1078        let (signal, trigger) = StopSignal::new();
1079        let signal_clone = signal.clone();
1080
1081        assert!(!signal.is_stopped());
1082        assert!(!signal_clone.is_stopped());
1083
1084        trigger.stop();
1085
1086        assert!(signal.is_stopped());
1087        assert!(signal_clone.is_stopped());
1088    }
1089
1090    #[test]
1091    fn stop_signal_wait_wakes_immediately_when_already_stopped() {
1092        let (signal, trigger) = StopSignal::new();
1093        trigger.stop();
1094
1095        // Should return immediately, not wait for timeout. The bound is a
1096        // hang guard at half the timeout, not a speed assertion: a loaded
1097        // runner may add tens of milliseconds, never seconds (G04.2).
1098        let start = Instant::now();
1099        let stopped = signal.wait_timeout(Duration::from_secs(10));
1100        let elapsed = start.elapsed();
1101
1102        assert!(stopped);
1103        assert!(
1104            elapsed < Duration::from_secs(5),
1105            "wait_timeout on a stopped signal must not wait for the timeout; took {elapsed:?}"
1106        );
1107    }
1108
1109    #[test]
1110    fn stop_signal_wait_is_interrupted_by_trigger() {
1111        let (signal, trigger) = StopSignal::new();
1112
1113        let signal_clone = signal.clone();
1114        let handle = thread::spawn(move || signal_clone.wait_timeout(Duration::from_secs(10)));
1115
1116        // Give thread time to start waiting
1117        thread::sleep(Duration::from_millis(20));
1118        trigger.stop();
1119
1120        let stopped = handle.join().unwrap();
1121        assert!(stopped);
1122    }
1123
1124    #[test]
1125    fn channel_subscription_no_messages_without_events() {
1126        let (sub, _event_tx) = channel_subscription(1);
1127        let (tx, rx) = mpsc::channel();
1128        let (signal, trigger) = StopSignal::new();
1129
1130        let handle = thread::spawn(move || {
1131            sub.run(tx, signal);
1132        });
1133
1134        thread::sleep(Duration::from_millis(10));
1135        trigger.stop();
1136        handle.join().unwrap();
1137
1138        let msgs: Vec<_> = rx.try_iter().collect();
1139        assert!(msgs.is_empty());
1140    }
1141
1142    #[test]
1143    fn channel_subscription_id_is_preserved() {
1144        let (sub, _tx) = channel_subscription(42);
1145        assert_eq!(sub.id(), 42);
1146    }
1147
1148    #[test]
1149    fn channel_subscription_stops_on_disconnected_receiver() {
1150        let (sub, event_tx) = channel_subscription(1);
1151        let (tx, _rx) = mpsc::channel();
1152        let (signal, _trigger) = StopSignal::new();
1153
1154        drop(event_tx);
1155
1156        let handle = thread::spawn(move || {
1157            sub.run(tx, signal);
1158        });
1159
1160        let result = handle.join();
1161        assert!(result.is_ok());
1162    }
1163
1164    #[test]
1165    fn every_with_id_preserves_custom_id() {
1166        let sub = Every::<TestMsg>::with_id(12345, Duration::from_secs(1), || TestMsg::Tick);
1167        assert_eq!(sub.id(), 12345);
1168    }
1169
1170    #[test]
1171    fn every_stops_on_disconnected_receiver() {
1172        let sub = Every::new(Duration::from_millis(5), || TestMsg::Tick);
1173        let (tx, rx) = mpsc::channel();
1174        let (signal, _trigger) = StopSignal::new();
1175
1176        // Drop receiver before running
1177        drop(rx);
1178
1179        // Should exit the loop when send fails
1180        let handle = thread::spawn(move || {
1181            sub.run(tx, signal);
1182        });
1183
1184        // Should complete quickly, not hang
1185        let result = handle.join();
1186        assert!(result.is_ok());
1187    }
1188
1189    #[test]
1190    fn every_respects_interval() {
1191        let interval = Duration::from_millis(50);
1192        let sub = Every::with_id(1, interval, Instant::now);
1193        let (tx, rx) = mpsc::channel();
1194        let (signal, trigger) = StopSignal::new();
1195
1196        let start = Instant::now();
1197        let handle = thread::spawn(move || {
1198            sub.run(tx, signal);
1199        });
1200
1201        // Wait for three ticks by receiving them rather than sleeping a
1202        // fixed time. Timestamp at the actual producer: receiver scheduling
1203        // can bunch queued messages even when production respects the interval.
1204        // Keep the original 50ms minimum between generated ticks (G04.2).
1205        let mut arrivals = Vec::new();
1206        let deadline = Instant::now() + Duration::from_secs(10);
1207        while arrivals.len() < 3 && Instant::now() < deadline {
1208            match rx.recv_timeout(Duration::from_millis(100)) {
1209                Ok(produced_at) => arrivals.push(produced_at),
1210                Err(mpsc::RecvTimeoutError::Timeout) => {}
1211                Err(mpsc::RecvTimeoutError::Disconnected) => break,
1212            }
1213        }
1214        trigger.stop();
1215        handle.join().unwrap();
1216
1217        assert!(
1218            arrivals.len() >= 2,
1219            "expected at least 2 ticks within 10 s, got {}",
1220            arrivals.len()
1221        );
1222        for pair in arrivals.windows(2) {
1223            let gap = pair[1].duration_since(pair[0]);
1224            assert!(
1225                gap >= interval,
1226                "ticks were generated {gap:?} apart, closer than the {interval:?} interval"
1227            );
1228        }
1229        assert!(
1230            start.elapsed() >= interval * 2,
1231            "two ticks cannot arrive before two intervals have passed"
1232        );
1233    }
1234
1235    #[test]
1236    fn subscription_manager_empty_reconcile() {
1237        let mut mgr = SubscriptionManager::<TestMsg>::new();
1238
1239        // Reconcile with empty list should not panic
1240        mgr.reconcile(vec![]);
1241        let msgs = mgr.drain_messages();
1242        assert!(msgs.is_empty());
1243    }
1244
1245    #[test]
1246    fn subscription_manager_drain_messages_returns_all() {
1247        let mut mgr = SubscriptionManager::<TestMsg>::new();
1248        let (sub, event_tx) = channel_subscription(1);
1249        let subs: Vec<Box<dyn Subscription<TestMsg>>> = vec![Box::new(sub)];
1250
1251        mgr.reconcile(subs);
1252        event_tx.send(TestMsg::Value(1)).unwrap();
1253        event_tx.send(TestMsg::Value(2)).unwrap();
1254        thread::sleep(Duration::from_millis(20));
1255
1256        let msgs = mgr.drain_messages();
1257        assert_eq!(msgs.len(), 2);
1258        assert_eq!(msgs[0], TestMsg::Value(1));
1259        assert_eq!(msgs[1], TestMsg::Value(2));
1260
1261        // Second drain should be empty
1262        let msgs2 = mgr.drain_messages();
1263        assert!(msgs2.is_empty());
1264    }
1265
1266    #[test]
1267    fn subscription_manager_replaces_subscription_with_different_id() {
1268        let mut mgr = SubscriptionManager::<TestMsg>::new();
1269        let (sub1, tx1) = channel_subscription(1);
1270
1271        // Start with ID 1
1272        mgr.reconcile(vec![Box::new(sub1)]);
1273        tx1.send(TestMsg::Value(1)).unwrap();
1274        thread::sleep(Duration::from_millis(20));
1275        let msgs1 = mgr.drain_messages();
1276        assert_eq!(msgs1, vec![TestMsg::Value(1)]);
1277
1278        // Replace with ID 2
1279        let (sub2, tx2) = channel_subscription(2);
1280        mgr.reconcile(vec![Box::new(sub2)]);
1281        tx2.send(TestMsg::Value(2)).unwrap();
1282        thread::sleep(Duration::from_millis(20));
1283        let msgs2 = mgr.drain_messages();
1284        assert_eq!(msgs2, vec![TestMsg::Value(2)]);
1285    }
1286
1287    #[test]
1288    fn subscription_manager_multiple_subscriptions() {
1289        let mut mgr = SubscriptionManager::<TestMsg>::new();
1290        let (sub1, tx1) = channel_subscription(1);
1291        let (sub2, tx2) = channel_subscription(2);
1292        let (sub3, tx3) = channel_subscription(3);
1293        let subs: Vec<Box<dyn Subscription<TestMsg>>> =
1294            vec![Box::new(sub1), Box::new(sub2), Box::new(sub3)];
1295
1296        mgr.reconcile(subs);
1297        tx1.send(TestMsg::Value(10)).unwrap();
1298        tx2.send(TestMsg::Value(20)).unwrap();
1299        tx3.send(TestMsg::Value(30)).unwrap();
1300        thread::sleep(Duration::from_millis(30));
1301
1302        let mut msgs = mgr.drain_messages();
1303        msgs.sort_by_key(|m| match m {
1304            TestMsg::Value(v) => *v,
1305            _ => 0,
1306        });
1307
1308        assert_eq!(msgs.len(), 3);
1309        assert_eq!(msgs[0], TestMsg::Value(10));
1310        assert_eq!(msgs[1], TestMsg::Value(20));
1311        assert_eq!(msgs[2], TestMsg::Value(30));
1312    }
1313
1314    #[test]
1315    fn subscription_manager_partial_update() {
1316        let mut mgr = SubscriptionManager::<TestMsg>::new();
1317
1318        // Start with 3 subscriptions
1319        mgr.reconcile(vec![
1320            Box::new(Every::with_id(1, Duration::from_millis(10), || {
1321                TestMsg::Value(1)
1322            })),
1323            Box::new(Every::with_id(2, Duration::from_millis(10), || {
1324                TestMsg::Value(2)
1325            })),
1326            Box::new(Every::with_id(3, Duration::from_millis(10), || {
1327                TestMsg::Value(3)
1328            })),
1329        ]);
1330
1331        thread::sleep(Duration::from_millis(30));
1332        let _ = mgr.drain_messages();
1333
1334        // Remove subscription 2, keep 1 and 3
1335        mgr.reconcile(vec![
1336            Box::new(Every::with_id(1, Duration::from_millis(10), || {
1337                TestMsg::Value(1)
1338            })),
1339            Box::new(Every::with_id(3, Duration::from_millis(10), || {
1340                TestMsg::Value(3)
1341            })),
1342        ]);
1343
1344        // Drain any in-flight messages that were sent before the stop signal was processed.
1345        // This clears the race window between stop signal and message send.
1346        let _ = mgr.drain_messages();
1347
1348        // Now wait for new messages from the remaining subscriptions
1349        thread::sleep(Duration::from_millis(30));
1350        let msgs = mgr.drain_messages();
1351
1352        // Should only have values 1 and 3, not 2
1353        let values: Vec<i32> = msgs
1354            .iter()
1355            .filter_map(|m| match m {
1356                TestMsg::Value(v) => Some(*v),
1357                _ => None,
1358            })
1359            .collect();
1360
1361        assert!(
1362            values.contains(&1),
1363            "Should still receive from subscription 1"
1364        );
1365        assert!(
1366            values.contains(&3),
1367            "Should still receive from subscription 3"
1368        );
1369        assert!(
1370            !values.contains(&2),
1371            "Should not receive from stopped subscription 2"
1372        );
1373    }
1374
1375    #[test]
1376    fn subscription_manager_drop_stops_all() {
1377        let (_signal, _) = StopSignal::new();
1378        let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1379        let flag_clone = flag.clone();
1380
1381        struct FlagSubscription {
1382            id: SubId,
1383            flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
1384        }
1385
1386        impl Subscription<TestMsg> for FlagSubscription {
1387            fn id(&self) -> SubId {
1388                self.id
1389            }
1390
1391            fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1392                while !stop.is_stopped() {
1393                    thread::sleep(Duration::from_millis(5));
1394                }
1395                self.flag.store(true, std::sync::atomic::Ordering::SeqCst);
1396            }
1397        }
1398
1399        {
1400            let mut mgr = SubscriptionManager::<TestMsg>::new();
1401            mgr.reconcile(vec![Box::new(FlagSubscription {
1402                id: 1,
1403                flag: flag_clone,
1404            })]);
1405
1406            thread::sleep(Duration::from_millis(20));
1407            // mgr drops here, should stop all subscriptions
1408        }
1409
1410        thread::sleep(Duration::from_millis(50));
1411        assert!(
1412            flag.load(std::sync::atomic::Ordering::SeqCst),
1413            "Subscription should have stopped on drop"
1414        );
1415    }
1416
1417    #[test]
1418    fn running_subscription_stop_joins_thread() {
1419        use std::sync::atomic::{AtomicBool, Ordering};
1420
1421        let completed = std::sync::Arc::new(AtomicBool::new(false));
1422        let completed_clone = completed.clone();
1423
1424        let (signal, trigger) = StopSignal::new();
1425        let (_tx, _rx) = mpsc::channel::<TestMsg>();
1426
1427        let thread = thread::spawn(move || {
1428            while !signal.is_stopped() {
1429                thread::sleep(Duration::from_millis(5));
1430            }
1431            completed_clone.store(true, Ordering::SeqCst);
1432        });
1433
1434        let running = RunningSubscription {
1435            id: 1,
1436            trigger,
1437            thread: Some(thread),
1438            panicked: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1439        };
1440
1441        running.stop();
1442        assert!(completed.load(Ordering::SeqCst));
1443    }
1444
1445    #[test]
1446    fn running_subscription_stop_times_out_for_uncooperative_thread() {
1447        use std::sync::atomic::{AtomicBool, Ordering};
1448
1449        let completed = std::sync::Arc::new(AtomicBool::new(false));
1450        let completed_clone = completed.clone();
1451
1452        // The thread ignores the stop signal for 3 s; stop() honours its
1453        // 250 ms join timeout, so it must return long before that. The 1.5 s
1454        // bound leaves a 1.25 s margin for a loaded runner (G04.2) while
1455        // still distinguishing "timed out" from "blocked for the full sleep".
1456        let (_signal, trigger) = StopSignal::new();
1457        let thread = thread::spawn(move || {
1458            thread::sleep(Duration::from_secs(3));
1459            completed_clone.store(true, Ordering::SeqCst);
1460        });
1461
1462        let running = RunningSubscription {
1463            id: 7,
1464            trigger,
1465            thread: Some(thread),
1466            panicked: std::sync::Arc::new(AtomicBool::new(false)),
1467        };
1468
1469        let start = Instant::now();
1470        running.stop();
1471        let elapsed = start.elapsed();
1472        assert!(
1473            elapsed < Duration::from_millis(1500),
1474            "stop() should not block behind an uncooperative subscription thread; took {elapsed:?}"
1475        );
1476
1477        // The detached thread keeps running to completion.
1478        let deadline = Instant::now() + Duration::from_secs(10);
1479        while !completed.load(Ordering::SeqCst) && Instant::now() < deadline {
1480            thread::sleep(Duration::from_millis(10));
1481        }
1482        assert!(completed.load(Ordering::SeqCst));
1483    }
1484
1485    #[test]
1486    fn every_id_stable_across_instances() {
1487        // Same interval should produce same ID
1488        let sub1 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1489        let sub2 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1490        let sub3 = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Value(1));
1491
1492        assert_eq!(sub1.id(), sub2.id());
1493        assert_eq!(sub2.id(), sub3.id()); // ID is based on interval, not message factory
1494    }
1495
1496    #[test]
1497    fn drain_messages_preserves_order() {
1498        let mut mgr = SubscriptionManager::<TestMsg>::new();
1499
1500        // Use a custom subscription that sends messages in order
1501        struct OrderedSubscription {
1502            values: Vec<i32>,
1503        }
1504
1505        impl Subscription<TestMsg> for OrderedSubscription {
1506            fn id(&self) -> SubId {
1507                999
1508            }
1509
1510            fn run(&self, sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1511                for v in &self.values {
1512                    let _ = sender.send(TestMsg::Value(*v));
1513                    thread::sleep(Duration::from_millis(1));
1514                }
1515            }
1516        }
1517
1518        mgr.reconcile(vec![Box::new(OrderedSubscription {
1519            values: vec![1, 2, 3, 4, 5],
1520        })]);
1521
1522        thread::sleep(Duration::from_millis(30));
1523        let msgs = mgr.drain_messages();
1524
1525        let values: Vec<i32> = msgs
1526            .iter()
1527            .filter_map(|m| match m {
1528                TestMsg::Value(v) => Some(*v),
1529                _ => None,
1530            })
1531            .collect();
1532
1533        assert_eq!(values, vec![1, 2, 3, 4, 5]);
1534    }
1535
1536    #[test]
1537    fn subscription_manager_new_is_empty() {
1538        let mgr = SubscriptionManager::<TestMsg>::new();
1539        let msgs = mgr.drain_messages();
1540        assert!(msgs.is_empty());
1541    }
1542
1543    // =========================================================================
1544    // LIFECYCLE CONTRACT TESTS (bd-1dg21)
1545    //
1546    // These tests capture the observable behavioral contract of the subscription
1547    // system that MUST be preserved during the Asupersync migration. Each test
1548    // documents a specific guarantee that downstream code relies on.
1549    // =========================================================================
1550
1551    /// CONTRACT: StopSignal backed by CancellationToken must remain functional
1552    /// even after concurrent thread panics. The AtomicBool-based implementation
1553    /// is inherently poison-resistant.
1554    #[test]
1555    fn contract_stop_signal_resilient_to_thread_panics() {
1556        let (signal, trigger) = StopSignal::new();
1557        let signal_clone = signal.clone();
1558
1559        // Panic in a thread that holds a clone of the signal
1560        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1561            assert!(!signal_clone.is_stopped());
1562            panic!("intentional panic while holding signal clone");
1563        }));
1564        assert!(result.is_err());
1565
1566        // Signal must still be checkable and triggerable after thread panic
1567        assert!(
1568            !signal.is_stopped(),
1569            "signal should still report not-stopped"
1570        );
1571        trigger.stop();
1572        assert!(
1573            signal.is_stopped(),
1574            "signal should report stopped after trigger"
1575        );
1576        assert!(
1577            signal.wait_timeout(Duration::from_millis(10)),
1578            "wait_timeout should return true when stopped"
1579        );
1580    }
1581
1582    /// CONTRACT: StopSignal exposes its underlying CancellationToken for
1583    /// Asupersync integration.
1584    #[test]
1585    fn contract_stop_signal_exposes_cancellation_token() {
1586        let (signal, trigger) = StopSignal::new();
1587        let token = signal.cancellation_token();
1588        assert!(!token.is_cancelled(), "token should start uncancelled");
1589        trigger.stop();
1590        assert!(token.is_cancelled(), "token should be cancelled after stop");
1591    }
1592
1593    /// CONTRACT: stop_all() must complete within a bounded time even if subscription
1594    /// threads are uncooperative. The 250ms join timeout per subscription is the
1595    /// upper bound.
1596    #[test]
1597    fn contract_stop_all_bounded_time_with_uncooperative_subscriptions() {
1598        let mut mgr = SubscriptionManager::<TestMsg>::new();
1599
1600        // Create subscriptions that ignore the stop signal
1601        struct UncooperativeSub {
1602            id: SubId,
1603        }
1604
1605        impl Subscription<TestMsg> for UncooperativeSub {
1606            fn id(&self) -> SubId {
1607                self.id
1608            }
1609
1610            fn run(&self, _sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1611                // Ignore stop signal entirely, sleep for a long time
1612                thread::sleep(Duration::from_secs(5));
1613            }
1614        }
1615
1616        mgr.reconcile(vec![
1617            Box::new(UncooperativeSub { id: 100 }),
1618            Box::new(UncooperativeSub { id: 200 }),
1619        ]);
1620
1621        thread::sleep(Duration::from_millis(20)); // let threads start
1622
1623        let start = Instant::now();
1624        mgr.stop_all();
1625        let elapsed = start.elapsed();
1626
1627        // Both subscriptions sleep 5 s and ignore the stop signal. stop_all
1628        // must give up on each after its 250 ms join timeout (about 500 ms
1629        // in total); the bound is half the sleep, so it fails only when
1630        // stop_all actually waited for a thread, never on a loaded runner
1631        // (G04.2).
1632        assert!(
1633            elapsed < Duration::from_millis(2500),
1634            "stop_all took {elapsed:?}: it blocked on an uncooperative subscription"
1635        );
1636    }
1637
1638    /// CONTRACT: reconcile() must not start a new subscription for an ID that is
1639    /// already active, even if the subscription object is different.
1640    #[test]
1641    fn contract_reconcile_deduplicates_by_id_not_identity() {
1642        let mut mgr = SubscriptionManager::<TestMsg>::new();
1643        let counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
1644
1645        struct CountingSub {
1646            id: SubId,
1647            counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1648        }
1649
1650        impl Subscription<TestMsg> for CountingSub {
1651            fn id(&self) -> SubId {
1652                self.id
1653            }
1654
1655            fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1656                self.counter
1657                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1658                while !stop.is_stopped() {
1659                    thread::sleep(Duration::from_millis(5));
1660                }
1661            }
1662        }
1663
1664        // First reconcile starts one thread
1665        mgr.reconcile(vec![Box::new(CountingSub {
1666            id: 42,
1667            counter: counter.clone(),
1668        })]);
1669        thread::sleep(Duration::from_millis(20));
1670        assert_eq!(
1671            counter.load(std::sync::atomic::Ordering::SeqCst),
1672            1,
1673            "first reconcile should start exactly 1 thread"
1674        );
1675
1676        // Second reconcile with same ID must NOT start another thread
1677        mgr.reconcile(vec![Box::new(CountingSub {
1678            id: 42,
1679            counter: counter.clone(),
1680        })]);
1681        thread::sleep(Duration::from_millis(20));
1682        assert_eq!(
1683            counter.load(std::sync::atomic::Ordering::SeqCst),
1684            1,
1685            "second reconcile with same ID must not start another thread"
1686        );
1687
1688        mgr.stop_all();
1689    }
1690
1691    /// CONTRACT: When a subscription is removed via reconcile(), messages it sent
1692    /// before being stopped may still be in the channel. drain_messages() must
1693    /// return these buffered messages.
1694    #[test]
1695    fn contract_buffered_messages_available_after_subscription_stopped() {
1696        let mut mgr = SubscriptionManager::<TestMsg>::new();
1697
1698        struct BurstSub;
1699
1700        impl Subscription<TestMsg> for BurstSub {
1701            fn id(&self) -> SubId {
1702                77
1703            }
1704
1705            fn run(&self, sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1706                // Send a burst of messages immediately
1707                for i in 0..10 {
1708                    let _ = sender.send(TestMsg::Value(i));
1709                }
1710                // Then wait for stop
1711                while !stop.is_stopped() {
1712                    thread::sleep(Duration::from_millis(5));
1713                }
1714            }
1715        }
1716
1717        mgr.reconcile(vec![Box::new(BurstSub)]);
1718        thread::sleep(Duration::from_millis(30));
1719
1720        // Remove the subscription
1721        mgr.reconcile(vec![]);
1722
1723        // Messages sent before stop should still be drainable
1724        let msgs = mgr.drain_messages();
1725        let values: Vec<i32> = msgs
1726            .iter()
1727            .filter_map(|m| match m {
1728                TestMsg::Value(v) => Some(*v),
1729                _ => None,
1730            })
1731            .collect();
1732
1733        assert!(
1734            values.len() >= 5,
1735            "Expected at least 5 buffered messages after stop, got {}",
1736            values.len()
1737        );
1738    }
1739
1740    /// CONTRACT: active_count() must accurately reflect the number of running
1741    /// subscriptions at all times.
1742    #[test]
1743    fn contract_active_count_tracks_running_subscriptions() {
1744        let mut mgr = SubscriptionManager::<TestMsg>::new();
1745
1746        assert_eq!(mgr.active_count(), 0, "empty manager");
1747
1748        mgr.reconcile(vec![
1749            Box::new(Every::with_id(1, Duration::from_millis(50), || {
1750                TestMsg::Tick
1751            })),
1752            Box::new(Every::with_id(2, Duration::from_millis(50), || {
1753                TestMsg::Tick
1754            })),
1755        ]);
1756        assert_eq!(mgr.active_count(), 2, "after starting 2");
1757
1758        mgr.reconcile(vec![Box::new(Every::with_id(
1759            1,
1760            Duration::from_millis(50),
1761            || TestMsg::Tick,
1762        ))]);
1763        assert_eq!(mgr.active_count(), 1, "after removing 1");
1764
1765        mgr.stop_all();
1766        assert_eq!(mgr.active_count(), 0, "after stop_all");
1767    }
1768
1769    /// CONTRACT: The Every subscription ID must be derived from interval only,
1770    /// not from the message factory closure. Two Every subscriptions with the
1771    /// same interval MUST have the same ID regardless of message content.
1772    #[test]
1773    fn contract_every_id_derived_from_interval_only() {
1774        let sub_a = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Tick);
1775        let sub_b = Every::<TestMsg>::new(Duration::from_millis(100), || TestMsg::Value(999));
1776        assert_eq!(
1777            sub_a.id(),
1778            sub_b.id(),
1779            "Every ID must depend only on interval, not message factory"
1780        );
1781
1782        let sub_c = Every::<TestMsg>::new(Duration::from_millis(200), || TestMsg::Tick);
1783        assert_ne!(
1784            sub_a.id(),
1785            sub_c.id(),
1786            "Different intervals must produce different IDs"
1787        );
1788    }
1789
1790    /// CONTRACT: The Every subscription ID formula must remain stable across
1791    /// versions. This captures the exact formula: interval_nanos XOR 0x5449_434B.
1792    #[test]
1793    fn contract_every_id_formula_is_stable() {
1794        let interval = Duration::from_millis(100);
1795        let expected_id = interval.as_nanos() as u64 ^ 0x5449_434B;
1796        let sub = Every::<TestMsg>::new(interval, || TestMsg::Tick);
1797        assert_eq!(
1798            sub.id(),
1799            expected_id,
1800            "Every ID formula must be: interval.as_nanos() as u64 ^ 0x5449_434B"
1801        );
1802    }
1803
1804    /// CONTRACT: Drop on SubscriptionManager must stop all subscriptions.
1805    /// This is the safety net for cleanup even if stop_all() is not called.
1806    #[test]
1807    fn contract_drop_triggers_stop_all() {
1808        use std::sync::atomic::{AtomicUsize, Ordering};
1809
1810        let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
1811
1812        struct StopCountingSub {
1813            id: SubId,
1814            counter: std::sync::Arc<AtomicUsize>,
1815        }
1816
1817        impl Subscription<TestMsg> for StopCountingSub {
1818            fn id(&self) -> SubId {
1819                self.id
1820            }
1821
1822            fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1823                while !stop.is_stopped() {
1824                    thread::sleep(Duration::from_millis(5));
1825                }
1826                self.counter.fetch_add(1, Ordering::SeqCst);
1827            }
1828        }
1829
1830        {
1831            let mut mgr = SubscriptionManager::<TestMsg>::new();
1832            mgr.reconcile(vec![
1833                Box::new(StopCountingSub {
1834                    id: 1,
1835                    counter: stop_count.clone(),
1836                }),
1837                Box::new(StopCountingSub {
1838                    id: 2,
1839                    counter: stop_count.clone(),
1840                }),
1841                Box::new(StopCountingSub {
1842                    id: 3,
1843                    counter: stop_count.clone(),
1844                }),
1845            ]);
1846            thread::sleep(Duration::from_millis(20));
1847            // mgr dropped here
1848        }
1849
1850        // Give threads time to notice stop signal and exit
1851        thread::sleep(Duration::from_millis(400));
1852        assert_eq!(
1853            stop_count.load(std::sync::atomic::Ordering::SeqCst),
1854            3,
1855            "all 3 subscription threads must have observed stop signal on drop"
1856        );
1857    }
1858
1859    /// CONTRACT: SUBSCRIPTION_STOP_JOIN_TIMEOUT must be exactly 250ms.
1860    /// The Asupersync migration must preserve this timeout bound.
1861    #[test]
1862    fn contract_stop_join_timeout_is_250ms() {
1863        assert_eq!(
1864            SUBSCRIPTION_STOP_JOIN_TIMEOUT,
1865            Duration::from_millis(250),
1866            "join timeout must be 250ms"
1867        );
1868        assert_eq!(
1869            SUBSCRIPTION_STOP_JOIN_POLL,
1870            Duration::from_millis(1),
1871            "join poll interval must be 1ms (bd-1f2aw)"
1872        );
1873    }
1874
1875    // =========================================================================
1876    // STRUCTURED LIFECYCLE TESTS (bd-1f2aw)
1877    //
1878    // These tests validate the structured cancellation, panic resilience,
1879    // and parallel shutdown improvements.
1880    // =========================================================================
1881
1882    /// bd-1f2aw: A panicking subscription must not crash the runtime.
1883    /// The panic is caught, the panicked flag is set, and telemetry is emitted.
1884    #[test]
1885    fn lifecycle_panic_in_subscription_is_caught() {
1886        use std::sync::atomic::Ordering;
1887
1888        let mut mgr = SubscriptionManager::<TestMsg>::new();
1889
1890        struct PanickingSub;
1891
1892        impl Subscription<TestMsg> for PanickingSub {
1893            fn id(&self) -> SubId {
1894                0xDEAD
1895            }
1896
1897            fn run(&self, _sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1898                panic!("intentional test panic in subscription");
1899            }
1900        }
1901
1902        mgr.reconcile(vec![Box::new(PanickingSub)]);
1903
1904        // The real failure notification is sent after the panic flag is stored.
1905        // Waiting for it establishes completion without guessing how quickly
1906        // the worker will be scheduled under the full workspace test load.
1907        let failure = mgr
1908            .failure_receiver
1909            .recv_timeout(Duration::from_secs(5))
1910            .expect("subscription panic must be caught and reported");
1911        assert_eq!(failure.id, 0xDEAD);
1912        assert_eq!(failure.error, "intentional test panic in subscription");
1913
1914        // The manager should still be functional.
1915        assert_eq!(
1916            mgr.active_count(),
1917            1,
1918            "panicked sub still tracked as active"
1919        );
1920
1921        // The panicked flag should be set.
1922        assert!(
1923            mgr.active[0].panicked.load(Ordering::Acquire),
1924            "panicked flag should be set after subscription panic"
1925        );
1926
1927        // stop_all should not panic even with a panicked subscription.
1928        mgr.stop_all();
1929        assert_eq!(mgr.active_count(), 0);
1930    }
1931
1932    /// bd-1f2aw: A panicking subscription must not prevent other subscriptions
1933    /// from continuing to deliver messages.
1934    #[test]
1935    fn lifecycle_panic_does_not_affect_sibling_subscriptions() {
1936        let mut mgr = SubscriptionManager::<TestMsg>::new();
1937
1938        struct PanickingSub;
1939        impl Subscription<TestMsg> for PanickingSub {
1940            fn id(&self) -> SubId {
1941                0xBAD
1942            }
1943            fn run(&self, _sender: mpsc::Sender<TestMsg>, _stop: StopSignal) {
1944                panic!("boom");
1945            }
1946        }
1947
1948        mgr.reconcile(vec![
1949            Box::new(PanickingSub),
1950            Box::new(Every::with_id(42, Duration::from_millis(10), || {
1951                TestMsg::Tick
1952            })),
1953        ]);
1954
1955        // Wait for panic to happen and ticks to arrive.
1956        // The tick subscription fires every 10ms; wait long enough for several.
1957        thread::sleep(Duration::from_millis(100));
1958
1959        let msgs = mgr.drain_messages();
1960        assert!(
1961            !msgs.is_empty(),
1962            "sibling subscription should still deliver messages after a panic in another sub"
1963        );
1964
1965        mgr.stop_all();
1966    }
1967
1968    /// bd-1f2aw: Parallel phased shutdown (stop_all) must be faster than
1969    /// sequential shutdown when multiple subscriptions need to wind down.
1970    #[test]
1971    fn lifecycle_stop_all_parallel_shutdown() {
1972        use std::sync::atomic::{AtomicUsize, Ordering};
1973
1974        let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
1975        let sub_count = 4;
1976
1977        // Proves the stops overlap without timing them (G04.2): each
1978        // subscription's wind-down waits until every peer is also winding
1979        // down. With the parallel signal phase all four are released at
1980        // once; a sequential signal+join would leave the first one waiting
1981        // alone until its guard trips, which `stranded` records.
1982        let winding_down = std::sync::Arc::new(AtomicUsize::new(0));
1983        let stranded = std::sync::Arc::new(AtomicUsize::new(0));
1984
1985        struct SlowStopSub {
1986            id: SubId,
1987            expected: usize,
1988            winding_down: std::sync::Arc<AtomicUsize>,
1989            stranded: std::sync::Arc<AtomicUsize>,
1990            counter: std::sync::Arc<AtomicUsize>,
1991        }
1992
1993        impl Subscription<TestMsg> for SlowStopSub {
1994            fn id(&self) -> SubId {
1995                self.id
1996            }
1997
1998            fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
1999                while !stop.is_stopped() {
2000                    thread::sleep(Duration::from_millis(5));
2001                }
2002                self.winding_down.fetch_add(1, Ordering::SeqCst);
2003                let guard = Instant::now();
2004                while self.winding_down.load(Ordering::SeqCst) < self.expected {
2005                    if guard.elapsed() > Duration::from_secs(5) {
2006                        self.stranded.fetch_add(1, Ordering::SeqCst);
2007                        return;
2008                    }
2009                    thread::sleep(Duration::from_millis(1));
2010                }
2011                self.counter.fetch_add(1, Ordering::SeqCst);
2012            }
2013        }
2014
2015        let mut mgr = SubscriptionManager::<TestMsg>::new();
2016        let subs: Vec<Box<dyn Subscription<TestMsg>>> = (0..sub_count)
2017            .map(|i| -> Box<dyn Subscription<TestMsg>> {
2018                Box::new(SlowStopSub {
2019                    id: 1000 + i,
2020                    expected: sub_count as usize,
2021                    winding_down: winding_down.clone(),
2022                    stranded: stranded.clone(),
2023                    counter: stop_count.clone(),
2024                })
2025            })
2026            .collect();
2027
2028        mgr.reconcile(subs);
2029        thread::sleep(Duration::from_millis(20));
2030
2031        mgr.stop_all();
2032
2033        // Every subscription completed its overlapped cleanup and none was
2034        // stranded waiting for a peer that was only signalled later.
2035        let deadline = Instant::now() + Duration::from_secs(10);
2036        while stop_count.load(Ordering::SeqCst) + stranded.load(Ordering::SeqCst)
2037            < sub_count as usize
2038            && Instant::now() < deadline
2039        {
2040            thread::sleep(Duration::from_millis(1));
2041        }
2042        assert_eq!(
2043            stranded.load(Ordering::SeqCst),
2044            0,
2045            "stop phases did not overlap: stop_all signalled subscriptions sequentially"
2046        );
2047        assert_eq!(
2048            stop_count.load(Ordering::SeqCst),
2049            sub_count as usize,
2050            "all subscriptions should have completed their cleanup"
2051        );
2052    }
2053
2054    /// bd-1f2aw: Two-phase signal+join in reconcile should allow parallel
2055    /// wind-down when removing multiple subscriptions at once.
2056    #[test]
2057    fn lifecycle_reconcile_removal_uses_parallel_stop() {
2058        use std::sync::atomic::{AtomicUsize, Ordering};
2059
2060        let stop_count = std::sync::Arc::new(AtomicUsize::new(0));
2061
2062        // Same overlap proof as `lifecycle_stop_all_parallel_shutdown`: the
2063        // three wind-downs wait for each other, so only a parallel signal
2064        // phase lets any of them finish (G04.2).
2065        let winding_down = std::sync::Arc::new(AtomicUsize::new(0));
2066        let stranded = std::sync::Arc::new(AtomicUsize::new(0));
2067
2068        struct SlowStopSub {
2069            id: SubId,
2070            winding_down: std::sync::Arc<AtomicUsize>,
2071            stranded: std::sync::Arc<AtomicUsize>,
2072            counter: std::sync::Arc<AtomicUsize>,
2073        }
2074
2075        impl Subscription<TestMsg> for SlowStopSub {
2076            fn id(&self) -> SubId {
2077                self.id
2078            }
2079
2080            fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
2081                while !stop.is_stopped() {
2082                    thread::sleep(Duration::from_millis(5));
2083                }
2084                self.winding_down.fetch_add(1, Ordering::SeqCst);
2085                let guard = Instant::now();
2086                while self.winding_down.load(Ordering::SeqCst) < 3 {
2087                    if guard.elapsed() > Duration::from_secs(5) {
2088                        self.stranded.fetch_add(1, Ordering::SeqCst);
2089                        return;
2090                    }
2091                    thread::sleep(Duration::from_millis(1));
2092                }
2093                self.counter.fetch_add(1, Ordering::SeqCst);
2094            }
2095        }
2096
2097        let mut mgr = SubscriptionManager::<TestMsg>::new();
2098        mgr.reconcile(
2099            [2000, 2001, 2002]
2100                .into_iter()
2101                .map(|id| -> Box<dyn Subscription<TestMsg>> {
2102                    Box::new(SlowStopSub {
2103                        id,
2104                        winding_down: winding_down.clone(),
2105                        stranded: stranded.clone(),
2106                        counter: stop_count.clone(),
2107                    })
2108                })
2109                .collect(),
2110        );
2111        thread::sleep(Duration::from_millis(20));
2112
2113        // Remove all subscriptions via reconcile.
2114        mgr.reconcile(vec![]);
2115
2116        let deadline = Instant::now() + Duration::from_secs(10);
2117        while stop_count.load(Ordering::SeqCst) + stranded.load(Ordering::SeqCst) < 3
2118            && Instant::now() < deadline
2119        {
2120            thread::sleep(Duration::from_millis(1));
2121        }
2122        assert_eq!(
2123            stranded.load(Ordering::SeqCst),
2124            0,
2125            "reconcile removal stopped subscriptions sequentially"
2126        );
2127        assert_eq!(stop_count.load(Ordering::SeqCst), 3);
2128    }
2129
2130    /// bd-1f2aw: has_panicked() must reflect the actual panic state of the thread.
2131    #[test]
2132    fn lifecycle_has_panicked_tracks_state() {
2133        let panicked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2134        let panicked_flag = panicked.clone();
2135
2136        let (signal, trigger) = StopSignal::new();
2137        let thread = thread::spawn(move || {
2138            signal.wait_timeout(Duration::from_secs(10));
2139        });
2140
2141        let running = RunningSubscription {
2142            id: 999,
2143            trigger,
2144            thread: Some(thread),
2145            panicked,
2146        };
2147
2148        assert!(!running.has_panicked(), "should not be panicked initially");
2149
2150        // Simulate a panic flag (normally set by the catch_unwind wrapper).
2151        panicked_flag.store(true, std::sync::atomic::Ordering::Release);
2152        assert!(running.has_panicked(), "should reflect panicked state");
2153
2154        running.stop();
2155    }
2156
2157    /// bd-1f2aw: signal_stop + join_bounded should work correctly as a two-phase
2158    /// shutdown for individual subscriptions.
2159    #[test]
2160    fn lifecycle_signal_then_join_works() {
2161        use std::sync::atomic::{AtomicBool, Ordering};
2162
2163        let completed = std::sync::Arc::new(AtomicBool::new(false));
2164        let completed_clone = completed.clone();
2165
2166        let (signal, trigger) = StopSignal::new();
2167        let thread = thread::spawn(move || {
2168            while !signal.is_stopped() {
2169                thread::sleep(Duration::from_millis(5));
2170            }
2171            completed_clone.store(true, Ordering::SeqCst);
2172        });
2173
2174        let running = RunningSubscription {
2175            id: 888,
2176            trigger,
2177            thread: Some(thread),
2178            panicked: std::sync::Arc::new(AtomicBool::new(false)),
2179        };
2180
2181        running.signal_stop();
2182        let leftover = running.join_bounded();
2183        assert!(
2184            leftover.is_none(),
2185            "cooperative thread should join within timeout"
2186        );
2187        assert!(
2188            completed.load(Ordering::SeqCst),
2189            "thread should have completed"
2190        );
2191    }
2192
2193    /// bd-1f2aw: join_bounded must return the handle for uncooperative threads.
2194    #[test]
2195    fn lifecycle_join_bounded_returns_handle_for_uncooperative() {
2196        use std::sync::atomic::AtomicBool;
2197
2198        // The thread sleeps 3 s; join_bounded gives up after 250 ms. The
2199        // bound is half the sleep so it only trips when join_bounded really
2200        // waited for the thread, never on a loaded runner (G04.2).
2201        let (_signal, trigger) = StopSignal::new();
2202        let thread = thread::spawn(move || {
2203            thread::sleep(Duration::from_secs(3));
2204        });
2205
2206        let running = RunningSubscription {
2207            id: 777,
2208            trigger,
2209            thread: Some(thread),
2210            panicked: std::sync::Arc::new(AtomicBool::new(false)),
2211        };
2212
2213        running.signal_stop();
2214        let start = Instant::now();
2215        let leftover = running.join_bounded();
2216        let elapsed = start.elapsed();
2217
2218        assert!(
2219            leftover.is_some(),
2220            "uncooperative thread should not join within timeout"
2221        );
2222        assert!(
2223            elapsed < Duration::from_millis(1500),
2224            "join_bounded should respect the 250ms timeout, took {elapsed:?}"
2225        );
2226    }
2227
2228    /// bd-1f2aw: Restart semantics — a subscription that was stopped via
2229    /// reconcile can be re-started by including it in a subsequent reconcile.
2230    #[test]
2231    fn lifecycle_restart_after_stop() {
2232        let mut mgr = SubscriptionManager::<TestMsg>::new();
2233
2234        // Start subscription.
2235        mgr.reconcile(vec![Box::new(Every::with_id(
2236            300,
2237            Duration::from_millis(10),
2238            || TestMsg::Tick,
2239        ))]);
2240        thread::sleep(Duration::from_millis(30));
2241        let msgs = mgr.drain_messages();
2242        assert!(!msgs.is_empty(), "should receive ticks");
2243
2244        // Remove it.
2245        mgr.reconcile(vec![]);
2246        thread::sleep(Duration::from_millis(20));
2247        let _ = mgr.drain_messages();
2248        thread::sleep(Duration::from_millis(30));
2249        let msgs = mgr.drain_messages();
2250        assert!(msgs.is_empty(), "should stop receiving after removal");
2251
2252        // Restart with same ID.
2253        mgr.reconcile(vec![Box::new(Every::with_id(
2254            300,
2255            Duration::from_millis(10),
2256            || TestMsg::Value(99),
2257        ))]);
2258        thread::sleep(Duration::from_millis(30));
2259        let msgs = mgr.drain_messages();
2260        assert!(
2261            !msgs.is_empty(),
2262            "should receive messages again after restart"
2263        );
2264        assert!(
2265            msgs.iter().any(|m| matches!(m, TestMsg::Value(99))),
2266            "restarted sub should use the new message factory"
2267        );
2268
2269        mgr.stop_all();
2270    }
2271
2272    /// bd-1f2aw: Non-interference contract — subscriptions communicate
2273    /// exclusively through the mpsc channel. They have no access to terminal
2274    /// state, frame buffers, or render surfaces.
2275    ///
2276    /// This test verifies the architectural invariant by demonstrating that
2277    /// subscription threads only interact with the manager through messages,
2278    /// and that the manager's state is consistent after concurrent operations.
2279    #[test]
2280    fn lifecycle_non_interference_with_manager_state() {
2281        use std::sync::atomic::{AtomicUsize, Ordering};
2282
2283        let msg_count = std::sync::Arc::new(AtomicUsize::new(0));
2284
2285        struct CountingSub {
2286            id: SubId,
2287            counter: std::sync::Arc<AtomicUsize>,
2288        }
2289
2290        impl Subscription<TestMsg> for CountingSub {
2291            fn id(&self) -> SubId {
2292                self.id
2293            }
2294
2295            fn run(&self, sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
2296                while !stop.is_stopped() {
2297                    if sender.send(TestMsg::Tick).is_err() {
2298                        break;
2299                    }
2300                    self.counter.fetch_add(1, Ordering::SeqCst);
2301                    thread::sleep(Duration::from_millis(5));
2302                }
2303            }
2304        }
2305
2306        let mut mgr = SubscriptionManager::<TestMsg>::new();
2307
2308        // Start multiple subscriptions.
2309        mgr.reconcile(vec![
2310            Box::new(CountingSub {
2311                id: 400,
2312                counter: msg_count.clone(),
2313            }),
2314            Box::new(CountingSub {
2315                id: 401,
2316                counter: msg_count.clone(),
2317            }),
2318        ]);
2319
2320        thread::sleep(Duration::from_millis(50));
2321
2322        // Manager state is consistent while subscriptions are running.
2323        assert_eq!(mgr.active_count(), 2);
2324        let drained = mgr.drain_messages();
2325        let sent_count = msg_count.load(Ordering::SeqCst);
2326        assert!(sent_count > 0, "subscriptions should have sent messages");
2327        assert!(
2328            drained.len() <= sent_count,
2329            "drained {} but only {} sent",
2330            drained.len(),
2331            sent_count
2332        );
2333
2334        // Stop all — manager state is consistent after shutdown.
2335        mgr.stop_all();
2336        assert_eq!(mgr.active_count(), 0);
2337
2338        // Drain remaining buffered messages.
2339        let remaining = mgr.drain_messages();
2340        let total_drained = drained.len() + remaining.len();
2341        let final_sent = msg_count.load(Ordering::SeqCst);
2342        assert!(
2343            total_drained <= final_sent,
2344            "total drained ({total_drained}) must not exceed total sent ({final_sent})"
2345        );
2346    }
2347
2348    /// bd-1f2aw: Shutdown ordering contract — stop_all() must signal all
2349    /// subscriptions before joining any. Verify by checking that all subs
2350    /// observe the stop signal approximately simultaneously.
2351    #[test]
2352    fn lifecycle_shutdown_signal_ordering() {
2353        use std::sync::atomic::{AtomicU64, Ordering};
2354
2355        let signal_times =
2356            std::sync::Arc::new([AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]);
2357        let epoch = Instant::now();
2358
2359        struct TimingStopSub {
2360            id: SubId,
2361            index: usize,
2362            signal_times: std::sync::Arc<[AtomicU64; 3]>,
2363            epoch: Instant,
2364        }
2365
2366        impl Subscription<TestMsg> for TimingStopSub {
2367            fn id(&self) -> SubId {
2368                self.id
2369            }
2370
2371            fn run(&self, _sender: mpsc::Sender<TestMsg>, stop: StopSignal) {
2372                while !stop.is_stopped() {
2373                    thread::sleep(Duration::from_millis(1));
2374                }
2375                let elapsed_us = self.epoch.elapsed().as_micros() as u64;
2376                self.signal_times[self.index].store(elapsed_us, Ordering::SeqCst);
2377            }
2378        }
2379
2380        let mut mgr = SubscriptionManager::<TestMsg>::new();
2381        mgr.reconcile(vec![
2382            Box::new(TimingStopSub {
2383                id: 500,
2384                index: 0,
2385                signal_times: signal_times.clone(),
2386                epoch,
2387            }),
2388            Box::new(TimingStopSub {
2389                id: 501,
2390                index: 1,
2391                signal_times: signal_times.clone(),
2392                epoch,
2393            }),
2394            Box::new(TimingStopSub {
2395                id: 502,
2396                index: 2,
2397                signal_times: signal_times.clone(),
2398                epoch,
2399            }),
2400        ]);
2401        thread::sleep(Duration::from_millis(20));
2402
2403        mgr.stop_all();
2404
2405        // All three should have observed the stop signal at approximately
2406        // the same time (within 10ms of each other), because phase 1 signals
2407        // all before phase 2 joins any.
2408        let t0 = signal_times[0].load(Ordering::SeqCst);
2409        let t1 = signal_times[1].load(Ordering::SeqCst);
2410        let t2 = signal_times[2].load(Ordering::SeqCst);
2411
2412        assert!(
2413            t0 > 0 && t1 > 0 && t2 > 0,
2414            "all subs should have recorded stop time"
2415        );
2416
2417        let max_t = t0.max(t1).max(t2);
2418        let min_t = t0.min(t1).min(t2);
2419        let spread_us = max_t - min_t;
2420
2421        assert!(
2422            spread_us < 10_000, // 10ms
2423            "stop signal spread should be < 10ms for parallel signaling, got {spread_us}us \
2424             (t0={t0}, t1={t1}, t2={t2})"
2425        );
2426    }
2427}