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