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
//! The process-wide watchdog: when a call into app code (`boot`, `update`, `view`, a task's
//! poll) never returns, the test thread cannot be interrupted, so one thread per process
//! watches every running call and, past its budget, prints a report and aborts the process.
//!
//! It measures only while app code runs. Harness waits are bounded by the hang detector on
//! the test thread, and font loading, rendering and trace encoding are never watched.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use std::panic::Location;
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

use crate::config::{HangAfter, RealClock, SystemClock};
use crate::runtime::{SharedBook, lock};

/// What the watchdog prints before it aborts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HangReport {
    /// The app call that did not return.
    pub(crate) call: &'static str,
    /// The test thread's name.
    pub(crate) test: String,
    /// The step the call ran in, as the test's source line.
    pub(crate) step: Option<String>,
    /// The message being applied or the last one applied.
    pub(crate) last_message: Option<String>,
    /// Every task that had not finished.
    pub(crate) pending: Vec<String>,
    /// How long the call had run.
    pub(crate) elapsed: Duration,
}

impl fmt::Display for HangReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "harness aborted: app call did not return")?;
        writeln!(f, "  test: {}", self.test)?;
        writeln!(
            f,
            "  step: {}",
            self.step
                .as_deref()
                .unwrap_or("boot, before the first step")
        )?;
        writeln!(
            f,
            "  app call: {} (running for {:.1}s)",
            self.call,
            self.elapsed.as_secs_f64()
        )?;
        writeln!(
            f,
            "  last message: {}",
            self.last_message.as_deref().unwrap_or("none")
        )?;
        if self.pending.is_empty() {
            writeln!(f, "  pending tasks: none")?;
        } else {
            writeln!(f, "  pending tasks:")?;
            for task in &self.pending {
                writeln!(f, "    {task}")?;
            }
        }
        write!(
            f,
            "  Set ICEDWRIGHT_WATCHDOG to a longer duration, or to off in a debugger session."
        )
    }
}

/// Lists the tasks that have not finished, when the watchdog reports.
type PendingTasks = Arc<dyn Fn() -> Vec<String> + Send + Sync>;

/// One call into app code that has not returned yet.
struct Running {
    started: Instant,
    budget: Duration,
    call: &'static str,
    test: String,
    step: Option<String>,
    last_message: Option<String>,
    pending: PendingTasks,
}

impl Running {
    fn deadline(&self) -> Instant {
        self.started + self.budget
    }

    fn report(&self, now: Instant) -> HangReport {
        HangReport {
            call: self.call,
            test: self.test.clone(),
            step: self.step.clone(),
            last_message: self.last_message.clone(),
            pending: (self.pending)(),
            elapsed: now.saturating_duration_since(self.started),
        }
    }
}

#[derive(Default)]
struct Calls {
    next: u64,
    running: BTreeMap<u64, Running>,
    reported: bool,
}

/// What the watchdog thread does next.
#[derive(Debug, PartialEq, Eq)]
enum Next {
    /// Nothing is running: wait until a call starts.
    Idle,
    /// Wait this long, or until a call starts or ends.
    Wait(Duration),
    /// A call has run past its budget.
    Abort(HangReport),
}

impl Calls {
    fn next(&self, now: Instant) -> Next {
        let Some(earliest) = self.running.values().min_by_key(|call| call.deadline()) else {
            return Next::Idle;
        };
        match earliest.deadline().checked_duration_since(now) {
            Some(left) if !left.is_zero() => Next::Wait(left),
            _ => Next::Abort(earliest.report(now)),
        }
    }
}

/// Called with the report of a call that never returned. In a test process it aborts.
pub(crate) type AbortHook = Box<dyn Fn(&HangReport) + Send + Sync>;

/// Watches every call into app code in the process.
pub(crate) struct Watchdog {
    clock: Arc<dyn RealClock>,
    abort: AbortHook,
    calls: Mutex<Calls>,
    changed: Condvar,
}

impl fmt::Debug for Watchdog {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Watchdog")
            .field("running", &lock(&self.calls).running.len())
            .finish_non_exhaustive()
    }
}

impl Watchdog {
    pub(crate) fn new(clock: Arc<dyn RealClock>, abort: AbortHook) -> Self {
        Self {
            clock,
            abort,
            calls: Mutex::default(),
            changed: Condvar::new(),
        }
    }

    /// The process's watchdog, whose thread starts the first time it is asked for.
    pub(crate) fn global() -> Option<&'static Arc<Watchdog>> {
        static GLOBAL: OnceLock<Option<Arc<Watchdog>>> = OnceLock::new();
        GLOBAL
            .get_or_init(|| {
                let watchdog = Arc::new(Watchdog::new(
                    Arc::new(SystemClock),
                    Box::new(|report| {
                        eprintln!("{report}");
                        std::process::abort();
                    }),
                ));
                let watching = Arc::clone(&watchdog);
                std::thread::Builder::new()
                    .name("icedwright-watchdog".to_owned())
                    .spawn(move || watching.watch())
                    .ok()
                    .map(|_| watchdog)
            })
            .as_ref()
    }

    fn start(&self, budget: Duration, call: &'static str, context: &Context) -> u64 {
        let mut calls = lock(&self.calls);
        let id = calls.next;
        calls.next += 1;
        calls.running.insert(
            id,
            Running {
                started: self.clock.now(),
                budget,
                call,
                test: context.test.clone(),
                step: context.step.borrow().clone(),
                last_message: context.last_message.borrow().clone(),
                pending: Arc::clone(&context.pending),
            },
        );
        drop(calls);
        self.changed.notify_all();
        id
    }

    fn end(&self, id: u64) {
        lock(&self.calls).running.remove(&id);
        self.changed.notify_all();
    }

    /// Looks once: calls the abort hook with the first call past its budget. Returns whether
    /// it did.
    pub(crate) fn poll(&self) -> bool {
        let mut calls = lock(&self.calls);
        if calls.reported {
            return false;
        }
        let Next::Abort(report) = calls.next(self.clock.now()) else {
            return false;
        };
        calls.reported = true;
        drop(calls);
        (self.abort)(&report);
        true
    }

    /// The watchdog thread: waits on the calls changing or the earliest deadline, never on a
    /// fixed delay.
    fn watch(&self) {
        let mut calls = lock(&self.calls);
        loop {
            calls = match calls.next(self.clock.now()) {
                Next::Idle => self
                    .changed
                    .wait(calls)
                    .unwrap_or_else(std::sync::PoisonError::into_inner),
                Next::Wait(left) => {
                    self.changed
                        .wait_timeout(calls, left)
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .0
                }
                Next::Abort(_) => {
                    drop(calls);
                    self.poll();
                    lock(&self.calls)
                }
            };
        }
    }
}

/// One harness's view of the watchdog: its budget and what a report says about it.
pub(crate) struct Context {
    watchdog: Option<Arc<Watchdog>>,
    budget: Duration,
    test: String,
    step: RefCell<Option<String>>,
    last_message: RefCell<Option<String>>,
    pending: PendingTasks,
}

impl fmt::Debug for Context {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Context")
            .field("watched", &self.watchdog.is_some())
            .field("budget", &self.budget)
            .finish_non_exhaustive()
    }
}

/// The budget: `ICEDWRIGHT_WATCHDOG` when set, else the default hang window; `Off` in
/// either the environment or the harness's configuration turns it off.
pub(crate) fn budget(env: Option<HangAfter>, config: HangAfter) -> Option<Duration> {
    if config == HangAfter::Off {
        return None;
    }
    match env.unwrap_or_default() {
        HangAfter::After(budget) => Some(budget),
        HangAfter::Off => None,
    }
}

/// The tasks in `book` that have not finished, as the report lists them. A book locked by a
/// stuck poll is reported as such rather than waited on.
pub(crate) fn pending_tasks(book: SharedBook) -> PendingTasks {
    Arc::new(move || {
        let Ok(book) = book.try_lock() else {
            return vec!["(the task list is locked by the stuck call)".to_owned()];
        };
        book.tasks
            .iter()
            .filter(|(_, record)| record.state.is_live())
            .map(|(id, record)| format!("{id}: {:?}, {:?}", record.spawn, record.state))
            .collect()
    })
}

impl Context {
    pub(crate) fn new(
        watchdog: Option<Arc<Watchdog>>,
        budget: Option<Duration>,
        pending: PendingTasks,
    ) -> Self {
        let thread = std::thread::current();
        Self {
            watchdog: budget.and(watchdog),
            budget: budget.unwrap_or_default(),
            test: thread.name().unwrap_or("main").to_owned(),
            step: RefCell::new(None),
            last_message: RefCell::new(None),
            pending,
        }
    }

    pub(crate) fn set_step(&self, location: &Location<'_>) {
        *self.step.borrow_mut() = Some(format!(
            "{}:{}:{}",
            location.file(),
            location.line(),
            location.column()
        ));
    }

    pub(crate) fn set_message(&self, debug: &str) {
        *self.last_message.borrow_mut() = Some(debug.to_owned());
    }

    fn run<T>(&self, call: &'static str, f: impl FnOnce() -> T) -> T {
        let Some(watchdog) = &self.watchdog else {
            return f();
        };
        let id = watchdog.start(self.budget, call, self);
        let _end = End { watchdog, id };
        f()
    }
}

/// Ends a watched call when it returns or unwinds.
struct End<'w> {
    watchdog: &'w Watchdog,
    id: u64,
}

impl Drop for End<'_> {
    fn drop(&mut self) {
        self.watchdog.end(self.id);
    }
}

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

/// Makes a harness's context the one app calls on this thread report to.
#[derive(Debug)]
pub(crate) struct ContextGuard {
    context: Rc<Context>,
    previous: Option<Rc<Context>>,
}

impl ContextGuard {
    pub(crate) fn install(context: Context) -> Self {
        let context = Rc::new(context);
        let previous = CURRENT.with(|current| current.replace(Some(Rc::clone(&context))));
        Self { context, previous }
    }

    pub(crate) fn context(&self) -> &Context {
        &self.context
    }
}

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

/// Runs a call into app code under the watchdog of the harness installed on this thread.
pub(crate) fn app_call<T>(call: &'static str, f: impl FnOnce() -> T) -> T {
    let context = CURRENT.with(|current| current.borrow().clone());
    match context {
        Some(context) => context.run(call, f),
        None => f(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    /// A clock the test moves by hand; it never moves on its own.
    struct HandClock {
        start: Instant,
        offset_ms: AtomicU64,
    }

    impl HandClock {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                start: SystemClock.now(),
                offset_ms: AtomicU64::new(0),
            })
        }

        fn advance(&self, by: Duration) {
            let ms = u64::try_from(by.as_millis()).unwrap();
            self.offset_ms.fetch_add(ms, Ordering::SeqCst);
        }
    }

    impl RealClock for HandClock {
        fn now(&self) -> Instant {
            self.start + Duration::from_millis(self.offset_ms.load(Ordering::SeqCst))
        }
    }

    fn watchdog(clock: &Arc<HandClock>) -> (Arc<Watchdog>, Arc<Mutex<Vec<HangReport>>>) {
        let reports = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&reports);
        let watchdog = Watchdog::new(
            Arc::clone(clock) as Arc<dyn RealClock>,
            Box::new(move |report| sink.lock().unwrap().push(report.clone())),
        );
        (Arc::new(watchdog), reports)
    }

    fn context(watchdog: &Arc<Watchdog>, budget: Duration) -> Context {
        Context::new(
            Some(Arc::clone(watchdog)),
            Some(budget),
            Arc::new(|| vec!["#1: Boot, Pending".to_owned()]),
        )
    }

    #[test]
    fn a_call_past_its_budget_is_reported_with_its_context() {
        let clock = HandClock::new();
        let (watchdog, reports) = watchdog(&clock);
        let context = context(&watchdog, Duration::from_secs(1));
        context.set_step(Location::caller());
        context.set_message("Block");
        let ran = context.run("update", || {
            assert!(!watchdog.poll());
            clock.advance(Duration::from_millis(999));
            assert!(!watchdog.poll());
            clock.advance(Duration::from_millis(1));
            assert!(watchdog.poll());
            7
        });
        assert_eq!(ran, 7);
        let reports = reports.lock().unwrap();
        let [report] = reports.as_slice() else {
            panic!("expected one report, got {reports:?}");
        };
        assert_eq!(report.call, "update");
        assert_eq!(report.last_message.as_deref(), Some("Block"));
        assert_eq!(report.pending, vec!["#1: Boot, Pending".to_owned()]);
        assert_eq!(report.elapsed, Duration::from_secs(1));
        let step = report.step.as_deref().unwrap();
        assert!(step.contains("watchdog.rs"), "{step}");
        let text = report.to_string();
        assert!(
            text.starts_with("harness aborted: app call did not return"),
            "{text}"
        );
        for part in [
            "app call: update",
            "last message: Block",
            "#1: Boot, Pending",
        ] {
            assert!(text.contains(part), "{text}");
        }
    }

    #[test]
    fn a_call_that_returns_in_time_is_forgotten() {
        let clock = HandClock::new();
        let (watchdog, reports) = watchdog(&clock);
        let context = context(&watchdog, Duration::from_secs(1));
        context.run("view", || clock.advance(Duration::from_millis(500)));
        clock.advance(Duration::from_secs(600));
        assert!(!watchdog.poll());
        assert!(reports.lock().unwrap().is_empty());
        assert_eq!(lock(&watchdog.calls).next(clock.now()), Next::Idle);
    }

    #[test]
    fn a_call_that_unwinds_is_forgotten_too() {
        let clock = HandClock::new();
        let (watchdog, _) = watchdog(&clock);
        let context = context(&watchdog, Duration::from_secs(1));
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            context.run("update", || panic!("app bug"));
        }));
        assert!(unwound.is_err());
        assert!(lock(&watchdog.calls).running.is_empty());
    }

    #[test]
    fn the_thread_waits_for_the_earliest_deadline_and_reports_once() {
        let clock = HandClock::new();
        let (watchdog, reports) = watchdog(&clock);
        let slow = context(&watchdog, Duration::from_secs(10));
        let quick = context(&watchdog, Duration::from_secs(2));
        slow.run("view", || {
            quick.run("update", || {
                assert_eq!(
                    lock(&watchdog.calls).next(clock.now()),
                    Next::Wait(Duration::from_secs(2))
                );
                clock.advance(Duration::from_secs(3));
                assert!(watchdog.poll());
                assert!(!watchdog.poll());
            });
        });
        let reports = reports.lock().unwrap();
        assert_eq!(reports.len(), 1);
        assert_eq!(reports.first().map(|r| r.call), Some("update"));
    }

    #[test]
    fn an_unwatched_context_runs_calls_without_registering_them() {
        let clock = HandClock::new();
        let (watchdog, _) = watchdog(&clock);
        let context = Context::new(Some(Arc::clone(&watchdog)), None, Arc::new(Vec::new));
        context.run("update", || {
            assert!(lock(&watchdog.calls).running.is_empty());
        });
    }

    #[test]
    fn app_calls_report_to_the_innermost_installed_harness() {
        let clock = HandClock::new();
        let (watchdog, _) = watchdog(&clock);
        assert_eq!(app_call("view", || 1), 1);
        let outer = ContextGuard::install(context(&watchdog, Duration::from_secs(5)));
        {
            let _inner = ContextGuard::install(context(&watchdog, Duration::from_secs(1)));
            app_call("view", || {
                let calls = lock(&watchdog.calls);
                let budgets: Vec<Duration> = calls.running.values().map(|r| r.budget).collect();
                assert_eq!(budgets, vec![Duration::from_secs(1)]);
            });
        }
        app_call("view", || {
            let calls = lock(&watchdog.calls);
            let budgets: Vec<Duration> = calls.running.values().map(|r| r.budget).collect();
            assert_eq!(budgets, vec![Duration::from_secs(5)]);
        });
        assert_eq!(outer.context().budget, Duration::from_secs(5));
    }

    #[test]
    fn the_budget_comes_from_the_environment_and_off_wins() {
        let second = HangAfter::After(Duration::from_secs(1));
        assert_eq!(
            budget(None, second),
            Some(Duration::from_secs(120)),
            "a harness's own hang window does not shorten the watchdog"
        );
        assert_eq!(
            budget(Some(second), HangAfter::default()),
            Some(Duration::from_secs(1))
        );
        assert_eq!(budget(Some(HangAfter::Off), HangAfter::default()), None);
        assert_eq!(budget(Some(second), HangAfter::Off), None);
    }
}