Skip to main content

tilo_actions/
profiling.rs

1//! Bounded observations of named scopes in the real code on this thread.
2//!
3//! Resource publication, the app framework and apps mark their scopes with
4//! [`Phase::start`] or [`measure`]; a test wraps an interaction in
5//! [`observe`] and reads every scope that ran, aggregated by name. Scopes may
6//! nest, so their durations are not additive. Without an active observation a
7//! scope reads no clock: one thread-local read.
8//!
9//! A running app observes the same scopes across one key's journey, from the
10//! key to the frame answering it ([`begin_live`], [`take_live`]): the
11//! window's `INPUT-FRAME` record (`ui_core::input_frame`) names the work a
12//! keystroke did, in production builds.
13
14#[cfg(not(target_arch = "wasm32"))]
15pub use recorder::{Phase, Sample, begin_live, observe, take_live, unobserved};
16
17/// A named scope; the web build records none.
18#[cfg(target_arch = "wasm32")]
19pub struct Phase;
20
21#[cfg(target_arch = "wasm32")]
22impl Phase {
23    /// Open the scope `_name`; it closes when the value drops.
24    #[inline]
25    #[must_use]
26    pub const fn start(_name: &'static str) -> Self {
27        Self
28    }
29
30    /// Close the scope here, before the end of its block.
31    #[inline]
32    #[allow(
33        clippy::missing_const_for_fn,
34        reason = "const would stop compiling the moment this Phase gains a destructor, as the recorder's has"
35    )]
36    pub fn end(self) {
37        let Self = self;
38    }
39}
40
41/// Run `operation` without recording its scopes in an active observation:
42/// work a debug build does only to verify the production path (re-running
43/// what that path proved it could skip) is not the path an observation
44/// measures.
45#[cfg(target_arch = "wasm32")]
46#[inline]
47pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
48    operation()
49}
50
51/// One named scope's total over an observation; the web build records none.
52#[cfg(target_arch = "wasm32")]
53#[derive(Debug)]
54pub struct Sample {
55    /// Static operation name.
56    pub phase: &'static str,
57    /// Aggregate duration of the scope, nested and nonadditive.
58    pub elapsed_ns: u128,
59    /// Completed scopes on the observed thread.
60    pub calls: usize,
61}
62
63/// Run `operation`; the web build records no scope, so what it observed is
64/// empty.
65#[cfg(target_arch = "wasm32")]
66#[inline]
67pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
68    (operation(), Vec::new())
69}
70
71/// Start observing this thread's scopes until [`take_live`]; the web build
72/// records none, so it never starts one.
73#[cfg(target_arch = "wasm32")]
74#[inline]
75pub const fn begin_live() -> bool {
76    false
77}
78
79/// What this thread's scopes did since [`begin_live`]; the web build
80/// records none.
81#[cfg(target_arch = "wasm32")]
82#[inline]
83pub fn take_live() -> Vec<Sample> {
84    Vec::new()
85}
86
87/// Run `operation` as the scope `phase`.
88#[inline]
89pub fn measure<T>(phase: &'static str, operation: impl FnOnce() -> T) -> T {
90    let _scope = Phase::start(phase);
91    operation()
92}
93
94#[cfg(not(target_arch = "wasm32"))]
95mod recorder {
96    use std::cell::RefCell;
97    use tilo_clock::time::Instant;
98
99    thread_local! {
100        static RECORDS: RefCell<Option<Capture>> = const { RefCell::new(None) };
101    }
102
103    /// Distinct scope names one observation keeps.
104    pub(super) const MAX_PHASES: usize = 64;
105
106    #[derive(Default)]
107    struct Capture {
108        rows: Vec<Sample>,
109        overflow: bool,
110    }
111
112    /// Repeated scopes aggregate by name, with exact counts and bounded memory.
113    /// These nested durations must not be added to their enclosing scope.
114    #[derive(Debug, serde::Serialize)]
115    pub struct Sample {
116        /// Static operation name; no resource identities or document values.
117        pub phase: &'static str,
118        /// Aggregate duration of this actual scope, nested and nonadditive.
119        pub elapsed_ns: u128,
120        /// Exact number of completed scopes on the observed thread.
121        pub calls: usize,
122    }
123
124    /// A named scope, recorded when it drops inside an active observation.
125    #[must_use]
126    pub struct Phase(Option<(&'static str, Instant)>);
127
128    impl Phase {
129        /// Open the scope `name`; it closes when the value drops.
130        pub fn start(name: &'static str) -> Self {
131            Self(
132                RECORDS
133                    .with(|records| records.borrow().as_ref().map(|_| (name, tilo_clock::now()))),
134            )
135        }
136
137        /// Close the scope here, before the end of its block.
138        pub fn end(self) {
139            drop(self);
140        }
141    }
142
143    impl Drop for Phase {
144        fn drop(&mut self) {
145            let Some((name, start)) = self.0 else {
146                return;
147            };
148            RECORDS.with(|records| {
149                let mut records = records.borrow_mut();
150                let Some(capture) = records.as_mut() else {
151                    return;
152                };
153                let elapsed_ns = tilo_clock::now().duration_since(start).as_nanos();
154                if let Some(row) = capture.rows.iter_mut().find(|row| row.phase == name) {
155                    match (
156                        row.elapsed_ns.checked_add(elapsed_ns),
157                        row.calls.checked_add(1),
158                    ) {
159                        (Some(elapsed), Some(calls)) => {
160                            row.elapsed_ns = elapsed;
161                            row.calls = calls;
162                        }
163                        _ => capture.overflow = true,
164                    }
165                } else if capture.rows.len() < MAX_PHASES {
166                    capture.rows.push(Sample {
167                        phase: name,
168                        elapsed_ns,
169                        calls: 1,
170                    });
171                } else {
172                    capture.overflow = true;
173                }
174            });
175        }
176    }
177
178    struct Recording;
179
180    impl Drop for Recording {
181        fn drop(&mut self) {
182            RECORDS.with(|records| *records.borrow_mut() = None);
183        }
184    }
185
186    /// Run `operation` with the active observation, if any, set aside: its
187    /// scopes are not recorded, and the observation resumes afterwards.
188    pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
189        struct Resume(Option<Capture>);
190        impl Drop for Resume {
191            fn drop(&mut self) {
192                let capture = self.0.take();
193                RECORDS.with(|records| *records.borrow_mut() = capture);
194            }
195        }
196        let _resume = Resume(RECORDS.with(RefCell::take));
197        operation()
198    }
199
200    /// Start observing this thread's scopes, across events and frames,
201    /// until [`take_live`]: a running app's record of one key's journey, or
202    /// of one slow event. An observation already active (a test's, another
203    /// record's) is left as it is. Answers whether this call started one,
204    /// so only its starter takes it.
205    pub fn begin_live() -> bool {
206        RECORDS.with(|records| {
207            let mut records = records.borrow_mut();
208            if records.is_some() {
209                return false;
210            }
211            *records = Some(Capture::default());
212            true
213        })
214    }
215
216    /// Every scope that ran since [`begin_live`], by name, ending the
217    /// observation. Past [`MAX_PHASES`] names the rest are left out.
218    pub fn take_live() -> Vec<Sample> {
219        RECORDS
220            .with(RefCell::take)
221            .map(|capture| capture.rows)
222            .unwrap_or_default()
223    }
224
225    /// Run the real operation and return every scope it ran, by name.
226    pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
227        RECORDS.with(|records| {
228            let mut records = records.borrow_mut();
229            assert!(records.is_none(), "a phase observation is already active");
230            *records = Some(Capture::default());
231        });
232        let recording = Recording;
233        let result = operation();
234        let captured = RECORDS.with(RefCell::take);
235        assert!(captured.is_some(), "phase observation lost its recorder");
236        let capture = captured.unwrap_or_default();
237        drop(recording);
238        assert!(!capture.overflow, "phase observation exceeded its bound");
239        (result, capture.rows)
240    }
241}
242
243#[cfg(all(test, not(target_arch = "wasm32")))]
244mod tests {
245    use super::recorder::MAX_PHASES;
246    use super::{Phase, begin_live, measure, observe, take_live, unobserved};
247
248    tilo_test_env::scenario! {
249        fn an_observation_records_the_scopes_that_run_inside_it;
250
251        phase recording_is_opt_in_and_aggregates_nested_scopes_by_name;
252        {
253            drop(Phase::start("unobserved"));
254            let (value, samples) = observe(|| {
255                let _outer = Phase::start("outer");
256                drop(Phase::start("inner"));
257                measure("inner", || 42)
258            });
259            assert_eq!(value, 42);
260            let calls: Vec<_> = samples
261                .iter()
262                .map(|sample| (sample.phase, sample.calls))
263                .collect();
264            assert_eq!(calls, [("inner", 2), ("outer", 1)]);
265            assert!(observe(|| ()).1.is_empty());
266        }
267
268        phase unobserved_scopes_are_left_out_and_the_observation_resumes;
269        {
270            let ((), samples) = observe(|| {
271                drop(Phase::start("before"));
272                unobserved(|| measure("hidden", || ()));
273                drop(Phase::start("after"));
274            });
275            let names: Vec<_> = samples.iter().map(|sample| sample.phase).collect();
276            assert_eq!(names, ["before", "after"]);
277            // Outside an observation it records nothing and leaves none behind.
278            unobserved(|| drop(Phase::start("alone")));
279            assert!(observe(|| ()).1.is_empty());
280        }
281
282        phase a_live_observation_spans_calls_until_taken;
283        {
284            drop(Phase::start("before"));
285            begin_live();
286            drop(Phase::start("key"));
287            measure("frame", || drop(Phase::start("key")));
288            let calls: Vec<_> = take_live()
289                .iter()
290                .map(|sample| (sample.phase, sample.calls))
291                .collect();
292            assert_eq!(calls, [("key", 2), ("frame", 1)]);
293            assert!(take_live().is_empty(), "taking it ended it");
294            assert!(observe(|| ()).1.is_empty());
295        }
296    }
297
298    #[test]
299    fn recording_recovers_after_a_nested_observation_panics() {
300        let result = std::panic::catch_unwind(|| observe(|| observe(|| ())));
301        assert!(result.is_err());
302        assert!(observe(|| ()).1.is_empty());
303    }
304
305    #[test]
306    fn recording_refuses_incomplete_coverage_and_retires_its_recorder() {
307        let result = std::panic::catch_unwind(|| {
308            observe(|| {
309                for index in 0..=MAX_PHASES {
310                    let name: &'static str = Box::leak(format!("phase-{index}").into_boxed_str());
311                    drop(Phase::start(name));
312                }
313            })
314        });
315        assert!(result.is_err());
316        assert!(observe(|| ()).1.is_empty());
317    }
318}