Skip to main content

glory_render/
profile.rs

1//! Opt-in, fixed-size inclusive phase measurements. No event/row/frame history.
2use std::cell::{Cell, RefCell};
3use std::rc::Rc;
4use std::time::Duration;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7#[repr(usize)]
8pub enum Phase {
9    Flush,
10    Validate,
11    Derive,
12    Structure,
13    Bind,
14    Effect,
15    Build,
16    Window,
17    Reconcile,
18    Patch,
19    Commit,
20    Observe,
21    Action,
22    Resources,
23    Layout,
24    Paint,
25    Draw,
26    Task,
27    Style,
28    Damage,
29    Construct,
30    PostConstruct,
31    BoxLayout,
32    Transform,
33    PaintTree,
34    LayoutCleanup,
35    Hover,
36    Subdocuments,
37    TextShape,
38    TextBreak,
39    TextAlign,
40}
41impl Phase {
42    pub const ALL: [Self; 31] = [
43        Self::Flush,
44        Self::Validate,
45        Self::Derive,
46        Self::Structure,
47        Self::Bind,
48        Self::Effect,
49        Self::Build,
50        Self::Window,
51        Self::Reconcile,
52        Self::Patch,
53        Self::Commit,
54        Self::Observe,
55        Self::Action,
56        Self::Resources,
57        Self::Layout,
58        Self::Paint,
59        Self::Draw,
60        Self::Task,
61        Self::Style,
62        Self::Damage,
63        Self::Construct,
64        Self::PostConstruct,
65        Self::BoxLayout,
66        Self::Transform,
67        Self::PaintTree,
68        Self::LayoutCleanup,
69        Self::Hover,
70        Self::Subdocuments,
71        Self::TextShape,
72        Self::TextBreak,
73        Self::TextAlign,
74    ];
75    pub const fn name(self) -> &'static str {
76        match self {
77            Self::Flush => "flush",
78            Self::Validate => "validate",
79            Self::Derive => "derive",
80            Self::Structure => "structure",
81            Self::Bind => "bind",
82            Self::Effect => "effect",
83            Self::Build => "build",
84            Self::Window => "window",
85            Self::Reconcile => "reconcile",
86            Self::Patch => "patch",
87            Self::Commit => "commit",
88            Self::Observe => "observe",
89            Self::Action => "action",
90            Self::Resources => "resources",
91            Self::Layout => "layout",
92            Self::Paint => "paint",
93            Self::Draw => "draw",
94            Self::Task => "task",
95            Self::Style => "style",
96            Self::Damage => "damage",
97            Self::Construct => "construct",
98            Self::PostConstruct => "post_construct",
99            Self::BoxLayout => "box_layout",
100            Self::Transform => "transform",
101            Self::PaintTree => "paint_tree",
102            Self::LayoutCleanup => "layout_cleanup",
103            Self::Hover => "hover",
104            Self::Subdocuments => "subdocuments",
105            Self::TextShape => "text_shape",
106            Self::TextBreak => "text_break",
107            Self::TextAlign => "text_align",
108        }
109    }
110}
111#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
112pub struct Sample {
113    /// Attempts, including operations ending in an error or unwind.
114    pub calls: u64,
115    /// Call-site work units: dependency edges, keys, mutations, or 1 per call.
116    pub units: u64,
117    /// Includes nested phases; never add phase totals to estimate frame time.
118    pub elapsed: Duration,
119    pub max: Duration,
120    pub invalid_clock: u64,
121}
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub struct Snapshot([Sample; Phase::ALL.len()]);
124impl Snapshot {
125    pub fn sample(&self, phase: Phase) -> Sample {
126        self.0[phase as usize]
127    }
128    pub fn iter(&self) -> impl Iterator<Item = (Phase, Sample)> + '_ {
129        Phase::ALL
130            .into_iter()
131            .map(|phase| (phase, self.sample(phase)))
132    }
133}
134struct Inner {
135    clock: Box<dyn Fn() -> Duration>,
136    epoch: Cell<u64>,
137    samples: RefCell<Snapshot>,
138}
139/// Clones share one local collector. Construct a separate Profile per app or
140/// experiment. Clock must be lightweight/monotonic and must not reenter UI or
141/// graph work. The collector never calls it while borrowing its own samples.
142/// Attaching None disables instrumentation and all clock reads at call sites.
143#[derive(Clone)]
144pub struct Profile(Rc<Inner>);
145impl Profile {
146    pub fn new(clock: impl Fn() -> Duration + 'static) -> Self {
147        Self(Rc::new(Inner {
148            clock: Box::new(clock),
149            epoch: Cell::new(0),
150            samples: RefCell::new(Snapshot::default()),
151        }))
152    }
153    #[cfg(not(target_arch = "wasm32"))]
154    pub fn native() -> Self {
155        let start = std::time::Instant::now();
156        Self::new(move || start.elapsed())
157    }
158    pub fn snapshot(&self) -> Snapshot {
159        *self.0.samples.borrow()
160    }
161    /// Reset counters and retire all in-flight spans. Refuse epoch exhaustion
162    /// rather than charging an ancient span to a new measurement interval.
163    pub fn reset(&self) -> bool {
164        let Some(epoch) = self.0.epoch.get().checked_add(1) else {
165            return false;
166        };
167        self.0.epoch.set(epoch);
168        *self.0.samples.borrow_mut() = Snapshot::default();
169        true
170    }
171    pub fn span(&self, phase: Phase) -> Span {
172        let start = (self.0.clock)();
173        Span {
174            profile: self.clone(),
175            epoch: self.0.epoch.get(),
176            phase,
177            start,
178            units: 1,
179        }
180    }
181    /// Capture this interval without reading its clock. Native engines may
182    /// measure on worker threads with their own monotonic clock and import
183    /// fixed aggregates on the UI thread after joining that work. Reset retires
184    /// these recordings just like spans; the collector remains local.
185    pub fn recording(&self) -> Recording {
186        Recording {
187            profile: self.clone(),
188            epoch: self.0.epoch.get(),
189        }
190    }
191}
192#[derive(Clone)]
193pub struct Recording {
194    profile: Profile,
195    epoch: u64,
196}
197impl Recording {
198    /// Merge a validated external aggregate, not a timestamp or a phase total
199    /// derived by subtracting unrelated phases. Reject retired intervals and
200    /// impossible counter shapes without changing samples or reading a clock.
201    pub fn record(&self, phase: Phase, sample: Sample) -> bool {
202        if self.epoch != self.profile.0.epoch.get()
203            || sample.max > sample.elapsed
204            || sample.invalid_clock > sample.calls
205            || sample.calls == 0 && sample != Sample::default()
206        {
207            return false;
208        }
209        let mut snapshot = self.profile.0.samples.borrow_mut();
210        let destination = &mut snapshot.0[phase as usize];
211        destination.calls = destination.calls.saturating_add(sample.calls);
212        destination.units = destination.units.saturating_add(sample.units);
213        destination.elapsed = destination.elapsed.saturating_add(sample.elapsed);
214        destination.max = destination.max.max(sample.max);
215        destination.invalid_clock = destination
216            .invalid_clock
217            .saturating_add(sample.invalid_clock);
218        true
219    }
220}
221#[must_use]
222pub struct Span {
223    profile: Profile,
224    epoch: u64,
225    phase: Phase,
226    start: Duration,
227    units: u64,
228}
229impl Span {
230    pub fn set_work(&mut self, units: u64) {
231        self.units = units;
232    }
233    pub fn work(mut self, units: u64) -> Self {
234        self.units = units;
235        self
236    }
237}
238impl Drop for Span {
239    fn drop(&mut self) {
240        if self.epoch != self.profile.0.epoch.get() {
241            return;
242        }
243        let end = (self.profile.0.clock)();
244        if self.epoch != self.profile.0.epoch.get() {
245            return;
246        }
247        let mut snapshot = self.profile.0.samples.borrow_mut();
248        let sample = &mut snapshot.0[self.phase as usize];
249        sample.calls = sample.calls.saturating_add(1);
250        sample.units = sample.units.saturating_add(self.units);
251        if let Some(elapsed) = end.checked_sub(self.start) {
252            sample.elapsed = sample.elapsed.saturating_add(elapsed);
253            sample.max = sample.max.max(elapsed);
254        } else {
255            sample.invalid_clock = sample.invalid_clock.saturating_add(1);
256        }
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    fn clock() -> (Profile, Rc<Cell<u64>>) {
264        let time = Rc::new(Cell::new(0));
265        let value = time.clone();
266        (
267            Profile::new(move || Duration::from_nanos(value.get())),
268            time,
269        )
270    }
271    #[test]
272    fn nested_totals_are_inclusive_and_reset_retires_live_spans() {
273        let (profile, time) = clock();
274        let outer = profile.span(Phase::Flush);
275        time.set(10);
276        let inner = profile.span(Phase::Bind).work(3);
277        time.set(15);
278        drop(inner);
279        time.set(20);
280        drop(outer);
281        assert_eq!(
282            profile.snapshot().sample(Phase::Flush).elapsed,
283            Duration::from_nanos(20)
284        );
285        assert_eq!(profile.snapshot().sample(Phase::Bind).units, 3);
286        assert_eq!(
287            profile.snapshot().sample(Phase::Bind).elapsed,
288            Duration::from_nanos(5)
289        );
290        let old = profile.span(Phase::Draw);
291        assert!(profile.reset());
292        time.set(50);
293        drop(old);
294        assert_eq!(profile.snapshot(), Snapshot::default());
295    }
296    #[test]
297    fn regressing_clock_is_reported_and_unwind_releases_span() {
298        let (profile, time) = clock();
299        time.set(10);
300        let span = profile.span(Phase::Patch);
301        time.set(0);
302        drop(span);
303        let sample = profile.snapshot().sample(Phase::Patch);
304        assert_eq!((sample.calls, sample.invalid_clock), (1, 1));
305        assert_eq!(sample.elapsed, Duration::ZERO);
306        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
307            let _span = profile.span(Phase::Build);
308            panic!("fixture")
309        }));
310        assert_eq!(profile.snapshot().sample(Phase::Build).calls, 1);
311    }
312    #[test]
313    fn external_aggregates_merge_without_clock_reads_and_reset_retires_recordings() {
314        let reads = Rc::new(Cell::new(0));
315        let called = reads.clone();
316        let profile = Profile::new(move || {
317            called.set(called.get() + 1);
318            Duration::ZERO
319        });
320        let recording = profile.recording();
321        let sample = Sample {
322            calls: 2,
323            units: 7,
324            elapsed: Duration::from_nanos(10),
325            max: Duration::from_nanos(6),
326            invalid_clock: 0,
327        };
328        assert!(recording.record(Phase::TextShape, sample));
329        assert!(recording.record(Phase::TextShape, sample));
330        let value = profile.snapshot().sample(Phase::TextShape);
331        assert_eq!(
332            (value.calls, value.units, value.elapsed, value.max),
333            (4, 14, Duration::from_nanos(20), Duration::from_nanos(6))
334        );
335        assert!(profile.reset());
336        assert!(!recording.record(Phase::TextShape, sample));
337        assert_eq!(profile.snapshot(), Snapshot::default());
338        assert_eq!(reads.get(), 0);
339    }
340    #[test]
341    fn impossible_external_samples_do_not_change_the_collector() {
342        let (profile, _) = clock();
343        let recording = profile.recording();
344        for sample in [
345            Sample {
346                units: 1,
347                ..Sample::default()
348            },
349            Sample {
350                calls: 1,
351                max: Duration::from_nanos(2),
352                elapsed: Duration::from_nanos(1),
353                ..Sample::default()
354            },
355            Sample {
356                calls: 1,
357                invalid_clock: 2,
358                ..Sample::default()
359            },
360        ] {
361            assert!(!recording.record(Phase::Style, sample));
362            assert_eq!(profile.snapshot(), Snapshot::default());
363        }
364        assert!(recording.record(Phase::Style, Sample::default()));
365    }
366}