Skip to main content

ftui_core/
cx.rs

1//! Capability context (`Cx`) for cooperative cancellation and deadline propagation.
2//!
3//! `Cx` is a lightweight handle threaded through every async operation, I/O call,
4//! and timer in the FrankenTUI stack. It enables:
5//!
6//! - **Cooperative cancellation**: Any holder can check `cx.is_cancelled()` and
7//!   bail out early.
8//! - **Deadline propagation**: A parent context's deadline flows to children.
9//!   `cx.deadline()` returns the tightest deadline in the chain.
10//! - **Deterministic testing via Lab**: In `Lab` mode, time is controlled
11//!   externally, enabling fully reproducible test runs.
12//!
13//! # Design
14//!
15//! `Cx` is cheaply cloneable (`Arc` inside) and immutable from the outside.
16//! To cancel or advance Lab time, hold the companion [`CxController`].
17//!
18//! # Tracing
19//!
20//! When the `tracing` feature is active, cancellation emits a `WARN`-level event
21//! and deadline checks emit `cx.propagate` spans with `cx_id` and
22//! `deadline_remaining_us` fields.
23//!
24//! # Example
25//!
26//! ```
27//! use ftui_core::cx::{Cx, CxController};
28//! use web_time::Duration;
29//!
30//! // Create a root context with a 500ms deadline.
31//! let (cx, ctrl) = Cx::with_deadline(Duration::from_millis(500));
32//! assert!(!cx.is_cancelled());
33//! assert!(cx.deadline().is_some());
34//!
35//! // Cancel it.
36//! ctrl.cancel();
37//! assert!(cx.is_cancelled());
38//! ```
39
40use std::sync::Arc;
41use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
42use web_time::{Duration, Instant};
43
44// Import tracing macros (no-op when tracing feature is disabled).
45#[cfg(feature = "tracing")]
46use crate::logging::{info_span, warn};
47#[cfg(not(feature = "tracing"))]
48use crate::{info_span, warn};
49
50// ─── Cx ID generation ────────────────────────────────────────────────────────
51
52static NEXT_CX_ID: AtomicU64 = AtomicU64::new(1);
53
54fn next_cx_id() -> u64 {
55    NEXT_CX_ID.fetch_add(1, Ordering::Relaxed)
56}
57
58// ─── Metrics counters ────────────────────────────────────────────────────────
59
60/// Total number of Cx cancellations observed.
61static CX_CANCELLATIONS_TOTAL: AtomicU64 = AtomicU64::new(0);
62
63/// Read the total cancellation count (for diagnostics/telemetry).
64#[must_use]
65pub fn cx_cancellations_total() -> u64 {
66    CX_CANCELLATIONS_TOTAL.load(Ordering::Relaxed)
67}
68
69// ─── Time source ─────────────────────────────────────────────────────────────
70
71/// Time source abstraction for deterministic testing.
72///
73/// In production, `Cx` uses `web_time::Instant::now()`.
74/// In Lab mode, time is controlled via [`LabClock`].
75#[derive(Debug, Clone)]
76enum TimeSource {
77    /// Real wall-clock time.
78    Real,
79    /// Deterministic lab clock for testing.
80    Lab(LabClock),
81}
82
83/// A manually-advanceable clock for deterministic tests.
84///
85/// All `Cx` instances sharing the same `LabClock` see the same time.
86#[derive(Debug, Clone)]
87pub struct LabClock {
88    epoch: Instant,
89    offset_us: Arc<AtomicU64>,
90}
91
92impl LabClock {
93    /// Create a new lab clock starting at `Instant::now()`.
94    #[must_use]
95    pub fn new() -> Self {
96        Self {
97            epoch: Instant::now(),
98            offset_us: Arc::new(AtomicU64::new(0)),
99        }
100    }
101
102    /// Advance the lab clock by `delta`.
103    pub fn advance(&self, delta: Duration) {
104        let us = delta.as_micros().min(u64::MAX as u128) as u64;
105        self.offset_us.fetch_add(us, Ordering::Release);
106    }
107
108    /// Current lab time.
109    #[must_use]
110    pub fn now(&self) -> Instant {
111        let offset = Duration::from_micros(self.offset_us.load(Ordering::Acquire));
112        self.epoch + offset
113    }
114}
115
116impl Default for LabClock {
117    fn default() -> Self {
118        Self::new()
119    }
120}
121
122/// Read the `FTUI_TEST_TIME_SCALE` multiplier for sleep-based liveness bounds.
123///
124/// Defaults to `1` when unset, empty, zero, or unparseable; CI/DSR verification
125/// may set `FTUI_TEST_TIME_SCALE=4` on shared runners so hang-guard and liveness
126/// bounds scale proportionally without affecting deterministic [`LabClock`] tests.
127#[must_use]
128pub fn test_time_scale() -> u32 {
129    static SCALE: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
130    *SCALE.get_or_init(|| test_time_scale_from_reader(|key| std::env::var(key).ok()))
131}
132
133fn test_time_scale_from_reader(read: impl FnOnce(&str) -> Option<String>) -> u32 {
134    read("FTUI_TEST_TIME_SCALE")
135        .and_then(|raw| raw.trim().parse::<u32>().ok())
136        .filter(|&scale| scale >= 1)
137        .unwrap_or(1)
138}
139
140// ─── Inner shared state ──────────────────────────────────────────────────────
141
142#[derive(Debug)]
143struct CxInner {
144    id: u64,
145    cancelled: AtomicBool,
146    /// Deadline as microseconds since `created_at`. `u64::MAX` means no deadline.
147    deadline_us: u64,
148    created_at: Instant,
149    time_source: TimeSource,
150    /// Optional parent for deadline chain resolution.
151    parent: Option<Arc<CxInner>>,
152}
153
154// ─── Cx ──────────────────────────────────────────────────────────────────────
155
156/// Capability context handle.
157///
158/// Cheaply cloneable. Check `is_cancelled()` at natural yield points
159/// (loop iterations, before I/O, before expensive computation).
160#[derive(Clone, Debug)]
161pub struct Cx {
162    inner: Arc<CxInner>,
163}
164
165impl Cx {
166    // ── Constructors ─────────────────────────────────────────────────
167
168    /// Create a root context with no deadline.
169    #[must_use]
170    pub fn background() -> (Self, CxController) {
171        Self::new_inner(u64::MAX, TimeSource::Real, None)
172    }
173
174    /// Create a root context with a deadline.
175    #[must_use]
176    pub fn with_deadline(deadline: Duration) -> (Self, CxController) {
177        let us = deadline.as_micros().min(u64::MAX as u128) as u64;
178        Self::new_inner(us, TimeSource::Real, None)
179    }
180
181    /// Create a root context using a [`LabClock`] for deterministic testing.
182    #[must_use]
183    pub fn lab(clock: &LabClock) -> (Self, CxController) {
184        Self::new_inner(u64::MAX, TimeSource::Lab(clock.clone()), None)
185    }
186
187    /// Create a lab context with a deadline.
188    #[must_use]
189    pub fn lab_with_deadline(clock: &LabClock, deadline: Duration) -> (Self, CxController) {
190        let us = deadline.as_micros().min(u64::MAX as u128) as u64;
191        Self::new_inner(us, TimeSource::Lab(clock.clone()), None)
192    }
193
194    /// Derive a child context with a tighter deadline.
195    ///
196    /// The effective deadline is `min(parent.deadline(), child_deadline)`.
197    /// Cancelling the parent also cancels the child (checked via chain walk).
198    #[must_use]
199    pub fn child(&self, deadline: Duration) -> (Self, CxController) {
200        let us = deadline.as_micros().min(u64::MAX as u128) as u64;
201        let time_source = match &self.inner.time_source {
202            TimeSource::Real => TimeSource::Real,
203            TimeSource::Lab(c) => TimeSource::Lab(c.clone()),
204        };
205        Self::new_inner(us, time_source, Some(self.inner.clone()))
206    }
207
208    /// Derive a child context that inherits the parent deadline.
209    #[must_use]
210    pub fn child_inherit(&self) -> (Self, CxController) {
211        let time_source = match &self.inner.time_source {
212            TimeSource::Real => TimeSource::Real,
213            TimeSource::Lab(c) => TimeSource::Lab(c.clone()),
214        };
215        Self::new_inner(u64::MAX, time_source, Some(self.inner.clone()))
216    }
217
218    fn new_inner(
219        deadline_us: u64,
220        time_source: TimeSource,
221        parent: Option<Arc<CxInner>>,
222    ) -> (Self, CxController) {
223        let now = match &time_source {
224            TimeSource::Real => Instant::now(),
225            TimeSource::Lab(c) => c.now(),
226        };
227        let inner = Arc::new(CxInner {
228            id: next_cx_id(),
229            cancelled: AtomicBool::new(false),
230            deadline_us,
231            created_at: now,
232            time_source,
233            parent,
234        });
235        let cx = Self {
236            inner: inner.clone(),
237        };
238        let ctrl = CxController { inner };
239        (cx, ctrl)
240    }
241
242    // ── Queries ──────────────────────────────────────────────────────
243
244    /// Unique identifier for this context (for tracing/logging).
245    #[inline]
246    #[must_use]
247    pub fn id(&self) -> u64 {
248        self.inner.id
249    }
250
251    /// Check if this context (or any ancestor) has been cancelled.
252    #[inline]
253    #[must_use]
254    pub fn is_cancelled(&self) -> bool {
255        self.is_cancelled_inner(&self.inner)
256    }
257
258    fn is_cancelled_inner(&self, inner: &CxInner) -> bool {
259        if inner.cancelled.load(Ordering::Acquire) {
260            return true;
261        }
262        if let Some(ref parent) = inner.parent {
263            return self.is_cancelled_inner(parent);
264        }
265        false
266    }
267
268    /// Check if the deadline has passed.
269    #[inline]
270    #[must_use]
271    pub fn is_expired(&self) -> bool {
272        self.remaining().is_some_and(|d| d.is_zero())
273    }
274
275    /// Check if the context is done (cancelled or expired).
276    #[inline]
277    #[must_use]
278    pub fn is_done(&self) -> bool {
279        self.is_cancelled() || self.is_expired()
280    }
281
282    /// Return the effective deadline as a `Duration` from context creation,
283    /// considering the full parent chain. Returns `None` if no deadline is set.
284    #[must_use]
285    pub fn deadline(&self) -> Option<Duration> {
286        let own = self.inner.deadline_us;
287        let parent_remaining = self.parent_remaining_us();
288
289        let now = self.now();
290        let elapsed = now
291            .checked_duration_since(self.inner.created_at)
292            .unwrap_or(Duration::ZERO);
293        let elapsed_us = elapsed.as_micros().min(u64::MAX as u128) as u64;
294
295        // Own remaining
296        let own_remaining = if own == u64::MAX {
297            u64::MAX
298        } else {
299            own.saturating_sub(elapsed_us)
300        };
301
302        let effective = own_remaining.min(parent_remaining);
303        if effective == u64::MAX {
304            None
305        } else {
306            Some(Duration::from_micros(effective))
307        }
308    }
309
310    /// Remaining time until deadline (saturates to zero, never negative).
311    /// Returns `None` if no deadline is set.
312    #[must_use]
313    pub fn remaining(&self) -> Option<Duration> {
314        self.deadline()
315    }
316
317    /// Remaining time in microseconds, or `None` if no deadline.
318    #[must_use]
319    pub fn remaining_us(&self) -> Option<u64> {
320        self.remaining()
321            .map(|d| d.as_micros().min(u64::MAX as u128) as u64)
322    }
323
324    /// Current time according to this context's time source.
325    #[must_use]
326    pub fn now(&self) -> Instant {
327        match &self.inner.time_source {
328            TimeSource::Real => Instant::now(),
329            TimeSource::Lab(c) => c.now(),
330        }
331    }
332
333    /// Whether this context uses a lab clock.
334    #[inline]
335    #[must_use]
336    pub fn is_lab(&self) -> bool {
337        matches!(self.inner.time_source, TimeSource::Lab(_))
338    }
339
340    fn parent_remaining_us(&self) -> u64 {
341        match &self.inner.parent {
342            Some(parent) => {
343                let parent_cx = Cx {
344                    inner: parent.clone(),
345                };
346                parent_cx.remaining_us().unwrap_or(u64::MAX)
347            }
348            None => u64::MAX,
349        }
350    }
351
352    // ── Convenience ──────────────────────────────────────────────────
353
354    /// Sleep for the given duration, respecting cancellation and deadline.
355    ///
356    /// Returns `true` if the full duration elapsed, `false` if cancelled or
357    /// deadline expired early.
358    pub fn sleep(&self, duration: Duration) -> bool {
359        let effective = match self.remaining() {
360            Some(rem) => duration.min(rem),
361            None => duration,
362        };
363        if effective.is_zero() || self.is_cancelled() {
364            return false;
365        }
366
367        // Use small sleep chunks for responsive cancellation checking
368        let chunk = Duration::from_millis(10);
369        let mut remaining = effective;
370        while remaining > Duration::ZERO && !self.is_cancelled() {
371            let sleep_time = remaining.min(chunk);
372            std::thread::sleep(sleep_time);
373            remaining = remaining.saturating_sub(sleep_time);
374        }
375        !self.is_cancelled() && remaining.is_zero()
376    }
377}
378
379// ─── CxController ────────────────────────────────────────────────────────────
380
381/// Control handle for a [`Cx`].
382///
383/// Held by the owner of the context to trigger cancellation.
384/// Dropping the controller does **not** cancel the context — cancellation
385/// is always explicit.
386#[derive(Debug)]
387pub struct CxController {
388    inner: Arc<CxInner>,
389}
390
391impl CxController {
392    /// Cancel the associated context.
393    ///
394    /// All clones of the `Cx` (and children) will observe `is_cancelled() == true`.
395    pub fn cancel(&self) {
396        let was_cancelled = self.inner.cancelled.swap(true, Ordering::Release);
397        if !was_cancelled {
398            CX_CANCELLATIONS_TOTAL.fetch_add(1, Ordering::Relaxed);
399            warn!(cx_id = self.inner.id, "cx cancelled");
400        }
401    }
402
403    /// Whether this context has already been cancelled.
404    #[inline]
405    #[must_use]
406    pub fn is_cancelled(&self) -> bool {
407        self.inner.cancelled.load(Ordering::Acquire)
408    }
409}
410
411// ─── CxError ─────────────────────────────────────────────────────────────────
412
413/// Error returned when an operation is cancelled or times out via `Cx`.
414#[derive(Debug, Clone, PartialEq, Eq)]
415pub enum CxError {
416    /// The context was explicitly cancelled.
417    Cancelled,
418    /// The context deadline expired.
419    DeadlineExceeded,
420}
421
422impl std::fmt::Display for CxError {
423    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
424        match self {
425            Self::Cancelled => write!(f, "context cancelled"),
426            Self::DeadlineExceeded => write!(f, "deadline exceeded"),
427        }
428    }
429}
430
431impl std::error::Error for CxError {}
432
433impl Cx {
434    /// Check if the context is still live; return `Err` if cancelled or expired.
435    ///
436    /// Intended for use at yield points:
437    /// ```ignore
438    /// cx.check()?;
439    /// // ... continue work ...
440    /// ```
441    pub fn check(&self) -> Result<(), CxError> {
442        let cancelled = self.is_cancelled();
443        let deadline_remaining_us = self.remaining_us().unwrap_or(u64::MAX);
444        let propagate_span = info_span!(
445            "cx.propagate",
446            cx_id = self.id(),
447            deadline_remaining_us,
448            cx_cancelled = cancelled
449        );
450        let _propagate_span = propagate_span.enter();
451
452        if cancelled {
453            warn!(
454                cx_id = self.id(),
455                deadline_remaining_us, "cx.propagate cancelled"
456            );
457            return Err(CxError::Cancelled);
458        }
459        if deadline_remaining_us == 0 {
460            return Err(CxError::DeadlineExceeded);
461        }
462        Ok(())
463    }
464}
465
466// ─── Tests ───────────────────────────────────────────────────────────────────
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use std::sync::mpsc;
472    #[cfg(feature = "tracing-json")]
473    use std::sync::{Arc, Mutex};
474
475    #[cfg(feature = "tracing-json")]
476    use tracing::Subscriber;
477    #[cfg(feature = "tracing-json")]
478    use tracing::field::{Field, Visit};
479    #[cfg(feature = "tracing-json")]
480    use tracing_subscriber::filter::LevelFilter;
481    #[cfg(feature = "tracing-json")]
482    use tracing_subscriber::layer::{Context, Layer};
483    #[cfg(feature = "tracing-json")]
484    use tracing_subscriber::prelude::*;
485    #[cfg(feature = "tracing-json")]
486    use tracing_subscriber::registry::LookupSpan;
487
488    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
489    struct TestModel {
490        value: u32,
491    }
492
493    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
494    enum RenderStrategy {
495        Full,
496        Degraded,
497    }
498
499    #[derive(Debug, Clone, PartialEq, Eq)]
500    enum MissingCxError {
501        MissingContext,
502        Cx(CxError),
503    }
504
505    fn update_with_cx(cx: &Cx, model: &mut TestModel, delta: u32) -> Result<(), CxError> {
506        cx.check()?;
507        model.value = model.value.saturating_add(delta);
508        Ok(())
509    }
510
511    fn update_with_optional_cx(
512        cx: Option<&Cx>,
513        model: &mut TestModel,
514        delta: u32,
515    ) -> Result<(), MissingCxError> {
516        let cx = cx.ok_or(MissingCxError::MissingContext)?;
517        update_with_cx(cx, model, delta).map_err(MissingCxError::Cx)
518    }
519
520    fn render_widget_with_cx_atomic(
521        cx: &Cx,
522        source: &str,
523        sink: &mut String,
524        mut on_chunk: impl FnMut(usize),
525    ) -> Result<(), CxError> {
526        let mut scratch = String::new();
527        for (idx, ch) in source.chars().enumerate() {
528            scratch.push(ch);
529            on_chunk(idx);
530            cx.check()?;
531        }
532        sink.push_str(&scratch);
533        Ok(())
534    }
535
536    fn subscription_send_with_cx(
537        cx: &Cx,
538        sender: &mpsc::Sender<u32>,
539        payload: u32,
540    ) -> Result<(), CxError> {
541        cx.check()?;
542        sender.send(payload).map_err(|_| CxError::Cancelled)
543    }
544
545    fn choose_render_strategy(cx: &Cx, downgrade_threshold: Duration) -> RenderStrategy {
546        match cx.remaining() {
547            Some(remaining) if remaining <= downgrade_threshold => RenderStrategy::Degraded,
548            _ => RenderStrategy::Full,
549        }
550    }
551
552    #[test]
553    fn background_cx_is_not_cancelled() {
554        let (cx, _ctrl) = Cx::background();
555        assert!(!cx.is_cancelled());
556        assert!(!cx.is_expired());
557        assert!(!cx.is_done());
558        assert!(cx.deadline().is_none());
559    }
560
561    #[test]
562    fn cancel_propagates() {
563        let (cx, ctrl) = Cx::background();
564        assert!(!cx.is_cancelled());
565        ctrl.cancel();
566        assert!(cx.is_cancelled());
567        assert!(cx.is_done());
568    }
569
570    #[test]
571    fn clone_shares_cancellation() {
572        let (cx, ctrl) = Cx::background();
573        let cx2 = cx.clone();
574        ctrl.cancel();
575        assert!(cx.is_cancelled());
576        assert!(cx2.is_cancelled());
577    }
578
579    #[test]
580    fn deadline_reports_remaining() {
581        let (cx, _ctrl) = Cx::with_deadline(Duration::from_secs(10));
582        let rem = cx.remaining().expect("should have deadline");
583        // Should be close to 10 seconds (minus tiny elapsed)
584        assert!(rem.as_secs() >= 9);
585    }
586
587    #[test]
588    fn child_inherits_cancellation() {
589        let (parent, parent_ctrl) = Cx::background();
590        let (child, _child_ctrl) = parent.child(Duration::from_secs(60));
591        assert!(!child.is_cancelled());
592        parent_ctrl.cancel();
593        assert!(child.is_cancelled());
594    }
595
596    #[test]
597    fn child_has_tighter_deadline() {
598        let (parent, _) = Cx::with_deadline(Duration::from_secs(60));
599        let (child, _) = parent.child(Duration::from_millis(100));
600        let child_rem = child.remaining().expect("child has deadline");
601        // Child deadline should be ~100ms, much less than parent's 60s
602        assert!(child_rem < Duration::from_secs(1));
603    }
604
605    #[test]
606    fn child_respects_parent_tighter_deadline() {
607        let (parent, _) = Cx::with_deadline(Duration::from_millis(50));
608        let (child, _) = parent.child(Duration::from_secs(60));
609        let child_rem = child.remaining().expect("child has deadline via parent");
610        // Parent deadline is tighter, child should see ~50ms
611        assert!(child_rem < Duration::from_secs(1));
612    }
613
614    #[test]
615    fn lab_clock_deterministic() {
616        let clock = LabClock::new();
617        let (cx, _ctrl) = Cx::lab_with_deadline(&clock, Duration::from_millis(100));
618
619        // At t=0, should have ~100ms remaining
620        let r1 = cx.remaining().expect("has deadline");
621        assert!(r1 >= Duration::from_millis(90));
622
623        // Advance 80ms
624        clock.advance(Duration::from_millis(80));
625        let r2 = cx.remaining().expect("has deadline");
626        assert!(r2 <= Duration::from_millis(25));
627        assert!(!cx.is_expired());
628
629        // Advance past deadline
630        clock.advance(Duration::from_millis(30));
631        assert!(cx.is_expired());
632        assert!(cx.is_done());
633    }
634
635    #[test]
636    fn check_returns_ok_when_live() {
637        let (cx, _ctrl) = Cx::background();
638        assert!(cx.check().is_ok());
639    }
640
641    #[test]
642    fn check_returns_cancelled() {
643        let (cx, ctrl) = Cx::background();
644        ctrl.cancel();
645        assert_eq!(cx.check(), Err(CxError::Cancelled));
646    }
647
648    #[test]
649    fn check_returns_deadline_exceeded() {
650        let clock = LabClock::new();
651        let (cx, _ctrl) = Cx::lab_with_deadline(&clock, Duration::from_millis(10));
652        clock.advance(Duration::from_millis(20));
653        assert_eq!(cx.check(), Err(CxError::DeadlineExceeded));
654    }
655
656    #[test]
657    fn cx_id_is_unique() {
658        let (cx1, _) = Cx::background();
659        let (cx2, _) = Cx::background();
660        assert_ne!(cx1.id(), cx2.id());
661    }
662
663    #[test]
664    fn cx_is_lab() {
665        let clock = LabClock::new();
666        let (cx_lab, _) = Cx::lab(&clock);
667        let (cx_real, _) = Cx::background();
668        assert!(cx_lab.is_lab());
669        assert!(!cx_real.is_lab());
670    }
671
672    #[test]
673    fn child_inherit_no_deadline() {
674        let (parent, _) = Cx::background();
675        let (child, _) = parent.child_inherit();
676        assert!(child.deadline().is_none());
677    }
678
679    #[test]
680    fn child_inherit_with_parent_deadline() {
681        let (parent, _) = Cx::with_deadline(Duration::from_secs(30));
682        let (child, _) = parent.child_inherit();
683        // Child has no own deadline but inherits parent's
684        let rem = child.remaining().expect("inherits parent deadline");
685        assert!(rem > Duration::from_secs(28));
686    }
687
688    #[test]
689    fn cx_error_display() {
690        assert_eq!(CxError::Cancelled.to_string(), "context cancelled");
691        assert_eq!(CxError::DeadlineExceeded.to_string(), "deadline exceeded");
692    }
693
694    #[test]
695    fn controller_is_cancelled_matches_cx() {
696        let (cx, ctrl) = Cx::background();
697        assert!(!ctrl.is_cancelled());
698        ctrl.cancel();
699        assert!(ctrl.is_cancelled());
700        assert!(cx.is_cancelled());
701    }
702
703    #[test]
704    fn double_cancel_is_idempotent() {
705        let (cx, ctrl) = Cx::background();
706        ctrl.cancel();
707        ctrl.cancel();
708        assert!(cx.is_cancelled());
709    }
710
711    #[test]
712    fn lab_clock_advance_accumulates() {
713        let clock = LabClock::new();
714        let t0 = clock.now();
715        clock.advance(Duration::from_millis(100));
716        clock.advance(Duration::from_millis(200));
717        let elapsed = clock.now().saturating_duration_since(t0);
718        // Should be ~300ms
719        assert!(elapsed >= Duration::from_millis(290));
720        assert!(elapsed <= Duration::from_millis(310));
721    }
722
723    #[test]
724    fn cancellation_counter_increments() {
725        let before = cx_cancellations_total();
726        let (_cx, ctrl) = Cx::background();
727        ctrl.cancel();
728        assert!(cx_cancellations_total() > before);
729        // Double cancel should not increment again
730        let after_first = cx_cancellations_total();
731        ctrl.cancel();
732        assert_eq!(cx_cancellations_total(), after_first);
733    }
734
735    #[test]
736    fn sleep_respects_cancellation() {
737        let (cx, ctrl) = Cx::background();
738        // Cancel immediately so sleep returns false
739        ctrl.cancel();
740        let completed = cx.sleep(Duration::from_secs(10));
741        assert!(!completed);
742    }
743
744    #[test]
745    fn sleep_respects_lab_deadline() {
746        let clock = LabClock::new();
747        let (cx, _ctrl) = Cx::lab_with_deadline(&clock, Duration::from_millis(5));
748        // Advance past deadline
749        clock.advance(Duration::from_millis(10));
750        let completed = cx.sleep(Duration::from_secs(10));
751        assert!(!completed);
752    }
753
754    #[test]
755    fn cx_propagates_across_update_render_and_subscription_phases() {
756        let clock = LabClock::new();
757        let (cx, _ctrl) = Cx::lab_with_deadline(&clock, Duration::from_millis(100));
758        let mut model = TestModel::default();
759
760        update_with_cx(&cx, &mut model, 7).expect("update should respect live cx");
761        let mut rendered = String::new();
762        render_widget_with_cx_atomic(&cx, "ok", &mut rendered, |_| {})
763            .expect("render should respect live cx");
764
765        let (tx, rx) = mpsc::channel();
766        subscription_send_with_cx(&cx, &tx, model.value)
767            .expect("subscription should respect live cx");
768
769        assert_eq!(model.value, 7);
770        assert_eq!(rendered, "ok");
771        assert_eq!(rx.try_recv().expect("subscription payload"), 7);
772    }
773
774    #[test]
775    fn cancellation_mid_render_aborts_without_partial_output() {
776        let clock = LabClock::new();
777        let (cx, ctrl) = Cx::lab(&clock);
778        let mut sink = String::from("prefix:");
779
780        let result = render_widget_with_cx_atomic(&cx, "render-me", &mut sink, |idx| {
781            if idx == 2 {
782                ctrl.cancel();
783            }
784        });
785
786        assert_eq!(result, Err(CxError::Cancelled));
787        assert_eq!(sink, "prefix:");
788    }
789
790    #[test]
791    fn deadline_enforcement_triggers_strategy_downgrade() {
792        let clock = LabClock::new();
793        let (cx, _ctrl) = Cx::lab_with_deadline(&clock, Duration::from_millis(50));
794
795        assert_eq!(
796            choose_render_strategy(&cx, Duration::from_millis(10)),
797            RenderStrategy::Full
798        );
799
800        clock.advance(Duration::from_millis(45));
801        assert_eq!(
802            choose_render_strategy(&cx, Duration::from_millis(10)),
803            RenderStrategy::Degraded
804        );
805    }
806
807    #[test]
808    fn missing_cx_returns_clear_runtime_error() {
809        let mut model = TestModel::default();
810        let err = update_with_optional_cx(None, &mut model, 1).expect_err("missing cx");
811        assert_eq!(err, MissingCxError::MissingContext);
812        assert_eq!(model.value, 0, "state should remain unchanged without cx");
813    }
814
815    #[test]
816    fn test_time_scale_defaults_to_one() {
817        assert_eq!(test_time_scale_from_reader(|_| None), 1);
818        assert_eq!(test_time_scale_from_reader(|_| Some(String::new())), 1);
819        assert_eq!(test_time_scale_from_reader(|_| Some("0".to_string())), 1);
820        assert_eq!(
821            test_time_scale_from_reader(|_| Some("invalid".to_string())),
822            1
823        );
824        assert!(test_time_scale() >= 1);
825    }
826
827    #[test]
828    fn test_time_scale_parses_env() {
829        assert_eq!(
830            test_time_scale_from_reader(|key| {
831                assert_eq!(key, "FTUI_TEST_TIME_SCALE");
832                Some("4".to_string())
833            }),
834            4
835        );
836        assert_eq!(test_time_scale_from_reader(|_| Some(" 8 ".to_string())), 8);
837    }
838
839    #[cfg(feature = "tracing-json")]
840    #[derive(Default, Clone)]
841    struct TraceCaptureLayer {
842        spans: Arc<Mutex<Vec<String>>>,
843        events: Arc<Mutex<Vec<String>>>,
844    }
845
846    #[cfg(feature = "tracing-json")]
847    #[derive(Default)]
848    struct EventMessageVisitor {
849        message: Option<String>,
850    }
851
852    #[cfg(feature = "tracing-json")]
853    impl Visit for EventMessageVisitor {
854        fn record_str(&mut self, field: &Field, value: &str) {
855            if field.name() == "message" {
856                self.message = Some(value.to_string());
857            }
858        }
859
860        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
861            if field.name() == "message" {
862                self.message = Some(format!("{value:?}"));
863            }
864        }
865    }
866
867    #[cfg(feature = "tracing-json")]
868    impl<S> Layer<S> for TraceCaptureLayer
869    where
870        S: Subscriber + for<'lookup> LookupSpan<'lookup>,
871    {
872        fn on_new_span(
873            &self,
874            attrs: &tracing::span::Attributes<'_>,
875            _id: &tracing::span::Id,
876            _ctx: Context<'_, S>,
877        ) {
878            self.spans
879                .lock()
880                .expect("span capture lock")
881                .push(attrs.metadata().name().to_string());
882        }
883
884        fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
885            let mut visitor = EventMessageVisitor::default();
886            event.record(&mut visitor);
887            let message = visitor.message.unwrap_or_default();
888            self.events
889                .lock()
890                .expect("event capture lock")
891                .push(format!("{}:{}", event.metadata().level(), message));
892        }
893    }
894
895    #[cfg(feature = "tracing-json")]
896    #[test]
897    fn check_emits_cx_propagate_span_and_warns_on_cancellation() {
898        let capture = TraceCaptureLayer::default();
899        let subscriber =
900            tracing_subscriber::registry().with(capture.clone().with_filter(LevelFilter::TRACE));
901        let _guard = tracing::subscriber::set_default(subscriber);
902
903        let (cx, ctrl) = Cx::background();
904        ctrl.cancel();
905        let result = cx.check();
906        assert_eq!(result, Err(CxError::Cancelled));
907
908        let spans = capture.spans.lock().expect("span capture lock");
909        assert!(
910            spans.iter().any(|name| name == "cx.propagate"),
911            "expected cx.propagate span, got {spans:?}"
912        );
913        drop(spans);
914
915        let events = capture.events.lock().expect("event capture lock");
916        assert!(
917            events
918                .iter()
919                .any(|event| event.contains("WARN:cx cancelled")),
920            "expected cancellation WARN event, got {events:?}"
921        );
922        assert!(
923            events
924                .iter()
925                .any(|event| event.contains("WARN:cx.propagate cancelled")),
926            "expected cx.propagate WARN event, got {events:?}"
927        );
928    }
929}