waterui-testing 0.3.0

Headless testing helpers for WaterUI
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
use std::rc::Rc;
use std::time::{Duration, Instant};

use waterui_core::{AnyView, View};

use crate::app::{OffscreenApp, UiBuilder};
use crate::driver::FrameTiming;

const PERF_FRAME_RATE: u32 = 120;

/// Repeated offscreen render measurement configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PerfConfig {
    /// Number of unrecorded frames run before sampling.
    pub warmups: u32,
    /// Number of recorded frames per measurement.
    pub samples: u32,
    /// Number of independent measurement repetitions.
    pub repetitions: u32,
}

impl Default for PerfConfig {
    fn default() -> Self {
        Self {
            warmups: 10,
            samples: 120,
            repetitions: 7,
        }
    }
}

/// Aggregate render timing for one measured scenario.
#[derive(Clone, Debug)]
pub struct PerfMeasurement {
    /// Scenario name supplied to [`PerfApp::measure`].
    pub name: String,
    /// Recorded frame timings after warmup.
    pub frames: Vec<FrameTiming>,
}

impl PerfMeasurement {
    /// Computes aggregate statistics for this measurement.
    #[must_use]
    pub fn stats(&self) -> PerfStats {
        PerfStats::from_frames(&self.frames)
    }
}

/// Statistical summary of repeated Hydrolysis GPU frames.
#[derive(Clone, Copy, Debug, Default)]
pub struct PerfStats {
    /// Number of sampled frames.
    pub samples: usize,
    /// Arithmetic mean frame duration.
    pub mean: Duration,
    /// Median frame duration.
    pub median: Duration,
    /// Fastest sampled frame.
    pub min: Duration,
    /// Slowest sampled frame.
    pub max: Duration,
    /// 95th percentile frame duration.
    pub p95: Duration,
    /// Number of sampled frames that rebuilt scene/layout state.
    pub rebuilt_frames: usize,
    /// Number of sampled frames that rendered into the target surface.
    pub rendered_frames: usize,
    /// Number of sampled frames that had no render work.
    pub idle_frames: usize,
    /// Duration summary over rendered frames only.
    pub rendered_total: PerfDurationStats,
    /// Number of sampled frames that missed the 120fps frame budget.
    pub missed_120fps_frames: usize,
    /// Number of sampled frames that missed the 60fps frame budget.
    pub missed_60fps_frames: usize,
    /// Phase duration summaries for sampled frames.
    pub phases: PerfPhaseStats,
    /// Measurement cache hits across sampled frames.
    pub measurement_cache_hits: u64,
    /// Measurement cache misses across sampled frames.
    pub measurement_cache_misses: u64,
    /// Maximum compositor layers submitted by one sampled frame.
    pub scene_layers: u64,
    /// Maximum Vello scene layers submitted by one sampled frame.
    pub vello_scene_layers: u64,
    /// Maximum embedded GPU surface layers submitted by one sampled frame.
    pub gpu_surface_layers: u64,
    /// Maximum Vello clip layers pushed by one sampled frame.
    pub clip_layers: u64,
    /// Maximum nested Vello clip depth observed across sampled frames.
    pub max_clip_depth: u64,
    /// `AppliedFilter` nodes dispatched across sampled frames.
    pub applied_filter_count: u64,
    /// `AppliedFilter` subtree capture time across sampled frames, in microseconds.
    pub applied_filter_capture_us: u64,
    /// `AppliedFilter` GPU effect time across sampled frames, in microseconds.
    pub applied_filter_effect_us: u64,
}

/// Statistical summary for the measured frame phases.
#[derive(Clone, Copy, Debug, Default)]
pub struct PerfPhaseStats {
    /// Time spent draining local executor work before input.
    pub executor_before: PerfDurationStats,
    /// Time spent dispatching pending input.
    pub input: PerfDurationStats,
    /// Time spent advancing animation and invalidation clocks.
    pub animation: PerfDurationStats,
    /// Time spent rebuilding scene/layout state.
    pub rebuild: PerfDurationStats,
    /// Time spent building the root `WaterUI` view value during scene rebuild.
    pub build_content: PerfDurationStats,
    /// Time spent dispatching `WaterUI` views into Hydrolysis scene/layout state.
    pub scene_dispatch: PerfDurationStats,
    /// Time spent finalizing layout, interaction, and accessibility state after dispatch.
    pub scene_finish: PerfDurationStats,
    /// Time spent acquiring an offscreen frame.
    pub acquire: PerfDurationStats,
    /// Time spent submitting Hydrolysis/Vello rendering work.
    pub render: PerfDurationStats,
    /// Time spent presenting the offscreen frame.
    pub present: PerfDurationStats,
    /// Time spent draining local executor work after rendering.
    pub executor_after: PerfDurationStats,
}

/// Duration summary for one measured value.
#[derive(Clone, Copy, Debug, Default)]
pub struct PerfDurationStats {
    /// Arithmetic mean duration.
    pub mean: Duration,
    /// Median duration.
    pub median: Duration,
    /// 95th percentile duration.
    pub p95: Duration,
    /// Slowest duration in the summarized set.
    pub max: Duration,
}

impl PerfStats {
    /// Builds a statistical summary from frame timings.
    #[must_use]
    pub fn from_frames(frames: &[FrameTiming]) -> Self {
        if frames.is_empty() {
            return Self::default();
        }
        let total = PerfDurationStats::from_durations(frames.iter().map(|frame| frame.total));
        let samples = frames.len();

        let rendered_frames = frames
            .iter()
            .filter(|frame| frame.profile.counters.rendered)
            .count();

        Self {
            samples,
            mean: total.mean,
            median: total.median,
            min: frames
                .iter()
                .map(|frame| frame.total)
                .min()
                .unwrap_or_default(),
            max: frames
                .iter()
                .map(|frame| frame.total)
                .max()
                .unwrap_or_default(),
            p95: total.p95,
            rebuilt_frames: frames.iter().filter(|frame| frame.rebuilt).count(),
            rendered_frames,
            idle_frames: samples - rendered_frames,
            rendered_total: PerfDurationStats::from_durations(
                frames
                    .iter()
                    .filter(|frame| frame.profile.counters.rendered)
                    .map(|frame| frame.total),
            ),
            missed_120fps_frames: frames
                .iter()
                .filter(|frame| frame.total > Duration::from_nanos(8_333_333))
                .count(),
            missed_60fps_frames: frames
                .iter()
                .filter(|frame| frame.total > Duration::from_nanos(16_666_667))
                .count(),
            phases: PerfPhaseStats::from_frames(frames),
            measurement_cache_hits: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.measurement_cache_hits))
                .sum(),
            measurement_cache_misses: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.measurement_cache_misses))
                .sum(),
            scene_layers: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.scene_layers))
                .max()
                .unwrap_or_default(),
            vello_scene_layers: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.vello_scene_layers))
                .max()
                .unwrap_or_default(),
            gpu_surface_layers: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.gpu_surface_layers))
                .max()
                .unwrap_or_default(),
            clip_layers: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.clip_layers))
                .max()
                .unwrap_or_default(),
            max_clip_depth: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.max_clip_depth))
                .max()
                .unwrap_or_default(),
            applied_filter_count: frames
                .iter()
                .map(|frame| u64::from(frame.profile.counters.applied_filter_count))
                .sum(),
            applied_filter_capture_us: frames
                .iter()
                .map(|frame| frame.profile.counters.applied_filter_capture_us)
                .sum(),
            applied_filter_effect_us: frames
                .iter()
                .map(|frame| frame.profile.counters.applied_filter_effect_us)
                .sum(),
        }
    }
}

impl PerfPhaseStats {
    fn from_frames(frames: &[FrameTiming]) -> Self {
        Self {
            executor_before: PerfDurationStats::from_durations(
                frames
                    .iter()
                    .map(|frame| frame.profile.phases.executor_before),
            ),
            input: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.input),
            ),
            animation: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.animation),
            ),
            rebuild: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.rebuild),
            ),
            build_content: PerfDurationStats::from_durations(
                frames
                    .iter()
                    .map(|frame| frame.profile.phases.build_content),
            ),
            scene_dispatch: PerfDurationStats::from_durations(
                frames
                    .iter()
                    .map(|frame| frame.profile.phases.scene_dispatch),
            ),
            scene_finish: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.scene_finish),
            ),
            acquire: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.acquire),
            ),
            render: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.render),
            ),
            present: PerfDurationStats::from_durations(
                frames.iter().map(|frame| frame.profile.phases.present),
            ),
            executor_after: PerfDurationStats::from_durations(
                frames
                    .iter()
                    .map(|frame| frame.profile.phases.executor_after),
            ),
        }
    }
}

impl PerfDurationStats {
    fn from_durations(values: impl IntoIterator<Item = Duration>) -> Self {
        let mut durations = values.into_iter().collect::<Vec<_>>();
        if durations.is_empty() {
            return Self::default();
        }
        durations.sort_unstable();
        let sum = durations.iter().copied().sum::<Duration>();
        let samples = durations.len();
        let p95_index = ((samples - 1) * 95).div_ceil(100);
        Self {
            mean: sum / u32::try_from(samples).expect("perf sample count should fit u32"),
            median: durations[samples / 2],
            p95: durations[p95_index],
            max: *durations.last().expect("duration list should not be empty"),
        }
    }
}

/// Result of a performance run.
#[derive(Clone, Debug, Default)]
pub struct PerfReport {
    measurements: Vec<PerfMeasurement>,
}

impl PerfReport {
    /// Returns all recorded measurements in insertion order.
    #[must_use]
    pub fn measurements(&self) -> &[PerfMeasurement] {
        &self.measurements
    }

    pub(crate) fn push(&mut self, measurement: PerfMeasurement) {
        self.measurements.push(measurement);
    }
}

/// Mutable app wrapper passed to performance automation closures.
#[derive(Debug)]
pub struct PerfRun<'a> {
    app: &'a mut OffscreenApp,
    frame_at: &'a mut Instant,
    frame_interval: Duration,
}

impl PerfRun<'_> {
    /// Advances one complete offscreen Hydrolysis GPU frame without snapshot readback.
    ///
    /// # Panics
    ///
    /// Panics if the synthetic frame clock overflows.
    pub fn frame(&mut self) -> FrameTiming {
        let timing = self.app.app.driver.pump_frame_at(
            &self.app.app.content,
            &self.app.app.env,
            *self.frame_at,
        );
        *self.frame_at = self
            .frame_at
            .checked_add(self.frame_interval)
            .expect("perf frame clock overflow");
        timing
    }

    /// Queues a pointer move for the next measured frame without settling the app.
    pub fn pointer_move(&mut self, x: f32, y: f32) {
        self.app.app.driver.pointer_move(x, y, &self.app.app.env);
    }

    /// Queues a primary pointer down for the next measured frame without settling the app.
    pub fn pointer_down(&mut self, x: f32, y: f32) {
        self.app.app.driver.pointer_down(x, y, &self.app.app.env);
    }

    /// Queues a primary pointer up for the next measured frame without settling the app.
    pub fn pointer_up(&mut self, x: f32, y: f32) {
        self.app.app.driver.pointer_up(x, y, &self.app.app.env);
    }

    /// Queues a wheel/trackpad scroll event for the next measured frame without settling the app.
    pub fn scroll_at(&mut self, x: f32, y: f32, dx: f32, dy: f32, is_line_delta: bool) {
        self.app
            .app
            .driver
            .scroll_at(x, y, dx, dy, is_line_delta, &self.app.app.env);
    }

    /// Requests a redraw for the next measured frame without changing semantic state.
    pub fn redraw(&mut self) {
        self.app
            .app
            .driver
            .request_redraw(&self.app.app.content, &self.app.app.env);
    }

    /// Accesses semantic assertions and interactions during a performance run.
    #[must_use]
    pub const fn app(&mut self) -> &mut OffscreenApp {
        self.app
    }
}

/// Records performance scenarios for one view.
///
/// The view factory is erased internally, so user-facing signatures (bench
/// bodies, automation closures) stay a plain `&mut PerfApp`.
pub struct PerfApp {
    builder: UiBuilder,
    view_fn: Rc<dyn Fn() -> AnyView>,
    config: PerfConfig,
    report: PerfReport,
}

impl core::fmt::Debug for PerfApp {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PerfApp")
            .field("builder", &self.builder)
            .field("config", &self.config)
            .field("report", &self.report)
            .finish_non_exhaustive()
    }
}

impl PerfApp {
    pub(crate) fn new<F, V>(builder: UiBuilder, view_fn: F, config: PerfConfig) -> Self
    where
        F: Fn() -> V + 'static,
        V: View + 'static,
    {
        Self {
            builder,
            view_fn: Rc::new(move || AnyView::new(view_fn())),
            config,
            report: PerfReport {
                measurements: Vec::new(),
            },
        }
    }

    /// Measures one scenario across warmup and sample frames.
    ///
    /// # Panics
    ///
    /// Panics if the configured sample count does not fit in memory on this target.
    pub fn measure<A>(&mut self, name: impl Into<String>, mut automation: A)
    where
        A: FnMut(&mut PerfRun<'_>),
    {
        let mut frames = Vec::with_capacity(
            usize::try_from(self.config.samples)
                .and_then(|samples| {
                    usize::try_from(self.config.repetitions).map(|repetitions| {
                        samples
                            .checked_mul(repetitions)
                            .expect("perf sample count should fit usize")
                    })
                })
                .expect("perf sample count should fit usize"),
        );
        for _ in 0..self.config.repetitions {
            let view_fn = Rc::clone(&self.view_fn);
            let mut app = self.builder.clone().mount_offscreen(move || view_fn());
            // Seed from the driver's virtual clock (the mount already pumped)
            // so perf frames and interleaved semantic pumps stay monotone.
            let mut frame_at = app.app.driver.clock().unwrap_or_else(Instant::now);
            let frame_interval = Duration::from_secs(1) / PERF_FRAME_RATE;
            for _ in 0..self.config.warmups {
                let mut run = PerfRun {
                    app: &mut app,
                    frame_at: &mut frame_at,
                    frame_interval,
                };
                automation(&mut run);
                let _ = run.frame();
            }

            for _ in 0..self.config.samples {
                let mut run = PerfRun {
                    app: &mut app,
                    frame_at: &mut frame_at,
                    frame_interval,
                };
                automation(&mut run);
                frames.push(run.frame());
            }
        }
        self.report.push(PerfMeasurement {
            name: name.into(),
            frames,
        });
    }

    /// Returns the number of scenarios recorded so far.
    #[must_use]
    pub const fn measurement_count(&self) -> usize {
        self.report.measurements.len()
    }

    pub(crate) fn finish(self) -> PerfReport {
        self.report
    }
}