hyperfile-reactor 0.3.2

A lightweight task execution framework built on top of Tokio's LocalSet
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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! A lightweight task execution framework built on top of Tokio's `LocalSet`.
//!
//! # Overview
//!
//! A [`Reactor`] owns a dedicated OS thread running a tokio `current_thread`
//! runtime plus a [`LocalSet`]. Users register their own **typed tasks** on
//! the reactor; each task listens on one or more **user-defined channels**,
//! each with its own **priority** and **capacity**, and processes incoming
//! contexts through a user-supplied handler. The dispatch policy is
//! pluggable via the [`Scheduler`] trait; [`FairPriority`] (the default) and
//! [`StrictPriority`] are provided.
//!
//! ```no_run
//! use hyperfile_reactor::{Capacity, Reactor, Task, TaskBuilder};
//!
//! struct MyTask;
//! impl Task<u64> for MyTask {
//!     async fn handle(&mut self, ctx: u64) {
//!         println!("got {ctx}");
//!     }
//! }
//!
//! let reactor = Reactor::<u64, MyTask>::new_current().unwrap();
//!
//! let mut builder = TaskBuilder::<u64>::new();
//! let high = builder.add_channel(0, Capacity::Bounded(64));  // backpressured
//! let low  = builder.add_channel(9, Capacity::Unbounded);
//!
//! let handler = reactor.spawn(MyTask, builder).expect("spawn");
//! handler.send(high, 1).unwrap();
//! handler.send(low,  2).unwrap();
//! ```
#![warn(missing_docs)]

use std::marker::PhantomData;
use std::sync::Arc;
use std::thread::JoinHandle;

use tokio::runtime::{Builder, Runtime};
use tokio::sync::{mpsc, oneshot};
use tokio::task::LocalSet;

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Returned when a send fails because the task has stopped.
///
/// The wrapped value is the context that could not be delivered, so the
/// caller can recover ownership and retry, log, or discard it.
#[derive(Debug)]
pub struct SendError<T>(pub T);

impl<T> SendError<T> {
    /// Recover the context that could not be sent.
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> std::fmt::Display for SendError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("task receiver closed")
    }
}

impl<T: std::fmt::Debug> std::error::Error for SendError<T> {}

/// Returned from non-blocking send paths: either the bounded channel is full
/// or the task has stopped.
///
/// This enum is `#[non_exhaustive]`; callers must include a wildcard arm
/// when matching to remain forward-compatible.
#[derive(Debug)]
#[non_exhaustive]
pub enum TrySendError<T> {
    /// Bounded channel currently full. The item is returned to the caller.
    Full(T),
    /// Receiver has been dropped / task has stopped.
    Closed(T),
}

impl<T> TrySendError<T> {
    /// Recover the context that could not be sent.
    pub fn into_inner(self) -> T {
        match self {
            Self::Full(t) | Self::Closed(t) => t,
        }
    }
}

impl<T> std::fmt::Display for TrySendError<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Full(_) => f.write_str("channel full"),
            Self::Closed(_) => f.write_str("task receiver closed"),
        }
    }
}

impl<T: std::fmt::Debug> std::error::Error for TrySendError<T> {}

/// Returned when spawning a task fails because the reactor thread is gone.
#[derive(Debug)]
pub struct SpawnError;

impl std::fmt::Display for SpawnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("reactor background thread has shut down")
    }
}

impl std::error::Error for SpawnError {}

// ---------------------------------------------------------------------------
// Task trait (business logic only)
// ---------------------------------------------------------------------------

/// Business-logic trait. Implemented by users for each task type.
///
/// The handler runs inside a single-threaded runtime. **Never block it.**
/// Offload blocking or long-running IO via `tokio::task::spawn`,
/// `spawn_blocking`, or similar.
pub trait Task<Ctx>: 'static {
    /// Process one context delivered through one of the task's channels.
    ///
    /// This is invoked sequentially by the scheduler loop on the reactor
    /// thread; while it is `await`ing, no other context for this task is
    /// processed. Keep the synchronous portion short, and detach
    /// long-running async work via `tokio::task::spawn` rather than
    /// awaiting it inline.
    fn handle(&mut self, ctx: Ctx) -> impl std::future::Future<Output = ()>;
}

// ---------------------------------------------------------------------------
// Capacity + DynSender / DynReceiver
// ---------------------------------------------------------------------------

/// Channel capacity policy.
///
/// `#[non_exhaustive]` so that adding new policies (e.g. bounded with an
/// overflow strategy) in a future release is not a breaking change.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum Capacity {
    /// Bounded channel; producers apply backpressure when full.
    Bounded(usize),
    /// Unbounded channel; producers never block, but producers can OOM the
    /// consumer if they vastly outpace it.
    Unbounded,
}

/// Internal unified sender.
pub(crate) enum DynSender<T> {
    Bounded(mpsc::Sender<T>),
    Unbounded(mpsc::UnboundedSender<T>),
}

impl<T> Clone for DynSender<T> {
    fn clone(&self) -> Self {
        match self {
            Self::Bounded(s) => Self::Bounded(s.clone()),
            Self::Unbounded(s) => Self::Unbounded(s.clone()),
        }
    }
}

impl<T> DynSender<T> {
    /// Non-blocking send. For bounded channels, returns `Full` if the queue
    /// is full.
    fn try_send(&self, value: T) -> Result<(), TrySendError<T>> {
        match self {
            Self::Bounded(s) => s.try_send(value).map_err(|e| match e {
                mpsc::error::TrySendError::Full(v) => TrySendError::Full(v),
                mpsc::error::TrySendError::Closed(v) => TrySendError::Closed(v),
            }),
            Self::Unbounded(s) => s.send(value).map_err(|e| TrySendError::Closed(e.0)),
        }
    }

    /// Async send. Unbounded channels resolve immediately; bounded channels
    /// await capacity.
    async fn send_async(&self, value: T) -> Result<(), SendError<T>> {
        match self {
            Self::Bounded(s) => s.send(value).await.map_err(|e| SendError(e.0)),
            Self::Unbounded(s) => s.send(value).map_err(|e| SendError(e.0)),
        }
    }
}

/// Internal unified receiver used by [`Scheduler`] implementations.
///
/// User code should treat this as opaque: only call [`try_recv`](Self::try_recv)
/// or [`poll_recv`](Self::poll_recv). Both the enum and its variants are
/// `#[non_exhaustive]`; new representations may be added without a major
/// version bump, and external code may not construct or destructure them.
#[non_exhaustive]
pub enum DynReceiver<T> {
    /// Wraps a bounded `tokio::sync::mpsc::Receiver`.
    #[non_exhaustive]
    Bounded(mpsc::Receiver<T>),
    /// Wraps a `tokio::sync::mpsc::UnboundedReceiver`.
    #[non_exhaustive]
    Unbounded(mpsc::UnboundedReceiver<T>),
}

impl<T> DynReceiver<T> {
    /// Non-blocking receive. Returns `Err(TryRecvError::Empty)` if no value
    /// is ready; `Err(TryRecvError::Disconnected)` if all senders are gone.
    pub fn try_recv(&mut self) -> Result<T, mpsc::error::TryRecvError> {
        match self {
            Self::Bounded(r) => r.try_recv(),
            Self::Unbounded(r) => r.try_recv(),
        }
    }

    /// Poll-based receive; mirrors `Receiver::poll_recv`.
    pub fn poll_recv(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<T>> {
        match self {
            Self::Bounded(r) => r.poll_recv(cx),
            Self::Unbounded(r) => r.poll_recv(cx),
        }
    }
}

fn make_channel<T>(cap: Capacity) -> (DynSender<T>, DynReceiver<T>) {
    match cap {
        Capacity::Bounded(n) => {
            let (tx, rx) = mpsc::channel(n.max(1));
            (DynSender::Bounded(tx), DynReceiver::Bounded(rx))
        }
        Capacity::Unbounded => {
            let (tx, rx) = mpsc::unbounded_channel();
            (DynSender::Unbounded(tx), DynReceiver::Unbounded(rx))
        }
    }
}

// ---------------------------------------------------------------------------
// Channel token + TaskBuilder
// ---------------------------------------------------------------------------

/// An opaque token identifying one channel registered on a task.
///
/// Obtained from [`TaskBuilder::add_channel`] (or the `add_bounded` /
/// `add_unbounded` convenience methods) and passed to
/// [`TaskHandler::send`] / [`try_send`](TaskHandler::try_send) /
/// [`send_async`](TaskHandler::send_async) to select which channel to
/// produce on. Cheap to copy.
pub struct Channel<Ctx> {
    idx: usize,
    _marker: PhantomData<fn(Ctx)>,
}

impl<Ctx> Clone for Channel<Ctx> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Ctx> Copy for Channel<Ctx> {}

impl<Ctx> std::fmt::Debug for Channel<Ctx> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Channel").field("idx", &self.idx).finish()
    }
}

#[derive(Clone, Copy, Debug)]
struct ChannelSpec {
    /// Lower value = higher priority. 0 is the highest.
    priority: u8,
    capacity: Capacity,
}

/// Declares the set of channels a task will receive on.
///
/// Build it up with [`add_channel`](Self::add_channel),
/// [`add_unbounded`](Self::add_unbounded), or
/// [`add_bounded`](Self::add_bounded), each of which returns a
/// [`Channel`] token to hold onto. Then pass the builder to
/// [`Reactor::spawn`](crate::Reactor::spawn) to start the task.
pub struct TaskBuilder<Ctx> {
    channels: Vec<ChannelSpec>,
    _marker: PhantomData<fn(Ctx)>,
}

impl<Ctx> Default for TaskBuilder<Ctx> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Ctx> TaskBuilder<Ctx> {
    /// Create an empty builder.
    pub fn new() -> Self {
        Self {
            channels: Vec::new(),
            _marker: PhantomData,
        }
    }

    /// Register a channel with the given priority (0 = highest) and capacity.
    ///
    /// Multiple channels may share the same priority; among equals the
    /// default scheduler visits them in registration order.
    pub fn add_channel(&mut self, priority: u8, capacity: Capacity) -> Channel<Ctx> {
        let idx = self.channels.len();
        self.channels.push(ChannelSpec { priority, capacity });
        Channel {
            idx,
            _marker: PhantomData,
        }
    }

    /// Convenience: register an unbounded channel.
    pub fn add_unbounded(&mut self, priority: u8) -> Channel<Ctx> {
        self.add_channel(priority, Capacity::Unbounded)
    }

    /// Convenience: register a bounded channel with the given capacity.
    pub fn add_bounded(&mut self, priority: u8, capacity: usize) -> Channel<Ctx> {
        self.add_channel(priority, Capacity::Bounded(capacity))
    }

    /// Number of channels registered so far.
    pub fn channel_count(&self) -> usize {
        self.channels.len()
    }
}

// ---------------------------------------------------------------------------
// TaskHandler (producer side)
// ---------------------------------------------------------------------------

/// Producer-side handle. Cheap to clone; can be shared across threads.
pub struct TaskHandler<Ctx> {
    senders: Arc<[DynSender<Ctx>]>,
}

impl<Ctx> Clone for TaskHandler<Ctx> {
    fn clone(&self) -> Self {
        Self {
            senders: self.senders.clone(),
        }
    }
}

impl<Ctx> TaskHandler<Ctx> {
    /// Non-blocking send. On a bounded channel this returns `Full` when the
    /// queue is at capacity; on an unbounded channel it is effectively
    /// infallible except when the task has already stopped.
    pub fn try_send(&self, ch: Channel<Ctx>, ctx: Ctx) -> Result<(), TrySendError<Ctx>> {
        self.senders[ch.idx].try_send(ctx)
    }

    /// Convenience wrapper over [`try_send`](Self::try_send) that flattens
    /// `Full` back into `Closed`-style errors. Use [`send_async`](Self::send_async)
    /// when you want proper backpressure on bounded channels.
    ///
    /// For unbounded channels this is equivalent to `try_send`.
    pub fn send(&self, ch: Channel<Ctx>, ctx: Ctx) -> Result<(), TrySendError<Ctx>> {
        self.try_send(ch, ctx)
    }

    /// Async send with backpressure. On bounded channels this awaits free
    /// capacity; on unbounded channels it resolves immediately.
    pub async fn send_async(&self, ch: Channel<Ctx>, ctx: Ctx) -> Result<(), SendError<Ctx>> {
        self.senders[ch.idx].send_async(ctx).await
    }

    /// Number of channels registered on this task.
    pub fn channel_count(&self) -> usize {
        self.senders.len()
    }
}

// ---------------------------------------------------------------------------
// Scheduler trait + built-in implementations
// ---------------------------------------------------------------------------

/// Pluggable dispatch policy.
///
/// Given the task's receivers and their priorities (parallel arrays, aligned
/// by channel index), a scheduler decides which context to process next.
/// Return `None` only when every receiver is closed and the task should
/// terminate.
pub trait Scheduler<Ctx>: Send + 'static {
    /// Pick the next context to process.
    ///
    /// `rxs` and `priorities` are parallel arrays aligned by channel index
    /// (registration order on the [`TaskBuilder`]). Implementations should
    /// not assume any ordering between the two; the priorities slice is
    /// read-only metadata.
    ///
    /// Returning `None` signals that every receiver is permanently closed
    /// and the task's scheduler loop should exit.
    fn next_ctx<'a>(
        &'a mut self,
        rxs: &'a mut [DynReceiver<Ctx>],
        priorities: &'a [u8],
    ) -> impl std::future::Future<Output = Option<Ctx>> + 'a;
}

/// Strict priority: always serve the highest-priority non-empty channel.
/// Lower-priority channels may starve if higher ones never drain.
#[derive(Clone, Copy, Debug, Default)]
pub struct StrictPriority;

impl<Ctx> Scheduler<Ctx> for StrictPriority {
    async fn next_ctx<'a>(
        &'a mut self,
        rxs: &'a mut [DynReceiver<Ctx>],
        priorities: &'a [u8],
    ) -> Option<Ctx> {
        let order = sort_order(priorities);

        // Non-blocking scan.
        if let Some(v) = try_recv_in_order(rxs, &order) {
            return Some(v);
        }
        // Block until something arrives.
        await_any(rxs, &order).await.map(|(v, _)| v)
    }
}

/// Strict priority with anti-starvation: after `budget` consecutive items
/// from the top-priority band, serve one item from the lowest non-empty
/// band if any is waiting.
///
/// The default ([`FairPriority::default`]) uses `budget = 16`, which is a
/// reasonable middle ground for most workloads. Lower the budget if your
/// low-priority work is latency-sensitive; raise it if high-priority
/// throughput dominates.
#[derive(Clone, Copy, Debug)]
pub struct FairPriority {
    budget: u32,
    top_streak: u32,
}

impl FairPriority {
    /// Build a fair-priority scheduler with the given anti-starvation
    /// budget. After `budget` consecutive top-priority items, one
    /// lower-priority item is served (if any is waiting).
    pub fn new(budget: u32) -> Self {
        Self {
            budget,
            top_streak: 0,
        }
    }

    /// Read back the configured budget.
    pub fn budget(&self) -> u32 {
        self.budget
    }
}

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

impl<Ctx> Scheduler<Ctx> for FairPriority {
    async fn next_ctx<'a>(
        &'a mut self,
        rxs: &'a mut [DynReceiver<Ctx>],
        priorities: &'a [u8],
    ) -> Option<Ctx> {
        let order = sort_order(priorities);
        if order.is_empty() {
            return None;
        }
        let top_idx = order[0];

        // 1) Starvation relief.
        if self.top_streak >= self.budget {
            self.top_streak = 0;
            if let Some(v) = try_recv_lowest_nonempty(rxs, &order) {
                return Some(v);
            }
            // nothing below waiting; fall through
        }

        // 2) Non-blocking priority scan.
        if let Some((v, idx)) = try_recv_in_order_tagged(rxs, &order) {
            self.top_streak = if idx == top_idx {
                self.top_streak.saturating_add(1)
            } else {
                0
            };
            return Some(v);
        }

        // 3) Await any; track top-streak.
        match await_any(rxs, &order).await {
            Some((v, is_top)) => {
                self.top_streak = if is_top {
                    self.top_streak.saturating_add(1)
                } else {
                    0
                };
                Some(v)
            }
            None => None,
        }
    }
}

// --- shared scheduler helpers ---

/// Return indices 0..N sorted by ascending priority value (stable).
fn sort_order(priorities: &[u8]) -> Vec<usize> {
    let mut order: Vec<usize> = (0..priorities.len()).collect();
    order.sort_by_key(|&i| priorities[i]);
    order
}

fn try_recv_in_order<Ctx>(rxs: &mut [DynReceiver<Ctx>], order: &[usize]) -> Option<Ctx> {
    for &idx in order {
        if let Ok(v) = rxs[idx].try_recv() {
            return Some(v);
        }
    }
    None
}

fn try_recv_in_order_tagged<Ctx>(
    rxs: &mut [DynReceiver<Ctx>],
    order: &[usize],
) -> Option<(Ctx, usize)> {
    for &idx in order {
        if let Ok(v) = rxs[idx].try_recv() {
            return Some((v, idx));
        }
    }
    None
}

fn try_recv_lowest_nonempty<Ctx>(rxs: &mut [DynReceiver<Ctx>], order: &[usize]) -> Option<Ctx> {
    for &idx in order.iter().rev() {
        if let Ok(v) = rxs[idx].try_recv() {
            return Some(v);
        }
    }
    None
}

async fn await_any<Ctx>(rxs: &mut [DynReceiver<Ctx>], order: &[usize]) -> Option<(Ctx, bool)> {
    use std::future::poll_fn;
    use std::task::Poll;

    if order.is_empty() {
        return None;
    }
    let top = order[0];

    poll_fn(|cx| {
        let mut all_closed = true;
        for &idx in order {
            match rxs[idx].poll_recv(cx) {
                Poll::Ready(Some(v)) => return Poll::Ready(Some((v, idx == top))),
                Poll::Ready(None) => { /* closed; keep scanning */ }
                Poll::Pending => all_closed = false,
            }
        }
        if all_closed {
            Poll::Ready(None)
        } else {
            Poll::Pending
        }
    })
    .await
}

// ---------------------------------------------------------------------------
// Reactor (owns the background thread)
// ---------------------------------------------------------------------------

type SpawnRequest = Box<dyn FnOnce() + Send>;

/// Owns the background thread running the tokio runtime + `LocalSet`.
///
/// # Shutdown
///
/// Dropping the reactor (or calling [`shutdown`](Self::shutdown)) closes the
/// spawn control channel and joins the background thread. **The background
/// thread only exits once every [`TaskHandler`] clone has been dropped.**
/// If producers are still alive, `Drop`/`shutdown` will block.
pub struct Reactor<Ctx, T> {
    ctrl: Option<mpsc::UnboundedSender<SpawnRequest>>,
    thread: Option<JoinHandle<()>>,
    _marker: PhantomData<fn(Ctx, T)>,
}

impl<Ctx, T> Reactor<Ctx, T>
where
    Ctx: Send + 'static,
    T: Task<Ctx> + Send + 'static,
{
    /// Build a reactor on a freshly created `current_thread` runtime.
    pub fn new_current() -> std::io::Result<Self> {
        Self::new(None)
    }

    /// Build a reactor. Supply `Some(rt)` to reuse an existing runtime.
    pub fn new(runtime: Option<Arc<Runtime>>) -> std::io::Result<Self> {
        let (ctrl_tx, mut ctrl_rx) = mpsc::unbounded_channel::<SpawnRequest>();

        let rt = match runtime {
            Some(r) => r,
            None => Arc::new(Builder::new_current_thread().enable_all().build()?),
        };

        let thread = std::thread::Builder::new()
            .name("hyperfile-reactor".into())
            .spawn(move || {
                let local = LocalSet::new();

                local.spawn_local(async move {
                    while let Some(req) = ctrl_rx.recv().await {
                        req();
                    }
                });

                rt.block_on(local);
            })?;

        Ok(Self {
            ctrl: Some(ctrl_tx),
            thread: Some(thread),
            _marker: PhantomData,
        })
    }

    /// Spawn a task using the default scheduler ([`FairPriority`] with
    /// budget 16).
    ///
    /// Blocks the current thread until the task has been started. **Do not
    /// call this from inside a tokio runtime**; use [`spawn_async`](Self::spawn_async)
    /// instead.
    pub fn spawn(
        &self,
        task: T,
        builder: TaskBuilder<Ctx>,
    ) -> Result<TaskHandler<Ctx>, SpawnError> {
        self.spawn_with(task, builder, FairPriority::default())
    }

    /// Spawn a task with a user-supplied scheduler (blocking).
    pub fn spawn_with<S>(
        &self,
        task: T,
        builder: TaskBuilder<Ctx>,
        scheduler: S,
    ) -> Result<TaskHandler<Ctx>, SpawnError>
    where
        S: Scheduler<Ctx>,
    {
        let rx = self.submit(task, builder, scheduler)?;
        rx.blocking_recv().map_err(|_| SpawnError)
    }

    /// Async version of [`spawn`](Self::spawn). Use this from inside a
    /// tokio runtime.
    pub async fn spawn_async(
        &self,
        task: T,
        builder: TaskBuilder<Ctx>,
    ) -> Result<TaskHandler<Ctx>, SpawnError> {
        self.spawn_with_async(task, builder, FairPriority::default())
            .await
    }

    /// Async version of [`spawn_with`](Self::spawn_with).
    pub async fn spawn_with_async<S>(
        &self,
        task: T,
        builder: TaskBuilder<Ctx>,
        scheduler: S,
    ) -> Result<TaskHandler<Ctx>, SpawnError>
    where
        S: Scheduler<Ctx>,
    {
        let rx = self.submit(task, builder, scheduler)?;
        rx.await.map_err(|_| SpawnError)
    }

    /// Shared internals: build the spawn request, push it onto the reactor
    /// control channel, return the oneshot receiver.
    fn submit<S>(
        &self,
        task: T,
        builder: TaskBuilder<Ctx>,
        scheduler: S,
    ) -> Result<oneshot::Receiver<TaskHandler<Ctx>>, SpawnError>
    where
        S: Scheduler<Ctx>,
    {
        let ctrl = self.ctrl.as_ref().ok_or(SpawnError)?;
        let (tx, rx) = oneshot::channel::<TaskHandler<Ctx>>();

        let req: SpawnRequest = Box::new(move || {
            let handler = start_task(task, builder, scheduler);
            let _ = tx.send(handler);
        });

        ctrl.send(req).map_err(|_| SpawnError)?;
        Ok(rx)
    }

    /// Close the control channel and join the background thread.
    pub fn shutdown(mut self) -> std::thread::Result<()> {
        drop(self.ctrl.take());
        if let Some(h) = self.thread.take() {
            h.join()
        } else {
            Ok(())
        }
    }
}

impl<Ctx, T> Drop for Reactor<Ctx, T> {
    fn drop(&mut self) {
        drop(self.ctrl.take());
        if let Some(h) = self.thread.take() {
            let _ = h.join();
        }
    }
}

// ---------------------------------------------------------------------------
// start_task: create channels + spawn scheduler loop
// ---------------------------------------------------------------------------

fn start_task<Ctx, T, S>(
    mut task: T,
    builder: TaskBuilder<Ctx>,
    mut scheduler: S,
) -> TaskHandler<Ctx>
where
    Ctx: Send + 'static,
    T: Task<Ctx> + 'static,
    S: Scheduler<Ctx>,
{
    let cap_hint = builder.channels.len().max(1);
    let mut senders: Vec<DynSender<Ctx>> = Vec::with_capacity(cap_hint);
    let mut receivers: Vec<DynReceiver<Ctx>> = Vec::with_capacity(cap_hint);
    let mut priorities: Vec<u8> = Vec::with_capacity(cap_hint);

    if builder.channels.is_empty() {
        // Degenerate case: create a single unbounded channel so the handler
        // is usable.
        let (tx, rx) = make_channel::<Ctx>(Capacity::Unbounded);
        senders.push(tx);
        receivers.push(rx);
        priorities.push(0);
    } else {
        for spec in &builder.channels {
            let (tx, rx) = make_channel::<Ctx>(spec.capacity);
            senders.push(tx);
            receivers.push(rx);
            priorities.push(spec.priority);
        }
    }

    let handler = TaskHandler {
        senders: senders.into(),
    };

    tokio::task::spawn_local(async move {
        while let Some(ctx) = scheduler.next_ctx(&mut receivers, &priorities).await {
            task.handle(ctx).await;
            // Cooperatively yield to the runtime after each item.
            //
            // The scheduler's non-blocking `try_recv` fast path bypasses
            // tokio's coop budget; so does an `async fn handle` whose body
            // never reaches an `.await` point. Without this nudge, a
            // handler that synchronously re-queues onto a channel
            // (e.g. `ResourceBusy => send_cb(ctx); return;`) would drive
            // the scheduler in a tight loop and starve the runtime's I/O
            // and timer drivers, including any `tokio::task::spawn`'d
            // futures that the handler itself launched.
            //
            // `consume_budget().await` decrements the task-local coop
            // budget; when exhausted (after ~128 iterations by default)
            // it returns Pending, returning control to the runtime so it
            // can drive timers / I/O before re-polling.
            tokio::task::consume_budget().await;
        }
    });

    handler
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use std::time::Duration;

    /// Drive the reactor with a gated task so all messages get enqueued
    /// before the scheduler sees any.
    fn run_with_gate<S>(channels: Vec<(u8, Capacity, Vec<u32>)>, scheduler: S) -> Vec<u32>
    where
        S: Scheduler<u32>,
    {
        use tokio::sync::Notify;

        let log = Arc::new(Mutex::new(Vec::<u32>::new()));

        struct Gated {
            log: Arc<Mutex<Vec<u32>>>,
            gate: Arc<Notify>,
            gate_passed: bool,
        }

        impl Task<u32> for Gated {
            async fn handle(&mut self, ctx: u32) {
                if !self.gate_passed {
                    self.gate.notified().await;
                    self.gate_passed = true;
                }
                self.log.lock().unwrap().push(ctx);
            }
        }

        let gate = Arc::new(Notify::new());
        let task = Gated {
            log: log.clone(),
            gate: gate.clone(),
            gate_passed: false,
        };

        let reactor = Reactor::<u32, Gated>::new_current().unwrap();

        let mut builder = TaskBuilder::<u32>::new();
        let tokens: Vec<Channel<u32>> = channels
            .iter()
            .map(|(prio, cap, _)| builder.add_channel(*prio, *cap))
            .collect();

        let handler = reactor.spawn_with(task, builder, scheduler).unwrap();

        // Dummy sentinel on first channel to force scheduler into the gate.
        handler.send(tokens[0], u32::MAX).unwrap();
        std::thread::sleep(Duration::from_millis(50));

        for (i, (_prio, _cap, msgs)) in channels.iter().enumerate() {
            for m in msgs {
                handler.send(tokens[i], *m).unwrap();
            }
        }

        gate.notify_one();

        let expected: usize = 1 + channels.iter().map(|(_, _, m)| m.len()).sum::<usize>();
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        loop {
            if log.lock().unwrap().len() >= expected {
                break;
            }
            if std::time::Instant::now() >= deadline {
                panic!(
                    "timeout: got {} / {} items",
                    log.lock().unwrap().len(),
                    expected
                );
            }
            std::thread::sleep(Duration::from_millis(10));
        }

        drop(handler);
        reactor.shutdown().unwrap();

        let mut recorded = log.lock().unwrap().clone();
        assert_eq!(recorded.remove(0), u32::MAX);
        recorded
    }

    #[test]
    fn fair_priority_order_default() {
        let result = run_with_gate(
            vec![
                (0, Capacity::Unbounded, vec![10, 11, 12]),
                (1, Capacity::Unbounded, vec![20, 21, 22]),
                (2, Capacity::Unbounded, vec![30, 31, 32]),
            ],
            FairPriority::default(),
        );
        assert_eq!(result, vec![10, 11, 12, 20, 21, 22, 30, 31, 32]);
    }

    #[test]
    fn strict_priority_scheduler() {
        let result = run_with_gate(
            vec![
                (0, Capacity::Unbounded, (0..50).collect()),
                (2, Capacity::Unbounded, vec![999]),
            ],
            StrictPriority,
        );

        // StrictPriority: all 50 high-prio items come out before the low one.
        let pos = result.iter().position(|&v| v == 999).unwrap();
        assert_eq!(pos, 50, "low-prio must come last under StrictPriority");
    }

    #[test]
    fn fair_priority_anti_starvation() {
        let high: Vec<u32> = (0..40).map(|i| 1000 + i).collect();
        let low = vec![9999_u32];

        let result = run_with_gate(
            vec![
                (0, Capacity::Unbounded, high.clone()),
                (2, Capacity::Unbounded, low),
            ],
            FairPriority::new(16),
        );

        let pos = result.iter().position(|&v| v == 9999).unwrap();
        assert!(
            pos <= 16,
            "FairPriority must relieve starvation within budget: pos={pos}"
        );

        let highs: Vec<u32> = result.iter().copied().filter(|&v| v != 9999).collect();
        let mut sorted = highs.clone();
        sorted.sort();
        assert_eq!(sorted, high);
    }

    #[test]
    fn bounded_channel_applies_backpressure() {
        // Bounded(1) channel. The consumer blocks on the *first* item only;
        // that leaves the pipeline with:
        //   - 1 item in-flight (held by the handler, awaiting release)
        //   - 1 item buffered (capacity = 1)
        // A further `try_send` must then return `Full`.
        use tokio::sync::Notify;

        struct Slow {
            release: Arc<Notify>,
            blocked_once: bool,
        }
        impl Task<u32> for Slow {
            async fn handle(&mut self, _ctx: u32) {
                if !self.blocked_once {
                    self.blocked_once = true;
                    self.release.notified().await;
                }
            }
        }

        let release = Arc::new(Notify::new());
        let reactor = Reactor::<u32, Slow>::new_current().unwrap();
        let mut builder = TaskBuilder::<u32>::new();
        let ch = builder.add_bounded(0, 1);
        let handler = reactor
            .spawn(
                Slow {
                    release: release.clone(),
                    blocked_once: false,
                },
                builder,
            )
            .unwrap();

        // Consumer picks up item 1 and blocks on `notified`.
        handler.try_send(ch, 1).expect("send 1");
        std::thread::sleep(Duration::from_millis(100));

        // Fill the 1-slot buffer.
        handler.try_send(ch, 2).expect("send 2 fills buffer");
        // Now Full.
        match handler.try_send(ch, 3) {
            Err(TrySendError::Full(3)) => { /* expected */ }
            other => panic!("expected Full(3), got {:?}", other.map(|_| ())),
        }

        // Release the consumer; subsequent items process instantly.
        release.notify_one();
        drop(handler);
        reactor.shutdown().expect("shutdown");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn send_async_awaits_capacity() {
        // Reactor on its own thread, task that processes each item after a
        // small sleep. A bounded(1) channel; producer uses send_async to
        // push 5 items, which should all land eventually.
        struct Trickle {
            log: Arc<Mutex<Vec<u32>>>,
        }
        impl Task<u32> for Trickle {
            async fn handle(&mut self, ctx: u32) {
                tokio::time::sleep(Duration::from_millis(20)).await;
                self.log.lock().unwrap().push(ctx);
            }
        }

        let log = Arc::new(Mutex::new(Vec::<u32>::new()));
        let reactor = Reactor::<u32, Trickle>::new_current().unwrap();
        let mut builder = TaskBuilder::<u32>::new();
        let ch = builder.add_bounded(0, 1);
        // Use the async spawn variant since we're inside a tokio runtime.
        let handler = reactor
            .spawn_async(Trickle { log: log.clone() }, builder)
            .await
            .unwrap();

        for i in 0..5u32 {
            handler.send_async(ch, i).await.unwrap();
        }

        // Wait for the task to drain.
        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        loop {
            if log.lock().unwrap().len() == 5 {
                break;
            }
            if std::time::Instant::now() >= deadline {
                panic!("didn't drain in time");
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        assert_eq!(*log.lock().unwrap(), vec![0, 1, 2, 3, 4]);
        drop(handler);
        // Move the blocking shutdown to a blocking thread to avoid
        // stalling the current-thread runtime.
        tokio::task::spawn_blocking(move || reactor.shutdown().unwrap())
            .await
            .unwrap();
    }

    #[test]
    fn shutdown_is_clean() {
        struct Noop;
        impl Task<()> for Noop {
            async fn handle(&mut self, _ctx: ()) {}
        }

        let reactor = Reactor::<(), Noop>::new_current().unwrap();
        let mut builder = TaskBuilder::<()>::new();
        let ch = builder.add_unbounded(0);
        let handler = reactor.spawn(Noop, builder).unwrap();

        for _ in 0..10 {
            handler.send(ch, ()).unwrap();
        }

        drop(handler);
        reactor.shutdown().expect("shutdown clean");
    }

    /// Regression test for the I/O/timer-starvation bug fixed by adding
    /// `consume_budget` to the scheduler loop.
    ///
    /// A handler that synchronously re-queues onto the same channel used
    /// to drive the scheduler in a tight loop, preventing the reactor
    /// thread's tokio runtime from polling sibling tasks (e.g. timers
    /// spawned via `tokio::task::spawn`). Here we ensure a 100 ms
    /// `tokio::time::sleep` spawned from within `handle` actually fires
    /// even while the scheduler is otherwise looping on a re-queued
    /// context.
    #[test]
    fn handler_resubmit_does_not_starve_spawned_timer() {
        use tokio::sync::Notify;

        enum Msg {
            /// Hand the worker its own producer + channel token.
            Init {
                handler: TaskHandler<Msg>,
                ch: Channel<Msg>,
            },
            /// Kicks the loop and arms the timer once.
            Start,
            /// Re-queued by the handler on every iteration.
            Retry,
            /// Sent by the spawned timer; releases the watchdog.
            Done,
        }

        struct Worker {
            handler: Option<TaskHandler<Msg>>,
            ch: Option<Channel<Msg>>,
            armed: bool,
            done: Arc<Notify>,
        }

        impl Task<Msg> for Worker {
            async fn handle(&mut self, msg: Msg) {
                match msg {
                    Msg::Init { handler, ch } => {
                        self.handler = Some(handler);
                        self.ch = Some(ch);
                    }
                    Msg::Start => {
                        let h = self.handler.clone().unwrap();
                        let ch = self.ch.unwrap();
                        if !self.armed {
                            self.armed = true;
                            let h_for_timer = h.clone();
                            tokio::task::spawn(async move {
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                let _ = h_for_timer.send(ch, Msg::Done);
                            });
                        }
                        let _ = h.send(ch, Msg::Retry);
                    }
                    Msg::Retry => {
                        let h = self.handler.as_ref().unwrap();
                        let ch = self.ch.unwrap();
                        let _ = h.send(ch, Msg::Retry);
                    }
                    Msg::Done => {
                        self.done.notify_one();
                    }
                }
            }
        }

        let done = Arc::new(Notify::new());
        let reactor = Reactor::<Msg, Worker>::new_current().unwrap();

        let mut builder = TaskBuilder::<Msg>::new();
        let cb = builder.add_channel(0, Capacity::Unbounded);
        let ext = builder.add_channel(1, Capacity::Unbounded);

        let handler = reactor
            .spawn(
                Worker {
                    handler: None,
                    ch: None,
                    armed: false,
                    done: done.clone(),
                },
                builder,
            )
            .unwrap();

        handler
            .send(
                ext,
                Msg::Init {
                    handler: handler.clone(),
                    ch: cb,
                },
            )
            .ok()
            .expect("init send");
        handler.send(ext, Msg::Start).ok().expect("start send");

        // Wait up to 2 s for the spawned timer to fire. With the bug,
        // it never fires. With the fix, it fires in ~100 ms.
        let waited = std::thread::scope(|s| {
            let done = done.clone();
            let h = s.spawn(move || {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                rt.block_on(async {
                    tokio::time::timeout(Duration::from_secs(2), done.notified())
                        .await
                        .is_ok()
                })
            });
            h.join().unwrap()
        });

        assert!(
            waited,
            "spawned timer did not fire within 2 s: scheduler is starving the runtime"
        );

        // The handler keeps re-queueing forever, so we can't `shutdown`
        // cleanly here — the receivers will never close. Drop the
        // reactor and let the OS reap the thread on process exit.
        std::mem::forget(handler);
        std::mem::forget(reactor);
    }
}