icedwright 0.0.1

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

use std::cell::Cell;
use std::collections::BTreeMap;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::ThreadId;
use std::time::Duration;

use iced_futures::futures::Stream;

use crate::effects::{Spawn, TaskState, UntypedTaskId};
use crate::time::VirtualClock;

/// The name of the harness's one blocking thread.
pub(crate) const BLOCKING_THREAD: &str = "icedwright-blocking";

/// Locks a mutex, carrying on past a poisoned one: a panic the harness caught already
/// reported itself.
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

/// A generation counter the harness thread can block on until another thread bumps it.
#[derive(Debug, Default)]
pub(crate) struct Signal {
    generation: Mutex<u64>,
    changed: Condvar,
}

impl Signal {
    pub(crate) fn notify(&self) {
        *lock(&self.generation) += 1;
        self.changed.notify_all();
    }

    pub(crate) fn generation(&self) -> u64 {
        *lock(&self.generation)
    }

    /// Blocks until the generation passes `seen` or `limit` passes, and returns the
    /// generation. A wait for a condition: the limit only bounds how long before the caller
    /// checks the hang detector again.
    pub(crate) fn wait_past(&self, seen: u64, limit: Duration) -> u64 {
        let guard = lock(&self.generation);
        let (guard, _) = self
            .changed
            .wait_timeout_while(guard, limit, |generation| *generation <= seen)
            .unwrap_or_else(PoisonError::into_inner);
        *guard
    }
}

/// Blocking work in flight: the count rises in `thread_name_fn`, which tokio calls on the
/// spawning thread before `spawn_blocking` returns, and falls in `on_thread_stop`. With one
/// thread and no keep-alive, a thread lives exactly while blocking work is queued or running.
///
/// A new blocking thread starts its work only once the runtime round that spawned it has
/// ended. A job queued behind another runs on the same thread without that gate, so the
/// harness also waits for the count to reach zero before each turn and each round; together
/// no round or app call can see blocking work finish, however the OS schedules the threads.
#[derive(Debug, Clone, Default)]
pub(crate) struct Blocking {
    count: Arc<AtomicUsize>,
    signal: Arc<Signal>,
    in_round: Arc<(Mutex<bool>, Condvar)>,
}

impl Blocking {
    pub(crate) fn new(signal: Arc<Signal>) -> Self {
        Self {
            count: Arc::default(),
            signal,
            in_round: Arc::default(),
        }
    }

    pub(crate) fn in_flight(&self) -> usize {
        self.count.load(Ordering::SeqCst)
    }

    /// Runs one runtime round with blocking threads kept from starting until it ends.
    pub(crate) fn round<T>(&self, round: impl FnOnce() -> T) -> T {
        let (flag, ended) = &*self.in_round;
        *lock(flag) = true;
        let out = round();
        *lock(flag) = false;
        ended.notify_all();
        out
    }

    fn on_start(&self) -> impl Fn() + Send + Sync + 'static {
        let in_round = self.in_round.clone();
        move || {
            let (flag, ended) = &*in_round;
            let mut running = lock(flag);
            while *running {
                running = ended.wait(running).unwrap_or_else(PoisonError::into_inner);
            }
        }
    }

    fn on_spawn(&self) -> impl Fn() -> String + Send + Sync + 'static {
        let count = self.count.clone();
        move || {
            count.fetch_add(1, Ordering::SeqCst);
            BLOCKING_THREAD.to_owned()
        }
    }

    fn on_stop(&self) -> impl Fn() + Send + Sync + 'static {
        let count = self.count.clone();
        let signal = self.signal.clone();
        move || {
            count.fetch_sub(1, Ordering::SeqCst);
            signal.notify();
        }
    }
}

/// The harness's runtime: one thread, a paused clock, one blocking thread with no keep-alive.
pub(crate) fn build(blocking: &Blocking) -> std::io::Result<tokio::runtime::Runtime> {
    tokio::runtime::Builder::new_current_thread()
        .enable_time()
        .enable_io()
        .start_paused(true)
        .max_blocking_threads(1)
        .thread_keep_alive(Duration::ZERO)
        .thread_name_fn(blocking.on_spawn())
        .on_thread_start(blocking.on_start())
        .on_thread_stop(blocking.on_stop())
        .build()
}

/// What the harness knows of one unnamed task or subscription.
#[derive(Debug)]
pub(crate) struct TaskRecord {
    pub(crate) spawn: Spawn,
    pub(crate) spawned_at: icedwright_types::VirtualInstant,
    pub(crate) state: TaskState,
    pub(crate) polls: u64,
    pub(crate) produced: Vec<String>,
    pub(crate) foreign_wakes: u32,
    pub(crate) held: bool,
    pub(crate) waker: Option<Waker>,
    pub(crate) abort: Option<tokio::task::AbortHandle>,
    pub(crate) replaced: bool,
}

impl TaskRecord {
    pub(crate) fn new(spawn: Spawn, spawned_at: icedwright_types::VirtualInstant) -> Self {
        Self {
            spawn,
            spawned_at,
            state: TaskState::Pending,
            polls: 0,
            produced: Vec::new(),
            foreign_wakes: 0,
            held: false,
            waker: None,
            abort: None,
            replaced: false,
        }
    }
}

/// Every unnamed task and subscription, shared by the instrumented futures and the harness.
/// Named tasks are kept by the controller, which lives on the harness thread.
#[derive(Debug, Default)]
pub(crate) struct Book {
    next_id: u64,
    pub(crate) tasks: BTreeMap<UntypedTaskId, TaskRecord>,
    /// Polls of instrumented tasks, ever.
    pub(crate) polls: u64,
    /// Instrumented tasks that ran to completion, ever.
    pub(crate) completions: u64,
    pub(crate) panics: Vec<(UntypedTaskId, String)>,
    /// Foreign wakes not yet seen by a wait, by task.
    pub(crate) foreign: Vec<UntypedTaskId>,
}

impl Book {
    pub(crate) fn allocate(&mut self) -> UntypedTaskId {
        self.next_id += 1;
        UntypedTaskId::new(self.next_id)
    }

    pub(crate) fn insert(&mut self, record: TaskRecord) -> UntypedTaskId {
        let id = self.allocate();
        self.tasks.insert(id, record);
        id
    }
}

pub(crate) type SharedBook = Arc<Mutex<Book>>;

thread_local! {
    /// The instrumented task being polled on this thread, so a named probe inside it knows
    /// its parent.
    static CURRENT: Cell<Option<UntypedTaskId>> = const { Cell::new(None) };
}

pub(crate) fn current_task() -> Option<UntypedTaskId> {
    CURRENT.with(Cell::get)
}

/// Which thread woke a task.
#[derive(Debug)]
pub(crate) struct WakeHub {
    harness: ThreadId,
    book: SharedBook,
    signal: Arc<Signal>,
    /// Told whenever an instrumented task is polled, so a sleep can end early.
    activity: Arc<tokio::sync::Notify>,
    /// Wakes from the blocking thread, held until the harness starts its next turn.
    held: Mutex<Vec<Waker>>,
    /// Whether subscriptions are a declared external source, whose foreign wakes are held.
    hold_subscriptions: bool,
    /// Foreign wakes of declared subscriptions, held until a wait blocks on its sources.
    deliveries: Mutex<Vec<(UntypedTaskId, Waker)>>,
}

impl WakeHub {
    pub(crate) fn new(
        harness: ThreadId,
        book: SharedBook,
        signal: Arc<Signal>,
        activity: Arc<tokio::sync::Notify>,
        hold_subscriptions: bool,
    ) -> Self {
        Self {
            harness,
            book,
            signal,
            activity,
            held: Mutex::default(),
            hold_subscriptions,
            deliveries: Mutex::default(),
        }
    }

    /// Wakes a task, unless the wake comes from the blocking thread or delivers a declared
    /// subscription source. A blocking-thread wake waits for [`WakeHub::deliver_held`], so
    /// blocking work finishing mid-round is never seen by that round. A delivery waits for
    /// [`WakeHub::deliver_sources`], so the virtual instant it lands at never depends on how
    /// fast the sending thread is.
    fn wake(&self, inner: &Waker, task: UntypedTaskId) {
        let thread = std::thread::current();
        if thread.id() == self.harness {
            inner.wake_by_ref();
        } else if thread.name() == Some(BLOCKING_THREAD) {
            lock(&self.held).push(inner.clone());
        } else if self.is_held_source(task) {
            let mut deliveries = lock(&self.deliveries);
            if !deliveries.iter().any(|(held, _)| *held == task) {
                deliveries.push((task, inner.clone()));
            }
        } else {
            inner.wake_by_ref();
        }
        self.woke(task);
    }

    fn is_held_source(&self, task: UntypedTaskId) -> bool {
        self.hold_subscriptions
            && lock(&self.book)
                .tasks
                .get(&task)
                .is_some_and(|record| record.spawn == Spawn::Subscription)
    }

    /// Delivers the wakes held from the blocking thread, in the order they came.
    pub(crate) fn deliver_held(&self) {
        let held = std::mem::take(&mut *lock(&self.held));
        held.into_iter().for_each(Waker::wake);
    }

    /// Delivers what declared subscription sources have sent, in the order it came, and
    /// returns the first task delivered to.
    pub(crate) fn deliver_sources(&self) -> Option<UntypedTaskId> {
        let deliveries = std::mem::take(&mut *lock(&self.deliveries));
        let first = deliveries.first().map(|(task, _)| *task);
        deliveries.into_iter().for_each(|(_, waker)| waker.wake());
        first
    }

    /// A wake from the harness thread is the runtime's own business; one from the blocking
    /// thread is owned work finishing; anything else is foreign and recorded.
    fn woke(&self, task: UntypedTaskId) {
        let thread = std::thread::current();
        if thread.id() == self.harness {
            return;
        }
        if thread.name() != Some(BLOCKING_THREAD) {
            let mut book = lock(&self.book);
            book.foreign.push(task);
            if let Some(record) = book.tasks.get_mut(&task) {
                record.foreign_wakes = record.foreign_wakes.saturating_add(1);
            }
        }
        self.signal.notify();
    }
}

struct ProbeWaker {
    inner: Waker,
    task: UntypedTaskId,
    hub: Arc<WakeHub>,
}

/// The task is scheduled, or its wake held, before the wake is recorded, so a recorded wake
/// always means a later runtime round polls the task.
impl Wake for ProbeWaker {
    fn wake(self: Arc<Self>) {
        self.hub.wake(&self.inner, self.task);
    }

    fn wake_by_ref(self: &Arc<Self>) {
        self.hub.wake(&self.inner, self.task);
    }
}

/// One task's stream, or one subscription's future, with the harness's bookkeeping around
/// every poll. Boxed streams and futures are `Unpin`, so no projection is needed.
pub(crate) struct Instrumented<T> {
    inner: T,
    id: UntypedTaskId,
    book: SharedBook,
    hub: Arc<WakeHub>,
    done: bool,
}

impl<T> Instrumented<T> {
    pub(crate) fn new(inner: T, id: UntypedTaskId, book: SharedBook, hub: Arc<WakeHub>) -> Self {
        Self {
            inner,
            id,
            book,
            hub,
            done: false,
        }
    }

    /// `None` to go on polling, or the answer when the task is held.
    fn before_poll(&mut self, cx: &Context<'_>) -> Option<()> {
        self.hub.activity.notify_waiters();
        let mut book = lock(&self.book);
        book.polls += 1;
        let record = book.tasks.get_mut(&self.id)?;
        record.polls += 1;
        if record.held {
            record.state = TaskState::Held;
            record.waker = Some(cx.waker().clone());
            return Some(());
        }
        None
    }

    fn poll_with<R>(
        &mut self,
        cx: &mut Context<'_>,
        poll: impl FnOnce(&mut T, &mut Context<'_>) -> Poll<R>,
    ) -> Option<Poll<R>> {
        if self.before_poll(cx).is_some() {
            return Some(Poll::Pending);
        }
        let waker = Waker::from(Arc::new(ProbeWaker {
            inner: cx.waker().clone(),
            task: self.id,
            hub: self.hub.clone(),
        }));
        let mut probed = Context::from_waker(&waker);
        let previous = CURRENT.with(|current| current.replace(Some(self.id)));
        let result = catch_unwind(AssertUnwindSafe(|| poll(&mut self.inner, &mut probed)));
        CURRENT.with(|current| current.set(previous));
        match result {
            Ok(poll) => Some(poll),
            Err(payload) => {
                let message = panic_message(payload.as_ref());
                let mut book = lock(&self.book);
                book.panics.push((self.id, message));
                if let Some(record) = book.tasks.get_mut(&self.id) {
                    record.state = TaskState::Failed;
                }
                self.done = true;
                None
            }
        }
    }

    fn finished(&mut self) {
        self.done = true;
        let mut book = lock(&self.book);
        book.completions += 1;
        if let Some(record) = book.tasks.get_mut(&self.id)
            && record.state != TaskState::Aborted
        {
            record.state = TaskState::Finished;
        }
    }
}

fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    if let Some(text) = payload.downcast_ref::<&str>() {
        return (*text).to_owned();
    }
    if let Some(text) = payload.downcast_ref::<String>() {
        return text.clone();
    }
    "a panic with a non-string payload".to_owned()
}

impl<S: Stream + Unpin> Stream for Instrumented<S> {
    type Item = S::Item;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
        if self.done {
            return Poll::Ready(None);
        }
        let Some(poll) = self.poll_with(cx, |inner, cx| Pin::new(inner).poll_next(cx)) else {
            return Poll::Ready(None);
        };
        if let Poll::Ready(None) = poll {
            self.finished();
        }
        poll
    }
}

impl<F: Future<Output = ()> + Unpin> Future for Instrumented<F> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        if self.done {
            return Poll::Ready(());
        }
        let Some(poll) = self.poll_with(cx, |inner, cx| Pin::new(inner).poll(cx)) else {
            return Poll::Ready(());
        };
        if poll.is_ready() {
            self.finished();
        }
        poll
    }
}

/// The executor iced's subscription tracker spawns into. Task streams are spawned by the
/// harness directly; everything that arrives here is a subscription.
#[derive(Debug, Clone)]
pub(crate) struct HarnessExecutor {
    handle: tokio::runtime::Handle,
    book: SharedBook,
    hub: Arc<WakeHub>,
    clock: VirtualClock,
}

impl HarnessExecutor {
    pub(crate) fn new(
        handle: tokio::runtime::Handle,
        book: SharedBook,
        hub: Arc<WakeHub>,
        clock: VirtualClock,
    ) -> Self {
        Self {
            handle,
            book,
            hub,
            clock,
        }
    }

    /// Spawns a task stream that is already instrumented.
    pub(crate) fn spawn_task(
        &self,
        future: impl Future<Output = ()> + Send + 'static,
        id: UntypedTaskId,
    ) {
        let _enter = self.handle.enter();
        let handle = self.handle.spawn(future);
        if let Some(record) = lock(&self.book).tasks.get_mut(&id) {
            record.abort = Some(handle.abort_handle());
        }
    }

    pub(crate) fn hub(&self) -> Arc<WakeHub> {
        self.hub.clone()
    }
}

impl iced_futures::Executor for HarnessExecutor {
    fn new() -> Result<Self, iced_futures::futures::io::Error> {
        Err(std::io::Error::other(
            "the harness executor is built by the harness, never by iced",
        ))
    }

    fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
        let _enter = self.handle.enter();
        let at = self.clock.of(tokio::time::Instant::now());
        let id = lock(&self.book).insert(TaskRecord::new(Spawn::Subscription, at));
        let instrumented =
            Instrumented::new(Box::pin(future), id, self.book.clone(), self.hub.clone());
        let handle = self.handle.spawn(instrumented);
        if let Some(record) = lock(&self.book).tasks.get_mut(&id) {
            record.abort = Some(handle.abort_handle());
        }
    }

    fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
        self.handle.block_on(future)
    }

    fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
        let _enter = self.handle.enter();
        f()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iced_futures::futures::{StreamExt, stream};

    fn book() -> SharedBook {
        Arc::default()
    }

    fn hub(book: &SharedBook) -> Arc<WakeHub> {
        Arc::new(WakeHub::new(
            std::thread::current().id(),
            book.clone(),
            Arc::default(),
            Arc::default(),
            false,
        ))
    }

    fn record(book: &SharedBook) -> UntypedTaskId {
        lock(book).insert(TaskRecord::new(
            Spawn::Boot,
            icedwright_types::VirtualInstant::__from_offset(
                icedwright_types::VirtualDuration::ZERO,
            ),
        ))
    }

    fn runtime(blocking: &Blocking) -> tokio::runtime::Runtime {
        build(blocking).unwrap()
    }

    #[test]
    fn blocking_work_counts_from_the_moment_spawn_blocking_returns() {
        let blocking = Blocking::new(Arc::default());
        let rt = runtime(&blocking);
        let (release, gate) = std::sync::mpsc::channel::<()>();
        let seen = rt.block_on(async {
            let handle = tokio::task::spawn_blocking(move || {
                let _ = gate.recv();
            });
            let seen = blocking.in_flight();
            release.send(()).unwrap();
            handle.await.unwrap();
            seen
        });
        assert_eq!(seen, 1);
        let signal = blocking.signal.clone();
        let mut generation = signal.generation();
        while blocking.in_flight() != 0 {
            generation = signal.wait_past(generation, Duration::from_secs(15));
        }
        assert_eq!(blocking.in_flight(), 0);
    }

    #[test]
    fn two_queued_jobs_keep_the_count_at_one_until_the_second_finishes() {
        let blocking = Blocking::new(Arc::default());
        let rt = runtime(&blocking);
        let (first_go, first_gate) = std::sync::mpsc::channel::<()>();
        let (second_go, second_gate) = std::sync::mpsc::channel::<()>();
        let order = Arc::new(Mutex::new(Vec::new()));
        let (a, b) = (order.clone(), order.clone());
        let counts = rt.block_on(async {
            let first = tokio::task::spawn_blocking(move || {
                let _ = first_gate.recv();
                lock(&a).push(1);
            });
            let second = tokio::task::spawn_blocking(move || {
                let _ = second_gate.recv();
                lock(&b).push(2);
            });
            let queued = blocking.in_flight();
            first_go.send(()).unwrap();
            first.await.unwrap();
            let between = blocking.in_flight();
            second_go.send(()).unwrap();
            second.await.unwrap();
            (queued, between)
        });
        assert_eq!(counts, (1, 1));
        assert_eq!(*lock(&order), vec![1, 2]);
    }

    #[test]
    fn a_panic_inside_a_poll_is_caught_and_recorded() {
        let book = book();
        let hub = hub(&book);
        let id = record(&book);
        let panicking = stream::once(async { panic!("boom") }).map(|()| 1).boxed();
        let mut instrumented = Instrumented::new(panicking, id, book.clone(), hub);
        let rt = runtime(&Blocking::default());
        let next = rt.block_on(instrumented.next());
        assert_eq!(next, None);
        let book = lock(&book);
        assert_eq!(book.panics, vec![(id, "boom".to_owned())]);
        assert_eq!(book.tasks[&id].state, TaskState::Failed);
    }

    #[test]
    fn a_held_task_is_not_polled() {
        let book = book();
        let id = record(&book);
        lock(&book).tasks.get_mut(&id).unwrap().held = true;
        let polled = Arc::new(AtomicUsize::new(0));
        let counter = polled.clone();
        let inner = stream::poll_fn(move |_| {
            counter.fetch_add(1, Ordering::SeqCst);
            Poll::Ready(Some(1))
        })
        .boxed();
        let mut instrumented = Instrumented::new(inner, id, book.clone(), hub(&book));
        let waker = Waker::noop();
        let mut cx = Context::from_waker(waker);
        assert!(Pin::new(&mut instrumented).poll_next(&mut cx).is_pending());
        assert_eq!(polled.load(Ordering::SeqCst), 0);
        assert_eq!(lock(&book).tasks[&id].state, TaskState::Held);
    }

    #[test]
    fn a_wake_from_a_joined_thread_is_foreign_and_one_from_the_harness_thread_is_not() {
        let book = book();
        let hub = hub(&book);
        let id = record(&book);
        let waker = Waker::from(Arc::new(ProbeWaker {
            inner: Waker::noop().clone(),
            task: id,
            hub: hub.clone(),
        }));
        waker.wake_by_ref();
        assert!(lock(&book).foreign.is_empty());
        let remote = waker.clone();
        std::thread::spawn(move || remote.wake()).join().unwrap();
        assert_eq!(lock(&book).foreign, vec![id]);
        assert_eq!(lock(&book).tasks[&id].foreign_wakes, 1);
    }

    #[test]
    fn a_wake_from_the_blocking_thread_is_owned_work() {
        let book = book();
        let hub = hub(&book);
        let id = record(&book);
        let waker = Waker::from(Arc::new(ProbeWaker {
            inner: Waker::noop().clone(),
            task: id,
            hub,
        }));
        std::thread::Builder::new()
            .name(BLOCKING_THREAD.to_owned())
            .spawn(move || waker.wake())
            .unwrap()
            .join()
            .unwrap();
        assert!(lock(&book).foreign.is_empty());
    }

    #[test]
    fn blocking_work_starts_only_after_the_round_that_spawned_it() {
        let blocking = Blocking::new(Arc::default());
        let rt = runtime(&blocking);
        let ran = Arc::new(AtomicUsize::new(0));
        let job = ran.clone();
        let handle = blocking.round(|| {
            let _entered = rt.enter();
            let handle = tokio::task::spawn_blocking(move || job.fetch_add(1, Ordering::SeqCst));
            rt.block_on(tokio::task::yield_now());
            assert_eq!(ran.load(Ordering::SeqCst), 0);
            handle
        });
        assert_eq!(rt.block_on(handle).unwrap(), 0);
        assert_eq!(ran.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn a_wake_from_the_blocking_thread_waits_for_the_next_turn() {
        struct Count(AtomicUsize);
        impl Wake for Count {
            fn wake(self: Arc<Self>) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }
        let book = book();
        let hub = hub(&book);
        let id = record(&book);
        let count = Arc::new(Count(AtomicUsize::new(0)));
        let waker = Waker::from(Arc::new(ProbeWaker {
            inner: Waker::from(count.clone()),
            task: id,
            hub: hub.clone(),
        }));
        std::thread::Builder::new()
            .name(BLOCKING_THREAD.to_owned())
            .spawn(move || waker.wake())
            .unwrap()
            .join()
            .unwrap();
        assert_eq!(count.0.load(Ordering::SeqCst), 0);
        hub.deliver_held();
        assert_eq!(count.0.load(Ordering::SeqCst), 1);
        hub.deliver_held();
        assert_eq!(count.0.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn a_declared_subscription_delivery_waits_until_the_sources_are_waited_on() {
        struct Count(AtomicUsize);
        impl Wake for Count {
            fn wake(self: Arc<Self>) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }
        let book = book();
        let hub = Arc::new(WakeHub::new(
            std::thread::current().id(),
            book.clone(),
            Arc::default(),
            Arc::default(),
            true,
        ));
        let id = lock(&book).insert(TaskRecord::new(
            Spawn::Subscription,
            icedwright_types::VirtualInstant::__from_offset(
                icedwright_types::VirtualDuration::ZERO,
            ),
        ));
        let count = Arc::new(Count(AtomicUsize::new(0)));
        let waker = Waker::from(Arc::new(ProbeWaker {
            inner: Waker::from(count.clone()),
            task: id,
            hub: hub.clone(),
        }));
        let twice = waker.clone();
        std::thread::spawn(move || {
            waker.wake();
            twice.wake();
        })
        .join()
        .unwrap();
        hub.deliver_held();
        assert_eq!(count.0.load(Ordering::SeqCst), 0);
        assert_eq!(lock(&book).foreign, vec![id, id]);
        assert_eq!(hub.deliver_sources(), Some(id));
        assert_eq!(count.0.load(Ordering::SeqCst), 1);
        assert_eq!(hub.deliver_sources(), None);
    }

    #[test]
    fn the_signal_wakes_a_waiter_from_another_thread() {
        let signal = Arc::new(Signal::default());
        let seen = signal.generation();
        let remote = signal.clone();
        let thread = std::thread::spawn(move || remote.notify());
        let after = signal.wait_past(seen, Duration::from_secs(15));
        thread.join().unwrap();
        assert!(after > seen);
    }
}