1
//! Executor for running tests with mocked environment
2
//!
3
//! See [`MockExecutor`]
4

            
5
use std::any::Any;
6
use std::cell::Cell;
7
use std::collections::VecDeque;
8
use std::fmt::{self, Debug, Display};
9
use std::future::Future;
10
use std::io::{self, Write as _};
11
use std::iter;
12
use std::panic::{AssertUnwindSafe, catch_unwind, panic_any};
13
use std::pin::{Pin, pin};
14
use std::sync::{Arc, Mutex, MutexGuard, Weak};
15
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
16

            
17
use futures::FutureExt as _;
18
use futures::pin_mut;
19
use futures::task::{FutureObj, Spawn, SpawnError};
20

            
21
use assert_matches::assert_matches;
22
use educe::Educe;
23
use itertools::Either::{self, *};
24
use itertools::{chain, izip};
25
use slotmap_careful::DenseSlotMap;
26
use std::backtrace::Backtrace;
27
use strum::EnumIter;
28

            
29
// NB: when using traced_test, the trace! and error! output here is generally suppressed
30
// in tests of other crates.  To see it, you can write something like this
31
// (in the dev-dependencies of the crate whose tests you're running):
32
//    tracing-test = { version = "0.2.4", features = ["no-env-filter"] }
33
use tracing::{error, trace};
34

            
35
use oneshot_fused_workaround::{self as oneshot, Canceled};
36
use tor_error::error_report;
37
use tor_rtcompat::join_set::FuturesJoinSet;
38
use tor_rtcompat::{Blocking, JoinSetProvider, ToplevelBlockOn};
39

            
40
use Poll::*;
41
use TaskState::*;
42

            
43
/// Type-erased future, one for each of our (normal) tasks
44
type TaskFuture = FutureObj<'static, ()>;
45

            
46
/// Future for the argument to `block_on`, which is handled specially
47
type MainFuture<'m> = Pin<&'m mut dyn Future<Output = ()>>;
48

            
49
//---------- principal data structures ----------
50

            
51
/// Executor for running tests with mocked environment
52
///
53
/// For test cases which don't actually wait for anything in the real world.
54
///
55
/// This is the executor.
56
/// It implements [`Spawn`] and [`ToplevelBlockOn`]
57
///
58
/// It will usually be used as part of a `MockRuntime`.
59
///
60
/// To run futures, call [`ToplevelBlockOn::block_on`]
61
///
62
/// # Restricted environment
63
///
64
/// Tests run with this executor must not attempt to block
65
/// on anything "outside":
66
/// every future that anything awaits must (eventually) be woken directly
67
/// *by some other task* in the same test case.
68
///
69
/// (By directly we mean that the [`Waker::wake`] call is made
70
/// by that waking future, before that future itself awaits anything.)
71
///
72
/// # Panics
73
///
74
/// The executor will panic
75
/// if the toplevel future (passed to `block_on`)
76
/// doesn't complete (without externally blocking),
77
/// but instead waits for something.
78
///
79
/// The executor will malfunction or panic if reentered.
80
/// (Eg, if `block_on` is reentered.)
81
#[derive(Clone, Default, Educe)]
82
#[educe(Debug)]
83
pub struct MockExecutor {
84
    /// Mutable state
85
    #[educe(Debug(ignore))]
86
    shared: Arc<Shared>,
87
}
88

            
89
/// Shared state and ancillary information
90
///
91
/// This is always within an `Arc`.
92
#[derive(Default)]
93
struct Shared {
94
    /// Shared state
95
    data: Mutex<Data>,
96
    /// Condition variable for thread scheduling
97
    ///
98
    /// Signaled when [`Data.thread_to_run`](struct.Data.html#structfield.thread_to_run)
99
    /// is modified.
100
    thread_condvar: std::sync::Condvar,
101
}
102

            
103
/// Task id, module to hide `Ti` alias
104
mod task_id {
105
    slotmap_careful::new_key_type! {
106
        /// Task ID, usually called `TaskId`
107
        ///
108
        /// Short name in special `task_id` module so that [`Debug`] is nice
109
        pub(super) struct Ti;
110
    }
111
}
112
use task_id::Ti as TaskId;
113

            
114
/// Executor's state
115
///
116
/// ### Task state machine
117
///
118
/// A task is created in `tasks`, `Awake`, so also in `awake`.
119
///
120
/// When we poll it, we take it out of `awake` and set it to `Asleep`,
121
/// and then call `poll()`.
122
/// Any time after that, it can be made `Awake` again (and put back onto `awake`)
123
/// by the waker ([`ActualWaker`], wrapped in [`Waker`]).
124
///
125
/// The task's future is of course also present here in this data structure.
126
/// However, during poll we must release the lock,
127
/// so we cannot borrow the future from `Data`.
128
/// Instead, we move it out.  So `Task.fut` is an `Option`.
129
///
130
/// ### "Main" task - the argument to `block_on`
131
///
132
/// The signature of `BlockOn::block_on` accepts a non-`'static` future
133
/// (and a non-`Send`/`Sync` one).
134
///
135
/// So we cannot store that future in `Data` because `Data` is `'static`.
136
/// Instead, this main task future is passed as an argument down the call stack.
137
/// In the data structure we simply store a placeholder, `TaskFutureInfo::Main`.
138
#[derive(Educe, derive_more::Debug)]
139
#[educe(Default)]
140
struct Data {
141
    /// Tasks
142
    ///
143
    /// Includes tasks spawned with `spawn`,
144
    /// and also the future passed to `block_on`.
145
    #[debug("{:?}", DebugTasks(self, || tasks.keys()))]
146
    tasks: DenseSlotMap<TaskId, Task>,
147

            
148
    /// `awake` lists precisely: tasks that are `Awake`, plus maybe stale `TaskId`s
149
    ///
150
    /// Tasks are pushed onto the *back* when woken,
151
    /// so back is the most recently woken.
152
    #[debug("{:?}", DebugTasks(self, || awake.iter().cloned()))]
153
    awake: VecDeque<TaskId>,
154

            
155
    /// If a future from `progress_until_stalled` exists
156
    progressing_until_stalled: Option<ProgressingUntilStalled>,
157

            
158
    /// Scheduling policy
159
    scheduling: SchedulingPolicy,
160

            
161
    /// (Sub)thread we want to run now
162
    ///
163
    /// At any one time only one thread is meant to be running.
164
    /// Other threads are blocked in condvar wait, waiting for this to change.
165
    ///
166
    /// **Modified only** within
167
    /// [`thread_context_switch_send_instruction_to_run`](Shared::thread_context_switch_send_instruction_to_run),
168
    /// which takes responsibility for preserving the following **invariants**:
169
    ///
170
    ///  1. no-one but the named thread is allowed to modify this field.
171
    ///  2. after modifying this field, signal `thread_condvar`
172
    #[educe(Default(expression = ThreadDescriptor::Executor))]
173
    thread_to_run: ThreadDescriptor,
174
}
175

            
176
/// How we should schedule?
177
#[derive(Debug, Clone, Default, EnumIter)]
178
#[non_exhaustive]
179
pub enum SchedulingPolicy {
180
    /// Task *most* recently woken is run
181
    ///
182
    /// This is the default.
183
    ///
184
    /// It will expose starvation bugs if a task never sleeps.
185
    /// (Which is a good thing in tests.)
186
    #[default]
187
    Stack,
188
    /// Task *least* recently woken is run.
189
    Queue,
190
}
191

            
192
/// Record of a single task
193
///
194
/// Tracks a spawned task, or the main task (the argument to `block_on`).
195
///
196
/// Stored in [`Data`]`.tasks`.
197
struct Task {
198
    /// For debugging output
199
    desc: String,
200
    /// Has this been woken via a waker?  (And is it in `Data.awake`?)
201
    ///
202
    /// **Set to `Awake` only by [`Task::set_awake`]**,
203
    /// preserving the invariant that
204
    /// every `Awake` task is in [`Data.awake`](struct.Data.html#structfield.awake).
205
    state: TaskState,
206
    /// The actual future (or a placeholder for it)
207
    ///
208
    /// May be `None` briefly in the executor main loop, because we've
209
    /// temporarily moved it out so we can poll it,
210
    /// or if this is a Subthread task which is currently running sync code
211
    /// (in which case we're blocked in the executor waiting to be
212
    /// woken up by [`thread_context_switch`](Shared::thread_context_switch).
213
    ///
214
    /// Note that the `None` can be observed outside the main loop, because
215
    /// the main loop unlocks while it polls, so other (non-main-loop) code
216
    /// might see it.
217
    fut: Option<TaskFutureInfo>,
218
}
219

            
220
/// A future as stored in our record of a [`Task`]
221
#[derive(Educe)]
222
#[educe(Debug)]
223
enum TaskFutureInfo {
224
    /// The [`Future`].  All is normal.
225
    Normal(#[educe(Debug(ignore))] TaskFuture),
226
    /// The future isn't here because this task is the main future for `block_on`
227
    Main,
228
    /// This task is actually a [`Subthread`](MockExecutor::subthread_spawn)
229
    ///
230
    /// Instead of polling it, we'll switch to it with
231
    /// [`thread_context_switch`](Shared::thread_context_switch).
232
    Subthread,
233
}
234

            
235
/// State of a task - do we think it needs to be polled?
236
///
237
/// Stored in [`Task`]`.state`.
238
#[derive(Debug)]
239
enum TaskState {
240
    /// Awake - needs to be polled
241
    ///
242
    /// Established by [`waker.wake()`](Waker::wake)
243
    Awake,
244
    /// Asleep - does *not* need to be polled
245
    ///
246
    /// Established each time just before we call the future's [`poll`](Future::poll)
247
    Asleep(Vec<SleepLocation>),
248
}
249

            
250
/// Actual implementor of `Wake` for use in a `Waker`
251
///
252
/// Futures (eg, channels from [`futures`]) will use this to wake a task
253
/// when it should be polled.
254
///
255
/// This type must not be `Cloned` with the `Data` lock held.
256
/// Consequently, a `Waker` mustn't either.
257
struct ActualWaker {
258
    /// Executor state
259
    ///
260
    /// The Waker mustn't to hold a strong reference to the executor,
261
    /// since typically a task holds a future that holds a Waker,
262
    /// and the executor holds the task - so that would be a cycle.
263
    data: Weak<Shared>,
264

            
265
    /// Which task this is
266
    id: TaskId,
267
}
268

            
269
/// State used for an in-progress call to
270
/// [`progress_until_stalled`][`MockExecutor::progress_until_stalled`]
271
///
272
/// If present in [`Data`], an (async) call to `progress_until_stalled`
273
/// is in progress.
274
///
275
/// The future from `progress_until_stalled`, [`ProgressUntilStalledFuture`]
276
/// is a normal-ish future.
277
/// It can be polled in the normal way.
278
/// When it is polled, it looks here, in `finished`, to see if it's `Ready`.
279
///
280
/// The future is made ready, and woken (via `waker`),
281
/// by bespoke code in the task executor loop.
282
///
283
/// When `ProgressUntilStalledFuture` (maybe completes and) is dropped,
284
/// its `Drop` impl is used to remove this from `Data.progressing_until_stalled`.
285
#[derive(Debug)]
286
struct ProgressingUntilStalled {
287
    /// Have we, in fact, stalled?
288
    ///
289
    /// Made `Ready` by special code in the executor loop
290
    finished: Poll<()>,
291

            
292
    /// Waker
293
    ///
294
    /// Signalled by special code in the executor loop
295
    waker: Option<Waker>,
296
}
297

            
298
/// Future from
299
/// [`progress_until_stalled`][`MockExecutor::progress_until_stalled`]
300
///
301
/// See [`ProgressingUntilStalled`] for an overview of this aspect of the contraption.
302
///
303
/// Existence of this struct implies `Data.progressing_until_stalled` is `Some`.
304
/// There can only be one at a time.
305
#[derive(Educe)]
306
#[educe(Debug)]
307
struct ProgressUntilStalledFuture {
308
    /// Executor's state; this future's state is in `.progressing_until_stalled`
309
    #[educe(Debug(ignore))]
310
    shared: Arc<Shared>,
311
}
312

            
313
/// Identifies a thread we know about - the executor thread, or a Subthread
314
///
315
/// Not related to `std::thread::ThreadId`.
316
///
317
/// See [`spawn_subthread`](MockExecutor::subthread_spawn) for definition of a Subthread.
318
///
319
/// This being a thread-local and not scoped by which `MockExecutor` we're talking about
320
/// means that we can't cope if there are multiple `MockExecutor`s involved in the same thread.
321
/// That's OK (and documented).
322
#[derive(Copy, Clone, Eq, PartialEq, derive_more::Debug)]
323
enum ThreadDescriptor {
324
    /// Foreign - neither the (running) executor, nor a Subthread
325
    #[debug("FOREIGN")]
326
    Foreign,
327
    /// The executor.
328
    #[debug("Exe")]
329
    Executor,
330
    /// This task, which is a Subthread.
331
    #[debug("{_0:?}")]
332
    Subthread(TaskId),
333
}
334

            
335
/// Marker indicating that this task is a Subthread, not an async task.
336
///
337
/// See [`spawn_subthread`](MockExecutor::subthread_spawn) for definition of a Subthread.
338
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
339
struct IsSubthread;
340

            
341
/// [`Shared::subthread_yield`] should set our task awake before switching to the executor
342
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
343
struct SetAwake;
344

            
345
thread_local! {
346
    /// Identifies this thread.
347
    pub static THREAD_DESCRIPTOR: Cell<ThreadDescriptor> = const {
348
        Cell::new(ThreadDescriptor::Foreign)
349
    };
350
}
351

            
352
//---------- creation ----------
353

            
354
impl MockExecutor {
355
    /// Make a `MockExecutor` with default parameters
356
2
    pub fn new() -> Self {
357
2
        Self::default()
358
2
    }
359

            
360
    /// Make a `MockExecutor` with a specific `SchedulingPolicy`
361
15797
    pub fn with_scheduling(scheduling: SchedulingPolicy) -> Self {
362
15797
        Data {
363
15797
            scheduling,
364
15797
            ..Default::default()
365
15797
        }
366
15797
        .into()
367
15797
    }
368
}
369

            
370
impl From<Data> for MockExecutor {
371
15797
    fn from(data: Data) -> MockExecutor {
372
15797
        let shared = Shared {
373
15797
            data: Mutex::new(data),
374
15797
            thread_condvar: std::sync::Condvar::new(),
375
15797
        };
376
15797
        MockExecutor {
377
15797
            shared: Arc::new(shared),
378
15797
        }
379
15797
    }
380
}
381

            
382
//---------- spawning ----------
383

            
384
impl MockExecutor {
385
    /// Spawn a task and return something to identify it
386
    ///
387
    /// `desc` should `Display` as some kind of short string (ideally without spaces)
388
    /// and will be used in the `Debug` impl and trace log messages from `MockExecutor`.
389
    ///
390
    /// The returned value is an opaque task identifier which is very cheap to clone
391
    /// and which can be used by the caller in debug logging,
392
    /// if it's desired to correlate with the debug output from `MockExecutor`.
393
    /// Most callers will want to ignore it.
394
    ///
395
    /// This method is infallible.  (The `MockExecutor` cannot be shut down.)
396
127
    pub fn spawn_identified(
397
127
        &self,
398
127
        desc: impl Display,
399
127
        fut: impl Future<Output = ()> + Send + 'static,
400
127
    ) -> impl Debug + Clone + Send + 'static {
401
127
        self.spawn_internal(desc.to_string(), FutureObj::from(Box::new(fut)))
402
127
    }
403

            
404
    /// Spawn a task and return its output for further usage
405
    ///
406
    /// `desc` should `Display` as some kind of short string (ideally without spaces)
407
    /// and will be used in the `Debug` impl and trace log messages from `MockExecutor`.
408
40
    pub fn spawn_join<T: Debug + Send + 'static>(
409
40
        &self,
410
40
        desc: impl Display,
411
40
        fut: impl Future<Output = T> + Send + 'static,
412
40
    ) -> impl Future<Output = T> {
413
40
        let (tx, rx) = oneshot::channel();
414
40
        self.spawn_identified(desc, async move {
415
40
            let res = fut.await;
416
40
            tx.send(res)
417
40
                .expect("Failed to send future's output, did future panic?");
418
40
        });
419
40
        rx.map(|m| m.expect("Failed to receive future's output"))
420
40
    }
421

            
422
    /// Spawn a task and return its `TaskId`
423
    ///
424
    /// Convenience method for use by `spawn_identified` and `spawn_obj`.
425
    /// The future passed to `block_on` is not handled here.
426
95897
    fn spawn_internal(&self, desc: String, fut: TaskFuture) -> TaskId {
427
95897
        let mut data = self.shared.lock();
428
95897
        data.insert_task(desc, TaskFutureInfo::Normal(fut))
429
95897
    }
430
}
431

            
432
impl Data {
433
    /// Insert a task given its `TaskFutureInfo` and return its `TaskId`.
434
113850
    fn insert_task(&mut self, desc: String, fut: TaskFutureInfo) -> TaskId {
435
113850
        let state = Awake;
436
113850
        let id = self.tasks.insert(Task {
437
113850
            state,
438
113850
            desc,
439
113850
            fut: Some(fut),
440
113850
        });
441
113850
        self.awake.push_back(id);
442
113850
        trace!("MockExecutor spawned {:?}={:?}", id, self.tasks[id]);
443
113850
        id
444
113850
    }
445
}
446

            
447
impl Spawn for MockExecutor {
448
90640
    fn spawn_obj(&self, future: TaskFuture) -> Result<(), SpawnError> {
449
90640
        self.spawn_internal("spawn_obj".into(), future);
450
90640
        Ok(())
451
90640
    }
452
}
453

            
454
impl Blocking for MockExecutor {
455
    type ThreadHandle<T: Send + 'static> = Pin<Box<dyn Future<Output = T>>>;
456

            
457
30
    fn spawn_blocking<F, T>(&self, f: F) -> Self::ThreadHandle<T>
458
30
    where
459
30
        F: FnOnce() -> T + Send + 'static,
460
30
        T: Send + 'static,
461
    {
462
30
        assert_matches!(
463
30
            THREAD_DESCRIPTOR.get(),
464
            ThreadDescriptor::Executor | ThreadDescriptor::Subthread(_),
465
            "MockExecutor::spawn_blocking_io only allowed from future or subthread, being run by this executor"
466
        );
467
30
        Box::pin(
468
30
            self.subthread_spawn("spawn_blocking", f)
469
2
                .map(|x| x.expect("Error in spawn_blocking subthread.")),
470
        )
471
30
    }
472

            
473
902
    fn reenter_block_on<F>(&self, future: F) -> F::Output
474
902
    where
475
902
        F: Future,
476
902
        F::Output: Send + 'static,
477
    {
478
902
        self.subthread_block_on_future(future)
479
902
    }
480
}
481

            
482
impl JoinSetProvider for MockExecutor {
483
    type JoinSet<T: Send + Sync + 'static> = FuturesJoinSet<T, Self>;
484

            
485
10
    fn new_join_set<T>(&self) -> Self::JoinSet<T>
486
10
    where
487
10
        T: Send + Sync + 'static,
488
    {
489
10
        FuturesJoinSet::new(self.clone())
490
10
    }
491
}
492

            
493
//---------- block_on ----------
494

            
495
impl ToplevelBlockOn for MockExecutor {
496
315
    fn block_on<F>(&self, input_fut: F) -> F::Output
497
315
    where
498
315
        F: Future,
499
    {
500
315
        let mut value: Option<F::Output> = None;
501

            
502
        // Box this just so that we can conveniently control precisely when it's dropped.
503
        // (We could do this with Option and Pin::set but that seems clumsier.)
504
315
        let mut input_fut = Box::pin(input_fut);
505

            
506
        let run_store_fut = {
507
315
            let value = &mut value;
508
315
            let input_fut = &mut input_fut;
509
315
            async {
510
315
                trace!("MockExecutor block_on future...");
511
315
                let t = input_fut.await;
512
315
                trace!("MockExecutor block_on future returned...");
513
315
                *value = Some(t);
514
315
                trace!("MockExecutor block_on future exiting.");
515
315
            }
516
        };
517

            
518
        {
519
315
            pin_mut!(run_store_fut);
520

            
521
315
            let main_id = self
522
315
                .shared
523
315
                .lock()
524
315
                .insert_task("main".into(), TaskFutureInfo::Main);
525
315
            trace!("MockExecutor {main_id:?} is task for block_on");
526
315
            self.execute_to_completion(run_store_fut);
527
        }
528

            
529
        #[allow(clippy::let_and_return)] // clarity
530
315
        let value = value.take().unwrap_or_else(|| {
531
            // eprintln can be captured by libtest, but the debug_dump goes to io::stderr.
532
            // use the latter, so that the debug dump is prefixed by this message.
533
            let _: io::Result<()> = writeln!(io::stderr(), "all futures blocked, crashing...");
534
            // write to tracing too, so the tracing log is clear about when we crashed
535
            error!("all futures blocked, crashing...");
536

            
537
            // Sequencing here is subtle.
538
            //
539
            // We should do the dump before dropping the input future, because the input
540
            // future is likely to own things that, when dropped, wake up other tasks,
541
            // rendering the dump inaccurate.
542
            //
543
            // But also, dropping the input future may well drop a ProgressUntilStalledFuture
544
            // which then reenters us.  More generally, we mustn't call user code
545
            // with the lock held.
546
            //
547
            // And, we mustn't panic with the data lock held.
548
            //
549
            // If value was Some, then this closure is dropped without being called,
550
            // which drops the future after it has yielded the value, which is correct.
551
            {
552
                let mut data = self.shared.lock();
553
                data.debug_dump();
554
            }
555
            drop(input_fut);
556

            
557
            panic!(
558
                r"
559
all futures blocked. waiting for the real world? or deadlocked (waiting for each other) ?
560
"
561
            );
562
        });
563

            
564
315
        value
565
315
    }
566
}
567

            
568
//---------- execution - core implementation ----------
569

            
570
impl MockExecutor {
571
    /// Keep polling tasks until nothing more can be done
572
    ///
573
    /// Ie, stop when `awake` is empty and `progressing_until_stalled` is `None`.
574
16407
    fn execute_to_completion(&self, mut main_fut: MainFuture) {
575
16407
        trace!("MockExecutor execute_to_completion...");
576
        loop {
577
4048180
            self.execute_until_first_stall(main_fut.as_mut());
578

            
579
            // Handle `progressing_until_stalled`
580
            let pus_waker = {
581
4048180
                let mut data = self.shared.lock();
582
4048180
                let pus = &mut data.progressing_until_stalled;
583
4048180
                trace!("MockExecutor execute_to_completion PUS={:?}", &pus);
584
4048180
                let Some(pus) = pus else {
585
                    // No progressing_until_stalled, we're actually done.
586
16407
                    break;
587
                };
588
4031773
                assert_eq!(
589
4031773
                    pus.finished, Pending,
590
                    "ProgressingUntilStalled finished twice?!"
591
                );
592
4031773
                pus.finished = Ready(());
593

            
594
                // Release the lock temporarily so that ActualWaker::clone doesn't deadlock
595
4031773
                let waker = pus
596
4031773
                    .waker
597
4031773
                    .take()
598
4031773
                    .expect("ProgressUntilStalledFuture not ever polled!");
599
4031773
                drop(data);
600
4031773
                let waker_copy = waker.clone();
601
4031773
                let mut data = self.shared.lock();
602

            
603
4031773
                let pus = &mut data.progressing_until_stalled;
604
4031773
                if let Some(double) = pus
605
4031773
                    .as_mut()
606
4031773
                    .expect("progressing_until_stalled updated under our feet!")
607
4031773
                    .waker
608
4031773
                    .replace(waker)
609
                {
610
                    panic!("double progressing_until_stalled.waker! {double:?}");
611
4031773
                }
612

            
613
4031773
                waker_copy
614
            };
615
4031773
            pus_waker.wake();
616
        }
617
16407
        trace!("MockExecutor execute_to_completion done");
618
16407
    }
619

            
620
    /// Keep polling tasks until `awake` is empty
621
    ///
622
    /// (Ignores `progressing_until_stalled` - so if one is active,
623
    /// will return when all other tasks have blocked.)
624
    ///
625
    /// # Panics
626
    ///
627
    /// Might malfunction or panic if called reentrantly
628
4048180
    fn execute_until_first_stall(&self, main_fut: MainFuture) {
629
4048180
        trace!("MockExecutor execute_until_first_stall ...");
630

            
631
4048180
        assert_eq!(
632
4048180
            THREAD_DESCRIPTOR.get(),
633
4048180
            ThreadDescriptor::Foreign,
634
            "MockExecutor executor re-entered"
635
        );
636
4048180
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Executor);
637

            
638
4048180
        let r = catch_unwind(AssertUnwindSafe(|| self.executor_main_loop(main_fut)));
639

            
640
4048180
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Foreign);
641

            
642
4048180
        match r {
643
4048180
            Ok(()) => trace!("MockExecutor execute_until_first_stall done."),
644
            Err(e) => {
645
                trace!("MockExecutor executor, or async task, panicked!");
646
                panic_any(e)
647
            }
648
        }
649
4048180
    }
650

            
651
    /// Keep polling tasks until `awake` is empty (inner, executor main loop)
652
    ///
653
    /// This is only called from [`MockExecutor::execute_until_first_stall`],
654
    /// so it could also be called `execute_until_first_stall_inner`.
655
4048180
    fn executor_main_loop(&self, mut main_fut: MainFuture) {
656
        'outer: loop {
657
            // Take a `Awake` task off `awake` and make it `Asleep`
658
            let (id, mut fut) = 'inner: loop {
659
9991882
                let mut data = self.shared.lock();
660
9991882
                let Some(id) = data.schedule() else {
661
4048180
                    break 'outer;
662
                };
663
5943702
                let Some(task) = data.tasks.get_mut(id) else {
664
3686
                    trace!("MockExecutor {id:?} vanished");
665
3686
                    continue;
666
                };
667
5940016
                task.state = Asleep(vec![]);
668
5940016
                let fut = task.fut.take().expect("future missing from task!");
669
5940016
                break 'inner (id, fut);
670
            };
671

            
672
            // Poll the selected task
673
5940016
            trace!("MockExecutor {id:?} polling...");
674
5940016
            let waker = ActualWaker::make_waker(&self.shared, id);
675
5940016
            let mut cx = Context::from_waker(&waker);
676
5940016
            let r: Either<Poll<()>, IsSubthread> = match &mut fut {
677
4165103
                TaskFutureInfo::Normal(fut) => Left(fut.poll_unpin(&mut cx)),
678
1667356
                TaskFutureInfo::Main => Left(main_fut.as_mut().poll(&mut cx)),
679
107557
                TaskFutureInfo::Subthread => Right(IsSubthread),
680
            };
681

            
682
            // Deal with the returned `Poll`
683
            let _fut_drop_late;
684
            {
685
5940016
                let mut data = self.shared.lock();
686
5940016
                let task = data
687
5940016
                    .tasks
688
5940016
                    .get_mut(id)
689
5940016
                    .expect("task vanished while we were polling it");
690

            
691
5940016
                match r {
692
                    Left(Pending) => {
693
5760857
                        trace!("MockExecutor {id:?} -> Pending");
694
5760857
                        if task.fut.is_some() {
695
                            panic!("task reinserted while we polled it?!");
696
5760857
                        }
697
                        // The task might have been woken *by its own poll method*.
698
                        // That's why we set it to `Asleep` *earlier* rather than here.
699
                        // All we need to do is put the future back.
700
5760857
                        task.fut = Some(fut);
701
                    }
702
                    Left(Ready(())) => {
703
71602
                        trace!("MockExecutor {id:?} -> Ready");
704
                        // Oh, it finished!
705
                        // It might be in `awake`, but that's allowed to contain stale tasks,
706
                        // so we *don't* need to scan that list and remove it.
707
71602
                        data.tasks.remove(id);
708
                        // It is important that we don't drop `fut` until we have released
709
                        // the data lock, since it is an external type and might try to reenter
710
                        // us (eg by calling spawn).  If we do that here, we risk deadlock.
711
                        // So, move `fut` to a variable with scope outside the block with `data`.
712
71602
                        _fut_drop_late = fut;
713
                    }
714
                    Right(IsSubthread) => {
715
107557
                        trace!("MockExecutor {id:?} -> Ready, waking Subthread");
716
                        // Task is a subthread, which has called thread_context_switch
717
                        // to switch to us.  We "poll" it by switching back.
718

            
719
                        // Put back `TFI::Subthread`, which was moved out temporarily, above.
720
107557
                        task.fut = Some(fut);
721

            
722
107557
                        self.shared.thread_context_switch(
723
107557
                            data,
724
107557
                            ThreadDescriptor::Executor,
725
107557
                            ThreadDescriptor::Subthread(id),
726
107557
                        );
727

            
728
                        // Now, if the Subthread still exists, that's because it's switched
729
                        // back to us, and is waiting in subthread_block_on_future again.
730
                        // Or it might have ended, in which case it's not in `tasks` any more.
731
                        // In any case we can go back to scheduling futures.
732
                    }
733
                }
734
            }
735
        }
736
4048180
    }
737
}
738

            
739
impl Data {
740
    /// Return the next task to run
741
    ///
742
    /// The task is removed from `awake`, but **`state` is not set to `Asleep`**.
743
    /// The caller must restore the invariant!
744
9991882
    fn schedule(&mut self) -> Option<TaskId> {
745
        use SchedulingPolicy as SP;
746
9991882
        match self.scheduling {
747
5014829
            SP::Stack => self.awake.pop_back(),
748
4977053
            SP::Queue => self.awake.pop_front(),
749
        }
750
9991882
    }
751
}
752

            
753
impl ActualWaker {
754
    /// Obtain a strong reference to the executor's data
755
24184863
    fn upgrade_data(&self) -> Option<Arc<Shared>> {
756
24184863
        self.data.upgrade()
757
24184863
    }
758

            
759
    /// Wake the task corresponding to this `ActualWaker`
760
    ///
761
    /// This is like `<Self as std::task::Wake>::wake()` but takes `&self`, not `Arc`
762
6671220
    fn wake(&self) {
763
6671220
        let Some(data) = self.upgrade_data() else {
764
            // The executor is gone!  Don't try to wake.
765
2
            return;
766
        };
767
6671218
        let mut data = data.lock();
768
6671218
        let data = &mut *data;
769
6671218
        trace!("MockExecutor {:?} wake", &self.id);
770
6671218
        let Some(task) = data.tasks.get_mut(self.id) else {
771
16335
            return;
772
        };
773
6654883
        task.set_awake(self.id, &mut data.awake);
774
6671220
    }
775

            
776
    /// Create and return a `Waker` for task `id`
777
5997175
    fn make_waker(shared: &Arc<Shared>, id: TaskId) -> Waker {
778
5997175
        ActualWaker {
779
5997175
            data: Arc::downgrade(shared),
780
5997175
            id,
781
5997175
        }
782
5997175
        .new_waker()
783
5997175
    }
784
}
785

            
786
//---------- "progress until stalled" functionality ----------
787

            
788
impl MockExecutor {
789
    /// Run tasks in the current executor until every other task is waiting
790
    ///
791
    /// # Panics
792
    ///
793
    /// Might malfunction or panic if more than one such call is running at once.
794
    ///
795
    /// (Ie, you must `.await` or drop the returned `Future`
796
    /// before calling this method again.)
797
    ///
798
    /// Must be called and awaited within a future being run by `self`.
799
4031773
    pub fn progress_until_stalled(&self) -> impl Future<Output = ()> + use<> {
800
4031773
        let mut data = self.shared.lock();
801
4031773
        assert!(
802
4031773
            data.progressing_until_stalled.is_none(),
803
            "progress_until_stalled called more than once"
804
        );
805
4031773
        trace!("MockExecutor progress_until_stalled...");
806
4031773
        data.progressing_until_stalled = Some(ProgressingUntilStalled {
807
4031773
            finished: Pending,
808
4031773
            waker: None,
809
4031773
        });
810
4031773
        ProgressUntilStalledFuture {
811
4031773
            shared: self.shared.clone(),
812
4031773
        }
813
4031773
    }
814
}
815

            
816
impl Future for ProgressUntilStalledFuture {
817
    type Output = ();
818

            
819
8063821
    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
820
8063821
        let waker = cx.waker().clone();
821
8063821
        let mut data = self.shared.lock();
822
8063821
        let pus = data.progressing_until_stalled.as_mut();
823
8063821
        trace!("MockExecutor progress_until_stalled polling... {:?}", &pus);
824
8063821
        let pus = pus.expect("ProgressingUntilStalled missing");
825
8063821
        pus.waker = Some(waker);
826
8063821
        pus.finished
827
8063821
    }
828
}
829

            
830
impl Drop for ProgressUntilStalledFuture {
831
4031773
    fn drop(&mut self) {
832
4031773
        self.shared.lock().progressing_until_stalled = None;
833
4031773
    }
834
}
835

            
836
//---------- (sub)threads ----------
837

            
838
impl MockExecutor {
839
    /// Spawn a "Subthread", for processing in a sync context
840
    ///
841
    /// `call` will be run on a separate thread, called a "Subthread".
842
    ///
843
    /// But it will **not run simultaneously** with the executor,
844
    /// nor with other Subthreads.
845
    /// So Subthreads are somewhat like coroutines.
846
    ///
847
    /// `call` must be capable of making progress without waiting for any other Subthreads.
848
    /// `call` may wait for async futures, using
849
    /// [`subthread_block_on_future`](MockExecutor::subthread_block_on_future).
850
    ///
851
    /// Subthreads may be used for cpubound activity,
852
    /// or synchronous IO (such as large volumes of disk activity),
853
    /// provided that the synchronous code will reliably make progress,
854
    /// without waiting (directly or indirectly) for any async task or Subthread -
855
    /// except via `subthread_block_on_future`.
856
    ///
857
    /// # Subthreads vs raw `std::thread` threads
858
    ///
859
    /// Programs using `MockExecutor` may use `std::thread` threads directly.
860
    /// However, this is not recommended.  There are severe limitations:
861
    ///
862
    ///  * Only a Subthread can re-enter the async context from sync code:
863
    ///    this must be done with
864
    ///    using [`subthread_block_on_future`](MockExecutor::subthread_block_on_future).
865
    ///    (Re-entering the executor with
866
    ///    [`block_on`](tor_rtcompat::ToplevelBlockOn::block_on)
867
    ///    is not allowed.)
868
    ///  * If async tasks want to suspend waiting for synchronous code,
869
    ///    the synchronous code must run on a Subthread.
870
    ///    This allows the `MockExecutor` to know when
871
    ///    that synchronous code is still making progress.
872
    ///    (This is needed for
873
    ///    [`progress_until_stalled`](MockExecutor::progress_until_stalled)
874
    ///    and the facilities which use it, such as
875
    ///    [`MockRuntime::advance_until_stalled`](crate::MockRuntime::advance_until_stalled).)
876
    ///  * Subthreads never run in parallel -
877
    ///    they only run as scheduled deterministically by the `MockExecutor`.
878
    ///    So using Subthreads eliminates a source of test nonndeterminism.
879
    ///    (Execution order is still varied due to explicitly varying the scheduling policy.)
880
    ///
881
    /// # Panics, abuse, and malfunctions
882
    ///
883
    /// If `call` panics and unwinds, `spawn_subthread` yields `Err`.
884
    /// The application code should to do something about it if this happens,
885
    /// typically, logging errors, tearing things down, or failing a test case.
886
    ///
887
    /// If the executor doesn't run, the subthread will not run either, and will remain stuck.
888
    /// (So, typically, if the thread supposed to run the executor panics,
889
    /// for example because a future or the executor itself panics,
890
    /// all the subthreads will become stuck - effectively, they'll be leaked.)
891
    ///
892
    /// `spawn_subthread` panics if OS thread spawning fails.
893
    /// (Like `std::thread::spawn()` does.)
894
    ///
895
    /// `MockExecutor`s will malfunction or panic if
896
    /// any executor invocation method (eg `block_on`) is called on a Subthread.
897
34
    pub fn subthread_spawn<T: Send + 'static>(
898
34
        &self,
899
34
        desc: impl Display,
900
34
        call: impl FnOnce() -> T + Send + 'static,
901
34
    ) -> impl Future<Output = Result<T, Box<dyn Any + Send>>> + Unpin + Send + Sync + 'static {
902
34
        let desc = desc.to_string();
903
34
        let (output_tx, output_rx) = oneshot::channel();
904

            
905
        // NB: we don't know which thread we're on!
906
        // In principle we might be on another Subthread.
907
        // So we can't context switch here.  That would be very confusing.
908
        //
909
        // Instead, we prepare the new Subthread as follows:
910
        //   - There is a task in the executor
911
        //   - The task is ready to be polled, whenever the executor decides to
912
        //   - The thread starts running right away, but immediately waits until it is scheduled
913
        // See `subthread_entrypoint`.
914

            
915
        {
916
34
            let mut data = self.shared.lock();
917
34
            let id = data.insert_task(desc.clone(), TaskFutureInfo::Subthread);
918

            
919
34
            let _: std::thread::JoinHandle<()> = std::thread::Builder::new()
920
34
                .name(desc)
921
                .spawn({
922
34
                    let shared = self.shared.clone();
923
34
                    move || shared.subthread_entrypoint(id, call, output_tx)
924
                })
925
34
                .expect("spawn failed");
926
        }
927

            
928
34
        output_rx.map(|r| {
929
6
            r.unwrap_or_else(|_: Canceled| panic!("Subthread cancelled but should be impossible!"))
930
6
        })
931
34
    }
932

            
933
    /// Call an async `Future` from a Subthread
934
    ///
935
    /// Blocks the Subthread, and arranges to run async tasks,
936
    /// including `fut`, until `fut` completes.
937
    ///
938
    /// `fut` is polled on the executor thread, not on the Subthread.
939
    /// (We may change that in the future, allowing passing a non-`Send` future.)
940
    ///
941
    /// # Panics, abuse, and malfunctions
942
    ///
943
    /// `subthread_block_on_future` will malfunction or panic
944
    /// if called on a thread that isn't a Subthread from the same `MockExecutor`
945
    /// (ie a thread made with [`spawn_subthread`](MockExecutor::subthread_spawn)).
946
    ///
947
    /// If `fut` itself panics, the executor will panic.
948
    ///
949
    /// If the executor isn't running, `subthread_block_on_future` will hang indefinitely.
950
    /// See `spawn_subthread`.
951
914
    pub fn subthread_block_on_future<T: Send + 'static>(&self, fut: impl Future<Output = T>) -> T {
952
914
        let id = match THREAD_DESCRIPTOR.get() {
953
914
            ThreadDescriptor::Subthread(id) => id,
954
            ThreadDescriptor::Executor => {
955
                panic!("subthread_block_on_future called from MockExecutor thread (async task?)")
956
            }
957
            ThreadDescriptor::Foreign => panic!(
958
                "subthread_block_on_future called on foreign thread (not spawned with spawn_subthread)"
959
            ),
960
        };
961
914
        trace!("MockExecutor thread {id:?}, subthread_block_on_future...");
962
914
        let mut fut = pin!(fut);
963

            
964
        // We yield once before the first poll, and once after Ready, to shake up the
965
        // execution order a bit, depending on the scheduling policy.
966
1967
        let yield_ = |set_awake| self.shared.subthread_yield(id, set_awake);
967
914
        yield_(Some(SetAwake));
968

            
969
        let ret = loop {
970
            // Poll the provided future
971
1053
            trace!("MockExecutor thread {id:?}, s.t._block_on_future polling...");
972
1053
            let waker = ActualWaker::make_waker(&self.shared, id);
973
1053
            let mut cx = Context::from_waker(&waker);
974
1053
            let r: Poll<T> = fut.as_mut().poll(&mut cx);
975

            
976
1053
            if let Ready(r) = r {
977
914
                trace!("MockExecutor thread {id:?}, s.t._block_on_future poll -> Ready");
978
914
                break r;
979
139
            }
980

            
981
            // Pending.  Switch back to the executor thread.
982
            // When the future becomes ready, the Waker will be woken, waking the task,
983
            // so that the executor will "poll" us again.
984
139
            trace!("MockExecutor thread {id:?}, s.t._block_on_future poll -> Pending");
985

            
986
139
            yield_(None);
987
        };
988

            
989
914
        yield_(Some(SetAwake));
990

            
991
914
        trace!("MockExecutor thread {id:?}, subthread_block_on_future complete.");
992

            
993
914
        ret
994
914
    }
995
}
996

            
997
impl Shared {
998
    /// Main entrypoint function for a Subthread
999
    ///
    /// Entered on a new `std::thread` thread created by
    /// [`subthread_spawn`](MockExecutor::subthread_spawn).
    ///
    /// When `call` completes, sends its returned value `T` to `output_tx`.
34
    fn subthread_entrypoint<T: Send + 'static>(
34
        self: Arc<Self>,
34
        id: TaskId,
34
        call: impl FnOnce() -> T + Send + 'static,
34
        output_tx: oneshot::Sender<Result<T, Box<dyn Any + Send>>>,
34
    ) {
34
        THREAD_DESCRIPTOR.set(ThreadDescriptor::Subthread(id));
34
        trace!("MockExecutor thread {id:?}, entrypoint");
        // We start out Awake, but we wait for the executor to tell us to run.
        // This will be done the first time the task is "polled".
        {
34
            let data = self.lock();
34
            self.thread_context_switch_waitfor_instruction_to_run(
34
                data,
34
                ThreadDescriptor::Subthread(id),
34
            );
        }
34
        trace!("MockExecutor thread {id:?}, entering user code");
        // Run the user's actual thread function.
        // This will typically reenter us via subthread_block_on_future.
34
        let ret = catch_unwind(AssertUnwindSafe(call));
34
        trace!("MockExecutor thread {id:?}, completed user code");
        // This makes the return value from subthread_spawn ready.
        // It will be polled by the executor in due course, presumably.
34
        output_tx.send(ret).unwrap_or_else(
            #[allow(clippy::unnecessary_lazy_evaluations)]
14
            |_| {}, // receiver dropped, maybe executor dropped or something?
        );
        {
34
            let mut data = self.lock();
            // Never poll this task again (so never schedule this thread)
34
            let _: Task = data.tasks.remove(id).expect("Subthread task vanished!");
            // Tell the executor it is scheduled now.
            // We carry on exiting, in parallel (holding the data lock).
34
            self.thread_context_switch_send_instruction_to_run(
34
                &mut data,
34
                ThreadDescriptor::Subthread(id),
34
                ThreadDescriptor::Executor,
34
            );
        }
34
    }
    /// Yield back to the executor from a subthread
    ///
    /// Checks that things are in order
    /// (in particular, that this task is in the data structure as a subhtread)
    /// and switches to the executor thread.
    ///
    /// The caller must arrange that the task gets woken.
    ///
    /// With [`SetAwake`], sets our task awake, so that we'll be polled
    /// again as soon as we get to the top of the executor's queue.
    /// Otherwise, we'll be reentered after someone wakes a [`Waker`] for the task.
106781
    fn subthread_yield(&self, us: TaskId, set_awake: Option<SetAwake>) {
106781
        let mut data = self.lock();
        {
106781
            let data = &mut *data;
106781
            let task = data.tasks.get_mut(us).expect("Subthread task vanished!");
106781
            match &task.fut {
106781
                Some(TaskFutureInfo::Subthread) => {}
                other => panic!("subthread_block_on_future but TFI {other:?}"),
            };
106781
            if let Some(SetAwake) = set_awake {
98474
                task.set_awake(us, &mut data.awake);
8307
            }
        }
106781
        self.thread_context_switch(
106781
            data,
106781
            ThreadDescriptor::Subthread(us),
106781
            ThreadDescriptor::Executor,
106781
        );
106781
    }
    /// Switch from (sub)thread `us` to (sub)thread `them`
    ///
    /// Returns when someone calls `thread_context_switch(.., us)`.
214338
    fn thread_context_switch(
214338
        &self,
214338
        mut data: MutexGuard<Data>,
214338
        us: ThreadDescriptor,
214338
        them: ThreadDescriptor,
214338
    ) {
214338
        trace!("MockExecutor thread {us:?}, switching to {them:?}");
214338
        self.thread_context_switch_send_instruction_to_run(&mut data, us, them);
214338
        self.thread_context_switch_waitfor_instruction_to_run(data, us);
214338
    }
    /// Instruct the (sub)thread `them` to run
    ///
    /// Update `thread_to_run`, which will wake up `them`'s
    /// call to `thread_context_switch_waitfor_instruction_to_run`.
    ///
    /// Must be called from (sub)thread `us`.
    /// Part of `thread_context_switch`, not normally called directly.
215114
    fn thread_context_switch_send_instruction_to_run(
215114
        &self,
215114
        data: &mut MutexGuard<Data>,
215114
        us: ThreadDescriptor,
215114
        them: ThreadDescriptor,
215114
    ) {
215114
        assert_eq!(data.thread_to_run, us);
215114
        data.thread_to_run = them;
215114
        self.thread_condvar.notify_all();
215114
    }
    /// Await an instruction for this thread, `us`, to run
    ///
    /// Waits for `thread_to_run` to be `us`,
    /// waiting for `thread_condvar` as necessary.
    ///
    /// Part of `thread_context_switch`, not normally called directly.
215884
    fn thread_context_switch_waitfor_instruction_to_run(
215884
        &self,
215884
        data: MutexGuard<Data>,
215884
        us: ThreadDescriptor,
215884
    ) {
        #[allow(let_underscore_lock)]
215884
        let _: MutexGuard<_> = self
215884
            .thread_condvar
613324
            .wait_while(data, |data| {
613324
                let live = data.thread_to_run;
613324
                let resume = live == us;
613324
                if resume {
215114
                    trace!("MockExecutor thread {us:?}, resuming");
                } else {
398210
                    trace!("MockExecutor thread {us:?}, waiting for {live:?}");
                }
                // We're in `.wait_while`, not `.wait_until`.  Confusing.
613324
                !resume
613324
            })
215884
            .expect("data lock poisoned");
215884
    }
}
//---------- ancillary and convenience functions ----------
/// Trait to let us assert at compile time that something is nicely `Sync` etc.
#[allow(dead_code)] // yes, we don't *use* anything from this trait
trait EnsureSyncSend: Sync + Send + 'static {}
impl EnsureSyncSend for ActualWaker {}
impl EnsureSyncSend for MockExecutor {}
impl MockExecutor {
    /// Return the number of tasks running in this executor
    ///
    /// One possible use is for a test case to check that task(s)
    /// that ought to have exited, have indeed done so.
    ///
    /// In the usual case, the answer will be at least 1,
    /// because it counts the future passed to
    /// [`block_on`](MockExecutor::block_on)
    /// (perhaps via [`MockRuntime::test_with_various`](crate::MockRuntime::test_with_various)).
220
    pub fn n_tasks(&self) -> usize {
220
        self.shared.lock().tasks.len()
220
    }
}
impl Shared {
    /// Lock and obtain the guard
    ///
    /// Convenience method which panics on poison
64547253
    fn lock(&self) -> MutexGuard<Data> {
64547253
        self.data.lock().expect("data lock poisoned")
64547253
    }
}
impl Task {
    /// Set task `id` to `Awake` and arrange that it will be polled.
6753357
    fn set_awake(&mut self, id: TaskId, data_awake: &mut VecDeque<TaskId>) {
6753357
        match self.state {
889955
            Awake => {}
            Asleep(_) => {
5863402
                self.state = Awake;
5863402
                data_awake.push_back(id);
            }
        }
6753357
    }
}
//---------- ActualWaker as RawWaker ----------
/// Using [`ActualWaker`] in a [`RawWaker`]
///
/// We need to make a
/// [`Waker`] (the safe, type-erased, waker, used by actual futures)
/// which contains an
/// [`ActualWaker`] (our actual waker implementation, also safe).
///
/// `std` offers `Waker::from<Arc<impl Wake>>`.
/// But we want a bespoke `Clone` implementation, so we don't want to use `Arc`.
///
/// So instead, we implement the `RawWaker` API in terms of `ActualWaker`.
/// We keep the `ActualWaker` in a `Box`, and actually `clone` it (and the `Box`).
///
/// SAFETY
///
///  * The data pointer is `Box::<ActualWaker>::into_raw()`
///  * We share these when we clone
///  * No-one is allowed `&mut ActualWaker` unless there are no other clones
///  * So we may make references `&ActualWaker`
impl ActualWaker {
    /// Wrap up an [`ActualWaker`] as a type-erased [`Waker`] for passing to futures etc.
5997175
    fn new_waker(self) -> Waker {
5997175
        unsafe { Waker::from_raw(self.raw_new()) }
5997175
    }
    /// Helper: wrap up an [`ActualWaker`] as a [`RawWaker`].
23510818
    fn raw_new(self) -> RawWaker {
23510818
        let self_: Box<ActualWaker> = self.into();
23510818
        let self_: *mut ActualWaker = Box::into_raw(self_);
23510818
        let self_: *const () = self_ as _;
23510818
        RawWaker::new(self_, &RAW_WAKER_VTABLE)
23510818
    }
    /// Implementation of [`RawWakerVTable`]'s `clone`
17513643
    unsafe fn raw_clone(self_: *const ()) -> RawWaker {
        unsafe {
17513643
            let self_: *const ActualWaker = self_ as _;
17513643
            let self_: &ActualWaker = self_.as_ref().unwrap_unchecked();
17513643
            let copy: ActualWaker = self_.clone();
17513643
            copy.raw_new()
        }
17513643
    }
    /// Implementation of [`RawWakerVTable`]'s `wake`
6084865
    unsafe fn raw_wake(self_: *const ()) {
        unsafe {
6084865
            Self::raw_wake_by_ref(self_);
6084865
            Self::raw_drop(self_);
        }
6084865
    }
    /// Implementation of [`RawWakerVTable`]'s `wake_ref_by`
6671220
    unsafe fn raw_wake_by_ref(self_: *const ()) {
        unsafe {
6671220
            let self_: *const ActualWaker = self_ as _;
6671220
            let self_: &ActualWaker = self_.as_ref().unwrap_unchecked();
6671220
            self_.wake();
        }
6671220
    }
    /// Implementation of [`RawWakerVTable`]'s `drop`
23473418
    unsafe fn raw_drop(self_: *const ()) {
        unsafe {
23473418
            let self_: *mut ActualWaker = self_ as _;
23473418
            let self_: Box<ActualWaker> = Box::from_raw(self_);
23473418
            drop(self_);
        }
23473418
    }
}
/// vtable for `Box<ActualWaker>` as `RawWaker`
//
// This ought to be in the impl block above, but
//   "associated `static` items are not allowed"
static RAW_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
    ActualWaker::raw_clone,
    ActualWaker::raw_wake,
    ActualWaker::raw_wake_by_ref,
    ActualWaker::raw_drop,
);
//---------- Sleep location tracking and dumping ----------
/// We record "where a future went to sleep" as (just) a backtrace
///
/// This type alias allows us to mock `Backtrace` for miri.
/// (It also insulates from future choices about sleep location representation.0
#[cfg(not(miri))]
type SleepLocation = Backtrace;
impl Data {
    /// Dump tasks and their sleep location backtraces
1
    fn dump_backtraces(&self, f: &mut fmt::Formatter) -> fmt::Result {
1
        for (id, task) in self.tasks.iter() {
4
            let prefix = |f: &mut fmt::Formatter| write!(f, "{id:?}={task:?}: ");
4
            match &task.state {
                Awake => {
1
                    prefix(f)?;
1
                    writeln!(f, "awake")?;
                }
                Asleep(locs) => {
3
                    let n = locs.len();
3
                    for (i, loc) in locs.iter().enumerate() {
3
                        prefix(f)?;
3
                        writeln!(f, "asleep, backtrace {i}/{n}:\n{loc}",)?;
                    }
3
                    if n == 0 {
                        prefix(f)?;
                        writeln!(f, "asleep, no backtraces, Waker never cloned, stuck!",)?;
3
                    }
                }
            }
        }
1
        writeln!(
1
            f,
1
            "\nNote: there might be spurious traces, see docs for MockExecutor::debug_dump\n"
        )?;
1
        Ok(())
1
    }
}
/// Track sleep locations via `<Waker as Clone>`.
///
/// See [`MockExecutor::debug_dump`] for the explanation.
impl Clone for ActualWaker {
17513643
    fn clone(&self) -> Self {
17513643
        let id = self.id;
17513643
        if let Some(data) = self.upgrade_data() {
            // If the executor is gone, there is nothing to adjust
17513643
            let mut data = data.lock();
17513643
            if let Some(task) = data.tasks.get_mut(self.id) {
17513643
                match &mut task.state {
706420
                    Awake => trace!("MockExecutor cloned waker for awake task {id:?}"),
16807223
                    Asleep(locs) => locs.push(SleepLocation::force_capture()),
                }
            } else {
                trace!("MockExecutor cloned waker for dead task {id:?}");
            }
        }
17513643
        ActualWaker {
17513643
            data: self.data.clone(),
17513643
            id,
17513643
        }
17513643
    }
}
//---------- API for full debug dump ----------
/// Debugging dump of a `MockExecutor`'s state
///
/// Returned by [`MockExecutor::as_debug_dump`]
//
// Existence implies backtraces have been resolved
//
// We use `Either` so that we can also use this internally when we have &mut Data.
pub struct DebugDump<'a>(Either<&'a Data, MutexGuard<'a, Data>>);
impl MockExecutor {
    /// Dump the executor's state including backtraces of waiting tasks, to stderr
    ///
    /// This is considerably more extensive than simply
    /// `MockExecutor as Debug`.
    ///
    /// (This is a convenience method, which wraps
    /// [`MockExecutor::as_debug_dump()`].
    ///
    /// ### Backtrace salience (possible spurious traces)
    ///
    /// **Summary**
    ///
    /// The technique used to capture backtraces when futures sleep is not 100% exact.
    /// It will usually show all the actual sleeping sites,
    /// but it might also show other backtraces which were part of
    /// the implementation of some complex relevant future.
    ///
    /// **Details**
    ///
    /// When a future's implementation wants to sleep,
    /// it needs to record the [`Waker`] (from the [`Context`])
    /// so that the "other end" can call `.wake()` on it later,
    /// when the future should be woken.
    ///
    /// Since `Context.waker()` gives `&Waker`, borrowed from the `Context`,
    /// the future must clone the `Waker`,
    /// and it must do so in within the `poll()` call.
    ///
    /// A future which is waiting in a `select!` will typically
    /// show multiple traces, one for each branch.
    /// But,
    /// if a future sleeps on one thing, and then when polled again later,
    /// sleeps on something different, without waking up in between,
    /// both backtrace locations will be shown.
    /// And,
    /// a complicated future contraption *might* clone the `Waker` more times.
    /// So not every backtrace will necessarily be informative.
    ///
    /// ### Panics
    ///
    /// Panics on write errors.
1
    pub fn debug_dump(&self) {
1
        self.as_debug_dump().to_stderr();
1
    }
    /// Dump the executor's state including backtraces of waiting tasks
    ///
    /// This is considerably more extensive than simply
    /// `MockExecutor as Debug`.
    ///
    /// Returns an object for formatting with [`Debug`].
    /// To simply print the dump to stderr (eg in a test),
    /// use [`.debug_dump()`](MockExecutor::debug_dump).
    ///
    /// **Backtrace salience (possible spurious traces)** -
    /// see [`.debug_dump()`](MockExecutor::debug_dump).
1
    pub fn as_debug_dump(&self) -> DebugDump {
1
        let data = self.shared.lock();
1
        DebugDump(Right(data))
1
    }
}
impl Data {
    /// Convenience function: dump including backtraces, to stderr
    fn debug_dump(&mut self) {
        DebugDump(Left(self)).to_stderr();
    }
}
impl DebugDump<'_> {
    /// Convenience function: dump tasks and backtraces to stderr
    #[allow(clippy::wrong_self_convention)] // "to_stderr" doesn't mean "convert to stderr"
1
    fn to_stderr(self) {
1
        write!(io::stderr().lock(), "{:?}", self)
            .unwrap_or_else(|e| error_report!(e, "failed to write debug dump to stderr"));
1
    }
}
//---------- bespoke Debug impls ----------
impl Debug for DebugDump<'_> {
1
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1
        let self_: &Data = &self.0;
1
        writeln!(f, "MockExecutor state:\n{self_:#?}")?;
1
        writeln!(f, "MockExecutor task dump:")?;
1
        self_.dump_backtraces(f)?;
1
        Ok(())
1
    }
}
// See `impl Debug for Data` for notes on the output
impl Debug for Task {
62
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62
        let Task { desc, state, fut } = self;
62
        write!(f, "{:?}", desc)?;
62
        write!(f, "=")?;
62
        match fut {
2
            None => write!(f, "P")?,
39
            Some(TaskFutureInfo::Normal(_)) => write!(f, "f")?,
15
            Some(TaskFutureInfo::Main) => write!(f, "m")?,
6
            Some(TaskFutureInfo::Subthread) => write!(f, "T")?,
        }
62
        match state {
56
            Awake => write!(f, "W")?,
6
            Asleep(locs) => write!(f, "s{}", locs.len())?,
        };
62
        Ok(())
62
    }
}
/// Helper: `Debug`s as a list of tasks, given the `Data` for lookups and a list of the ids
///
/// `Task`s in `Data` are printed as `Ti(ID)"SPEC"=FLAGS"`.
///
/// `FLAGS` are:
///
///  * `T`: this task is for a Subthread (from subthread_spawn).
///  * `P`: this task is being polled (its `TaskFutureInfo` is absent)
///  * `f`: this is a normal task with a future and its future is present in `Data`
///  * `m`: this is the main task from `block_on`
///
///  * `W`: the task is awake
///  * `s<n>`: the task is asleep, and `<n>` is the number of recorded sleeping locations
//
// We do it this way because the naive dump from derive is very expansive
// and makes it impossible to see the wood for the trees.
// This very compact representation it easier to find a task of interest in the output.
//
// This is implemented in `impl Debug for Task`.
//
//
// rustc doesn't think automatically-derived Debug impls count for whether a thing is used.
// This has caused quite some fallout.  https://github.com/rust-lang/rust/pull/85200
// I think derive_more emits #[automatically_derived], so that even though we use this
// in our Debug impl, that construction is unused.
#[allow(dead_code)]
struct DebugTasks<'d, F>(&'d Data, F);
// See `impl Debug for Data` for notes on the output
impl<F, I> Debug for DebugTasks<'_, F>
where
    F: Fn() -> I,
    I: Iterator<Item = TaskId>,
{
2
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2
        let DebugTasks(data, ids) = self;
2
        for (id, delim) in izip!(ids(), chain!(iter::once(""), iter::repeat(" ")),) {
5
            write!(f, "{delim}{id:?}")?;
5
            match data.tasks.get(id) {
                None => write!(f, "-")?,
5
                Some(task) => write!(f, "={task:?}")?,
            }
        }
2
        Ok(())
2
    }
}
/// Mock `Backtrace` for miri
///
/// See also the not-miri `type SleepLocation`, alias above.
#[cfg(miri)]
mod miri_sleep_location {
    #[derive(Debug, derive_more::Display)]
    #[display("<SleepLocation>")]
    pub(super) struct SleepLocation {}
    impl SleepLocation {
        pub(super) fn force_capture() -> Self {
            SleepLocation {}
        }
    }
}
#[cfg(miri)]
use miri_sleep_location::SleepLocation;
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;
    use futures::channel::mpsc;
    use futures::{SinkExt as _, StreamExt as _};
    use strum::IntoEnumIterator;
    use tracing::info;
    #[cfg(not(miri))] // trace! asks for the time, which miri doesn't support
    use tracing_test::traced_test;
    fn various_mock_executors() -> impl Iterator<Item = MockExecutor> {
        // This duplicates the part of the logic in MockRuntime::test_with_various which
        // relates to MockExecutor, because we don't have a MockRuntime::builder.
        // The only parameter to MockExecutor is its scheduling policy, so this seems fine.
        SchedulingPolicy::iter().map(|scheduling| {
            eprintln!("===== MockExecutor::with_scheduling({scheduling:?}) =====");
            MockExecutor::with_scheduling(scheduling)
        })
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn simple() {
        let runtime = MockExecutor::default();
        let val = runtime.block_on(async { 42 });
        assert_eq!(val, 42);
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn stall() {
        let runtime = MockExecutor::default();
        runtime.block_on({
            let runtime = runtime.clone();
            async move {
                const N: usize = 3;
                let (mut txs, mut rxs): (Vec<_>, Vec<_>) =
                    (0..N).map(|_| mpsc::channel::<usize>(5)).unzip();
                let mut rx_n = rxs.pop().unwrap();
                for (i, mut rx) in rxs.into_iter().enumerate() {
                    runtime.spawn_identified(i, {
                        let mut txs = txs.clone();
                        async move {
                            loop {
                                eprintln!("task {i} rx...");
                                let v = rx.next().await.unwrap();
                                let nv = v + 1;
                                eprintln!("task {i} rx {v}, tx {nv}");
                                let v = nv;
                                txs[v].send(v).await.unwrap();
                            }
                        }
                    });
                }
                dbg!();
                #[allow(deprecated)] // TODO(#2386)
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                dbg!();
                runtime.progress_until_stalled().await;
                dbg!();
                #[allow(deprecated)] // TODO(#2386)
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                dbg!();
                txs[0].send(0).await.unwrap();
                dbg!();
                runtime.progress_until_stalled().await;
                dbg!();
                let r = rx_n.next().await;
                assert_eq!(r, Some(N - 1));
                dbg!();
                #[allow(deprecated)] // TODO(#2386)
                let _: mpsc::TryRecvError = rx_n.try_next().unwrap_err();
                runtime.spawn_identified("tx", {
                    let txs = txs.clone();
                    async {
                        eprintln!("sending task...");
                        for (i, mut tx) in txs.into_iter().enumerate() {
                            eprintln!("sending 0 to {i}...");
                            tx.send(0).await.unwrap();
                        }
                        eprintln!("sending task done");
                    }
                });
                runtime.debug_dump();
                for i in 0..txs.len() {
                    eprintln!("main {i} wait stall...");
                    runtime.progress_until_stalled().await;
                    eprintln!("main {i} rx wait...");
                    let r = rx_n.next().await;
                    eprintln!("main {i} rx = {r:?}");
                    assert!(r == Some(0) || r == Some(N - 1));
                }
                eprintln!("finishing...");
                runtime.progress_until_stalled().await;
                eprintln!("finished.");
            }
        });
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn spawn_blocking() {
        let runtime = MockExecutor::default();
        runtime.block_on({
            let runtime = runtime.clone();
            async move {
                let thr_1 = runtime.spawn_blocking(|| 42);
                let thr_2 = runtime.spawn_blocking(|| 99);
                assert_eq!(thr_2.await, 99);
                assert_eq!(thr_1.await, 42);
            }
        });
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn drop_reentrancy() {
        // Check that dropping a completed task future is done *outside* the data lock.
        // Involves a contrived future whose Drop impl reenters the executor.
        //
        // If `_fut_drop_late = fut` in execute_until_first_stall (the main loop)
        // is replaced with `drop(fut)` (dropping the future at the wrong moment),
        // we do indeed get deadlock, so this test case is working.
        struct ReentersOnDrop {
            runtime: MockExecutor,
        }
        impl Future for ReentersOnDrop {
            type Output = ();
            fn poll(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<()> {
                Poll::Ready(())
            }
        }
        impl Drop for ReentersOnDrop {
            fn drop(&mut self) {
                self.runtime
                    .spawn_identified("dummy", futures::future::ready(()));
            }
        }
        for runtime in various_mock_executors() {
            runtime.block_on(async {
                runtime.spawn_identified("trapper", {
                    let runtime = runtime.clone();
                    ReentersOnDrop { runtime }
                });
            });
        }
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn subthread_oneshot() {
        for runtime in various_mock_executors() {
            runtime.block_on(async {
                let (tx, rx) = oneshot::channel();
                info!("spawning subthread");
                let thr = runtime.subthread_spawn("thr1", {
                    let runtime = runtime.clone();
                    move || {
                        info!("subthread_block_on_future...");
                        let i = runtime.subthread_block_on_future(rx).unwrap();
                        info!("subthread_block_on_future => {i}");
                        i + 1
                    }
                });
                info!("main task sending");
                tx.send(12).unwrap();
                info!("main task sent");
                let r = thr.await.unwrap();
                info!("main task thr => {r}");
                assert_eq!(r, 13);
            });
        }
    }
    #[cfg_attr(not(miri), traced_test)]
    #[test]
    fn subthread_pingpong() {
        for runtime in various_mock_executors() {
            runtime.block_on(async {
                let (mut i_tx, mut i_rx) = mpsc::channel(1);
                let (mut o_tx, mut o_rx) = mpsc::channel(1);
                info!("spawning subthread");
                let thr = runtime.subthread_spawn("thr", {
                    let runtime = runtime.clone();
                    move || {
                        while let Some(i) = {
                            info!("thread receiving ...");
                            runtime.subthread_block_on_future(i_rx.next())
                        } {
                            let o = i + 12;
                            info!("thread received {i}, sending {o}");
                            runtime.subthread_block_on_future(o_tx.send(o)).unwrap();
                            info!("thread sent {o}");
                        }
                        info!("thread exiting");
                        42
                    }
                });
                for i in 0..2 {
                    info!("main task sending {i}");
                    i_tx.send(i).await.unwrap();
                    info!("main task sent {i}");
                    let o = o_rx.next().await.unwrap();
                    info!("main task recv => {o}");
                    assert_eq!(o, i + 12);
                }
                info!("main task dropping sender");
                drop(i_tx);
                info!("main task awaiting thread");
                let r = thr.await.unwrap();
                info!("main task complete");
                assert_eq!(r, 42);
            });
        }
    }
}