hisi-rf-core 0.1.0-alpha.24

Chip-neutral async radio controller contracts for HiSilicon embedded Rust
Documentation
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
//! Experimental incremental backend contract.
//!
//! This module is deliberately feature-gated. It freezes the operation identity,
//! cancellation, work-budget, and wait-set vocabulary before the validated WS63
//! backend is migrated. It does not replace [`crate::WifiBackend`] yet.

use core::{
    num::{NonZeroU16, NonZeroU32},
    task::{Context, Poll},
};

use crate::{
    BackendError, ConnectionInfo, ScanConfig, ScanOutcome, ScanResult, StationConfig, WifiConfig,
};

mod command;
mod driver;
mod facade;
mod runner;

pub use command::{
    CommandArbiter, CommandArbiterAction, CommandArbiterError, CommandSequence, PendingCommand,
    SubmitError,
};
pub use driver::{
    IncrementalBackendDriver, IncrementalDriverError, IncrementalDriverEvent, IncrementalWaitIntent,
};
pub use facade::{
    IncrementalRadioParts, IncrementalRadioRunner, IncrementalRadioRunnerError,
    IncrementalRunnerDiagnostics,
};
pub use runner::{
    CancelDirective, FairWakeSelector, IncrementalRunnerState, RunnerStateError, RunnerStep,
    RunnerTransition,
};

/// Identity of one backend operation slot and its current generation.
///
/// Reusing a slot increments `generation`, so a completion retained from an
/// earlier operation cannot complete the new operation accidentally.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct OperationId {
    slot: u8,
    generation: NonZeroU32,
}

impl OperationId {
    /// Operation slot selected by the runner.
    pub const fn slot(self) -> u8 {
        self.slot
    }

    /// Non-zero identity generation for this use of the slot.
    pub const fn generation(self) -> NonZeroU32 {
        self.generation
    }
}

/// Explicit lifecycle of the single operation tracked by a runner slot.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperationLifecycle {
    /// Accepted by the runner but not yet handed to the backend.
    Queued,
    /// Accepted by the backend and eligible for bounded polling.
    Started,
    /// Cancellation was requested; only a cancelled or terminal result may follow.
    CancelRequested,
    /// One terminal result has been committed and awaits collection.
    Terminal,
}

/// Rejection of an operation lifecycle transition.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperationStateError {
    /// The one operation slot is still owned by another live operation.
    Busy,
    /// The supplied identity refers to an older generation or another slot.
    Stale,
    /// The requested transition is not legal from the current lifecycle state.
    InvalidTransition,
    /// A terminal result has already been committed.
    AlreadyTerminal,
}

/// Whether a cancellation request changed the operation state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CancelOutcome {
    /// The operation moved to `CancelRequested`.
    Requested,
    /// Cancellation had already been requested for this operation.
    AlreadyRequested,
}

/// Small state machine used by the future incremental runner.
///
/// It intentionally tracks one slot: the public controller serializes control
/// operations today. Additional slots can be added without weakening generation
/// checks if a demonstrated use case appears.
#[derive(Debug)]
pub struct OperationTracker {
    next_generation: u32,
    current: Option<(OperationId, OperationLifecycle)>,
}

impl OperationTracker {
    /// Construct an idle tracker.
    pub const fn new() -> Self {
        Self {
            next_generation: 0,
            current: None,
        }
    }

    /// Queue a new operation in `slot` and allocate its identity generation.
    pub fn queue(&mut self, slot: u8) -> Result<OperationId, OperationStateError> {
        if self.current.is_some() {
            return Err(OperationStateError::Busy);
        }
        self.next_generation = self.next_generation.wrapping_add(1);
        if self.next_generation == 0 {
            self.next_generation = 1;
        }
        let id = OperationId {
            slot,
            generation: NonZeroU32::new(self.next_generation).expect("generation is non-zero"),
        };
        self.current = Some((id, OperationLifecycle::Queued));
        Ok(id)
    }

    /// Return the current operation and lifecycle, if the slot is occupied.
    pub const fn current(&self) -> Option<(OperationId, OperationLifecycle)> {
        self.current
    }

    /// Mark a queued operation as accepted by the backend.
    pub fn mark_started(&mut self, id: OperationId) -> Result<(), OperationStateError> {
        let lifecycle = self.lifecycle_mut(id)?;
        if *lifecycle != OperationLifecycle::Queued {
            return Err(OperationStateError::InvalidTransition);
        }
        *lifecycle = OperationLifecycle::Started;
        Ok(())
    }

    /// Request cancellation without committing a terminal result.
    pub fn request_cancel(
        &mut self,
        id: OperationId,
    ) -> Result<CancelOutcome, OperationStateError> {
        let lifecycle = self.lifecycle_mut(id)?;
        match *lifecycle {
            OperationLifecycle::Queued | OperationLifecycle::Started => {
                *lifecycle = OperationLifecycle::CancelRequested;
                Ok(CancelOutcome::Requested)
            }
            OperationLifecycle::CancelRequested => Ok(CancelOutcome::AlreadyRequested),
            OperationLifecycle::Terminal => Err(OperationStateError::AlreadyTerminal),
        }
    }

    /// Commit the operation's sole terminal result.
    ///
    /// The return value says whether cancellation was pending when the result
    /// became terminal. A runner must suppress a late success when it is `true`.
    pub fn commit_terminal(&mut self, id: OperationId) -> Result<bool, OperationStateError> {
        let lifecycle = self.lifecycle_mut(id)?;
        let cancelled = match *lifecycle {
            OperationLifecycle::Started => false,
            OperationLifecycle::CancelRequested => true,
            OperationLifecycle::Queued => return Err(OperationStateError::InvalidTransition),
            OperationLifecycle::Terminal => return Err(OperationStateError::AlreadyTerminal),
        };
        *lifecycle = OperationLifecycle::Terminal;
        Ok(cancelled)
    }

    /// Mark a queued request terminal when the backend rejects `start`.
    pub fn reject_queued(&mut self, id: OperationId) -> Result<(), OperationStateError> {
        let lifecycle = self.lifecycle_mut(id)?;
        if *lifecycle != OperationLifecycle::Queued {
            return Err(OperationStateError::InvalidTransition);
        }
        *lifecycle = OperationLifecycle::Terminal;
        Ok(())
    }

    /// Release a collected terminal operation so the slot may be reused.
    pub fn reap(&mut self, id: OperationId) -> Result<(), OperationStateError> {
        let lifecycle = self.lifecycle(id)?;
        if lifecycle != OperationLifecycle::Terminal {
            return Err(OperationStateError::InvalidTransition);
        }
        self.current = None;
        Ok(())
    }

    /// Return the lifecycle of `id`, rejecting stale identities.
    pub fn lifecycle(&self, id: OperationId) -> Result<OperationLifecycle, OperationStateError> {
        let Some((current, lifecycle)) = self.current else {
            return Err(OperationStateError::Stale);
        };
        if current != id {
            return Err(OperationStateError::Stale);
        }
        Ok(lifecycle)
    }

    fn lifecycle_mut(
        &mut self,
        id: OperationId,
    ) -> Result<&mut OperationLifecycle, OperationStateError> {
        let Some((current, lifecycle)) = self.current.as_mut() else {
            return Err(OperationStateError::Stale);
        };
        if *current != id {
            return Err(OperationStateError::Stale);
        }
        Ok(lifecycle)
    }
}

impl Default for OperationTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// Upper bound granted to one incremental backend poll.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WorkBudget {
    max_events: NonZeroU16,
    max_time_us: NonZeroU32,
}

impl WorkBudget {
    /// Construct a non-empty event and elapsed-time budget.
    pub const fn try_new(max_events: u16, max_time_us: u32) -> Option<Self> {
        match (NonZeroU16::new(max_events), NonZeroU32::new(max_time_us)) {
            (Some(max_events), Some(max_time_us)) => Some(Self {
                max_events,
                max_time_us,
            }),
            _ => None,
        }
    }

    /// Maximum backend events that may be consumed by one poll.
    pub const fn max_events(self) -> NonZeroU16 {
        self.max_events
    }

    /// Maximum elapsed backend time, in microseconds, for one poll.
    pub const fn max_time_us(self) -> NonZeroU32 {
        self.max_time_us
    }
}

/// Wake sources that an idle radio runner may wait on together.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WaitSet(u8);

impl WaitSet {
    /// A controller command entered the command queue.
    pub const COMMAND: Self = Self(1 << 0);
    /// A backend callback or deferred IRQ made protocol work ready.
    pub const BACKEND: Self = Self(1 << 1);
    /// Link-layer receive work is ready.
    pub const L2_RX: Self = Self(1 << 2);
    /// The next backend deadline elapsed.
    pub const TIMER: Self = Self(1 << 3);
    /// A dropped control future requested cancellation.
    pub const CANCEL: Self = Self(1 << 4);

    /// An empty set, used when another poll should happen immediately.
    pub const fn empty() -> Self {
        Self(0)
    }

    /// Combine independent wake sources.
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Test whether all sources in `other` are present.
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Stable machine-readable bit representation.
    pub const fn bits(self) -> u8 {
        self.0
    }

    /// Construct the singleton set for one wake reason.
    pub const fn from_reason(reason: WakeReason) -> Self {
        Self(reason.bit())
    }

    /// Test whether the set has no wake sources.
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Test whether the sets share at least one wake source.
    pub const fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    /// Retain only sources also present in `other`.
    pub const fn intersection(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }

    /// Remove every source present in `other`.
    pub const fn without(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }
}

/// Executor-neutral bridge for backend, L2, and timer wake sources.
///
/// The runner handles [`WaitSet::COMMAND`] itself. Implementations receive only
/// the remaining subscribed sources and must use level-triggered readiness:
/// before returning [`Poll::Pending`], register `cx.waker()` so an event that
/// becomes ready before or during registration cannot be lost. A ready result
/// may contain only bits from `sources`; the runner rejects extras.
///
/// `deadline_us` uses the backend's monotonic microsecond clock. When TIMER is
/// subscribed and the deadline has elapsed, return a set containing
/// [`WaitSet::TIMER`] without sleeping. Registration must be idempotent; a
/// dropped wait future may leave its waker installed until the next poll.
pub trait IncrementalWaitPlatform {
    /// Platform-specific timer or wake-registration failure.
    type Error;

    /// Poll the currently subscribed non-command wake sources.
    fn poll_ready(
        &mut self,
        cx: &mut Context<'_>,
        sources: WaitSet,
        deadline_us: Option<u64>,
    ) -> Poll<Result<WaitSet, Self::Error>>;
}

/// Failure while composing command and platform wake sources.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IncrementalWaitError<E> {
    /// The platform could not arm or poll a subscribed source.
    Platform(E),
    /// The platform reported a source that was not subscribed in this snapshot.
    UnexpectedSources {
        /// Non-command sources requested from the platform.
        subscribed: WaitSet,
        /// Sources reported ready by the platform.
        ready: WaitSet,
    },
}

/// One wake source selected for the next bounded runner step.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WakeReason {
    /// A controller command is waiting.
    Command,
    /// A backend callback or deferred IRQ made protocol work ready.
    Backend,
    /// Link-layer receive work is ready.
    L2Rx,
    /// The next backend deadline elapsed.
    Timer,
}

impl WakeReason {
    const COUNT: u8 = 4;

    const fn from_index(index: u8) -> Self {
        match index {
            0 => Self::Command,
            1 => Self::Backend,
            2 => Self::L2Rx,
            _ => Self::Timer,
        }
    }

    const fn index(self) -> u8 {
        match self {
            Self::Command => 0,
            Self::Backend => 1,
            Self::L2Rx => 2,
            Self::Timer => 3,
        }
    }

    const fn bit(self) -> u8 {
        1 << self.index()
    }
}

/// Request moved into an incremental backend.
#[derive(Debug)]
pub enum IncrementalRequest {
    /// Initialize the radio runtime.
    Initialize(WifiConfig),
    /// Start one bounded scan.
    Scan(ScanConfig),
    /// Associate and authorize one station.
    Connect(StationConfig),
    /// Disconnect the station interface.
    Disconnect(WifiConfig),
}

/// Typed successful terminal result from an incremental backend.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IncrementalCompletion {
    /// Initialization completed.
    Initialized,
    /// Scan completed and wrote results into the runner-owned buffer.
    Scan(ScanOutcome),
    /// Association and authorization completed.
    Connected(ConnectionInfo),
    /// Disconnection completed.
    Disconnected,
}

/// State returned by one bounded backend poll.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PollDisposition {
    /// No terminal result; wait for these sources before polling again.
    Pending(WaitSet),
    /// One successful terminal result is ready.
    Complete(IncrementalCompletion),
    /// Cancellation reached a terminal state.
    Cancelled,
    /// The poll reached or overran its granted budget and requires another fair turn.
    ///
    /// Event accounting is a hard bound: a backend must never report more
    /// events than granted. Elapsed time is measured after a backend call
    /// returns, so an uninterruptible platform operation can be observed
    /// overrunning the deadline even though it cannot be preempted in place.
    BudgetExhausted(WaitSet),
}

/// Verified accounting for one backend poll.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WorkReport {
    operation: OperationId,
    consumed_events: u16,
    elapsed_us: u32,
    time_budget_exhausted: bool,
    made_progress: bool,
    disposition: PollDisposition,
}

impl WorkReport {
    /// Construct a report with strict event accounting and observable time overruns.
    ///
    /// A non-terminal time overrun is valid only when reported as
    /// [`PollDisposition::BudgetExhausted`]. A terminal completion or
    /// cancellation remains terminal while carrying the overrun observation.
    /// This preserves operation ownership after an external side effect while
    /// making the missed deadline visible. Event overruns remain invalid
    /// because the backend controls how many events it consumes.
    pub const fn try_new(
        operation: OperationId,
        budget: WorkBudget,
        consumed_events: u16,
        elapsed_us: u32,
        made_progress: bool,
        disposition: PollDisposition,
    ) -> Option<Self> {
        if consumed_events > budget.max_events.get() {
            return None;
        }
        let time_budget_exhausted = elapsed_us >= budget.max_time_us.get();
        if matches!(disposition, PollDisposition::BudgetExhausted(_))
            && consumed_events != budget.max_events.get()
            && !time_budget_exhausted
        {
            return None;
        }
        if elapsed_us > budget.max_time_us.get()
            && !matches!(
                disposition,
                PollDisposition::BudgetExhausted(_)
                    | PollDisposition::Complete(_)
                    | PollDisposition::Cancelled
            )
        {
            return None;
        }
        if matches!(disposition, PollDisposition::Pending(wait) if wait.is_empty())
            && !made_progress
        {
            return None;
        }
        Some(Self {
            operation,
            consumed_events,
            elapsed_us,
            time_budget_exhausted,
            made_progress,
            disposition,
        })
    }

    /// Operation identity advanced by this report.
    pub const fn operation(self) -> OperationId {
        self.operation
    }

    /// Number of protocol/backend events consumed by this poll.
    pub const fn consumed_events(self) -> u16 {
        self.consumed_events
    }

    /// Backend-measured elapsed time in microseconds.
    pub const fn elapsed_us(self) -> u32 {
        self.elapsed_us
    }

    /// Whether this poll reached or overran its elapsed-time grant.
    pub const fn time_budget_exhausted(self) -> bool {
        self.time_budget_exhausted
    }

    /// Whether the backend changed protocol-visible state.
    pub const fn made_progress(self) -> bool {
        self.made_progress
    }

    /// Pending, complete, or cancelled result.
    pub const fn disposition(self) -> PollDisposition {
        self.disposition
    }
}

/// Opt-in bounded backend contract used by the A5B prototype.
///
/// `start`, `poll`, and `cancel` are called only by the unique radio runner.
/// Implementations must not invoke application callbacks. `start` and `cancel`
/// may only update bounded in-memory operation state; they must not enter
/// vendor, transport, or hardware operations. All such work is advanced by
/// repeated bounded `poll` calls. After `start` succeeds, the runner grants one
/// immediate poll turn before waiting for an external source.
pub trait IncrementalWifiBackend {
    /// Accept an operation identity and owned request without external work.
    fn start(&mut self, id: OperationId, request: IncrementalRequest) -> Result<(), BackendError>;

    /// Advance one operation without exceeding `budget`.
    fn poll(
        &mut self,
        id: OperationId,
        reason: WakeReason,
        budget: WorkBudget,
        scan_output: &mut [ScanResult],
    ) -> Result<WorkReport, BackendError>;

    /// Record cancellation without external work.
    ///
    /// Any disconnect, scan abort, or key cleanup is advanced by `poll`.
    /// Terminal cancellation is also observed through `poll`.
    fn cancel(&mut self, id: OperationId) -> Result<(), BackendError>;

    /// Monotonic deadline for the next timer wake, in microseconds.
    fn next_deadline_us(&self, id: OperationId) -> Option<u64>;

    /// Snapshot immutable L2 identity after initialization completes.
    fn l2_capabilities(&self) -> Option<crate::WifiL2Capabilities> {
        None
    }
}

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

    struct FakeIncrementalBackend {
        active: Option<OperationId>,
        polls: u8,
    }

    impl IncrementalWifiBackend for FakeIncrementalBackend {
        fn start(
            &mut self,
            id: OperationId,
            _request: IncrementalRequest,
        ) -> Result<(), BackendError> {
            if self.active.replace(id).is_some() {
                return Err(BackendError::new(crate::BackendErrorClass::Busy, 1));
            }
            self.polls = 0;
            Ok(())
        }

        fn poll(
            &mut self,
            id: OperationId,
            _reason: WakeReason,
            budget: WorkBudget,
            _scan_output: &mut [ScanResult],
        ) -> Result<WorkReport, BackendError> {
            if self.active != Some(id) {
                return Err(BackendError::new(crate::BackendErrorClass::Other, 2));
            }
            self.polls += 1;
            let disposition = if self.polls == 1 {
                PollDisposition::Pending(WaitSet::BACKEND.union(WaitSet::TIMER))
            } else {
                self.active = None;
                PollDisposition::Complete(IncrementalCompletion::Initialized)
            };
            WorkReport::try_new(id, budget, 1, 10, true, disposition)
                .ok_or_else(|| BackendError::new(crate::BackendErrorClass::Other, 3))
        }

        fn cancel(&mut self, id: OperationId) -> Result<(), BackendError> {
            if self.active == Some(id) {
                self.active = None;
                Ok(())
            } else {
                Err(BackendError::new(crate::BackendErrorClass::Other, 2))
            }
        }

        fn next_deadline_us(&self, id: OperationId) -> Option<u64> {
            (self.active == Some(id)).then_some(1_000)
        }
    }

    #[test]
    fn stale_completion_cannot_commit_after_slot_reuse() {
        let mut tracker = OperationTracker::new();
        let first = tracker.queue(0).unwrap();
        tracker.mark_started(first).unwrap();
        assert!(!tracker.commit_terminal(first).unwrap());
        tracker.reap(first).unwrap();

        let second = tracker.queue(0).unwrap();
        assert_ne!(first.generation(), second.generation());
        assert_eq!(
            tracker.commit_terminal(first),
            Err(OperationStateError::Stale)
        );
        assert_eq!(
            tracker.current(),
            Some((second, OperationLifecycle::Queued))
        );
    }

    #[test]
    fn cancellation_is_idempotent_and_suppresses_late_success() {
        let mut tracker = OperationTracker::new();
        let id = tracker.queue(0).unwrap();
        tracker.mark_started(id).unwrap();
        assert_eq!(tracker.request_cancel(id), Ok(CancelOutcome::Requested));
        assert_eq!(
            tracker.request_cancel(id),
            Ok(CancelOutcome::AlreadyRequested)
        );
        assert!(tracker.commit_terminal(id).unwrap());
        assert_eq!(
            tracker.request_cancel(id),
            Err(OperationStateError::AlreadyTerminal)
        );
        tracker.reap(id).unwrap();
    }

    #[test]
    fn work_report_enforces_events_and_observes_time_overruns() {
        let budget = WorkBudget::try_new(3, 200).unwrap();
        let wait = WaitSet::COMMAND
            .union(WaitSet::BACKEND)
            .union(WaitSet::TIMER);
        let mut tracker = OperationTracker::new();
        let id = tracker.queue(0).unwrap();
        let report =
            WorkReport::try_new(id, budget, 3, 200, true, PollDisposition::Pending(wait)).unwrap();
        assert_eq!(report.operation(), id);
        assert_eq!(report.consumed_events(), 3);
        assert_eq!(report.elapsed_us(), 200);
        assert!(report.time_budget_exhausted());
        assert!(report.made_progress());
        assert!(wait.contains(WaitSet::COMMAND));
        assert!(wait.contains(WaitSet::BACKEND));
        assert!(!wait.contains(WaitSet::L2_RX));
        assert!(
            WorkReport::try_new(id, budget, 4, 1, true, PollDisposition::Pending(wait)).is_none()
        );
        assert!(
            WorkReport::try_new(
                id,
                budget,
                1,
                201,
                true,
                PollDisposition::BudgetExhausted(wait),
            )
            .is_some()
        );
        let completed_after_overrun = WorkReport::try_new(
            id,
            budget,
            1,
            201,
            true,
            PollDisposition::Complete(IncrementalCompletion::Initialized),
        )
        .unwrap();
        assert!(completed_after_overrun.time_budget_exhausted());
        assert!(
            WorkReport::try_new(id, budget, 1, 201, true, PollDisposition::Pending(wait),)
                .is_none()
        );
        assert!(
            WorkReport::try_new(
                id,
                budget,
                1,
                1,
                true,
                PollDisposition::BudgetExhausted(wait),
            )
            .is_none()
        );
        assert!(
            WorkReport::try_new(
                id,
                budget,
                3,
                1,
                true,
                PollDisposition::BudgetExhausted(wait),
            )
            .is_some()
        );
        assert!(
            WorkReport::try_new(
                id,
                budget,
                0,
                0,
                false,
                PollDisposition::Pending(WaitSet::empty()),
            )
            .is_none()
        );
    }

    #[test]
    fn incremental_backend_advances_only_through_bounded_polling() {
        let mut tracker = OperationTracker::new();
        let mut backend = FakeIncrementalBackend {
            active: None,
            polls: 0,
        };
        let id = tracker.queue(0).unwrap();
        backend
            .start(id, IncrementalRequest::Initialize(WifiConfig::default()))
            .unwrap();
        tracker.mark_started(id).unwrap();

        let budget = WorkBudget::try_new(2, 50).unwrap();
        let mut scan_results = [ScanResult::EMPTY; 1];
        let first = backend
            .poll(id, WakeReason::Backend, budget, &mut scan_results)
            .unwrap();
        assert_eq!(
            first.disposition(),
            PollDisposition::Pending(WaitSet::BACKEND.union(WaitSet::TIMER))
        );
        let second = backend
            .poll(id, WakeReason::Timer, budget, &mut scan_results)
            .unwrap();
        assert_eq!(
            second.disposition(),
            PollDisposition::Complete(IncrementalCompletion::Initialized)
        );
        assert!(!tracker.commit_terminal(id).unwrap());
        tracker.reap(id).unwrap();
    }

    #[test]
    fn fair_selector_rotates_across_continuously_ready_sources() {
        let all = WaitSet::COMMAND
            .union(WaitSet::BACKEND)
            .union(WaitSet::L2_RX)
            .union(WaitSet::TIMER);
        let mut selector = FairWakeSelector::new();
        assert_eq!(selector.select(all, all), Some(WakeReason::Command));
        assert_eq!(selector.select(all, all), Some(WakeReason::Backend));
        assert_eq!(selector.select(all, all), Some(WakeReason::L2Rx));
        assert_eq!(selector.select(all, all), Some(WakeReason::Timer));
        assert_eq!(selector.select(all, all), Some(WakeReason::Command));
    }

    #[test]
    fn cancellation_before_start_completes_without_backend_notification() {
        let mut runner = IncrementalRunnerState::new();
        let id = runner.queue(0).unwrap();
        assert_eq!(
            runner.queue(1),
            Err(RunnerStateError::Operation(OperationStateError::Busy))
        );
        assert_eq!(
            runner.request_cancel(id),
            Ok(CancelDirective::CompleteLocally)
        );
        assert_eq!(runner.current(), Some((id, OperationLifecycle::Terminal)));
        assert_eq!(runner.select_step(WaitSet::COMMAND), RunnerStep::Idle);
        runner.reap(id).unwrap();
        assert_eq!(runner.current(), None);
    }

    #[test]
    fn queued_operation_rejects_a_backend_report() {
        let mut runner = IncrementalRunnerState::new();
        let id = runner.queue(0).unwrap();
        let budget = WorkBudget::try_new(1, 10).unwrap();
        let report = WorkReport::try_new(
            id,
            budget,
            1,
            10,
            true,
            PollDisposition::Complete(IncrementalCompletion::Initialized),
        )
        .unwrap();
        assert_eq!(
            runner.apply_report(id, report),
            Err(RunnerStateError::Operation(
                OperationStateError::InvalidTransition
            ))
        );
    }

    #[test]
    fn start_failure_terminalizes_and_releases_the_slot() {
        let mut runner = IncrementalRunnerState::new();
        let id = runner.queue(0).unwrap();
        let error = BackendError::new(crate::BackendErrorClass::Initialize, 7);
        assert_eq!(
            runner.reject_start(id, error),
            Ok(RunnerTransition::Failed {
                error,
                cancellation_pending: false,
            })
        );
        runner.reap(id).unwrap();
        assert!(runner.queue(0).is_ok());
    }

    #[test]
    fn poll_failure_preserves_whether_cancellation_was_pending() {
        let error = BackendError::new(crate::BackendErrorClass::Other, 9);

        let mut active = IncrementalRunnerState::new();
        let active_id = active.queue(0).unwrap();
        active.mark_started(active_id).unwrap();
        assert_eq!(
            active.apply_error(active_id, error),
            Ok(RunnerTransition::Failed {
                error,
                cancellation_pending: false,
            })
        );

        let mut cancelling = IncrementalRunnerState::new();
        let cancelling_id = cancelling.queue(0).unwrap();
        cancelling.mark_started(cancelling_id).unwrap();
        assert_eq!(
            cancelling.request_cancel(cancelling_id),
            Ok(CancelDirective::NotifyBackend)
        );
        assert_eq!(
            cancelling.apply_error(cancelling_id, error),
            Ok(RunnerTransition::Failed {
                error,
                cancellation_pending: true,
            })
        );
    }

    #[test]
    fn cancellation_after_start_suppresses_a_late_success() {
        let mut runner = IncrementalRunnerState::new();
        let id = runner.queue(0).unwrap();
        runner.mark_started(id).unwrap();
        assert_eq!(
            runner.request_cancel(id),
            Ok(CancelDirective::NotifyBackend)
        );
        let budget = WorkBudget::try_new(1, 10).unwrap();
        let report = WorkReport::try_new(
            id,
            budget,
            1,
            10,
            true,
            PollDisposition::Complete(IncrementalCompletion::Initialized),
        )
        .unwrap();
        assert_eq!(
            runner.apply_report(id, report),
            Ok(RunnerTransition::Cancelled {
                suppressed_completion: true,
            })
        );
    }

    #[test]
    fn stale_report_cannot_complete_a_reused_runner_slot() {
        let mut runner = IncrementalRunnerState::new();
        let first = runner.queue(0).unwrap();
        runner.mark_started(first).unwrap();
        let budget = WorkBudget::try_new(1, 10).unwrap();
        let first_report = WorkReport::try_new(
            first,
            budget,
            1,
            10,
            true,
            PollDisposition::Complete(IncrementalCompletion::Initialized),
        )
        .unwrap();
        runner.apply_report(first, first_report).unwrap();
        runner.reap(first).unwrap();

        let second = runner.queue(0).unwrap();
        runner.mark_started(second).unwrap();
        assert_eq!(
            runner.apply_report(second, first_report),
            Err(RunnerStateError::StaleReport {
                expected: second,
                actual: first,
            })
        );
        assert_eq!(
            runner.current(),
            Some((second, OperationLifecycle::Started))
        );
    }

    #[test]
    fn runner_selects_control_without_starving_backend_rx_or_timer() {
        let mut runner = IncrementalRunnerState::new();
        let id = runner.queue(0).unwrap();
        runner.mark_started(id).unwrap();
        let budget = WorkBudget::try_new(4, 100).unwrap();
        let all = WaitSet::COMMAND
            .union(WaitSet::BACKEND)
            .union(WaitSet::L2_RX)
            .union(WaitSet::TIMER);
        let subscribed =
            WorkReport::try_new(id, budget, 1, 10, true, PollDisposition::Pending(all)).unwrap();
        runner.apply_report(id, subscribed).unwrap();

        assert_eq!(runner.select_step(all), RunnerStep::CommandReady(id));
        assert_eq!(
            runner.select_step(all),
            RunnerStep::PollBackend {
                operation: id,
                reason: WakeReason::Backend,
            }
        );
        assert_eq!(
            runner.select_step(all),
            RunnerStep::PollBackend {
                operation: id,
                reason: WakeReason::L2Rx,
            }
        );
        assert_eq!(
            runner.select_step(all),
            RunnerStep::PollBackend {
                operation: id,
                reason: WakeReason::Timer,
            }
        );
        assert_eq!(runner.select_step(all), RunnerStep::CommandReady(id));
    }

    #[test]
    fn budget_exhaustion_requires_a_fair_follow_up_turn() {
        let mut runner = IncrementalRunnerState::new();
        let id = runner.queue(0).unwrap();
        runner.mark_started(id).unwrap();
        let budget = WorkBudget::try_new(2, 100).unwrap();
        let wait_for = WaitSet::BACKEND.union(WaitSet::TIMER);
        let report = WorkReport::try_new(
            id,
            budget,
            2,
            20,
            true,
            PollDisposition::BudgetExhausted(wait_for),
        )
        .unwrap();
        assert_eq!(
            runner.apply_report(id, report),
            Ok(RunnerTransition::BudgetExhausted {
                made_progress: true,
                wait_for,
            })
        );
        assert_eq!(
            runner.select_step(WaitSet::COMMAND),
            RunnerStep::Waiting(wait_for)
        );
        assert_eq!(
            runner.select_step(WaitSet::TIMER),
            RunnerStep::PollBackend {
                operation: id,
                reason: WakeReason::Timer,
            }
        );
    }
}