cdk-rsx-executor 0.1.0

Async executor for CDK RSX canisters
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
use crate::lifecycle::{Reclaimable, ReclaimableKey as _};
use crate::method_registry::{MethodId, MethodRegistry};
use std::{
    collections::VecDeque,
    future::Future,
    mem::take,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll, Wake, Waker},
};

use slotmap::{SlotMap, new_key_type};
use smallvec::SmallVec;
#[cfg(not(target_family = "wasm"))]
use std::cell::Cell;

/// Represents an active canister method.
#[derive(Clone, Debug)]
pub(crate) struct MethodContext {
    /// Whether this method is an update or a query.
    pub(crate) kind: ContextKind,
    /// The number of handles to this method context. When this drops to zero, the method context gets deleted.
    /// The refcount is managed by `MethodHandle`.
    pub(crate) handles: usize,
    /// An index for Task.method_binding; all protected tasks attached to this method.
    pub(crate) tasks: SmallVec<[TaskId; 4]>,
    /// Woken protected tasks wait with the context that owns them.
    wakeups: VecDeque<TaskId>,
}

impl MethodContext {
    pub(crate) fn new_update() -> Self {
        Self {
            kind: ContextKind::Update,
            handles: 0,
            tasks: SmallVec::new(),
            wakeups: VecDeque::new(),
        }
    }
    pub(crate) fn new_query() -> Self {
        Self {
            kind: ContextKind::Query,
            handles: 0,
            tasks: SmallVec::new(),
            wakeups: VecDeque::new(),
        }
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) enum ContextKind {
    Update,
    Query,
}

// Null method ID corresponds to 'null context', used for migratory tasks.
// Null task ID is an error.
new_key_type! {
    pub(crate) struct TaskId;
}

#[cfg(not(target_family = "wasm"))]
thread_local! {
    // global: list of all method contexts currently active
    pub(crate) static METHODS: Reclaimable<MethodRegistry> = const { Reclaimable::new() };
    // global: list of all tasks currently spawned
    pub(crate) static TASKS: Reclaimable<SlotMap<TaskId, Task>> = const { Reclaimable::new() };
    // global: list of migratory tasks that have been woken up
    pub(crate) static MIGRATORY_WAKEUPS: Reclaimable<VecDeque<TaskId>> = const { Reclaimable::new() };
    // dynamically scoped: the current method context. None means a context function was not called (which is a user error),
    // vs null which means no method in particular.
    // Memory capability fence remains active through task cancellation/destructors.
    // It does not change method handles, scheduling or cancellation transitions.
    pub(crate) static QUERY_EXECUTION: Cell<bool> = const { Cell::new(false) };
    pub(crate) static CURRENT_METHOD: Cell<Option<MethodId>> = const { Cell::new(None) };
    // dynamically scoped: whether we are currently recovering from a trap
    pub(crate) static RECOVERING: Cell<bool> = const { Cell::new(false) };
    // dynamically scoped: the current task ID, or None if a task is not running
    pub(crate) static CURRENT_TASK_ID: Cell<Option<TaskId>> = const { Cell::new(None) };
}

#[cfg(target_family = "wasm")]
pub(crate) use crate::hot_control::{
    CURRENT_METHOD, CURRENT_TASK_ID, METHODS, MIGRATORY_WAKEUPS, QUERY_EXECUTION, RECOVERING, TASKS,
};

/// A registered task in the executor.
pub(crate) struct Task {
    // Temporarily absent while the executor polls outside the registry borrow.
    future: Option<Pin<Box<dyn Future<Output = ()>>>>,
    // The owning method, or the null context for a migratory task. Wakers
    // use this binding even while the future is out of the slot.
    method_binding: MethodId,
}

/// Execute an update function in a context that allows calling [`spawn_protected`] and [`spawn_migratory`].
pub fn in_tracking_executor_context<R>(f: impl FnOnce() -> R) -> R {
    in_tracking_executor_context_without_poll(|| {
        let res = f();
        poll_all();
        res
    })
}

/// Track callbacks from SDK dispatch without polling task futures on exit.
#[doc(hidden)]
pub fn in_tracking_executor_context_without_poll<R>(f: impl FnOnce() -> R) -> R {
    setup_panic_hook();
    let method = METHODS.with_borrow_mut(|methods| methods.insert(MethodContext::new_update()));
    enter_current_method(MethodHandle::for_method(method), f)
}

/// Execute a function in a context that is not tracked across callbacks, able to call [`spawn_migratory`]
/// but not [`spawn_protected`].
#[expect(dead_code)] // not used in current null context code but may be used for other things in the future
pub(crate) fn in_null_context<R>(f: impl FnOnce() -> R) -> R {
    setup_panic_hook();
    let guard = MethodHandle::for_method(MethodId::null());
    enter_current_method(guard, || {
        let res = f();
        poll_all();
        res
    })
}

/// Execute a query function in a context that allows calling [`spawn_protected`] but not [`spawn_migratory`].
pub fn in_tracking_query_executor_context<R>(f: impl FnOnce() -> R) -> R {
    setup_panic_hook();
    let method = METHODS.with_borrow_mut(|methods| methods.insert(MethodContext::new_query()));
    let guard = MethodHandle::for_method(method);
    enter_current_method(guard, || {
        let res = f();
        poll_all();
        res
    })
}

/// Execute an inter-canister call callback in the context of the method that made it.
pub fn in_callback_executor_context_for<R>(
    method_handle: MethodHandle,
    f: impl FnOnce() -> R,
) -> R {
    setup_panic_hook();
    enter_current_method(method_handle, || {
        let res = f();
        poll_all();
        res
    })
}

/// Enters a trap/panic recovery context for calling [`cancel_all_tasks_attached_to_current_method`] in.
pub fn in_trap_recovery_context_for<R>(method: MethodHandle, f: impl FnOnce() -> R) -> R {
    setup_panic_hook();
    enter_current_method(method, || {
        RECOVERING.set(true);
        let res = f();
        RECOVERING.set(false);
        res
    })
}

/// Cancels all tasks made with [`spawn_protected`] attached to the current method.
pub fn cancel_all_tasks_attached_to_current_method() {
    let Some(method_id) = CURRENT_METHOD.get() else {
        panic!(
            "`cancel_all_tasks_attached_to_current_method` can only be called within a method context"
        );
    };
    cancel_all_tasks_attached_to_method(method_id);
}

/// Cancels all tasks made with [`spawn_protected`] attached to the given method.
fn cancel_all_tasks_attached_to_method(method_id: MethodId) {
    let Some(to_cancel) = METHODS.with_borrow_mut(|methods| {
        methods
            .get_mut(method_id)
            .map(|method| take(&mut method.tasks))
    }) else {
        return; // method context null or already deleted
    };
    let _tasks = TASKS.with(|tasks| {
        let Ok(mut tasks) = tasks.try_borrow_mut() else {
            panic!(
                "`cancel_all_tasks_attached_to_current_method` cannot be called from an async task"
            );
        };
        let mut canceled = Vec::with_capacity(to_cancel.len());
        for task_id in to_cancel {
            canceled.push(tasks.remove(task_id));
        }
        canceled
    });
    drop(_tasks); // always run task destructors outside of a refcell borrow
}

/// Removes a specific task. Use this instead of `remove` for guaranteed drop order.
pub(crate) fn delete_task(task_id: TaskId) {
    let _task = TASKS.with_borrow_mut(|tasks| tasks.remove(task_id));
    drop(_task); // always run task destructors outside of a refcell borrow
}

/// Cancels a specific task by its handle.
pub fn cancel_task(task_handle: &TaskHandle) {
    delete_task(task_handle.task_id);
}

/// Returns true if tasks are being canceled due to a trap or panic.
pub fn is_recovering_from_trap() -> bool {
    RECOVERING.get()
}

/// Produces a handle to the current method context.
///
/// The method is active as long as the handle is alive.
pub fn extend_current_method_context() -> MethodHandle {
    setup_panic_hook();
    let Some(method_id) = CURRENT_METHOD.get() else {
        panic!("`extend_method_context` can only be called within a tracking executor context");
    };
    MethodHandle::for_method(method_id)
}

/// Polls all tasks that have been woken up. Called after all context closures besides cancelation.
///
/// Should never be called inside a task, because it should only be called inside a context closure, and context closures
/// should only be at the top level of an entrypoint.
pub(crate) fn poll_all() {
    let Some(method_id) = CURRENT_METHOD.get() else {
        panic!("tasks can only be polled within an executor context");
    };
    let kind = METHODS
        .with_borrow(|methods| methods.get(method_id).map(|m| m.kind))
        .unwrap_or(ContextKind::Update);
    fn pop_wakeup(method_id: MethodId, update: bool) -> Option<TaskId> {
        if let Some(task_id) = METHODS.with_borrow_mut(|methods| {
            methods
                .get_mut(method_id)
                .and_then(|method| method.wakeups.pop_front())
        }) {
            Some(task_id)
        } else if update {
            MIGRATORY_WAKEUPS.with_borrow_mut(|unattached| unattached.pop_front())
        } else {
            None
        }
    }
    while let Some(task_id) = pop_wakeup(method_id, kind == ContextKind::Update) {
        // Move the future out to poll with TASKS unborrowed. The slot still
        // holds the binding so a wake from inside poll reaches its method.
        let Some((mut future, binding)) = TASKS.with_borrow_mut(|tasks| {
            let task = tasks.get_mut(task_id)?;
            Some((task.future.take()?, task.method_binding))
        }) else {
            // This waker handle appears to be dead. The most likely cause is that the method returned before
            // a canceled call came back.
            continue;
            // In the case that a task panicked and that's why it's missing, but it was in an earlier callback so a later
            // one tries to re-wake, the responsibility for re-trapping lies with CallFuture.
        };
        let waker = Waker::from(Arc::new(TaskWaker { task_id }));
        let prev_current_method_var = CURRENT_METHOD.replace(Some(binding));
        CURRENT_TASK_ID.set(Some(task_id));
        let poll = future.as_mut().poll(&mut Context::from_waker(&waker));
        CURRENT_TASK_ID.set(None);
        CURRENT_METHOD.set(prev_current_method_var);
        match poll {
            Poll::Pending => {
                // Restore the future if the task was not cancelled during poll.
                let discarded = TASKS.with_borrow_mut(|tasks| match tasks.get_mut(task_id) {
                    Some(task) => task.future.replace(future),
                    None => Some(future),
                });
                drop(discarded);
            }
            Poll::Ready(()) => {
                // task complete, remove its entry from the table fully
                delete_task(task_id);
            }
        }
    }
}

struct QueryExecutionGuard(bool);
impl Drop for QueryExecutionGuard {
    fn drop(&mut self) {
        QUERY_EXECUTION.set(self.0);
    }
}

/// Begin a context closure for the given method. Destroys the method afterwards if there are no outstanding handles.
pub(crate) fn enter_current_method<R>(method_guard: MethodHandle, f: impl FnOnce() -> R) -> R {
    CURRENT_METHOD.with(|context_var| {
        assert!(
            context_var.get().is_none(),
            "in_*_context called within an existing async context"
        );
        context_var.set(Some(method_guard.method_id));
    });
    let query = METHODS.with_borrow(|methods| {
        methods
            .get(method_guard.method_id)
            .is_some_and(|m| m.kind == ContextKind::Query)
    });
    let _query_guard = QueryExecutionGuard(QUERY_EXECUTION.replace(QUERY_EXECUTION.get() || query));
    let r = f();
    drop(method_guard); // drop the guard *before* the method freeing logic, but *after* the in-context code
    let method_id = CURRENT_METHOD.replace(None);
    if let Some(method_id) = method_id {
        let handles = METHODS.with_borrow_mut(|methods| methods.get(method_id).map(|m| m.handles));
        if handles == Some(0) {
            cancel_all_tasks_attached_to_method(method_id);
            METHODS.with_borrow_mut(|methods| methods.remove(method_id));
        }
    }
    r
}

/// A handle to a method context. If the function returns and all handles have been dropped, the method is considered returned.
///
/// This should be created before performing an inter-canister call via [`extend_current_method_context`],
/// threaded through the `env` parameter, and then used when calling [`in_callback_executor_context_for`] or
/// [`in_trap_recovery_context_for`]. Failure to track this properly may result in unexpected cancellation of tasks.
#[derive(Debug)]
pub struct MethodHandle {
    method_id: MethodId,
}

impl MethodHandle {
    /// Creates a live handle for the given method.
    pub(crate) fn for_method(method_id: MethodId) -> Self {
        if method_id.is_null() {
            return Self { method_id };
        }
        METHODS.with_borrow_mut(|methods| {
            let Some(method) = methods.get_mut(method_id) else {
                panic!("internal error: method context deleted while in use (for_method)");
            };
            method.handles += 1;
        });
        Self { method_id }
    }
}

impl Drop for MethodHandle {
    fn drop(&mut self) {
        METHODS.with_borrow_mut(|methods| {
            if let Some(method) = methods.get_mut(self.method_id) {
                method.handles -= 1;
            }
        })
    }
}

/// A handle to a spawned task.
#[derive(Debug)]
pub struct TaskHandle {
    task_id: TaskId,
}

impl TaskHandle {
    /// A handle to the task currently executing, or None if no task is executing.
    pub fn current() -> Option<Self> {
        let task_id = CURRENT_TASK_ID.get()?;
        Some(Self { task_id })
    }
}

pub(crate) struct TaskWaker {
    pub(crate) task_id: TaskId,
}

impl Wake for TaskWaker {
    fn wake(self: Arc<Self>) {
        TASKS.with_borrow_mut(|tasks| {
            if let Some(task) = tasks.get(self.task_id) {
                let method_id = task.method_binding;
                if !method_id.is_null() {
                    METHODS.with_borrow_mut(|methods| {
                        if let Some(method) = methods.get_mut(method_id) {
                            method.wakeups.push_back(self.task_id);
                        }
                    });
                } else {
                    MIGRATORY_WAKEUPS.with_borrow_mut(|unattached| {
                        unattached.push_back(self.task_id);
                    });
                }
            }
        })
    }
}

/// Spawns a task that can migrate between methods.
///
/// When the task is awoken, it will run in the context of the method that woke it.
pub fn spawn_migratory(f: impl Future<Output = ()> + 'static) -> TaskHandle {
    setup_panic_hook();
    let Some(method_id) = CURRENT_METHOD.get() else {
        panic!("`spawn_*` can only be called within an executor context");
    };
    if is_recovering_from_trap() {
        panic!("tasks cannot be spawned while recovering from a trap");
    }
    let kind = METHODS
        .with_borrow(|methods| methods.get(method_id).map(|m| m.kind))
        .unwrap_or(ContextKind::Update);
    if kind == ContextKind::Query {
        panic!("unprotected spawns cannot be made within a query context");
    }
    let task = Task {
        future: Some(Box::pin(f)),
        method_binding: MethodId::null(),
    };
    let task_id = TASKS.with_borrow_mut(|tasks| tasks.insert(task));
    MIGRATORY_WAKEUPS.with_borrow_mut(|unattached| {
        unattached.push_back(task_id);
    });
    TaskHandle { task_id }
}

/// Spawns a task attached to the current method.
///
/// When the task is awoken, if a different method is currently running, the task will not run until the method
/// it is attached to continues. If the attached method returns before the task completes, the task will be canceled.
pub fn spawn_protected(f: impl Future<Output = ()> + 'static) -> TaskHandle {
    setup_panic_hook();
    if is_recovering_from_trap() {
        panic!("tasks cannot be spawned while recovering from a trap");
    }
    let Some(method_id) = CURRENT_METHOD.get() else {
        panic!("`spawn_*` can only be called within an executor context");
    };
    if method_id.is_null() {
        panic!("`spawn_protected` cannot be called outside of a tracked method context");
    }
    let task = Task {
        future: Some(Box::pin(f)),
        method_binding: method_id,
    };
    let task_id = TASKS.with_borrow_mut(|tasks| tasks.insert(task));
    METHODS.with_borrow_mut(|methods| {
        let Some(method) = methods.get_mut(method_id) else {
            panic!("internal error: method context deleted while in use (spawn_protected)");
        };
        method.tasks.push(task_id);
        method.wakeups.push_back(task_id);
    });
    TaskHandle { task_id }
}

#[cfg(target_family = "wasm")]
fn setup_panic_hook() {
    use crate::hot_control::SETUP;
    SETUP.call_once(|| {
        std::panic::set_hook(Box::new(|info| {
            let file = info.location().unwrap().file();
            let line = info.location().unwrap().line();
            let col = info.location().unwrap().column();

            let msg = match info.payload().downcast_ref::<&'static str>() {
                Some(s) => *s,
                None => match info.payload().downcast_ref::<String>() {
                    Some(s) => &s[..],
                    None => "Box<Any>",
                },
            };

            let err_info = format!("Panicked at '{msg}', {file}:{line}:{col}");
            cdk_rsx_sys::debug_print(err_info.as_bytes());
            cdk_rsx_sys::trap(err_info.as_bytes());
        }));
    });
}

// The canister hook uses IC-only imports. Native tests and tools retain their
// host panic hook and ordinary Rust unwinding.
#[cfg(not(target_family = "wasm"))]
fn setup_panic_hook() {}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{cell::RefCell, rc::Rc};

    #[cfg(not(target_family = "wasm"))]
    #[test]
    fn native_contexts_leave_expected_panics_catchable() {
        in_tracking_executor_context(|| {});
        let failure = std::panic::catch_unwind(|| panic!("expected native panic")).unwrap_err();
        assert_eq!(
            failure.downcast_ref::<&str>(),
            Some(&"expected native panic")
        );
        assert!(crate::is_idle());
        crate::shutdown().unwrap();
    }

    #[derive(Clone, Default)]
    struct Signal {
        ready: Rc<Cell<bool>>,
        waker: Rc<RefCell<Option<Waker>>>,
        polls: Rc<Cell<usize>>,
        drops: Rc<RefCell<Vec<(bool, bool)>>>,
    }

    impl Signal {
        fn wake(&self) {
            self.waker.borrow().as_ref().unwrap().wake_by_ref();
        }
    }

    struct Wait(Signal);

    impl Future for Wait {
        type Output = ();

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
            assert!(TaskHandle::current().is_some());
            self.0.polls.set(self.0.polls.get() + 1);
            *self.0.waker.borrow_mut() = Some(cx.waker().clone());
            if self.0.ready.get() {
                Poll::Ready(())
            } else {
                Poll::Pending
            }
        }
    }

    impl Drop for Wait {
        fn drop(&mut self) {
            // Destructors may access the method or cancel another task. Neither
            // registry may still be borrowed when a future is destroyed.
            let handle = CURRENT_METHOD
                .get()
                .map(|_| extend_current_method_context());
            assert!(METHODS.with(|methods| methods.try_borrow_mut().is_ok()));
            assert!(TASKS.with(|tasks| tasks.try_borrow_mut().is_ok()));
            self.0
                .drops
                .borrow_mut()
                .push((QUERY_EXECUTION.get(), is_recovering_from_trap()));
            drop(handle);
        }
    }

    #[test]
    fn callbacks_retain_their_context_across_overflow_growth_and_reuse() {
        let signals: Vec<_> = (0..12).map(|_| Signal::default()).collect();
        let callbacks: Vec<_> = signals
            .iter()
            .map(|signal| {
                in_tracking_executor_context(|| {
                    spawn_protected(Wait(signal.clone()));
                    extend_current_method_context()
                })
            })
            .collect();
        assert!(crate::shutdown().is_err());
        // Complete in an order unrelated to slot order, then exercise all the
        // old task wakers after the method and task generations have changed.
        for (signal, callback) in signals.iter().zip(callbacks).rev() {
            signal.ready.set(true);
            signal.wake();
            in_tracking_query_executor_context(|| {});
            assert_eq!(signal.polls.get(), 1);
            in_callback_executor_context_for(callback, || {
                assert!(!QUERY_EXECUTION.get());
                let alias = extend_current_method_context();
                assert_eq!(alias.method_id, CURRENT_METHOD.get().unwrap());
            });
            assert_eq!(signal.polls.get(), 2);
            assert_eq!(*signal.drops.borrow(), [(false, false)]);
        }
        assert!(crate::is_idle());
        for signal in &signals {
            signal.wake();
        }
        let fresh = Signal::default();
        in_tracking_executor_context(|| {
            spawn_protected(Wait(fresh.clone()));
        });
        assert_eq!(fresh.polls.get(), 1);
        assert_eq!(*fresh.drops.borrow(), [(false, false)]);
        assert!(crate::is_idle());
        crate::shutdown().unwrap();
        assert!(METHODS.inspect(|value| value.is_none()));
    }

    #[test]
    fn protected_wakes_wait_for_owner_while_migratory_wakes_skip_queries() {
        let protected = Signal::default();
        let migratory = Signal::default();
        let callback = in_tracking_executor_context(|| {
            spawn_protected(Wait(protected.clone()));
            spawn_migratory(Wait(migratory.clone()));
            extend_current_method_context()
        });
        assert_eq!(protected.polls.get(), 1);
        assert_eq!(migratory.polls.get(), 1);
        protected.ready.set(true);
        migratory.ready.set(true);
        protected.wake();
        migratory.wake();
        in_tracking_query_executor_context(|| {});
        assert_eq!(protected.polls.get(), 1);
        assert_eq!(migratory.polls.get(), 1);
        in_tracking_executor_context(|| {});
        assert_eq!(protected.polls.get(), 1);
        assert_eq!(migratory.polls.get(), 2);
        in_callback_executor_context_for(callback, || {});
        assert_eq!(protected.polls.get(), 2);
        assert!(crate::is_idle());
        crate::shutdown().unwrap();
    }

    #[test]
    fn protected_query_self_wakes_are_polled_in_the_current_entry() {
        let signal = Signal::default();
        let callback = in_tracking_query_executor_context(|| {
            let signal = signal.clone();
            spawn_protected(std::future::poll_fn(move |cx| {
                assert!(QUERY_EXECUTION.get());
                let polls = signal.polls.get();
                signal.polls.set(polls + 1);
                match polls {
                    0 | 2 => {
                        cx.waker().wake_by_ref();
                        Poll::Pending
                    }
                    1 => {
                        *signal.waker.borrow_mut() = Some(cx.waker().clone());
                        Poll::Pending
                    }
                    3 => Poll::Ready(()),
                    _ => panic!("polled after completion"),
                }
            }));
            extend_current_method_context()
        });
        assert_eq!(signal.polls.get(), 2);
        in_callback_executor_context_for(callback, || signal.wake());
        assert_eq!(signal.polls.get(), 4);
        assert!(MIGRATORY_WAKEUPS.inspect(|wakes| wakes.is_none_or(VecDeque::is_empty)));
        assert!(crate::is_idle());
        crate::shutdown().unwrap();
    }

    #[test]
    fn recovery_cancels_query_tasks_with_fence_and_retains_other_callback_handles() {
        let update = in_tracking_executor_context(extend_current_method_context);
        let signal = Signal::default();
        let (cleanup, late_callback) = in_tracking_query_executor_context(|| {
            spawn_protected(Wait(signal.clone()));
            (
                extend_current_method_context(),
                extend_current_method_context(),
            )
        });
        in_trap_recovery_context_for(cleanup, || {
            assert!(QUERY_EXECUTION.get());
            assert!(is_recovering_from_trap());
            cancel_all_tasks_attached_to_current_method();
        });
        assert!(!QUERY_EXECUTION.get());
        assert!(!is_recovering_from_trap());
        assert_eq!(*signal.drops.borrow(), [(true, true)]);
        assert!(!crate::is_idle());
        signal.wake();
        in_callback_executor_context_for(late_callback, || {
            assert!(QUERY_EXECUTION.get());
        });
        assert_eq!(signal.polls.get(), 1);
        assert!(!crate::is_idle());
        in_callback_executor_context_for(update, || {
            assert!(!QUERY_EXECUTION.get());
        });
        assert!(crate::is_idle());
        crate::shutdown().unwrap();
    }

    #[test]
    fn protected_tasks_can_spawn_during_poll_and_reenter_method_during_drop() {
        let child = Signal::default();
        let child_task = Rc::new(RefCell::new(None));
        in_tracking_executor_context(|| {
            let task = child_task.clone();
            let signal = child.clone();
            spawn_protected(async move {
                *task.borrow_mut() = Some(spawn_protected(Wait(signal)));
            });
        });
        assert_eq!(child.polls.get(), 1);
        assert_eq!(*child.drops.borrow(), [(false, false)]);
        // Cancellation of an already-finished identity cannot affect a newly
        // inserted task, even if the SlotMap reused its task slot.
        let stale = child_task.borrow_mut().take().unwrap();
        let fresh = Signal::default();
        in_tracking_executor_context(|| {
            spawn_protected(Wait(fresh.clone()));
            cancel_task(&stale);
        });
        assert_eq!(fresh.polls.get(), 1);
        assert!(crate::is_idle());
        crate::shutdown().unwrap();
    }
}