Skip to main content

strata/runtime/
profile.rs

1//! Per-phase frame profiling: input, signals, view render, reconcile, style cascade,
2//! layout, display-list compile, raster, 3D submit, present, and rolling p50/p95/p99 telemetry.
3
4use serde::{Deserialize, Serialize};
5use std::alloc::{GlobalAlloc, Layout};
6use std::collections::VecDeque;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::time::Duration;
9
10#[cfg(feature = "profiling")]
11static FRAME_HEAP_ALLOC_COUNT: AtomicU64 = AtomicU64::new(0);
12#[cfg(feature = "profiling")]
13static FRAME_HEAP_ALLOC_BYTES: AtomicU64 = AtomicU64::new(0);
14static TOTAL_HEAP_ALLOC_COUNT: AtomicU64 = AtomicU64::new(0);
15static TOTAL_HEAP_ALLOC_BYTES: AtomicU64 = AtomicU64::new(0);
16
17/// Optional zero-overhead-when-unused counting allocator wrapper that host apps (or `--features profiling`
18/// builds) can install as `#[global_allocator]` to measure real per-frame heap allocation count and bytes.
19///
20/// Example:
21/// ```ignore
22/// #[global_allocator]
23/// static ALLOC: strata::ProfilingAllocator<std::alloc::System> =
24///     strata::ProfilingAllocator::new(std::alloc::System);
25/// ```
26pub struct ProfilingAllocator<A> {
27    inner: A,
28}
29
30impl<A> ProfilingAllocator<A> {
31    pub const fn new(inner: A) -> Self {
32        Self { inner }
33    }
34}
35
36unsafe impl<A: GlobalAlloc> GlobalAlloc for ProfilingAllocator<A> {
37    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
38        let ptr = self.inner.alloc(layout);
39        if !ptr.is_null() {
40            record_heap_alloc(layout.size() as u64);
41        }
42        ptr
43    }
44
45    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
46        self.inner.dealloc(ptr, layout);
47    }
48
49    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
50        let ptr = self.inner.alloc_zeroed(layout);
51        if !ptr.is_null() {
52            record_heap_alloc(layout.size() as u64);
53        }
54        ptr
55    }
56
57    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
58        let out = self.inner.realloc(ptr, layout, new_size);
59        if !out.is_null() && new_size > layout.size() {
60            record_heap_alloc((new_size - layout.size()) as u64);
61        }
62        out
63    }
64}
65
66/// Records a heap allocation event for per-frame telemetry.
67#[inline]
68pub fn record_heap_alloc(bytes: u64) {
69    #[cfg(feature = "profiling")]
70    {
71        FRAME_HEAP_ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
72        FRAME_HEAP_ALLOC_BYTES.fetch_add(bytes, Ordering::Relaxed);
73        TOTAL_HEAP_ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
74        TOTAL_HEAP_ALLOC_BYTES.fetch_add(bytes, Ordering::Relaxed);
75    }
76    #[cfg(not(feature = "profiling"))]
77    {
78        let _ = bytes;
79    }
80}
81
82/// Drains and returns `(alloc_count, alloc_bytes)` recorded since the previous frame.
83#[inline]
84pub fn take_frame_heap_alloc_delta() -> (u64, u64) {
85    #[cfg(feature = "profiling")]
86    {
87        let count = FRAME_HEAP_ALLOC_COUNT.swap(0, Ordering::Relaxed);
88        let bytes = FRAME_HEAP_ALLOC_BYTES.swap(0, Ordering::Relaxed);
89        (count, bytes)
90    }
91    #[cfg(not(feature = "profiling"))]
92    {
93        (0, 0)
94    }
95}
96
97/// Returns cumulative `(total_alloc_count, total_alloc_bytes)` tracked when `profiling` is active.
98#[inline]
99pub fn total_heap_alloc_stats() -> (u64, u64) {
100    (
101        TOTAL_HEAP_ALLOC_COUNT.load(Ordering::Relaxed),
102        TOTAL_HEAP_ALLOC_BYTES.load(Ordering::Relaxed),
103    )
104}
105
106/// Wall-clock cost of each frame phase since the last [`AppRuntime::finish_frame_profile`].
107///
108/// Phases accumulate, so a frame that rebuilds twice reports both costs.
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
110pub struct FrameProfile {
111    /// Blueprint to layout-tree rebuild, including style resolution.
112    pub rebuild: Duration,
113    /// Layout computation.
114    pub layout: Duration,
115    /// Display-list compilation (compositor, scrollbars, path batch).
116    pub compile: Duration,
117    /// Rasterization, recorded by the presenting backend (Cairo or GPU 2D).
118    pub raster: Duration,
119    /// Presentation to the surface, recorded by the presenting backend.
120    pub present: Duration,
121    /// Platform/MCP input event dispatch duration.
122    pub input_dispatch: Duration,
123    /// Reactive signal drain and effect flushing duration.
124    pub signal_drain: Duration,
125    /// Host RSX view closure evaluation duration.
126    pub view_render: Duration,
127    /// Incremental layout-tree reconciliation duration.
128    pub reconcile: Duration,
129    /// Style cascade / hover subtree restyle duration.
130    pub style_cascade: Duration,
131    /// wgpu 3D command encoding and queue submission duration on CPU.
132    pub wgpu_3d_submit: Duration,
133    /// Hardware GPU timestamp query duration for 3D scene passes (microseconds; 0 when unavailable).
134    pub gpu_3d_us: u32,
135    /// Hardware GPU timestamp query duration for 2D overlay composite pass (microseconds; 0 when unavailable).
136    pub gpu_2d_overlay_us: u32,
137    /// Whether hardware `TIMESTAMP_QUERY` measurements populated `gpu_*_us`.
138    pub gpu_timestamps_valid: bool,
139}
140
141impl FrameProfile {
142    /// Sum of primary CPU phases (preserving non-overlapping accounting).
143    pub fn total(&self) -> Duration {
144        let tree_cost = if !self.rebuild.is_zero() {
145            self.rebuild
146        } else {
147            self.reconcile + self.style_cascade
148        };
149        self.input_dispatch
150            + self.signal_drain
151            + self.view_render
152            + tree_cost
153            + self.layout
154            + self.compile
155            + self.raster
156            + self.wgpu_3d_submit
157            + self.present
158    }
159}
160
161/// Complete per-frame telemetry snapshot exposed to host apps (e.g. F3 HUD) and MCP tools.
162#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
163pub struct FrameProfileRecord {
164    pub frame_index: u64,
165    pub timestamp_us: u64,
166    pub rebuild_reason: String,
167    pub outcome: String,
168    pub input_dispatch_us: u32,
169    pub signal_drain_us: u32,
170    pub view_render_us: u32,
171    pub reconcile_us: u32,
172    pub style_cascade_us: u32,
173    pub layout_us: u32,
174    pub display_list_build_us: u32,
175    pub raster_us: u32,
176    pub wgpu_3d_submit_us: u32,
177    pub present_us: u32,
178    pub total_cpu_us: u32,
179    pub gpu_3d_us: u32,
180    pub gpu_2d_overlay_us: u32,
181    pub gpu_timestamps_valid: bool,
182    pub dom_nodes: u32,
183    pub layout_nodes: u32,
184    pub display_cmds: u32,
185    pub tiles_dirty: u32,
186    pub tiles_total: u32,
187    pub tile_cache_hit_pct: f32,
188    pub reconciled_subtrees: u32,
189    pub rebuilt_nodes: u32,
190    pub full_rebuilds: u64,
191    pub reconciled: bool,
192    pub hover_fast_path_used: bool,
193    pub hover_fast_path_bailout: Option<String>,
194    pub reconcile_bailout: Option<String>,
195    pub scene3d_cache_hits: u64,
196    pub scene3d_cache_misses: u64,
197    pub scene3d_cache_hit_pct: f32,
198    pub glyph_atlas_hit_pct: f32,
199    pub gpu_memory_bytes: u64,
200    pub heap_alloc_count: u64,
201    pub heap_alloc_bytes: u64,
202    pub layout_shift_score: f32,
203}
204
205/// Rolling percentile distribution (in microseconds) over a ring buffer of frames.
206#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
207pub struct PerfPercentileStats {
208    pub p50_us: u32,
209    pub p95_us: u32,
210    pub p99_us: u32,
211    pub mean_us: f32,
212    pub max_us: u32,
213}
214
215impl PerfPercentileStats {
216    pub fn from_samples(mut values: Vec<u32>) -> Self {
217        if values.is_empty() {
218            return Self::default();
219        }
220        values.sort_unstable();
221        let n = values.len();
222        let sum: u64 = values.iter().map(|&v| v as u64).sum();
223        let pct = |p: f32| -> u32 {
224            let idx = (((n - 1) as f32) * p).round() as usize;
225            values[idx.min(n - 1)]
226        };
227        Self {
228            p50_us: pct(0.50),
229            p95_us: pct(0.95),
230            p99_us: pct(0.99),
231            mean_us: sum as f32 / n as f32,
232            max_us: *values.last().unwrap_or(&0),
233        }
234    }
235}
236
237/// Rolling performance summary across the active frame ring buffer (for host HUDs & CI gates).
238#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
239pub struct PerfProfileSummary {
240    pub window_frames: usize,
241    pub total_frames: u64,
242    pub last_frame: Option<FrameProfileRecord>,
243    pub total_cpu: PerfPercentileStats,
244    pub input_dispatch: PerfPercentileStats,
245    pub view_render: PerfPercentileStats,
246    pub reconcile: PerfPercentileStats,
247    pub style_cascade: PerfPercentileStats,
248    pub layout: PerfPercentileStats,
249    pub display_list: PerfPercentileStats,
250    pub raster: PerfPercentileStats,
251    pub wgpu_3d_submit: PerfPercentileStats,
252    pub gpu_3d: PerfPercentileStats,
253    pub gpu_2d_overlay: PerfPercentileStats,
254    pub present: PerfPercentileStats,
255    pub avg_tile_cache_hit_pct: f32,
256    pub avg_scene3d_cache_hit_pct: f32,
257    pub reconcile_hit_pct: f32,
258    pub full_rebuilds: u64,
259    pub reconciled_updates: u64,
260    pub gpu_memory_bytes: u64,
261    pub heap_alloc_bytes_peak: u64,
262}
263
264/// Bounded ring buffer of [`FrameProfileRecord`] snapshots.
265#[derive(Debug, Clone)]
266pub struct FrameProfileHistory {
267    records: VecDeque<FrameProfileRecord>,
268    capacity: usize,
269    heap_alloc_bytes_peak: u64,
270}
271
272impl Default for FrameProfileHistory {
273    fn default() -> Self {
274        Self::new(300)
275    }
276}
277
278impl FrameProfileHistory {
279    pub fn new(capacity: usize) -> Self {
280        let cap = capacity.max(1);
281        Self {
282            records: VecDeque::with_capacity(cap),
283            capacity: cap,
284            heap_alloc_bytes_peak: 0,
285        }
286    }
287
288    pub fn push(&mut self, record: FrameProfileRecord) {
289        self.heap_alloc_bytes_peak = self.heap_alloc_bytes_peak.max(record.heap_alloc_bytes);
290        if self.records.len() >= self.capacity {
291            self.records.pop_front();
292        }
293        self.records.push_back(record);
294    }
295
296    pub fn last(&self) -> Option<&FrameProfileRecord> {
297        self.records.back()
298    }
299
300    pub fn records(&self) -> &VecDeque<FrameProfileRecord> {
301        &self.records
302    }
303
304    pub fn summary(
305        &self,
306        total_frames: u64,
307        full_rebuilds: u64,
308        reconciled_updates: u64,
309    ) -> PerfProfileSummary {
310        let n = self.records.len();
311        let last_frame = self.records.back().cloned();
312        let tile_sum: f32 = self.records.iter().map(|r| r.tile_cache_hit_pct).sum();
313        let s3d_sum: f32 = self.records.iter().map(|r| r.scene3d_cache_hit_pct).sum();
314        let total_updates = full_rebuilds + reconciled_updates;
315        let reconcile_hit_pct = if total_updates > 0 {
316            (reconciled_updates as f32 / total_updates as f32) * 100.0
317        } else {
318            100.0
319        };
320        PerfProfileSummary {
321            window_frames: n,
322            total_frames,
323            gpu_memory_bytes: last_frame.as_ref().map_or(0, |r| r.gpu_memory_bytes),
324            last_frame,
325            total_cpu: PerfPercentileStats::from_samples(
326                self.records.iter().map(|r| r.total_cpu_us).collect(),
327            ),
328            input_dispatch: PerfPercentileStats::from_samples(
329                self.records.iter().map(|r| r.input_dispatch_us).collect(),
330            ),
331            view_render: PerfPercentileStats::from_samples(
332                self.records.iter().map(|r| r.view_render_us).collect(),
333            ),
334            reconcile: PerfPercentileStats::from_samples(
335                self.records.iter().map(|r| r.reconcile_us).collect(),
336            ),
337            style_cascade: PerfPercentileStats::from_samples(
338                self.records.iter().map(|r| r.style_cascade_us).collect(),
339            ),
340            layout: PerfPercentileStats::from_samples(
341                self.records.iter().map(|r| r.layout_us).collect(),
342            ),
343            display_list: PerfPercentileStats::from_samples(
344                self.records
345                    .iter()
346                    .map(|r| r.display_list_build_us)
347                    .collect(),
348            ),
349            raster: PerfPercentileStats::from_samples(
350                self.records.iter().map(|r| r.raster_us).collect(),
351            ),
352            wgpu_3d_submit: PerfPercentileStats::from_samples(
353                self.records.iter().map(|r| r.wgpu_3d_submit_us).collect(),
354            ),
355            gpu_3d: PerfPercentileStats::from_samples(
356                self.records.iter().map(|r| r.gpu_3d_us).collect(),
357            ),
358            gpu_2d_overlay: PerfPercentileStats::from_samples(
359                self.records.iter().map(|r| r.gpu_2d_overlay_us).collect(),
360            ),
361            present: PerfPercentileStats::from_samples(
362                self.records.iter().map(|r| r.present_us).collect(),
363            ),
364            avg_tile_cache_hit_pct: if n > 0 { tile_sum / n as f32 } else { 100.0 },
365            avg_scene3d_cache_hit_pct: if n > 0 { s3d_sum / n as f32 } else { 100.0 },
366            reconcile_hit_pct,
367            full_rebuilds,
368            reconciled_updates,
369            heap_alloc_bytes_peak: self.heap_alloc_bytes_peak,
370        }
371    }
372}
373
374/// Receives a completed [`FrameProfile`] each time a frame is presented.
375pub struct FrameProfileHook(pub Box<dyn FnMut(&FrameProfile)>);
376
377impl std::fmt::Debug for FrameProfileHook {
378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379        f.write_str("FrameProfileHook(..)")
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    #[test]
388    fn summary_computes_rolling_percentiles_for_all_stage_fields() {
389        let mut hist = FrameProfileHistory::new(16);
390        for &(inp, view, style, g2d) in &[
391            (100u32, 200u32, 50u32, 80u32),
392            (200, 400, 150, 160),
393            (400, 800, 350, 320),
394        ] {
395            hist.push(FrameProfileRecord {
396                input_dispatch_us: inp,
397                view_render_us: view,
398                style_cascade_us: style,
399                gpu_2d_overlay_us: g2d,
400                ..Default::default()
401            });
402        }
403        let s = hist.summary(3, 0, 3);
404        assert_eq!(s.input_dispatch.p50_us, 200);
405        assert_eq!(s.input_dispatch.p95_us, 400);
406        assert_eq!(s.input_dispatch.max_us, 400);
407        assert_eq!(s.view_render.p50_us, 400);
408        assert_eq!(s.view_render.max_us, 800);
409        assert_eq!(s.style_cascade.p50_us, 150);
410        assert_eq!(s.style_cascade.max_us, 350);
411        assert_eq!(s.gpu_2d_overlay.p50_us, 160);
412        assert_eq!(s.gpu_2d_overlay.max_us, 320);
413    }
414}