fluxframe-cli 0.8.0

fluxframe CLI binary: list, check, run, benchmark.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Idle-mode state machine.
//!
//! Pure function over (current state, observed consumer status,
//! `now: Instant`, [`IdleConfig`]). No I/O, no global clock — the
//! worker injects the timestamp it observed. This makes every
//! transition reproducible in unit tests with synthetic timestamps.
//!
//! ## State diagram
//!
//! ```text
//!                 consumer Present ("capture")
//!                ┌──────────────────────────────────────┐
//!                │                                      │
//!                ▼                                      │
//!        ┌───────────────┐  Absent 5 s        ┌────────┴────────┐
//!        │    Active     │ ───────────────►   │      Idle       │
//!        │ (full chain)  │                    │ (input Null,    │
//!        │ engine_ready  │ ◄──────────────    │  placeholder)   │
//!        └───────┬───────┘   Present          └─────────────────┘
//!                │ Absent                       Idle is terminal
//!                │ (5s cooldown timer)          until a consumer
//!                ▼                              reattaches.
//!        ┌───────────────┐
//!        │   Cooldown    │
//!        │ (still full,  │
//!        │  flips soon)  │
//!        └───────────────┘
//! ```
//!
//! The `DeepIdle` state was removed in Stage 16: it never actually
//! unloaded the ONNX session (a parked TODO) so it was observationally
//! identical to `Idle`, and it could leave the daemon wedged. The
//! ONNX-unload RAM reclamation is deferred to a separate work item.
//!
//! Cooldown is observably identical to Active from the outside — it
//! just delays the flip to Idle so a consumer reopen within 5 s never
//! sees input torn down. A `Present` observation at any depth cancels
//! the cooldown timer and triggers `ResumeActive`.

use std::time::{Duration, Instant};

use fluxframe_core::IdleConfig;

/// Observed consumer status from the sysfs detector. The numeric
/// values are stable because Step 3 stores them in an `AtomicU8`.
///
/// ## Invariants
///
/// - `#[repr(u8)]` guarantees ABI stability of the discriminants across
///   rustc versions, so the `AtomicU8` payload survives recompiles.
/// - [`Self::from_u8`] is total: every `u8` maps to a defined variant
///   (unknown discriminants collapse to [`ConsumerStatus::Unknown`]).
///   This is the fail-open contract — a corrupted or future-tagged
///   write never panics the worker.
/// - The Step 3 detector → worker channel is single-producer /
///   single-consumer and carries advisory data only, so `Relaxed`
///   ordering would suffice in principle. The detector publishes
///   with `Release` and the worker loads with `Acquire` as a
///   defensive default: cost on x86_64 is identical to `Relaxed`,
///   and the stronger ordering simplifies correctness proofs if
///   future state is ever piggybacked on the status atomic.
/// - [`IdleStateMachine`] is owned exclusively by the worker thread.
///   The atomic only crosses the detector → worker boundary; the
///   state machine itself never sees concurrent access.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum ConsumerStatus {
    /// At least one reader is attached and streaming (sysfs reads
    /// `"capture"`).
    Present = 1,
    /// No reader streaming (sysfs reads `"output"`).
    Absent = 0,
    /// Sysfs file unreadable (missing, permission denied, or other I/O
    /// error). Treated as `Present` by the state machine — fail-open so
    /// idle never fires on a misconfigured detector.
    Unknown = 2,
}

impl ConsumerStatus {
    /// Decode an `AtomicU8` value. Unknown numeric values fall back to
    /// [`ConsumerStatus::Unknown`].
    pub(crate) fn from_u8(raw: u8) -> Self {
        match raw {
            0 => ConsumerStatus::Absent,
            1 => ConsumerStatus::Present,
            _ => ConsumerStatus::Unknown,
        }
    }

    /// Encode for the `AtomicU8`.
    pub(crate) fn as_u8(self) -> u8 {
        self as u8
    }

    /// Should the state machine treat this status as "consumer is
    /// there"? `Present` and `Unknown` are both fail-open; only
    /// `Absent` advances the cooldown.
    fn is_present_or_unknown(self) -> bool {
        !matches!(self, ConsumerStatus::Absent)
    }
}

/// Discrete lifecycle state. The state machine internally tracks the
/// instant of the last transition to compute cooldown elapsed time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IdleState {
    /// Full processing pipeline running.
    Active,
    /// Consumer just disconnected; the supervisor is waiting out
    /// `teardown_secs` before flipping to Idle. Externally identical
    /// to Active.
    Cooldown,
    /// Input torn down, placeholder published. ONNX session still
    /// resident. Terminal until a consumer reattaches.
    Idle,
}

/// One-shot side effect fired at a state transition. The worker
/// dispatches input pipeline state changes, reload-thread spawns,
/// and the placeholder-flush on `ResumeActive` based on this value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IdleEdge {
    /// No transition happened on this tick.
    None,
    /// Active/Cooldown → Idle. Tear down input, flush stale frames.
    EnterIdle,
    /// Idle → Active. Spawn the reload thread; the worker keeps
    /// publishing placeholder until `engine_ready` flips true.
    ResumeActive,
}

/// Steady-state behaviour for this iteration. The worker uses this
/// to choose between `process_one_frame` (Active) and
/// `push_placeholder` (Placeholder).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IdleLevel {
    /// Pull a frame from the slot and run the effect chain.
    Active,
    /// Push the cached placeholder.
    Placeholder,
}

/// Tick output. Edge fires once per transition; level describes the
/// steady-state for the next loop iteration; `next_tick_in` is the
/// upper bound the worker should park before re-evaluating.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct IdleTick {
    pub edge: IdleEdge,
    pub level: IdleLevel,
    pub next_tick_in: Duration,
}

/// Normalised, structurally exhaustive view of [`ConsumerStatus`]
/// used inside [`IdleStateMachine::tick`]. Unknown collapses to
/// `Present` at the call site (fail-open), so the match in `tick`
/// covers all `(IdleState, Effective)` pairs without a guard.
///
/// Private to the module — never appears in the public surface.
enum Effective {
    Present,
    Absent,
}

/// The state machine. Field visibility is `pub(crate)` only on the
/// public surface needed by the worker; the timer is internal.
///
/// Owned exclusively by the worker thread — never shared. The detector
/// publishes status through an `AtomicU8`; the worker decodes it once
/// per tick and feeds it here.
#[derive(Debug)]
pub(crate) struct IdleStateMachine {
    state: IdleState,
    /// Instant of the last state transition. Used to compute the
    /// cooldown elapsed time. Initialised to the construction instant
    /// so the first tick has a sensible baseline.
    last_change: Instant,
}

impl IdleStateMachine {
    /// New state machine starting in [`IdleState::Active`].
    ///
    /// `now` is injected so unit tests can fix the initial baseline.
    /// The production caller passes `Instant::now()` once at startup.
    pub(crate) fn new(now: Instant) -> Self {
        Self {
            state: IdleState::Active,
            last_change: now,
        }
    }

    /// Current state — exposed for telemetry / log lines only. The
    /// worker should never branch on this directly; use the
    /// `IdleTick::level` returned by [`Self::tick`].
    #[cfg_attr(
        not(test),
        expect(dead_code, reason = "Stage 15 Step 4 wires the supervisor")
    )]
    pub(crate) fn state(&self) -> IdleState {
        self.state
    }

    /// Advance the state machine.
    ///
    /// Pure function of (current state, observed status, elapsed
    /// since last transition, config). Returns the side-effect edge,
    /// the steady-state level for the next loop iteration, and a hint
    /// for how long the worker should park before re-evaluating.
    ///
    /// Cooldown/deep-idle thresholds come from `cfg` so a runtime
    /// `reload` of the config picks them up on the next tick without
    /// reconstructing the machine.
    pub(crate) fn tick(
        &mut self,
        status: ConsumerStatus,
        now: Instant,
        cfg: &IdleConfig,
    ) -> IdleTick {
        let elapsed = now.saturating_duration_since(self.last_change);
        let teardown = Duration::from_secs(u64::from(cfg.teardown_secs));

        // Normalise the tri-state observation into a structurally
        // exhaustive two-state input. Unknown collapses to Present —
        // fail-open so a misconfigured detector never advances the
        // cooldown. The match below operates on
        // `(IdleState, Effective)` and covers all eight pairs
        // explicitly; no `unreachable!()` placeholder is needed.
        let effective = if status.is_present_or_unknown() {
            Effective::Present
        } else {
            Effective::Absent
        };

        let (new_state, edge) = match (self.state, effective) {
            // Active
            (IdleState::Active, Effective::Present) => (IdleState::Active, IdleEdge::None),
            (IdleState::Active, Effective::Absent) => {
                // Enter Cooldown but do not tear anything down yet —
                // the timer ticks while the worker keeps pulling
                // real frames. The transition resets `last_change`.
                (IdleState::Cooldown, IdleEdge::None)
            }

            // Cooldown
            (IdleState::Cooldown, Effective::Present) => {
                // Reader came back during the grace window — cancel
                // the cooldown and snap back to Active. No teardown
                // happened, so no resume side-effect is needed.
                (IdleState::Active, IdleEdge::None)
            }
            (IdleState::Cooldown, Effective::Absent) => {
                if elapsed >= teardown {
                    (IdleState::Idle, IdleEdge::EnterIdle)
                } else {
                    (IdleState::Cooldown, IdleEdge::None)
                }
            }

            // Idle Present — a reader reattached; resume. The reload
            // thread spawned by `ResumeActive` restarts the input (the
            // engine is still warm, so the rebuild is cheap).
            (IdleState::Idle, Effective::Present) => (IdleState::Active, IdleEdge::ResumeActive),

            // Idle Absent — terminal until a consumer reattaches. The
            // worker keeps publishing the placeholder so the loopback
            // stays visible to capability-filtering consumers.
            (IdleState::Idle, Effective::Absent) => (IdleState::Idle, IdleEdge::None),
        };

        if new_state != self.state {
            self.last_change = now;
            self.state = new_state;
        }

        let level = match new_state {
            IdleState::Active | IdleState::Cooldown => IdleLevel::Active,
            IdleState::Idle => IdleLevel::Placeholder,
        };

        // Next-tick hint. In steady-state Active/Cooldown the worker
        // re-evaluates every frame, so any non-zero value works; we
        // pick the poll interval so the worker does not over-park
        // waiting for status changes. In Idle the worker sleeps
        // `1 / effective_fps` between placeholder pushes.
        let next_tick_in = match new_state {
            IdleState::Active | IdleState::Cooldown => {
                Duration::from_millis(u64::from(cfg.poll_interval_ms))
            }
            IdleState::Idle => {
                // Effective idle cadence is the max of the cosmetic
                // `fps` and the `min_visibility_fps` heartbeat: the
                // latter keeps v4l2loopback advertising CAPTURE caps so
                // Chrome/WebRTC keep enumerating the device. Both are
                // validated > 0 by FluxConfig::validate; saturate
                // defensively against a mid-flight Stage 13 control
                // command that lands before re-validation.
                let fps = cfg.fps.max(cfg.min_visibility_fps).max(1);
                Duration::from_millis(1000 / u64::from(fps))
            }
        };

        IdleTick {
            edge,
            level,
            next_tick_in,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fluxframe_core::IdleConfig;

    /// Build a config with explicit thresholds. The validated TOML
    /// defaults are: teardown = 5 s, deep = 30 s; tests use shorter
    /// values to keep the timestamp arithmetic readable.
    fn cfg(teardown_secs: u32, deep_idle_secs: u32) -> IdleConfig {
        IdleConfig {
            enabled: true,
            teardown_secs,
            deep_idle_secs,
            ..IdleConfig::default()
        }
    }

    fn t0() -> Instant {
        Instant::now()
    }

    // ============================================================
    // Active row (4 cases — Present, Absent, Unknown × before/after
    // are collapsed since Active has no internal timer that matters).
    // ============================================================

    #[test]
    fn active_present_stays_active() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        let tick = sm.tick(ConsumerStatus::Present, now, &cfg(5, 30));
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(tick.edge, IdleEdge::None);
        assert_eq!(tick.level, IdleLevel::Active);
    }

    #[test]
    fn active_unknown_stays_active() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        let tick = sm.tick(ConsumerStatus::Unknown, now, &cfg(5, 30));
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(tick.edge, IdleEdge::None);
        assert_eq!(tick.level, IdleLevel::Active);
    }

    #[test]
    fn active_absent_enters_cooldown_with_no_edge() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        let tick = sm.tick(ConsumerStatus::Absent, now, &cfg(5, 30));
        assert_eq!(sm.state(), IdleState::Cooldown);
        assert_eq!(
            tick.edge,
            IdleEdge::None,
            "cooldown entry has no side effect — input still running"
        );
        assert_eq!(tick.level, IdleLevel::Active);
    }

    // ============================================================
    // Cooldown row (6 cases — Present/Absent/Unknown × before timer
    // expires and after, except Present/Unknown which short-circuit).
    // ============================================================

    #[test]
    fn cooldown_present_cancels_to_active_no_edge() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(5, 30)); // → Cooldown
        let tick = sm.tick(
            ConsumerStatus::Present,
            now + Duration::from_secs(2),
            &cfg(5, 30),
        );
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(
            tick.edge,
            IdleEdge::None,
            "no teardown happened in Cooldown, so resume has no side effect"
        );
        assert_eq!(tick.level, IdleLevel::Active);
    }

    #[test]
    fn cooldown_unknown_cancels_to_active_no_edge() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(5, 30));
        let tick = sm.tick(
            ConsumerStatus::Unknown,
            now + Duration::from_secs(2),
            &cfg(5, 30),
        );
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(tick.edge, IdleEdge::None);
    }

    #[test]
    fn cooldown_absent_before_timer_stays_cooldown() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(5, 30));
        let tick = sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(2),
            &cfg(5, 30),
        );
        assert_eq!(sm.state(), IdleState::Cooldown);
        assert_eq!(tick.edge, IdleEdge::None);
        assert_eq!(tick.level, IdleLevel::Active);
    }

    #[test]
    fn cooldown_absent_at_timer_flips_to_idle_with_edge() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(5, 30));
        let tick = sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(5),
            &cfg(5, 30),
        );
        assert_eq!(sm.state(), IdleState::Idle);
        assert_eq!(
            tick.edge,
            IdleEdge::EnterIdle,
            "cooldown expiry must fire EnterIdle so worker tears down input"
        );
        assert_eq!(tick.level, IdleLevel::Placeholder);
    }

    #[test]
    fn cooldown_absent_past_timer_flips_to_idle() {
        // Worker may miss exact tick at the boundary; advance well
        // past the threshold.
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(5, 30));
        let tick = sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(10),
            &cfg(5, 30),
        );
        assert_eq!(sm.state(), IdleState::Idle);
        assert_eq!(tick.edge, IdleEdge::EnterIdle);
    }

    // ============================================================
    // Idle row (6 cases — Present/Absent/Unknown × before/after the
    // deep-idle threshold).
    // ============================================================

    #[test]
    fn idle_present_resumes_active_with_edge() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        // Force into Idle.
        sm.tick(ConsumerStatus::Absent, now, &cfg(1, 10));
        sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(1),
            &cfg(1, 10),
        );
        assert_eq!(sm.state(), IdleState::Idle);

        let tick = sm.tick(
            ConsumerStatus::Present,
            now + Duration::from_secs(2),
            &cfg(1, 10),
        );
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(
            tick.edge,
            IdleEdge::ResumeActive,
            "Idle → Active must fire ResumeActive so worker spawns reload thread"
        );
        assert_eq!(tick.level, IdleLevel::Active);
    }

    #[test]
    fn idle_unknown_resumes_active() {
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(1, 10));
        sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(1),
            &cfg(1, 10),
        );
        let tick = sm.tick(
            ConsumerStatus::Unknown,
            now + Duration::from_secs(2),
            &cfg(1, 10),
        );
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(tick.edge, IdleEdge::ResumeActive);
    }

    #[test]
    fn idle_absent_stays_idle_terminal() {
        // After DeepIdle removal (Stage 16), Idle is terminal under
        // continued Absent: the worker keeps streaming the placeholder
        // so the loopback stays visible, but the state never advances.
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg(1, 30));
        sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(1),
            &cfg(1, 30),
        );
        assert_eq!(sm.state(), IdleState::Idle);

        // Far past any former deep-idle threshold — still Idle, no edge.
        let tick = sm.tick(
            ConsumerStatus::Absent,
            now + Duration::from_secs(120),
            &cfg(1, 30),
        );
        assert_eq!(sm.state(), IdleState::Idle);
        assert_eq!(tick.edge, IdleEdge::None);
        assert_eq!(tick.level, IdleLevel::Placeholder);
    }

    // ============================================================
    // Cross-cutting properties.
    // ============================================================

    #[test]
    fn full_lifecycle_walk() {
        // Active → Cooldown → Idle → Active in one walk.
        let cfg = cfg(1, 5);
        let now = t0();
        let mut sm = IdleStateMachine::new(now);

        // Active → Cooldown (Absent).
        let t = now;
        sm.tick(ConsumerStatus::Absent, t, &cfg);
        assert_eq!(sm.state(), IdleState::Cooldown);

        // Cooldown → Idle (timer fires).
        let t = t + Duration::from_secs(1);
        let tick = sm.tick(ConsumerStatus::Absent, t, &cfg);
        assert_eq!(tick.edge, IdleEdge::EnterIdle);
        assert_eq!(sm.state(), IdleState::Idle);

        // Idle stays Idle under continued Absent (terminal).
        let t = t + Duration::from_secs(5);
        let tick = sm.tick(ConsumerStatus::Absent, t, &cfg);
        assert_eq!(tick.edge, IdleEdge::None);
        assert_eq!(sm.state(), IdleState::Idle);

        // Idle → Active (Present).
        let t = t + Duration::from_secs(1);
        let tick = sm.tick(ConsumerStatus::Present, t, &cfg);
        assert_eq!(tick.edge, IdleEdge::ResumeActive);
        assert_eq!(sm.state(), IdleState::Active);
    }

    #[test]
    fn consumer_status_round_trips_through_u8() {
        for s in [
            ConsumerStatus::Present,
            ConsumerStatus::Absent,
            ConsumerStatus::Unknown,
        ] {
            assert_eq!(ConsumerStatus::from_u8(s.as_u8()), s);
        }
        // Out-of-range numeric value falls back to Unknown rather than
        // panicking — the detector might one day write a status the
        // worker does not yet know about; fail-open is safer than
        // crashing.
        assert_eq!(ConsumerStatus::from_u8(99), ConsumerStatus::Unknown);
    }

    #[test]
    fn level_tracks_state() {
        let cfg = cfg(1, 5);
        let now = t0();
        let mut sm = IdleStateMachine::new(now);

        // Active level
        let tick = sm.tick(ConsumerStatus::Present, now, &cfg);
        assert_eq!(tick.level, IdleLevel::Active);

        // Cooldown level (still Active)
        let tick = sm.tick(ConsumerStatus::Absent, now, &cfg);
        assert_eq!(tick.level, IdleLevel::Active);

        // Idle level
        let tick = sm.tick(ConsumerStatus::Absent, now + Duration::from_secs(1), &cfg);
        assert_eq!(tick.level, IdleLevel::Placeholder);
    }

    #[test]
    fn next_tick_in_uses_poll_interval_when_active() {
        let cfg = IdleConfig {
            enabled: true,
            poll_interval_ms: 250,
            ..IdleConfig::default()
        };
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        let tick = sm.tick(ConsumerStatus::Present, now, &cfg);
        assert_eq!(tick.next_tick_in, Duration::from_millis(250));
    }

    #[test]
    fn next_tick_in_uses_fps_period_when_idle() {
        let cfg = IdleConfig {
            enabled: true,
            teardown_secs: 1,
            deep_idle_secs: 10,
            fps: 5,
            // Pin the visibility floor below `fps` so this test exercises
            // the cosmetic `fps` path, not the heartbeat clamp.
            min_visibility_fps: 1,
            ..IdleConfig::default()
        };
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg);
        let tick = sm.tick(ConsumerStatus::Absent, now + Duration::from_secs(1), &cfg);
        assert_eq!(sm.state(), IdleState::Idle);
        assert_eq!(
            tick.next_tick_in,
            Duration::from_millis(200),
            "5 fps → 200 ms per tick"
        );
    }

    #[test]
    fn next_tick_in_clamps_to_min_visibility_fps_when_idle() {
        // The cosmetic `fps` (1) is below the visibility heartbeat (10),
        // so the effective idle cadence must be 10 fps → 100 ms. This is
        // what keeps the loopback enumerable by Chrome while idle.
        let cfg = IdleConfig {
            enabled: true,
            teardown_secs: 1,
            fps: 1,
            min_visibility_fps: 10,
            ..IdleConfig::default()
        };
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        sm.tick(ConsumerStatus::Absent, now, &cfg);
        let tick = sm.tick(ConsumerStatus::Absent, now + Duration::from_secs(1), &cfg);
        assert_eq!(sm.state(), IdleState::Idle);
        assert_eq!(
            tick.next_tick_in,
            Duration::from_millis(100),
            "max(fps=1, min_visibility_fps=10) → 10 fps → 100 ms"
        );
    }

    #[test]
    fn resume_active_fires_once_on_double_present() {
        // Once we land back in Active, a second consecutive Present
        // observation must not re-fire ResumeActive — there is no
        // transition, so the worker must not spawn another reload.
        let cfg = cfg(1, 5);
        let now = t0();
        let mut sm = IdleStateMachine::new(now);

        // Force into Idle.
        sm.tick(ConsumerStatus::Absent, now, &cfg);
        let after_idle = now + Duration::from_secs(1);
        sm.tick(ConsumerStatus::Absent, after_idle, &cfg);
        assert_eq!(sm.state(), IdleState::Idle);

        // First Present: edge fires.
        let t1 = after_idle + Duration::from_secs(1);
        let first = sm.tick(ConsumerStatus::Present, t1, &cfg);
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(first.edge, IdleEdge::ResumeActive);

        // Second Present: state already Active, no edge.
        let t2 = t1 + Duration::from_millis(100);
        let second = sm.tick(ConsumerStatus::Present, t2, &cfg);
        assert_eq!(sm.state(), IdleState::Active);
        assert_eq!(
            second.edge,
            IdleEdge::None,
            "ResumeActive must not re-fire while we remain in Active"
        );
    }

    #[test]
    fn cooldown_unknown_after_timer_cancels_to_active() {
        // Unknown is fail-open ⇒ structurally equivalent to Present.
        // In Cooldown, even past the teardown threshold, an Unknown
        // observation must snap us back to Active with no edge —
        // mirroring the Present-after-timer path exactly. This pins
        // down the fail-open invariant against future regressions.
        let cfg = cfg(1, 30);
        let now = t0();
        let mut sm = IdleStateMachine::new(now);

        // Active → Cooldown.
        sm.tick(ConsumerStatus::Absent, now, &cfg);
        assert_eq!(sm.state(), IdleState::Cooldown);

        // Advance past teardown but observe Unknown rather than
        // Present or Absent.
        let tick = sm.tick(ConsumerStatus::Unknown, now + Duration::from_secs(5), &cfg);
        assert_eq!(
            sm.state(),
            IdleState::Active,
            "Unknown must be treated as Present and cancel the cooldown"
        );
        assert_eq!(
            tick.edge,
            IdleEdge::None,
            "no teardown happened in Cooldown, so no resume side effect"
        );
        assert_eq!(tick.level, IdleLevel::Active);
    }

    #[test]
    fn flapping_reader_does_not_destabilise() {
        // Absent → Present → Absent → Present rapid burst stays Active.
        let cfg = cfg(5, 30);
        let now = t0();
        let mut sm = IdleStateMachine::new(now);
        for (i, status) in [
            ConsumerStatus::Absent,
            ConsumerStatus::Present,
            ConsumerStatus::Absent,
            ConsumerStatus::Present,
            ConsumerStatus::Absent,
        ]
        .iter()
        .enumerate()
        {
            let t = now + Duration::from_millis(i as u64 * 100);
            sm.tick(*status, t, &cfg);
        }
        // Even though we ended on Absent, no tick exceeded teardown,
        // so we cannot have left Cooldown.
        assert!(
            matches!(sm.state(), IdleState::Active | IdleState::Cooldown),
            "flapping under teardown threshold must keep us out of Idle, got {:?}",
            sm.state()
        );
    }
}