auralis-task 0.1.15

Scoped async task runtime with cancellation and priority scheduling
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
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
//! Single-threaded executor with priority scheduling, time-budget
//! awareness, and deferred-signal support.
//!
//! ## Architecture
//!
//! The executor is stored via a pluggable [`ExecutorStorage`] strategy
//! (defaulting to a per-thread slot).  Before polling a task the future
//! is **temporarily removed** so that the poll never holds an executor
//! borrow — this allows nested spawns, wakes, and `set_deferred` calls
//! without `RefCell` panics.
//!
//! The waker carries only a `task_id: u64`, making it trivially
//! [`Send`] + [`Sync`] for [`Waker::from`].

#![allow(clippy::cast_possible_truncation)]

use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};

use auralis_signal::Signal;

use crate::Priority;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

type TaskId = u64;

// ---------------------------------------------------------------------------
// ScheduleFlush
// ---------------------------------------------------------------------------

/// Platform hook for scheduling a microtask callback.
pub trait ScheduleFlush {
    /// Request that `callback` runs at the next microtask boundary.
    fn schedule(&self, callback: Box<dyn FnOnce()>);
}

/// A [`ScheduleFlush`] that fires the callback synchronously.
///
/// Makes the executor run-to-completion in unit tests without a browser
/// event loop.
#[cfg(test)]
pub struct TestScheduleFlush;

#[cfg(test)]
impl ScheduleFlush for TestScheduleFlush {
    fn schedule(&self, callback: Box<dyn FnOnce()>) {
        callback();
    }
}

// ---------------------------------------------------------------------------
// TimeSource
// ---------------------------------------------------------------------------

/// High-resolution time source for the executor's time-budget
/// accounting.
///
/// When registered via [`init_time_source`], the executor queries this
/// before and after each task poll to decide whether it should yield
/// control back to the host event loop (default budget: 8 ms).
///
/// In Wasm environments the implementation typically delegates to
/// `performance.now()`.  If no [`TimeSource`] is registered the time
/// budget check is a no-op and the executor runs tasks until the
/// queues are drained.
pub trait TimeSource {
    /// Return the current time in milliseconds.
    fn now_ms(&self) -> u64;
}

/// A [`TimeSource`] whose value is explicitly controlled by the test.
///
/// Use [`set`](TestTimeSource::set) or [`advance`](TestTimeSource::advance)
/// to simulate the passage of time during a flush cycle.
#[cfg(test)]
pub struct TestTimeSource {
    now: std::cell::Cell<u64>,
}

#[cfg(test)]
impl TestTimeSource {
    /// Create a new [`TestTimeSource`] with the given initial time.
    #[must_use]
    pub fn new(initial_ms: u64) -> Self {
        Self {
            now: std::cell::Cell::new(initial_ms),
        }
    }

    /// Set the current time to `ms` milliseconds.
    pub fn set(&self, ms: u64) {
        self.now.set(ms);
    }

    /// Advance the current time by `ms` milliseconds.
    pub fn advance(&self, ms: u64) {
        self.now.set(self.now.get() + ms);
    }
}

#[cfg(test)]
impl TimeSource for TestTimeSource {
    fn now_ms(&self) -> u64 {
        self.now.get()
    }
}

// ---------------------------------------------------------------------------
// TaskWaker — routes wakes to the correct executor via a slot table.
//
// Waker::from requires Send + Sync + 'static, so the waker cannot hold
// an Rc<RefCell<Executor>>.  Instead it stores a slot index + generation
// number.  The SLOTS thread_local maps (index, generation) → Weak<Executor>.
// On wake, the generation is validated before the weak pointer is upgraded.
// Dead slots are reclaimed when new executors are registered.
// ---------------------------------------------------------------------------

/// A registered executor slot.  The `generation` counter distinguishes
/// between successive executors that occupy the same slot index (e.g.
/// after the previous one was dropped and a new one recycles the slot).
struct Slot {
    weak: Weak<RefCell<Executor>>,
    /// Incremented (wrapping) every time this slot is reused.
    /// A [`TaskWaker`] must present the generation it was created with;
    /// a mismatch means the waker is stale and is silently ignored.
    generation: u64,
}

thread_local! {
    /// Slot 0 is reserved for the global executor.  Instance executors
    /// occupy subsequent slots.  Dead slots (Weak::upgrade returns None)
    /// are recycled in [`register_executor`].
    static SLOTS: RefCell<Vec<Slot>> = const { RefCell::new(Vec::new()) };
}

/// Register an executor in the slot table, returning the assigned
/// (`slot_id`, `generation`) pair.  Dead slots are recycled in-place;
/// if no dead slot is found a new entry is appended.
fn register_executor(weak: Weak<RefCell<Executor>>) -> (u64, u64) {
    SLOTS.with(|slots| {
        let mut slots = slots.borrow_mut();
        for (i, slot) in slots.iter_mut().enumerate() {
            if slot.weak.upgrade().is_none() {
                slot.weak = weak;
                // Wrapping is safe: 2^64 reuses of a single slot
                // would take ~10^14 years at 1 reuse/μs.
                slot.generation = slot.generation.wrapping_add(1);
                return (i as u64, slot.generation);
            }
        }
        let gen = 0;
        slots.push(Slot {
            weak,
            generation: gen,
        });
        ((slots.len() - 1) as u64, gen)
    })
}

/// Look up an executor by slot id, validating the generation.
fn lookup_executor(slot_id: u64, generation: u64) -> Option<Rc<RefCell<Executor>>> {
    SLOTS.with(|slots| {
        let slots = slots.borrow();
        let slot = slots.get(slot_id as usize)?;
        if slot.generation != generation {
            return None;
        }
        slot.weak.upgrade()
    })
}

struct TaskWaker {
    task_id: TaskId,
    priority: Priority,
    slot_id: u64,
    generation: u64,
}

impl Wake for TaskWaker {
    fn wake(self: Arc<Self>) {
        let Some(exec) = lookup_executor(self.slot_id, self.generation) else {
            return;
        };
        let maybe_sched = if let Ok(mut ex) = exec.try_borrow_mut() {
            match self.priority {
                Priority::High => ex.high_queue.push_back(self.task_id),
                Priority::Low => ex.low_queue.push_back(self.task_id),
            }
            if ex.in_flush {
                None
            } else {
                ex.try_schedule_flush()
            }
        } else {
            PENDING_WAKES.with(|pw| {
                pw.borrow_mut()
                    .push((self.task_id, self.slot_id, self.generation));
            });
            None
        };
        if let Some(sched) = maybe_sched {
            let sid = self.slot_id;
            let gen = self.generation;
            sched.schedule(Box::new(move || {
                if let Some(ex) = lookup_executor(sid, gen) {
                    Executor::flush_instance(&ex);
                }
            }));
        }
    }
}

// ---------------------------------------------------------------------------
// TaskState
// ---------------------------------------------------------------------------

struct TaskState {
    future: Pin<Box<dyn Future<Output = ()> + 'static>>,
    priority: Priority,
    scope_id: u64,
    /// Key in [`Executor::timers`] for this task's pending sleep,
    /// or 0 if the task is not waiting on a timer.
    timer_deadline: u64,
    /// Number of times this task has been polled.
    total_poll_count: u64,
    /// Microseconds spent in the most recent poll.
    last_poll_duration_us: u64,
}

// ---------------------------------------------------------------------------
// Executor
// ---------------------------------------------------------------------------

/// Information about a task panic, passed to the user-registered
/// [`set_panic_hook`].
#[derive(Debug)]
pub struct PanicInfo {
    /// The executor-assigned task id.
    pub task_id: u64,
    /// The scope that owned the task (0 for global tasks).
    pub scope_id: u64,
    /// The boxed panic payload.
    pub payload: Box<dyn std::any::Any + Send>,
}

/// A single-threaded async task executor with priority queues.
///
/// Each [`Executor`] manages its own task slots, ready queues, and
/// deferred callback buffers.  Use [`Executor::new_instance`] to create
/// an isolated executor (e.g. per SSR request), or use the global
/// thread-local executor via [`spawn_global`](crate::spawn_global).
pub struct Executor {
    high_queue: VecDeque<TaskId>,
    low_queue: VecDeque<TaskId>,
    tasks: Vec<Option<TaskState>>,
    free_slots: Vec<TaskId>,
    next_task_id: TaskId,
    is_flush_scheduled: bool,
    in_flush: bool,
    deferred_ops: Vec<DeferredOp>,
    /// Callbacks pushed by `Signal::set` via the schedule hook.
    /// Drained at the start of every flush before polling tasks.
    ///
    /// Unbounded by design — in a single-threaded Wasm context, a tight
    /// loop of signal sets will block the UI thread anyway, so adding a
    /// capacity limit wouldn't improve the situation.  SSR / multi-tenant
    /// users should ensure that application code doesn't produce
    /// unbounded signal churn within a single request.
    deferred_callbacks: Vec<Box<dyn FnOnce()>>,
    flush_scheduler: Option<Rc<dyn ScheduleFlush>>,
    time_source: Option<Rc<dyn TimeSource>>,
    /// Maximum milliseconds to spend inside a single flush before
    /// yielding back to the host event loop.  Default: 8 ms.
    time_budget_ms: u64,
    /// Optional cap on the number of deferred signal callbacks that can
    /// accumulate between two flushes.  Exceeding this limit triggers a
    /// panic — useful as a safety net in SSR / multi-tenant deployments
    /// where a runaway signal loop could OOM the process.
    ///
    /// Default: `None` (no limit).
    max_deferred_callbacks: Option<usize>,
    /// Optional hook invoked when a spawned task panics.
    panic_hook: Option<Rc<dyn Fn(PanicInfo)>>,
    /// Timer queue: map from deadline (ms) to task ids that should be
    /// woken when that deadline expires.  Processed at the start of
    /// every flush.
    timers: BTreeMap<u64, Vec<TaskId>>,
    /// Slot index and generation in [`SLOTS`] for routing wakes back
    /// to this executor.  Set by [`new_instance`] or lazily for the
    /// global executor.
    slot_id: u64,
    generation: u64,
    /// Whether this executor has been registered in [`SLOTS`].
    registered: bool,
}

// Set by the executor before polling a task, cleared afterward.
// Lets futures discover their task id without threading it through
// layers of combinators.
thread_local! {
    static CURRENT_POLLING_TASK: Cell<Option<TaskId>> = const { Cell::new(None) };
}

pub(crate) fn with_current_polling_task<R>(f: impl FnOnce(Option<TaskId>) -> R) -> R {
    CURRENT_POLLING_TASK.with(|c| f(c.get()))
}

struct DeferredOp {
    f: Box<dyn FnOnce()>,
}

impl Executor {
    fn new() -> Self {
        Self {
            high_queue: VecDeque::new(),
            low_queue: VecDeque::new(),
            tasks: Vec::new(),
            free_slots: Vec::new(),
            next_task_id: 0,
            is_flush_scheduled: false,
            in_flush: false,
            deferred_ops: Vec::new(),
            deferred_callbacks: Vec::new(),
            flush_scheduler: None,
            time_source: None,
            time_budget_ms: 8,
            max_deferred_callbacks: None,
            panic_hook: None,
            timers: BTreeMap::new(),
            slot_id: 0,
            generation: 0,
            registered: false,
        }
    }

    fn allocate_id(&mut self) -> TaskId {
        if let Some(id) = self.free_slots.pop() {
            return id;
        }
        let id = self.next_task_id;
        self.next_task_id += 1;
        self.tasks.push(None);
        id
    }

    /// Release a task slot back to the free list.
    ///
    /// **Caller must ensure** that `task_id` has not already been freed
    /// (e.g. via [`cancel_task`] or [`cancel_scope_tasks_on`]).  This
    /// method unconditionally pushes to `free_slots` — pushing the same
    /// id twice would cause [`allocate_id`] to hand it out twice.
    fn free_slot(&mut self, task_id: TaskId) {
        // Clean up any pending timer for this task so a recycled
        // task ID is not spuriously woken by an old deadline.
        // This works when the slot is still occupied (scope cancel
        // path).  For normal completion (Poll::Ready), the slot is
        // already None and the caller must call cleanup_timer first.
        if let Some(Some(ref t)) = self.tasks.get(task_id as usize) {
            if t.timer_deadline != 0 {
                self.cleanup_timer(task_id, t.timer_deadline);
            }
        }
        self.tasks[task_id as usize] = None;
        self.free_slots.push(task_id);
    }

    /// Remove a timer entry for `task_id` from the timer map.
    fn cleanup_timer(&mut self, task_id: TaskId, deadline: u64) {
        if let Some(tids) = self.timers.get_mut(&deadline) {
            tids.retain(|id| *id != task_id);
            if tids.is_empty() {
                self.timers.remove(&deadline);
            }
        }
    }

    fn enqueue(&mut self, task_id: TaskId) {
        let priority = match self.tasks.get(task_id as usize).and_then(Option::as_ref) {
            Some(t) => t.priority,
            None => return,
        };
        match priority {
            Priority::High => self.high_queue.push_back(task_id),
            Priority::Low => self.low_queue.push_back(task_id),
        }
    }

    fn dequeue(&mut self) -> Option<TaskId> {
        self.high_queue
            .pop_front()
            .or_else(|| self.low_queue.pop_front())
    }

    /// Mark that a flush is needed and return the scheduler if one is
    /// registered.  The caller **must** invoke the scheduler **after**
    /// releasing the executor borrow.
    fn try_schedule_flush(&mut self) -> Option<Rc<dyn ScheduleFlush>> {
        if self.is_flush_scheduled {
            return None;
        }
        self.is_flush_scheduled = true;
        self.flush_scheduler.clone()
    }

    /// Return the current time in ms, or 0 if no [`TimeSource`] is
    /// registered.  When this returns 0 the time-budget check is
    /// effectively a no-op.
    pub(crate) fn now_ms(&self) -> u64 {
        self.time_source.as_ref().map_or(0, |ts| ts.now_ms())
    }

    /// Return the number of currently active (not-yet-completed) tasks.
    ///
    /// Used by streaming SSR to determine whether the stream should
    /// wait for more work or terminate.
    #[must_use]
    pub fn active_task_count(&self) -> usize {
        self.tasks.iter().filter(|t| t.is_some()).count()
    }
}

// ---------------------------------------------------------------------------
// Thread-local globals (default storage)
// ---------------------------------------------------------------------------

thread_local! {
    static EXECUTOR: Rc<RefCell<Executor>> = Rc::new(RefCell::new(Executor::new()));
    static PENDING_WAKES: RefCell<Vec<(TaskId, u64, u64)>> =
        const { RefCell::new(Vec::new()) };
}

/// Ensure the global executor is registered in slot 0 (lazy, idempotent).
/// Returns (`slot_id`, `generation`) for the global executor.
fn ensure_global_registered() -> (u64, u64) {
    SLOTS.with(|slots| {
        let mut slots = slots.borrow_mut();
        if slots.is_empty() {
            let weak = EXECUTOR.with(Rc::downgrade);
            slots.push(Slot {
                weak,
                generation: 0,
            });
        } else {
            // Verify slot 0 still holds the global executor.
            let global = EXECUTOR.with(Rc::clone);
            let is_global = slots[0]
                .weak
                .upgrade()
                .is_some_and(|ex| Rc::ptr_eq(&ex, &global));
            if !is_global {
                slots[0] = Slot {
                    weak: Rc::downgrade(&global),
                    generation: slots[0].generation.wrapping_add(1),
                };
            }
        }
        // Mark the global executor as registered so flush_instance
        // doesn't call this function again on every flush.
        EXECUTOR.with(|ex| {
            let mut e = ex.borrow_mut();
            e.slot_id = 0;
            e.generation = slots[0].generation;
            e.registered = true;
        });
        let gen = slots[0].generation;
        (0, gen)
    })
}

// ---------------------------------------------------------------------------
// Executor instance methods (for isolated executors, e.g. SSR)
// ---------------------------------------------------------------------------

impl Executor {
    /// Create a new isolated executor, wrapped for shared access.
    ///
    /// The returned executor is independent of the global thread-local
    /// executor.  Use [`with_executor`] to make it the current executor
    /// for the duration of a closure, so that spawned tasks and signal
    /// callbacks are routed to it.
    #[must_use]
    pub fn new_instance() -> Rc<RefCell<Executor>> {
        let ex = Rc::new(RefCell::new(Executor::new()));
        // Register in the slot table so TaskWaker can find this executor.
        let (slot_id, generation) = register_executor(Rc::downgrade(&ex));
        {
            let mut e = ex.borrow_mut();
            e.slot_id = slot_id;
            e.generation = generation;
            e.registered = true;
        }
        ex
    }

    /// Install a flush scheduler on this executor instance.
    pub fn install_flush_scheduler(ex: &Rc<RefCell<Executor>>, sched: Rc<dyn ScheduleFlush>) {
        ex.borrow_mut().flush_scheduler = Some(sched);
    }

    /// Install a time source on this executor instance.
    pub fn install_time_source(ex: &Rc<RefCell<Executor>>, ts: Rc<dyn TimeSource>) {
        ex.borrow_mut().time_source = Some(ts);
    }

    /// Set the maximum time (in milliseconds) a single flush may spend
    /// before yielding back to the host event loop.
    ///
    /// The default is 8 ms (~120 fps frame budget, leaving time for the
    /// browser to render between flushes).  Set to `u64::MAX` to disable
    /// time-budget yielding (flush runs to completion).
    ///
    /// # Semantics
    ///
    /// The budget is checked **between** task polls — the currently
    /// executing task is never interrupted.  When the budget is exhausted
    /// the executor sets `in_flush = false` and schedules a follow-up
    /// flush so the remaining ready tasks will be polled on the next
    /// microtask tick.  This is cooperative (`.await`-bound) yielding,
    /// not preemptive.
    ///
    /// This affects **this executor only**.  For the global thread-local
    /// executor use [`set_global_time_budget`].
    pub fn set_time_budget(ex: &Rc<RefCell<Executor>>, budget_ms: u64) {
        ex.borrow_mut().time_budget_ms = budget_ms;
    }

    /// Set a safety cap on the deferred signal callback queue.
    ///
    /// When set to `Some(n)`, the executor will panic if more than `n`
    /// deferred callbacks accumulate between two flush cycles.  This is a
    /// safety net for SSR / multi-tenant servers where a runaway signal
    /// loop could exhaust memory — in a single-threaded Wasm context,
    /// unbounded accumulation is acceptable because it blocks the UI
    /// thread anyway.
    ///
    /// Default: `None` (no limit).
    pub fn set_max_deferred_callbacks(ex: &Rc<RefCell<Executor>>, limit: Option<usize>) {
        ex.borrow_mut().max_deferred_callbacks = limit;
    }

    /// Register a callback invoked whenever a spawned task panics.
    ///
    /// The default is no hook — panicking tasks are silently removed
    /// from the executor (the same behaviour as a task returning
    /// `Poll::Ready(())`).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// Executor::set_panic_hook(&ex, Rc::new(|info| {
    ///     eprintln!("task {} in scope {} panicked", info.task_id, info.scope_id);
    /// }));
    /// ```
    pub fn set_panic_hook(ex: &Rc<RefCell<Executor>>, hook: Rc<dyn Fn(PanicInfo)>) {
        ex.borrow_mut().panic_hook = Some(hook);
    }

    /// Register a timer: when `now_ms() >= deadline_ms`, enqueue
    /// `task_id` so it gets polled on the next flush.
    pub(crate) fn schedule_timer(ex: &Rc<RefCell<Executor>>, deadline_ms: u64, task_id: TaskId) {
        let mut e = ex.borrow_mut();
        // If this task already has a pending timer (e.g. previous SleepFuture
        // was dropped via select!), clean up the old entry so the timer map
        // doesn't accumulate stale deadlines.
        let old_deadline = e
            .tasks
            .get(task_id as usize)
            .and_then(Option::as_ref)
            .map_or(0, |t| t.timer_deadline);
        if old_deadline != 0 {
            e.cleanup_timer(task_id, old_deadline);
        }
        e.timers.entry(deadline_ms).or_default().push(task_id);
        // Set the reverse index so cancel_scope_tasks can find this entry.
        if let Some(Some(ref mut t)) = e.tasks.get_mut(task_id as usize) {
            t.timer_deadline = deadline_ms;
        }
        // Request a flush so the timer is checked.
        e.is_flush_scheduled = false;
        let maybe_sched = e.try_schedule_flush();
        drop(e);
        if let Some(sched) = maybe_sched {
            let ex2 = Rc::clone(ex);
            sched.schedule(Box::new(move || Self::flush_instance(&ex2)));
        }
    }

    /// Spawn a future on this executor instance.
    pub fn spawn(ex: &Rc<RefCell<Executor>>, future: impl Future<Output = ()> + 'static) {
        let maybe_sched = {
            let mut e = ex.borrow_mut();
            let tid = e.allocate_id();
            e.tasks[tid as usize] = Some(TaskState {
                future: Box::pin(future),
                priority: Priority::Low,
                scope_id: 0,
                timer_deadline: 0,
                total_poll_count: 0,
                last_poll_duration_us: 0,
            });
            e.enqueue(tid);
            e.try_schedule_flush()
        };
        if let Some(sched) = maybe_sched {
            let ex2 = Rc::clone(ex);
            sched.schedule(Box::new(move || Self::flush_instance(&ex2)));
        }
    }

    /// Run a full flush cycle on this executor instance.
    ///
    /// Mirrors the global flush cycle but operates on an
    /// isolated executor (used for SSR).  Includes all the same
    /// protections: `catch_unwind`, suspend checks, time-budget
    /// yielding, and callback-drain budget.
    #[allow(clippy::too_many_lines)]
    pub fn flush_instance(ex: &Rc<RefCell<Executor>>) {
        // Guard against re-entrant flushes.
        {
            let mut e = ex.borrow_mut();
            if e.in_flush {
                #[cfg(debug_assertions)]
                {
                    eprintln!(
                        "[auralis-task] WARNING: Executor::flush_instance called \
                         re-entrantly (already inside a flush). This is a no-op. \
                         Check for nested flush() calls in signal callbacks or \
                         ScheduleFlush implementations."
                    );
                }
                return;
            }
            e.in_flush = true;
        }

        // Set this executor as the current one so that TaskWaker
        // (which cannot hold an Rc) can discover it via thread-local.
        // Restore on scope exit (including early returns for time-budget
        // yielding and re-entrancy).
        let prev_executor = CURRENT_EXECUTOR.with(|c| c.borrow_mut().replace(Rc::clone(ex)));
        let _restore = RestoreExecutor(prev_executor);

        // Step 0: drain expired timers.
        {
            let mut e = ex.borrow_mut();
            let now = e.now_ms();
            // When no TimeSource is registered (now == 0), expire all
            // timers — they've already been woken via wake_by_ref and
            // just need to be re-polled.
            if now == 0 {
                for (_, tasks) in std::mem::take(&mut e.timers) {
                    for tid in tasks {
                        // Clear the reverse index since the timer has fired.
                        if let Some(Some(ref mut t)) = e.tasks.get_mut(tid as usize) {
                            t.timer_deadline = 0;
                        }
                        e.enqueue(tid);
                    }
                }
            } else {
                let expired: Vec<u64> =
                    e.timers.keys().copied().take_while(|&d| d <= now).collect();
                for deadline in expired {
                    if let Some(tasks) = e.timers.remove(&deadline) {
                        for tid in tasks {
                            if let Some(Some(ref mut t)) = e.tasks.get_mut(tid as usize) {
                                t.timer_deadline = 0;
                            }
                            e.enqueue(tid);
                        }
                    }
                }
            }
        }

        // Step 1: deferred ops.
        let deferred = std::mem::take(&mut ex.borrow_mut().deferred_ops);
        for op in deferred {
            (op.f)();
        }

        // Steps 2+3 may need to re-run if task polling queues new
        // signal callbacks (re-entrant cross-scope propagation).
        for _pass in 0..3_u8 {
            {
                let cb_start = ex.borrow().now_ms();
                loop {
                    let callbacks = std::mem::take(&mut ex.borrow_mut().deferred_callbacks);
                    if callbacks.is_empty() {
                        break;
                    }
                    for cb in callbacks {
                        // Isolate each callback so a panic in one subscriber
                        // doesn't block the remaining notifications or wedge
                        // the executor (in_flush stays true on unwind).
                        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(cb));
                    }
                    if ex.borrow().now_ms().saturating_sub(cb_start) >= ex.borrow().time_budget_ms {
                        if !ex.borrow().deferred_callbacks.is_empty() {
                            let (sched, ex2) = {
                                let mut e = ex.borrow_mut();
                                e.in_flush = false;
                                e.is_flush_scheduled = false;
                                (e.try_schedule_flush(), Rc::clone(ex))
                            };
                            if let Some(sched) = sched {
                                sched.schedule(Box::new(move || Self::flush_instance(&ex2)));
                            }
                            return;
                        }
                        break;
                    }
                }
            }

            // Step 3: main poll loop with time-budget check.
            let poll_start = ex.borrow().now_ms();
            loop {
                let task_id = ex.borrow_mut().dequeue();
                let Some(tid) = task_id else {
                    let mut e = ex.borrow_mut();
                    e.is_flush_scheduled = false;
                    e.in_flush = false;
                    break;
                };

                // Take the task out so the poll doesn't hold an executor borrow.
                let maybe_state = ex.borrow_mut().tasks[tid as usize].take();
                if let Some(mut state) = maybe_state {
                    let priority = state.priority;
                    let scope_id = state.scope_id;

                    // Check if the owning scope is suspended.
                    let scope = crate::scope::find_scope(scope_id);
                    if let Some(ref s) = scope {
                        if s.is_suspended() {
                            let mut e = ex.borrow_mut();
                            if e.tasks[tid as usize].is_none() {
                                e.tasks[tid as usize] = Some(state);
                            }
                            continue;
                        }
                    }

                    // Ensure the executor is registered in the slot table.
                    // Must not call ensure_global_registered while holding
                    // a borrow on ex (it borrows the global EXECUTOR).
                    let (slot_id, gen) = {
                        let e = ex.borrow();
                        if e.registered {
                            (e.slot_id, e.generation)
                        } else {
                            drop(e);
                            ensure_global_registered()
                        }
                    };
                    let waker = Waker::from(Arc::new(TaskWaker {
                        task_id: tid,
                        priority,
                        slot_id,
                        generation: gen,
                    }));
                    let mut cx = Context::from_waker(&waker);

                    // Inject owning scope.
                    let prev_scope = crate::scope::get_scope_direct();
                    if scope.is_some() {
                        crate::scope::set_scope_direct(scope);
                    }

                    // Let futures discover their task id (used by timer::sleep).
                    // Save and restore so that a nested flush (sync scheduler)
                    // doesn't leave the outer task without its id afterward.
                    let prev_polling = CURRENT_POLLING_TASK.with(|c| c.replace(Some(tid)));

                    // Task isolation + timing.
                    state.total_poll_count = state.total_poll_count.wrapping_add(1);
                    let t0 = auralis_signal::now_us();
                    let result: Result<Poll<()>, Box<dyn std::any::Any + Send>> =
                        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                            state.future.as_mut().poll(&mut cx)
                        }));
                    let elapsed = auralis_signal::now_us().saturating_sub(t0);

                    CURRENT_POLLING_TASK.with(|c| c.set(prev_polling));
                    crate::scope::set_scope_direct(prev_scope);

                    // Extract timer_deadline before state is dropped, so
                    // we can clean up the timer entry (free_slot can't
                    // read it because the slot is already None).
                    let timer_dl = state.timer_deadline;

                    state.last_poll_duration_us = elapsed;
                    match result {
                        Ok(Poll::Ready(())) => {
                            if timer_dl != 0 {
                                ex.borrow_mut().cleanup_timer(tid, timer_dl);
                            }
                            ex.borrow_mut().free_slot(tid);
                        }
                        Err(payload) => {
                            if timer_dl != 0 {
                                ex.borrow_mut().cleanup_timer(tid, timer_dl);
                            }
                            let hook = ex.borrow().panic_hook.clone();
                            if let Some(h) = hook {
                                h(PanicInfo {
                                    task_id: tid,
                                    scope_id,
                                    payload,
                                });
                            }
                            ex.borrow_mut().free_slot(tid);
                        }
                        Ok(Poll::Pending) => {
                            let mut e = ex.borrow_mut();
                            if e.tasks[tid as usize].is_none() {
                                e.tasks[tid as usize] = Some(state);
                            }
                        }
                    }
                }

                // Time budget check.
                {
                    let elapsed = ex.borrow().now_ms().saturating_sub(poll_start);
                    if elapsed >= ex.borrow().time_budget_ms {
                        let (maybe_sched, ex_clone) = {
                            let mut e = ex.borrow_mut();
                            e.is_flush_scheduled = false;
                            e.in_flush = false;
                            let sched = if !e.high_queue.is_empty() || !e.low_queue.is_empty() {
                                e.try_schedule_flush()
                            } else {
                                None
                            };
                            (sched, Rc::clone(ex))
                        };
                        if let Some(sched) = maybe_sched {
                            sched.schedule(Box::new(move || Self::flush_instance(&ex_clone)));
                        }
                        break;
                    }
                }
            }

            // Drain any wakes that were buffered while the executor RefCell
            // was borrowed (PENDING_WAKES fallback in TaskWaker::wake).
            drain_pending_wakes();

            // Continue only if signal callbacks accumulated during
            // polling and there are tasks to wake.
            if ex.borrow().deferred_callbacks.is_empty() {
                break;
            }
        } // end passes loop
    }
}

// ---------------------------------------------------------------------------
// Current-executor storage — injectable, defaults to thread-local
// ---------------------------------------------------------------------------

pub(crate) type ExecutorRef = Rc<RefCell<Executor>>;

/// RAII guard that restores the previous executor when dropped.
struct RestoreExecutor(Option<ExecutorRef>);

impl Drop for RestoreExecutor {
    fn drop(&mut self) {
        CURRENT_EXECUTOR.with(|c| {
            *c.borrow_mut() = self.0.take();
        });
    }
}

thread_local! {
    static CURRENT_EXECUTOR: RefCell<Option<ExecutorRef>> = const { RefCell::new(None) };
}

/// Run `f` with `ex` set as the current executor.
///
/// Signal callbacks and `spawn_global` calls inside `f` will be routed
/// to `ex` instead of the global thread-local executor.  Restores the
/// previous executor afterward.
///
/// # Signal routing constraints
///
/// Auralis uses a **single global schedule hook** (installed once by the
/// first call to [`init_flush_scheduler`]) that decides where signal
/// notifications land by checking the current executor **at the time the
/// notification fires**, not at the time `Signal::set` is called.
///
/// This design implies two hard requirements for multi-instance users:
///
/// 1. **`init_flush_scheduler` must be called at least once** — without
///    it, `Signal::set` falls back to synchronous callback execution,
///    which breaks the deferred-notification model and can cause
///    re-entrant borrow panics.
/// 2. **The instance executor must still be "current" when the flush
///    runs** — if `with_executor` has already exited, deferred callbacks
///    from signals set inside `f` will be routed to the global executor
///    (or synchronously if no global hook is installed).
///
/// For the typical single-threaded case (Wasm, game loop, CLI), both
/// requirements are satisfied trivially: call `init_flush_scheduler`
/// once at startup and never use `with_executor`.  For SSR / multi-tenant
/// servers, ensure that `with_executor` wraps the entire request
/// lifecycle — from signal creation through the final flush.
///
/// # Example
///
/// ```rust,ignore
/// use auralis_task::Executor;
///
/// let ex = Executor::new_instance();
/// Executor::install_flush_scheduler(&ex, my_scheduler);
/// auralis_task::with_executor(&ex, || {
///     // Signal notifications and task spawns here go to `ex`.
/// });
/// ```
pub fn with_executor<R>(ex: &ExecutorRef, f: impl FnOnce() -> R) -> R {
    CURRENT_EXECUTOR.with(|exec| {
        let prev = exec.borrow_mut().replace(Rc::clone(ex));
        let result = f();
        *exec.borrow_mut() = prev;
        result
    })
}

/// Return the current executor, if any.
///
/// If no executor has been set via [`with_executor`], returns `None` —
/// callers should fall back to the global thread-local executor.
fn current_executor() -> Option<ExecutorRef> {
    CURRENT_EXECUTOR.with(|exec| exec.borrow().clone())
}

/// Return the currently active executor instance.
///
/// If [`with_executor`] was used to set an instance executor, returns
/// that; otherwise returns the global thread-local executor.
pub(crate) fn current_executor_instance() -> ExecutorRef {
    current_executor().unwrap_or_else(|| EXECUTOR.with(Rc::clone))
}

/// Return the current time in milliseconds from the active executor's
/// [`TimeSource`], or 0 if none is installed.
pub(crate) fn current_time_ms() -> u64 {
    current_executor_instance().borrow().now_ms()
}

// ---------------------------------------------------------------------------
// Helpers — use thread_local EXECUTOR
// ---------------------------------------------------------------------------

/// Drain wakes that were buffered into [`PENDING_WAKES`] because the
/// executor's `RefCell` was borrowed at the time [`TaskWaker::wake`]
/// fired.  Called at the end of every [`Executor::flush_instance`].
fn drain_pending_wakes() {
    PENDING_WAKES.with(|pw| {
        let wakes = std::mem::take(&mut *pw.borrow_mut());
        for (tid, slot_id, gen) in wakes {
            let Some(exec) = lookup_executor(slot_id, gen) else {
                continue;
            };
            // Use enqueue() for the stale-task-id safety check.
            exec.borrow_mut().enqueue(tid);
            let maybe_sched = exec.borrow_mut().try_schedule_flush();
            if let Some(sched) = maybe_sched {
                let sid = slot_id;
                let g = gen;
                sched.schedule(Box::new(move || {
                    if let Some(ex) = lookup_executor(sid, g) {
                        Executor::flush_instance(&ex);
                    }
                }));
            }
        }
    });
}

// ---------------------------------------------------------------------------
// Flush
// ---------------------------------------------------------------------------

fn flush() {
    EXECUTOR.with(Executor::flush_instance);
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Check the deferred callback limit before pushing.
fn check_callback_limit(ex: &Executor) {
    if let Some(limit) = ex.max_deferred_callbacks {
        assert!(
            ex.deferred_callbacks.len() < limit,
            "deferred callback limit exceeded ({limit}). \
             This usually indicates an unbounded signal-set loop. \
             Increase the limit via set_max_deferred_callbacks() \
             or disable it with None."
        );
    }
}

/// Set the platform flush scheduler and install the signal deferred-
/// callback hook.
///
/// Idempotent — subsequent calls are no-ops (the hook is installed via
/// [`std::sync::OnceLock`], so it fires exactly once per process).
///
/// # Threading constraint
///
/// The hook is **per-process** and routes signal notifications to the
/// executor that is "current" when the notification fires (see
/// [`with_executor`]).  For single-threaded use (Wasm, CLI) this is
/// transparent.  For multi-threaded SSR, enable the `ssr-tokio` feature
/// and call [`init_scope_store_tokio`](crate::init_scope_store_tokio).
/// See [`with_executor`] for the full routing contract.
pub fn init_flush_scheduler(sched: Rc<dyn ScheduleFlush>) {
    EXECUTOR.with(|exec| exec.borrow_mut().flush_scheduler = Some(sched));
    install_signal_hook_once();
}

/// Install the hook that bridges `auralis_signal::Signal::set` to the
/// executor's deferred-callback queue.
///
/// Idempotent — safe to call multiple times.
fn install_signal_hook_once() {
    use std::sync::OnceLock;
    static INSTALLED: OnceLock<()> = OnceLock::new();
    INSTALLED.get_or_init(|| {
        auralis_signal::install_schedule_hook(Box::new(|cb: Box<dyn FnOnce()>| {
            // Prefer the current executor (set via `with_executor`) for
            // SSR multi-request isolation; fall back to the global one.
            if let Some(ex) = current_executor() {
                let maybe_sched = {
                    let mut e = ex.borrow_mut();
                    check_callback_limit(&e);
                    e.deferred_callbacks.push(cb);
                    if e.in_flush {
                        None
                    } else {
                        e.try_schedule_flush()
                    }
                };
                if let Some(sched) = maybe_sched {
                    let ex2 = Rc::clone(&ex);
                    sched.schedule(Box::new(move || Executor::flush_instance(&ex2)));
                }
            } else {
                EXECUTOR.with(|exec| {
                    let maybe_sched = {
                        let mut ex = exec.borrow_mut();
                        check_callback_limit(&ex);
                        ex.deferred_callbacks.push(cb);
                        if ex.in_flush {
                            None
                        } else {
                            ex.try_schedule_flush()
                        }
                    };
                    if let Some(sched) = maybe_sched {
                        sched.schedule(Box::new(flush));
                    }
                });
            }
        }));
    });
}

/// Set the platform time source used for time-budget accounting.
///
/// If no [`TimeSource`] is registered the executor runs every flush to
/// completion without yielding, which is acceptable for short-running
/// workloads but may cause frame drops in the browser.
pub fn init_time_source(ts: Rc<dyn TimeSource>) {
    EXECUTOR.with(|exec| exec.borrow_mut().time_source = Some(ts));
}

/// Set the per-flush time budget on the **global** thread-local executor.
///
/// This does **not** affect instance executors created via
/// [`Executor::new_instance`] — those carry their own budget (default
/// 8 ms) and must be configured via [`Executor::set_time_budget`].
///
/// See [`Executor::set_time_budget`] for the full semantics.
pub fn set_global_time_budget(budget_ms: u64) {
    EXECUTOR.with(|exec| exec.borrow_mut().time_budget_ms = budget_ms);
}

/// Set the deferred callback safety cap on the global executor.
///
/// See [`Executor::set_max_deferred_callbacks`] for details.
pub fn set_global_max_deferred_callbacks(limit: Option<usize>) {
    EXECUTOR.with(|exec| exec.borrow_mut().max_deferred_callbacks = limit);
}

/// Register a global panic hook called when any globally-spawned
/// task panics.
///
/// See [`Executor::set_panic_hook`] for details.
pub fn set_panic_hook(hook: Rc<dyn Fn(PanicInfo)>) {
    EXECUTOR.with(|exec| exec.borrow_mut().panic_hook = Some(hook));
}

/// Remove the global panic hook, restoring the default silent
/// behaviour.
pub fn remove_panic_hook() {
    EXECUTOR.with(|exec| exec.borrow_mut().panic_hook = None);
}

/// Spawn a future on the global executor at low priority.
///
/// **Important:** [`init_flush_scheduler`] must be called before spawning
/// any tasks.  Without a flush scheduler, spawned tasks will sit in the
/// queue indefinitely because the executor has no way to schedule a flush
/// cycle.
pub fn spawn_global(future: impl Future<Output = ()> + 'static) {
    spawn_global_with_priority(Priority::Low, future);
}

/// Spawn a future on the global executor at the given priority.
pub fn spawn_global_with_priority(priority: Priority, future: impl Future<Output = ()> + 'static) {
    spawn_inner_on(&EXECUTOR.with(Rc::clone), Box::pin(future), priority, 0);
}

/// Spawn a future on a specific executor and scope.
pub(crate) fn spawn_scoped_on(
    ex: &Rc<RefCell<Executor>>,
    priority: Priority,
    scope_id: u64,
    future: impl Future<Output = ()> + 'static,
) -> TaskId {
    spawn_inner_on(ex, Box::pin(future), priority, scope_id)
}

fn spawn_inner_on(
    ex: &Rc<RefCell<Executor>>,
    future: Pin<Box<dyn Future<Output = ()> + 'static>>,
    priority: Priority,
    scope_id: u64,
) -> TaskId {
    let (task_id, maybe_sched) = {
        let mut e = ex.borrow_mut();
        let task_id = e.allocate_id();
        e.tasks[task_id as usize] = Some(TaskState {
            future,
            priority,
            scope_id,
            timer_deadline: 0,
            total_poll_count: 0,
            last_poll_duration_us: 0,
        });
        e.enqueue(task_id);
        let sched = e.try_schedule_flush();
        (task_id, sched)
    };
    if let Some(sched) = maybe_sched {
        let ex2 = Rc::clone(ex);
        sched.schedule(Box::new(move || Executor::flush_instance(&ex2)));
    }
    task_id
}

/// Enqueue all tasks belonging to `scope_id` on a given executor.
///
/// Used by [`TaskScope::resume`] to restart tasks after a suspend.
pub(crate) fn enqueue_scope_tasks_on(ex: &ExecutorRef, task_ids: &[TaskId]) {
    if task_ids.is_empty() {
        return;
    }
    let maybe_sched = {
        let mut e = ex.borrow_mut();
        for tid in task_ids {
            e.enqueue(*tid);
        }
        if e.in_flush {
            None
        } else {
            e.try_schedule_flush()
        }
    };
    if let Some(sched) = maybe_sched {
        let ex2 = Rc::clone(ex);
        sched.schedule(Box::new(move || Executor::flush_instance(&ex2)));
    }
}
/// Cancel all tasks belonging to `scope_id` on a specific executor.
pub(crate) fn cancel_scope_tasks_on(
    ex: &Rc<RefCell<Executor>>,
    task_ids: &[TaskId],
) -> Vec<Pin<Box<dyn Future<Output = ()>>>> {
    if task_ids.is_empty() {
        return Vec::new();
    }

    let mut e = ex.borrow_mut();
    let mut dropped = Vec::with_capacity(task_ids.len());

    // Collect timer deadlines before mutating.
    let mut timer_deadlines: Vec<(u64, TaskId)> = Vec::new();
    for &tid in task_ids {
        let idx = tid as usize;
        if idx < e.tasks.len() {
            if let Some(ref t) = e.tasks[idx] {
                if t.timer_deadline != 0 {
                    timer_deadlines.push((t.timer_deadline, tid));
                }
            }
        }
    }
    for (dl, tid) in &timer_deadlines {
        e.cleanup_timer(*tid, *dl);
    }

    // Cancel each task by id (direct lookup, no full-table scan).
    // Only push to free_slots for slots we actually took.
    for &tid in task_ids {
        let idx = tid as usize;
        if idx < e.tasks.len() {
            if let Some(state) = e.tasks[idx].take() {
                dropped.push(state.future);
                e.free_slots.push(tid);
            }
        }
    }
    e.free_slots.sort_unstable();
    e.free_slots.dedup();

    // Filter queues to remove cancelled tasks.
    let high: Vec<TaskId> = e
        .high_queue
        .iter()
        .copied()
        .filter(|&id| {
            let idx = id as usize;
            idx < e.tasks.len() && e.tasks[idx].is_some()
        })
        .collect();
    e.high_queue.clear();
    e.high_queue.extend(high);

    let low: Vec<TaskId> = e
        .low_queue
        .iter()
        .copied()
        .filter(|&id| {
            let idx = id as usize;
            idx < e.tasks.len() && e.tasks[idx].is_some()
        })
        .collect();
    e.low_queue.clear();
    e.low_queue.extend(low);

    dropped
}

/// Cancel a single task by its id, dropping its future and cleaning up
/// its timer if any.  No-op if the task has already completed.
pub(crate) fn cancel_task(ex: &Rc<RefCell<Executor>>, task_id: TaskId) {
    let mut e = ex.borrow_mut();
    let idx = task_id as usize;
    if idx >= e.tasks.len() {
        return;
    }
    let deadline = e.tasks[idx].as_ref().map_or(0, |t| t.timer_deadline);
    if deadline != 0 {
        e.cleanup_timer(task_id, deadline);
    }
    let slot = e.tasks[idx].take();
    if slot.is_some() {
        e.free_slots.push(task_id);
        e.high_queue.retain(|&id| id != task_id);
        e.low_queue.retain(|&id| id != task_id);
    }
}

/// Check whether a task slot is empty (task completed or was cancelled).
pub(crate) fn is_task_finished(ex: &Rc<RefCell<Executor>>, task_id: TaskId) -> bool {
    let e = ex.borrow();
    let idx = task_id as usize;
    idx >= e.tasks.len() || e.tasks[idx].is_none()
}

// ---------------------------------------------------------------------------
// yield_now
// ---------------------------------------------------------------------------

/// Return a [`Future`] that yields control back to the executor once.
#[must_use = "yield_now() does nothing unless awaited"]
pub fn yield_now() -> YieldNow {
    YieldNow { yielded: false }
}

/// Future returned by [`yield_now`].
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct YieldNow {
    yielded: bool,
}

impl Future for YieldNow {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if self.yielded {
            Poll::Ready(())
        } else {
            self.yielded = true;
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

// ---------------------------------------------------------------------------
// schedule_callback — hook for auralis-signal's deferred callback model
// ---------------------------------------------------------------------------

/// Schedule a closure to run at the start of the next executor flush.
///
/// Used internally by `auralis_signal` to defer subscriber callback
/// execution.  The closure is drained before the main poll loop.
///
/// Routes to the current executor (via [`with_executor`]) when one is
/// active; falls back to the global thread-local executor.
pub fn schedule_callback(f: Box<dyn FnOnce()>) {
    let exec = current_executor_instance();
    let maybe_sched = {
        let mut ex = exec.borrow_mut();
        check_callback_limit(&ex);
        ex.deferred_callbacks.push(f);
        if ex.in_flush {
            None
        } else {
            ex.try_schedule_flush()
        }
    };
    if let Some(sched) = maybe_sched {
        let ex2 = Rc::clone(&exec);
        sched.schedule(Box::new(move || Executor::flush_instance(&ex2)));
    }
}

// ---------------------------------------------------------------------------
// set_deferred
// ---------------------------------------------------------------------------

/// Schedule a [`Signal::set`] call for the **next** executor flush.
///
/// Safe to call from inside [`Drop`] — the actual `signal.set(value)` is
/// deferred to a subsequent flush, avoiding re-entrant borrow panics.
///
/// Routes to the current executor (via [`with_executor`]) when one is
/// active; falls back to the global thread-local executor.
pub fn set_deferred<T: 'static>(signal: &Signal<T>, value: T) {
    let signal = signal.clone();
    let exec = current_executor_instance();
    let maybe_sched = {
        let mut ex = exec.borrow_mut();
        ex.deferred_ops.push(DeferredOp {
            f: Box::new(move || signal.set(value)),
        });
        ex.try_schedule_flush()
    };
    if let Some(sched) = maybe_sched {
        let ex2 = Rc::clone(&exec);
        sched.schedule(Box::new(move || Executor::flush_instance(&ex2)));
    }
}

// ---------------------------------------------------------------------------
// Test / debug helpers
// ---------------------------------------------------------------------------

/// Completely reset the global executor to a pristine state.
///
/// Clears all task slots, queues, deferred ops, flush/scheduler flags,
/// and injected [`ScheduleFlush`]/[`TimeSource`].  Call at the start
/// of every test to prevent cross-test state leakage.
///
/// Note that the signal schedule hook (installed by
/// [`init_flush_scheduler`] via [`std::sync::OnceLock`]) **persists**
/// across resets — the hook references the global [`EXECUTOR`]
/// thread-local, and this function re-initialises that same executor
/// in place rather than replacing it.  This is correct behaviour:
/// after reset, signal notifications route to the freshly-cleared
/// global executor.
///
/// # Safety / usage
///
/// This function is intended **only** for testing.  Calling it while
/// the executor is processing tasks will silently drop all live
/// futures and may cause panics or undefined behavior in running
/// application code.
pub fn reset_executor_for_test() {
    PENDING_WAKES.with(|pw| pw.borrow_mut().clear());
    SLOTS.with(|s| s.borrow_mut().clear());
    CURRENT_EXECUTOR.with(|c| *c.borrow_mut() = None);
    EXECUTOR.with(|exec| {
        let mut ex = exec.borrow_mut();
        ex.high_queue.clear();
        ex.low_queue.clear();
        ex.tasks.clear();
        ex.free_slots.clear();
        ex.next_task_id = 0;
        ex.is_flush_scheduled = false;
        ex.in_flush = false;
        ex.deferred_ops.clear();
        ex.deferred_callbacks.clear();
        ex.flush_scheduler = None;
        ex.time_source = None;
        ex.slot_id = 0;
        ex.generation = 0;
        ex.registered = false;
    });
    crate::scope::clear_scope_registry();
}

#[cfg(any(test, feature = "debug"))]
pub(crate) fn debug_task_count() -> usize {
    EXECUTOR.with(|exec| exec.borrow().tasks.iter().filter(|t| t.is_some()).count())
}

/// Return timing info for all active tasks: `task_id` → (`total_poll_count`, `last_poll_us`).
#[cfg(feature = "debug")]
pub(crate) fn debug_task_timing() -> std::collections::HashMap<TaskId, (u64, u64)> {
    EXECUTOR.with(|exec| {
        let ex = exec.borrow();
        let mut map = std::collections::HashMap::new();
        for (idx, slot) in ex.tasks.iter().enumerate() {
            if let Some(ref t) = slot {
                map.insert(idx as u64, (t.total_poll_count, t.last_poll_duration_us));
            }
        }
        map
    })
}

/// Return a snapshot of all active tasks: `(task_id, priority, scope_id)`.
#[cfg(feature = "debug")]
pub(crate) fn debug_task_snapshot() -> Vec<(TaskId, Priority, u64)> {
    EXECUTOR.with(|exec| {
        let ex = exec.borrow();
        let mut snap = Vec::new();
        for (idx, slot) in ex.tasks.iter().enumerate() {
            if let Some(ref t) = slot {
                snap.push((idx as u64, t.priority, t.scope_id));
            }
        }
        snap
    })
}

/// Return the set of task IDs currently in the ready queues.
#[cfg(feature = "debug")]
pub(crate) fn debug_queued_task_ids() -> Vec<TaskId> {
    EXECUTOR.with(|exec| {
        let ex = exec.borrow();
        let mut ids: Vec<TaskId> = ex
            .high_queue
            .iter()
            .chain(ex.low_queue.iter())
            .copied()
            .collect();
        ids.sort_unstable();
        ids.dedup();
        ids
    })
}

/// Spawn a task without triggering an automatic flush.
/// Used in tests to batch multiple spawns before executing them.
#[cfg(test)]
pub(crate) fn spawn_no_auto_flush(
    priority: Priority,
    future: impl Future<Output = ()> + 'static,
) -> TaskId {
    EXECUTOR.with(|exec| {
        let mut ex = exec.borrow_mut();
        let task_id = ex.allocate_id();
        ex.tasks[task_id as usize] = Some(TaskState {
            future: Box::pin(future),
            priority,
            scope_id: 0,
            timer_deadline: 0,
            total_poll_count: 0,
            last_poll_duration_us: 0,
        });
        ex.enqueue(task_id);
        // Do NOT schedule flush.
        task_id
    })
}

/// Run a manual flush cycle (for tests that need to control timing).
#[cfg(test)]
pub(crate) fn flush_all() {
    flush();
}