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