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
//! Bounded observations of named scopes in the real code on this thread.
//!
//! Resource publication, the app framework and apps mark their scopes with
//! [`Phase::start`] or [`measure`]; a test wraps an interaction in
//! [`observe`] and reads every scope that ran, aggregated by name. Scopes may
//! nest, so their durations are not additive. Without an active observation a
//! scope reads no clock: one thread-local read.
//!
//! A running app observes the same scopes across one key's journey, from the
//! key to the frame answering it ([`begin_live`], [`take_live`]): the
//! window's `INPUT-FRAME` record (`ui_core::input_frame`) names the work a
//! keystroke did, in production builds.
#[cfg(not(target_arch = "wasm32"))]
pub use recorder::{Phase, Sample, begin_live, observe, take_live, unobserved};
/// A named scope; the web build records none.
#[cfg(target_arch = "wasm32")]
pub struct Phase;
#[cfg(target_arch = "wasm32")]
impl Phase {
/// Open the scope `_name`; it closes when the value drops.
#[inline]
#[must_use]
pub const fn start(_name: &'static str) -> Self {
Self
}
/// Close the scope here, before the end of its block.
#[inline]
#[allow(
clippy::missing_const_for_fn,
reason = "const would stop compiling the moment this Phase gains a destructor, as the recorder's has"
)]
pub fn end(self) {
let Self = self;
}
}
/// Run `operation` without recording its scopes in an active observation:
/// work a debug build does only to verify the production path (re-running
/// what that path proved it could skip) is not the path an observation
/// measures.
#[cfg(target_arch = "wasm32")]
#[inline]
pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
operation()
}
/// One named scope's total over an observation; the web build records none.
#[cfg(target_arch = "wasm32")]
#[derive(Debug)]
pub struct Sample {
/// Static operation name.
pub phase: &'static str,
/// Aggregate duration of the scope, nested and nonadditive.
pub elapsed_ns: u128,
/// Completed scopes on the observed thread.
pub calls: usize,
}
/// Run `operation`; the web build records no scope, so what it observed is
/// empty.
#[cfg(target_arch = "wasm32")]
#[inline]
pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
(operation(), Vec::new())
}
/// Start observing this thread's scopes until [`take_live`]; the web build
/// records none, so it never starts one.
#[cfg(target_arch = "wasm32")]
#[inline]
pub const fn begin_live() -> bool {
false
}
/// What this thread's scopes did since [`begin_live`]; the web build
/// records none.
#[cfg(target_arch = "wasm32")]
#[inline]
pub fn take_live() -> Vec<Sample> {
Vec::new()
}
/// Run `operation` as the scope `phase`.
#[inline]
pub fn measure<T>(phase: &'static str, operation: impl FnOnce() -> T) -> T {
let _scope = Phase::start(phase);
operation()
}
#[cfg(not(target_arch = "wasm32"))]
mod recorder {
use std::cell::RefCell;
use tilo_clock::time::Instant;
thread_local! {
static RECORDS: RefCell<Option<Capture>> = const { RefCell::new(None) };
}
/// Distinct scope names one observation keeps.
pub(super) const MAX_PHASES: usize = 64;
#[derive(Default)]
struct Capture {
rows: Vec<Sample>,
overflow: bool,
}
/// Repeated scopes aggregate by name, with exact counts and bounded memory.
/// These nested durations must not be added to their enclosing scope.
#[derive(Debug, serde::Serialize)]
pub struct Sample {
/// Static operation name; no resource identities or document values.
pub phase: &'static str,
/// Aggregate duration of this actual scope, nested and nonadditive.
pub elapsed_ns: u128,
/// Exact number of completed scopes on the observed thread.
pub calls: usize,
}
/// A named scope, recorded when it drops inside an active observation.
#[must_use]
pub struct Phase(Option<(&'static str, Instant)>);
impl Phase {
/// Open the scope `name`; it closes when the value drops.
pub fn start(name: &'static str) -> Self {
Self(
RECORDS
.with(|records| records.borrow().as_ref().map(|_| (name, tilo_clock::now()))),
)
}
/// Close the scope here, before the end of its block.
pub fn end(self) {
drop(self);
}
}
impl Drop for Phase {
fn drop(&mut self) {
let Some((name, start)) = self.0 else {
return;
};
RECORDS.with(|records| {
let mut records = records.borrow_mut();
let Some(capture) = records.as_mut() else {
return;
};
let elapsed_ns = tilo_clock::now().duration_since(start).as_nanos();
if let Some(row) = capture.rows.iter_mut().find(|row| row.phase == name) {
match (
row.elapsed_ns.checked_add(elapsed_ns),
row.calls.checked_add(1),
) {
(Some(elapsed), Some(calls)) => {
row.elapsed_ns = elapsed;
row.calls = calls;
}
_ => capture.overflow = true,
}
} else if capture.rows.len() < MAX_PHASES {
capture.rows.push(Sample {
phase: name,
elapsed_ns,
calls: 1,
});
} else {
capture.overflow = true;
}
});
}
}
struct Recording;
impl Drop for Recording {
fn drop(&mut self) {
RECORDS.with(|records| *records.borrow_mut() = None);
}
}
/// Run `operation` with the active observation, if any, set aside: its
/// scopes are not recorded, and the observation resumes afterwards.
pub fn unobserved<T>(operation: impl FnOnce() -> T) -> T {
struct Resume(Option<Capture>);
impl Drop for Resume {
fn drop(&mut self) {
let capture = self.0.take();
RECORDS.with(|records| *records.borrow_mut() = capture);
}
}
let _resume = Resume(RECORDS.with(RefCell::take));
operation()
}
/// Start observing this thread's scopes, across events and frames,
/// until [`take_live`]: a running app's record of one key's journey, or
/// of one slow event. An observation already active (a test's, another
/// record's) is left as it is. Answers whether this call started one,
/// so only its starter takes it.
pub fn begin_live() -> bool {
RECORDS.with(|records| {
let mut records = records.borrow_mut();
if records.is_some() {
return false;
}
*records = Some(Capture::default());
true
})
}
/// Every scope that ran since [`begin_live`], by name, ending the
/// observation. Past [`MAX_PHASES`] names the rest are left out.
pub fn take_live() -> Vec<Sample> {
RECORDS
.with(RefCell::take)
.map(|capture| capture.rows)
.unwrap_or_default()
}
/// Run the real operation and return every scope it ran, by name.
pub fn observe<T>(operation: impl FnOnce() -> T) -> (T, Vec<Sample>) {
RECORDS.with(|records| {
let mut records = records.borrow_mut();
assert!(records.is_none(), "a phase observation is already active");
*records = Some(Capture::default());
});
let recording = Recording;
let result = operation();
let captured = RECORDS.with(RefCell::take);
assert!(captured.is_some(), "phase observation lost its recorder");
let capture = captured.unwrap_or_default();
drop(recording);
assert!(!capture.overflow, "phase observation exceeded its bound");
(result, capture.rows)
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::recorder::MAX_PHASES;
use super::{Phase, begin_live, measure, observe, take_live, unobserved};
tilo_test_env::scenario! {
fn an_observation_records_the_scopes_that_run_inside_it;
phase recording_is_opt_in_and_aggregates_nested_scopes_by_name;
{
drop(Phase::start("unobserved"));
let (value, samples) = observe(|| {
let _outer = Phase::start("outer");
drop(Phase::start("inner"));
measure("inner", || 42)
});
assert_eq!(value, 42);
let calls: Vec<_> = samples
.iter()
.map(|sample| (sample.phase, sample.calls))
.collect();
assert_eq!(calls, [("inner", 2), ("outer", 1)]);
assert!(observe(|| ()).1.is_empty());
}
phase unobserved_scopes_are_left_out_and_the_observation_resumes;
{
let ((), samples) = observe(|| {
drop(Phase::start("before"));
unobserved(|| measure("hidden", || ()));
drop(Phase::start("after"));
});
let names: Vec<_> = samples.iter().map(|sample| sample.phase).collect();
assert_eq!(names, ["before", "after"]);
// Outside an observation it records nothing and leaves none behind.
unobserved(|| drop(Phase::start("alone")));
assert!(observe(|| ()).1.is_empty());
}
phase a_live_observation_spans_calls_until_taken;
{
drop(Phase::start("before"));
begin_live();
drop(Phase::start("key"));
measure("frame", || drop(Phase::start("key")));
let calls: Vec<_> = take_live()
.iter()
.map(|sample| (sample.phase, sample.calls))
.collect();
assert_eq!(calls, [("key", 2), ("frame", 1)]);
assert!(take_live().is_empty(), "taking it ended it");
assert!(observe(|| ()).1.is_empty());
}
}
#[test]
fn recording_recovers_after_a_nested_observation_panics() {
let result = std::panic::catch_unwind(|| observe(|| observe(|| ())));
assert!(result.is_err());
assert!(observe(|| ()).1.is_empty());
}
#[test]
fn recording_refuses_incomplete_coverage_and_retires_its_recorder() {
let result = std::panic::catch_unwind(|| {
observe(|| {
for index in 0..=MAX_PHASES {
let name: &'static str = Box::leak(format!("phase-{index}").into_boxed_str());
drop(Phase::start(name));
}
})
});
assert!(result.is_err());
assert!(observe(|| ()).1.is_empty());
}
}