tilo-rt 0.5.1

The one async runtime model for Tilo processes: an app runtime off the UI thread, bounded daemon runtimes, a CPU pool, a file-I/O pool, named threads, and the host background executors and wake routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Background work and timers, provided by the host.
//!
//! A toolkit service that must not block a frame (image decoding, transport calls,
//! periodic refreshes) hands its work to a [`Background`] rather than spawning
//! threads or sleeping. The host decides how it runs: [`ThreadPool`] when no
//! executor is entered, [`Pumped`] for deterministic tests and hosts that drive
//! work from their own loop, the page's own executor in a browser, or any other
//! [`Executor`] installed with [`Background::enter`].
//!
//! The executor is captured when a service is constructed, so enter it around
//! construction. An executor may refuse work with [`Unsupported`]: callers degrade
//! instead of retrying forever.

use std::cell::RefCell;
use std::collections::{BinaryHeap, VecDeque};
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError};

use tilo_clock::time::{Duration, Instant};

use crate::wake::WakeHandle;
use tilo_lock::MutexRecover as _;

pub type Job = Box<dyn FnOnce() + Send + 'static>;

#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("background work is not available on this host")]
pub struct Unsupported;

pub trait Executor: Send + Sync + 'static {
    /// Run `job` off the calling thread. `name` identifies the work in logs.
    ///
    /// Implementations must not run `job` before returning: callers may hold
    /// locks the job also takes.
    ///
    /// # Errors
    ///
    /// Returns [`Unsupported`] when this host cannot run background work.
    fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported>;

    fn wake_at(&self, deadline: Instant, wake: WakeHandle);

    fn now(&self) -> Instant {
        tilo_clock::now()
    }

    /// Block until background work may have made progress, or until
    /// `deadline`. For synchronous drivers only (headless capture, tests) —
    /// never call this on a live UI thread.
    fn park(&self, deadline: Instant);
}

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

#[derive(Clone)]
pub struct Background(Arc<dyn Executor>);

impl std::fmt::Debug for Background {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Background").finish_non_exhaustive()
    }
}

impl Default for Background {
    fn default() -> Self {
        Self::current()
    }
}

impl Background {
    pub fn new(executor: impl Executor) -> Self {
        Self(Arc::new(executor))
    }

    pub fn current() -> Self {
        CURRENT
            .with(|current| current.borrow().clone())
            .unwrap_or_else(native_default)
    }

    /// Make this executor [`current`](Self::current) on this thread until the
    /// guard drops. Drop guards in reverse entry order.
    #[must_use = "the executor stays current only while the guard lives"]
    pub fn enter(&self) -> BackgroundGuard {
        let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
        BackgroundGuard {
            previous,
            thread_affinity: PhantomData,
        }
    }

    pub fn spawn(
        &self,
        name: &'static str,
        job: impl FnOnce() + Send + 'static,
    ) -> Result<(), Unsupported> {
        self.0.spawn(name, Box::new(job))
    }

    pub fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
        self.0.wake_at(deadline, wake);
    }

    pub fn wake_after(&self, delay: Duration, wake: WakeHandle) {
        let now = self.now();
        self.0.wake_at(now.checked_add(delay).unwrap_or(now), wake);
    }

    pub fn now(&self) -> Instant {
        self.0.now()
    }

    pub fn park(&self, deadline: Instant) {
        self.0.park(deadline);
    }
}

pub struct BackgroundGuard {
    previous: Option<Background>,
    thread_affinity: PhantomData<Rc<()>>,
}

impl Drop for BackgroundGuard {
    fn drop(&mut self) {
        let previous = self.previous.take();
        CURRENT.with(|current| {
            current.replace(previous);
        });
    }
}

fn native_default() -> Background {
    static DEFAULT: OnceLock<Background> = OnceLock::new();
    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
    let make = || Background::new(ThreadPool::new(ThreadPool::default_threads()));
    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
    let make = || Background::new(PageExecutor);
    DEFAULT.get_or_init(make).clone()
}

/// The executor of a browser page, which has one thread and cannot block it.
///
/// Jobs run on the page thread from its microtask queue, after the caller
/// returns, so a long job delays the next frame; timers are `setTimeout`s.
/// [`Executor::park`] returns at once.
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
#[derive(Clone, Copy, Debug, Default)]
pub struct PageExecutor;

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
impl PageExecutor {
    /// `setTimeout` caps delays at 2^31 - 1 ms; longer waits re-arm.
    const MAX_TIMEOUT_MS: u128 = 0x7fff_ffff;

    #[allow(
        clippy::future_not_send,
        reason = "awaits a JavaScript promise on the page's only thread"
    )]
    async fn sleep(delay: Duration) {
        use wasm_bindgen::JsCast as _;
        let millis = delay.as_millis().min(Self::MAX_TIMEOUT_MS);
        #[allow(
            clippy::cast_precision_loss,
            reason = "bounded by MAX_TIMEOUT_MS, exact in an f64"
        )]
        let millis = wasm_bindgen::JsValue::from_f64(millis as f64);
        let timer = js_sys::Promise::new(&mut |resolve, _reject| {
            let global = js_sys::global();
            let armed = js_sys::Reflect::get(&global, &"setTimeout".into())
                .ok()
                .and_then(|f| f.dyn_into::<js_sys::Function>().ok())
                .is_some_and(|set_timeout| set_timeout.call2(&global, &resolve, &millis).is_ok());
            if !armed {
                let _ = resolve.call0(&wasm_bindgen::JsValue::NULL);
            }
        });
        let _ = wasm_bindgen_futures::JsFuture::from(timer).await;
    }
}

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
impl Executor for PageExecutor {
    fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported> {
        wasm_bindgen_futures::spawn_local(async move { run_job(name, job) });
        Ok(())
    }

    fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
        wasm_bindgen_futures::spawn_local(async move {
            loop {
                let now = tilo_clock::now();
                if deadline <= now {
                    break;
                }
                Self::sleep(deadline.saturating_duration_since(now)).await;
            }
            wake.wake();
        });
    }

    fn park(&self, _deadline: Instant) {}
}

fn run_job(name: &'static str, job: Job) {
    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).is_err() {
        tracing::warn!(job = name, "background job panicked");
    }
}

struct Timer {
    deadline: Instant,
    sequence: u64,
    wake: WakeHandle,
}

impl PartialEq for Timer {
    fn eq(&self, other: &Self) -> bool {
        self.deadline == other.deadline && self.sequence == other.sequence
    }
}
impl Eq for Timer {}
impl PartialOrd for Timer {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Timer {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (other.deadline, other.sequence).cmp(&(self.deadline, self.sequence))
    }
}

#[derive(Default)]
struct Timers {
    heap: BinaryHeap<Timer>,
    sequence: u64,
}

impl Timers {
    fn push(&mut self, deadline: Instant, wake: WakeHandle) {
        self.sequence = self.sequence.wrapping_add(1);
        self.heap.push(Timer {
            deadline,
            sequence: self.sequence,
            wake,
        });
    }

    fn pop_due(&mut self, now: Instant) -> Option<WakeHandle> {
        if self.heap.peek().is_some_and(|timer| timer.deadline <= now) {
            self.heap.pop().map(|timer| timer.wake)
        } else {
            None
        }
    }

    fn next_deadline(&self) -> Option<Instant> {
        self.heap.peek().map(|timer| timer.deadline)
    }
}

#[derive(Default)]
struct PoolState {
    queue: VecDeque<(&'static str, Job)>,
    threads: usize,
    idle: usize,
    timers: Timers,
    timer_thread: bool,
    progress: u64,
    /// The [`Self::progress`] each parking thread last returned with. A
    /// park waits for progress past it, not past the moment it is called:
    /// a job that finished between the caller's last check and its park
    /// would otherwise be missed, and the park would sleep to its deadline.
    parked: std::collections::HashMap<std::thread::ThreadId, u64>,
}

struct PoolShared {
    state: Mutex<PoolState>,
    work: Condvar,
    timer: Condvar,
    progress: Condvar,
    max_threads: usize,
}

#[derive(Clone)]
pub struct ThreadPool {
    shared: Arc<PoolShared>,
}

impl ThreadPool {
    pub fn new(max_threads: usize) -> Self {
        Self {
            shared: Arc::new(PoolShared {
                state: Mutex::new(PoolState::default()),
                work: Condvar::new(),
                timer: Condvar::new(),
                progress: Condvar::new(),
                max_threads: max_threads.max(1),
            }),
        }
    }

    /// Jobs are mostly blocking I/O (fetches, transport calls), so the
    /// default allows more workers than a CPU-bound pool would.
    pub fn default_threads() -> usize {
        std::thread::available_parallelism()
            .map_or(4, std::num::NonZeroUsize::get)
            .clamp(4, 16)
    }

    fn worker(shared: &PoolShared) {
        let mut state = shared.state.lock_recover();
        loop {
            if let Some((name, job)) = state.queue.pop_front() {
                drop(state);
                run_job(name, job);
                state = shared.state.lock_recover();
                state.progress = state.progress.wrapping_add(1);
                shared.progress.notify_all();
                continue;
            }
            state.idle = state.idle.saturating_add(1);
            state = shared
                .work
                .wait(state)
                .unwrap_or_else(PoisonError::into_inner);
            state.idle = state.idle.saturating_sub(1);
        }
    }

    fn timer_loop(shared: &PoolShared) {
        let mut state = shared.state.lock_recover();
        loop {
            let now = tilo_clock::now();
            let mut fired = Vec::new();
            while let Some(wake) = state.timers.pop_due(now) {
                fired.push(wake);
            }
            if !fired.is_empty() {
                state.progress = state.progress.wrapping_add(1);
                shared.progress.notify_all();
                drop(state);
                // Wake sinks may re-enter `wake_at`; never call them locked.
                for wake in fired {
                    wake.wake();
                }
                state = shared.state.lock_recover();
                continue;
            }
            state = match state.timers.next_deadline() {
                Some(deadline) => {
                    let timeout = deadline.saturating_duration_since(now);
                    shared
                        .timer
                        .wait_timeout(state, timeout)
                        .unwrap_or_else(PoisonError::into_inner)
                        .0
                }
                None => shared
                    .timer
                    .wait(state)
                    .unwrap_or_else(PoisonError::into_inner),
            };
        }
    }
}

impl Executor for ThreadPool {
    #[allow(
        clippy::significant_drop_tightening,
        reason = "the pool's lock stays held across the spawn so the thread count and queue agree"
    )]
    fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported> {
        crate::panic_boundary::abort_outside_boundaries_in_release();
        let mut state = self.shared.state.lock_recover();
        state.queue.push_back((name, job));
        if state.idle >= state.queue.len() || state.threads >= self.shared.max_threads {
            self.shared.work.notify_one();
            return Ok(());
        }
        let index = state.threads;
        let shared = Arc::clone(&self.shared);
        let spawned = std::thread::Builder::new()
            .name(format!("ui-background-{index}"))
            .spawn(move || Self::worker(&shared));
        if spawned.is_ok() {
            state.threads = state.threads.saturating_add(1);
            return Ok(());
        }
        if state.threads > 0 {
            self.shared.work.notify_one();
            return Ok(());
        }
        state.queue.pop_back();
        Err(Unsupported)
    }

    fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
        let mut state = self.shared.state.lock_recover();
        state.timers.push(deadline, wake);
        if !state.timer_thread {
            let shared = Arc::clone(&self.shared);
            let spawned = std::thread::Builder::new()
                .name("ui-background-timer".into())
                .spawn(move || Self::timer_loop(&shared));
            match spawned {
                Ok(_) => state.timer_thread = true,
                Err(error) => {
                    // Without a timer thread nothing would ever fire; wake now
                    // so the caller re-checks its own deadline on a frame.
                    tracing::warn!(%error, "background timer thread unavailable");
                    let due = state.timers.heap.drain().map(|timer| timer.wake);
                    let due: Vec<_> = due.collect();
                    drop(state);
                    for wake in due {
                        wake.wake();
                    }
                    return;
                }
            }
        }
        self.shared.timer.notify_one();
    }

    fn park(&self, deadline: Instant) {
        let thread = std::thread::current().id();
        let mut state = self.shared.state.lock_recover();
        let seen = state.parked.get(&thread).copied().unwrap_or(0);
        let timeout = deadline.saturating_duration_since(tilo_clock::now());
        state = self
            .shared
            .progress
            .wait_timeout_while(state, timeout, |state| state.progress == seen)
            .unwrap_or_else(PoisonError::into_inner)
            .0;
        let now = state.progress;
        state.parked.insert(thread, now);
    }
}

#[derive(Default)]
struct PumpedState {
    queue: VecDeque<(&'static str, Job)>,
    timers: Timers,
    now: Option<Instant>,
}

/// An executor that runs nothing until its owner pumps it.
///
/// Jobs queue until [`run_pending`](Self::run_pending); timers fire when
/// [`advance`](Self::advance) moves the virtual clock past their deadline.
/// Headless tests use it to make background completion deterministic, and a
/// host that drives work from its own loop can install it and pump it there.
#[derive(Clone, Default)]
pub struct Pumped {
    state: Arc<Mutex<PumpedState>>,
}

impl Pumped {
    pub fn new() -> Self {
        Self::starting_at(tilo_clock::now())
    }

    pub fn starting_at(now: Instant) -> Self {
        Self {
            state: Arc::new(Mutex::new(PumpedState {
                now: Some(now),
                ..PumpedState::default()
            })),
        }
    }

    pub fn background(&self) -> Background {
        Background::new(self.clone())
    }

    /// Run queued jobs, including any they queue, until none remain.
    /// Returns how many ran.
    pub fn run_pending(&self) -> usize {
        let mut ran = 0_usize;
        loop {
            let next = self.state.lock_recover().queue.pop_front();
            let Some((name, job)) = next else {
                return ran;
            };
            run_job(name, job);
            ran = ran.saturating_add(1);
        }
    }

    pub fn advance(&self, by: Duration) {
        let now = self
            .state
            .lock_recover()
            .now
            .unwrap_or_else(tilo_clock::now);
        let target = now.checked_add(by).unwrap_or(now);
        self.advance_to(target);
    }

    fn advance_to(&self, target: Instant) {
        self.run_pending();
        loop {
            let wake = {
                let mut state = self.state.lock_recover();
                match state.timers.next_deadline() {
                    Some(deadline) if deadline <= target => {
                        if state.now.is_none_or(|now| now < deadline) {
                            state.now = Some(deadline);
                        }
                        state.timers.pop_due(deadline)
                    }
                    _ => None,
                }
            };
            let Some(wake) = wake else { break };
            wake.wake();
            self.run_pending();
        }
        let mut state = self.state.lock_recover();
        if state.now.is_none_or(|now| now < target) {
            state.now = Some(target);
        }
    }

    /// Whether no job is queued. Armed timers do not count: a periodic
    /// refresh is always armed.
    pub fn is_idle(&self) -> bool {
        self.state.lock_recover().queue.is_empty()
    }

    pub fn next_deadline(&self) -> Option<Instant> {
        self.state.lock_recover().timers.next_deadline()
    }

    pub fn now(&self) -> Instant {
        let mut state = self.state.lock_recover();
        *state.now.get_or_insert_with(tilo_clock::now)
    }
}

impl Executor for Pumped {
    fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported> {
        self.state.lock_recover().queue.push_back((name, job));
        Ok(())
    }

    fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
        self.state.lock_recover().timers.push(deadline, wake);
    }

    fn now(&self) -> Instant {
        Self::now(self)
    }

    fn park(&self, deadline: Instant) {
        if self.run_pending() > 0 {
            return;
        }
        let target = self
            .next_deadline()
            .map_or(deadline, |next| next.min(deadline));
        self.advance_to(target);
    }
}

/// An executor that refuses all background work, for hosts that have none.
/// Timers still fire, on [`park`](Executor::park), so deadline-driven callers
/// in a synchronous driver make progress.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoBackground;

impl Executor for NoBackground {
    fn spawn(&self, _name: &'static str, _job: Job) -> Result<(), Unsupported> {
        Err(Unsupported)
    }

    fn wake_at(&self, _deadline: Instant, wake: WakeHandle) {
        // No clock to wait on: wake now so the caller re-checks its deadline
        // on the next frame.
        wake.wake();
    }

    fn park(&self, _deadline: Instant) {}
}

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

    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::mpsc;

    fn counting_scope() -> (WakeScope, Arc<AtomicUsize>) {
        let wakes = Arc::new(AtomicUsize::new(0));
        let seen = Arc::clone(&wakes);
        let mut scope = WakeScope::new();
        scope
            .bind(move |_| {
                seen.fetch_add(1, Ordering::SeqCst);
            })
            .unwrap();
        (scope, wakes)
    }

    #[test]
    fn thread_pool_runs_named_jobs_survives_panics_and_wakes_timers_in_order() {
        {
            let pool = ThreadPool::new(2);
            let (tx, rx) = mpsc::channel();
            for _ in 0..4 {
                let tx = tx.clone();
                pool.spawn(
                    "test",
                    Box::new(move || {
                        let name = std::thread::current().name().map(str::to_owned);
                        tx.send(name).unwrap();
                    }),
                )
                .unwrap();
            }
            for _ in 0..4 {
                let name = tilo_test_env::recv("a worker thread's name", &rx).unwrap();
                assert!(name.starts_with("ui-background-"), "{name}");
            }
            assert!(pool.shared.state.lock_recover().threads <= 2);
        }

        {
            let pool = ThreadPool::new(1);
            pool.spawn("panics", Box::new(|| panic!("job failure")))
                .unwrap();
            let (tx, rx) = mpsc::channel();
            pool.spawn("after", Box::new(move || tx.send(()).unwrap()))
                .unwrap();
            tilo_test_env::recv("the task spawned after", &rx);
        }

        {
            let pool = ThreadPool::new(1);
            let (tx, rx) = mpsc::channel();
            let bound = |label: &'static str| {
                let tx = tx.clone();
                let mut scope = WakeScope::new();
                scope
                    .bind(move |_| {
                        let _ = tx.send(label);
                    })
                    .unwrap();
                scope
            };
            let late = bound("late");
            let early = bound("early");
            let start = tilo_clock::now();
            pool.wake_at(start + Duration::from_millis(60), late.handle());
            pool.wake_at(start + Duration::from_millis(10), early.handle());
            assert_eq!(tilo_test_env::recv("the early wake", &rx), "early");
            assert_eq!(tilo_test_env::recv("the late wake", &rx), "late");
        }

        {
            let pool = ThreadPool::new(1);
            let (release, check) = mpsc::channel::<()>();
            pool.spawn("guarded", Box::new(move || check.recv().unwrap()))
                .unwrap();
            release.send(()).unwrap();
            let deadline = tilo_clock::now() + tilo_test_env::hang_bound();
            pool.park(deadline);
            assert!(
                tilo_clock::now() < deadline,
                "park waited for its deadline, not the finished job"
            );
        }

        {
            let pool = ThreadPool::new(1);
            let (done, finished) = mpsc::channel();
            pool.spawn("quick", Box::new(move || done.send(()).unwrap()))
                .unwrap();
            tilo_test_env::recv("the quick job", &finished);
            tilo_test_env::wait_until("the pool to count the quick job", || {
                pool.shared.state.lock_recover().progress > 0
            });
            let deadline = tilo_clock::now() + tilo_test_env::hang_bound();
            pool.park(deadline);
            assert!(
                tilo_clock::now() < deadline,
                "park missed a job that finished before it was called"
            );
        }
    }

    #[test]
    fn pumped_executor_runs_only_when_pumped_on_a_virtual_clock() {
        {
            let pumped = Pumped::new();
            let ran = Arc::new(AtomicUsize::new(0));
            let background = pumped.background();
            let counter = Arc::clone(&ran);
            let requeue = background.clone();
            background
                .spawn("outer", move || {
                    counter.fetch_add(1, Ordering::SeqCst);
                    let inner = Arc::clone(&counter);
                    requeue
                        .spawn("inner", move || {
                            inner.fetch_add(1, Ordering::SeqCst);
                        })
                        .unwrap();
                })
                .unwrap();
            assert_eq!(ran.load(Ordering::SeqCst), 0);
            assert!(!pumped.is_idle());
            assert_eq!(
                pumped.run_pending(),
                2,
                "work queued by a job runs in the same pump"
            );
            assert!(pumped.is_idle());
            assert_eq!(ran.load(Ordering::SeqCst), 2);
        }

        {
            let start = tilo_clock::now();
            let pumped = Pumped::starting_at(start);
            let (scope, wakes) = counting_scope();
            pumped.wake_at(start + Duration::from_secs(2), scope.handle());
            pumped.advance(Duration::from_millis(1999));
            assert_eq!(wakes.load(Ordering::SeqCst), 0);
            assert_eq!(pumped.next_deadline(), Some(start + Duration::from_secs(2)));
            pumped.advance(Duration::from_millis(1));
            assert_eq!(wakes.load(Ordering::SeqCst), 1);
            assert_eq!(pumped.now(), start + Duration::from_secs(2));
            assert_eq!(pumped.next_deadline(), None);
        }

        {
            let start = tilo_clock::now();
            let pumped = Pumped::starting_at(start);
            let (scope, wakes) = counting_scope();
            pumped.wake_at(start + Duration::from_secs(60), scope.handle());
            pumped.park(start + Duration::from_secs(3600));
            assert_eq!(wakes.load(Ordering::SeqCst), 1);
            assert_eq!(pumped.now(), start + Duration::from_secs(60));
            pumped.park(start + Duration::from_secs(120));
            assert_eq!(pumped.now(), start + Duration::from_secs(120));
        }

        {
            let pumped = Pumped::new();
            {
                let _guard = pumped.background().enter();
                Background::current().spawn("scoped", || {}).unwrap();
                {
                    let _inner = Background::new(NoBackground).enter();
                    assert_eq!(
                        Background::current().spawn("refused", || {}),
                        Err(Unsupported)
                    );
                }
                Background::current().spawn("scoped", || {}).unwrap();
            }
            assert_eq!(pumped.run_pending(), 2);
        }
    }
}