ailloli_ui_bench/
lib.rs

1//! Versioned JSONL performance recorder for Ailloli UI.
2//!
3//! New integrations should retain the [`BenchInit`] returned by
4//! [`try_init_from_env`] and call [`BenchInit::finish`] before shutdown. The
5//! session writes to a staging file through a bounded queue and publishes the
6//! final artifact only after a successful flush and sync.
7//!
8//! [`record`] and [`metric`] remain global conveniences. [`init_from_env`] is a
9//! deprecated, append-only compatibility path and must not be used for a
10//! regression gate.
11//!
12//! # Command-line gate
13//!
14//! The `ailloli-ui-bench` binary is intentionally opt-in. Every Cargo command
15//! which uses it must enable the `cli` feature explicitly, for example:
16//!
17//! ```text
18//! cargo run --release -p ailloli_ui_bench --features cli \
19//!   --bin ailloli-ui-bench --locked -- summarize --input <scenario-directory>
20//! ```
21//!
22//! A canonical native matrix first builds the measured child, then gives that
23//! executable to the CLI after `--`:
24//!
25//! ```text
26//! cargo build --release --locked -p ailloli_ui_winit \
27//!   --features test_support --example winit_regression_bench
28//! cargo run --release --locked -p ailloli_ui_bench --features cli \
29//!   --bin ailloli-ui-bench -- run-matrix \
30//!   --output-root artifacts/bench/winit_host_architecture --phase candidate \
31//!   --winit-version 0.30.13 --backend wayland --profile release \
32//!   --harness winit_regression_bench --scenario wake_single \
33//!   -- target/release/examples/winit_regression_bench
34//! ```
35//!
36//! Compare one exact backend/scenario pair at a time. `run-matrix` writes a
37//! `matrix-index.json` beside each scenario's replicates; `summarize` and
38//! `compare` validate that index and every recorded SHA-256 when it is present.
39//!
40//! ```text
41//! cargo run --release --locked -p ailloli_ui_bench --features cli \
42//!   --bin ailloli-ui-bench -- compare \
43//!   --baseline artifacts/bench/winit_host_architecture/baseline/winit-0.30.13/wayland/wake_single \
44//!   --candidate artifacts/bench/winit_host_architecture/candidate/winit-0.30.13/wayland/wake_single
45//! ```
46//!
47//! The only compatibility field which can be waived is `winit_version`, via an
48//! explicit `compare --allow-winit-version-diff`; schema, scenario, profile,
49//! geometry, requested/observed DPR and environment identity remain exact.
50//!
51//! There is no valid legacy pre-architecture wake/mailbox baseline: that path did not
52//! exist before the refactor. Its historical value is therefore **N/A**, not a
53//! synthetic measurement. The matrix index exposes this status explicitly.
54
55mod log;
56mod model;
57mod process;
58mod session;
59mod stats;
60
61use std::num::NonZeroUsize;
62use std::path::PathBuf;
63use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
64
65pub use log::{collect_run_files, read_run, BenchReadError, LogRecord, MetricSample, ParsedRun};
66pub use model::{
67    BenchEventRecord, BenchSurfaceId, BenchWindowId, Event, EventContext, EventId, FrameId,
68    MetadataUpdateRecord, MetricRole, RunEndRecord, RunId, RunMetadata, RunStartRecord,
69    SamplePhase, TimeOrigin, SCHEMA_VERSION,
70};
71pub use process::{
72    sample_current_process, sample_process, ProcessResourceSnapshot, ProcessSampleError,
73};
74pub use session::{
75    BenchInit, BenchInitError, BenchSession, BenchWriteError, CompletedRun, Recorder,
76};
77pub use stats::{
78    compare_metric, compare_metric_with_role, summarize_memory_trend, summarize_runs,
79    summarize_runs_with_roles, summarize_samples, theil_sen_slope, ComparisonMode,
80    MemoryTrendSummary, MetricComparison, MetricSummary, SampleSummary, StatsError,
81    MAX_RSS_EXTENT_MIB, MAX_RSS_SLOPE_MIB_PER_SEC,
82};
83
84/// Default number of pending records accepted by the nonblocking writer queue.
85const DEFAULT_QUEUE_CAPACITY: usize = 4096;
86
87/// Reads a primary, legacy, then historical environment variable.
88///
89/// A present non-Unicode higher-priority value disables fallback and maps to
90/// `None`; an empty Unicode string remains a present value for the caller to
91/// validate.
92fn env_value(primary: &str, legacy: &str, historical: &str) -> Option<String> {
93    match std::env::var(primary) {
94        Ok(value) => Some(value),
95        Err(std::env::VarError::NotUnicode(_)) => None,
96        Err(std::env::VarError::NotPresent) => match std::env::var(legacy) {
97            Ok(value) => Some(value),
98            Err(std::env::VarError::NotUnicode(_)) => None,
99            Err(std::env::VarError::NotPresent) => std::env::var(historical).ok(),
100        },
101    }
102}
103
104/// Whether benchmark recording is enabled through the environment.
105///
106/// Primary `AILLOLI_UI_BENCH` takes precedence over `OCTAVUI_BENCH`, then
107/// `UI_BENCH`. Only `1` and case-insensitive `true` enable recording; whitespace
108/// is not trimmed.
109///
110/// # Examples
111///
112/// ```
113/// let enabled: bool = ailloli_ui_bench::bench_enabled();
114/// let _ = enabled;
115/// ```
116pub fn bench_enabled() -> bool {
117    env_value("AILLOLI_UI_BENCH", "OCTAVUI_BENCH", "UI_BENCH")
118        .is_some_and(|value| value == "1" || value.eq_ignore_ascii_case("true"))
119}
120
121/// Initializes a gating benchmark session from environment variables.
122///
123/// Disabled collection is not an error. When enabled, the returned session
124/// must remain alive for the application run and must be explicitly finished
125/// so write, flush, sync, and publication errors remain observable.
126///
127/// The queue capacity comes from the modern/legacy/historical capacity variable;
128/// invalid or zero values fall back to 4096. `default_path` is used only when
129/// no nonempty path override exists.
130///
131/// # Errors
132///
133/// Propagates session path, metadata, writer startup, and global-install errors
134/// when collection is enabled.
135///
136/// # Panics
137///
138/// Panics only if the fixed fallback queue-capacity constant is changed to zero.
139///
140/// # Examples
141///
142/// ```no_run
143/// use ailloli_ui_bench::try_init_from_env;
144/// fn init() -> Result<(), Box<dyn std::error::Error>> {
145///     let init = try_init_from_env("artifacts/bench/run.jsonl")?;
146///     let _completed = init.finish()?;
147///     Ok(())
148/// }
149/// ```
150pub fn try_init_from_env(default_path: &str) -> Result<BenchInit, BenchInitError> {
151    if !bench_enabled() {
152        return Ok(BenchInit::Disabled);
153    }
154
155    let path = configured_path(default_path);
156    let capacity = env_value(
157        "AILLOLI_UI_BENCH_QUEUE_CAPACITY",
158        "OCTAVUI_BENCH_QUEUE_CAPACITY",
159        "BENCH_QUEUE_CAPACITY",
160    )
161    .and_then(|value| value.trim().parse::<usize>().ok())
162    .and_then(NonZeroUsize::new)
163    .unwrap_or_else(|| NonZeroUsize::new(DEFAULT_QUEUE_CAPACITY).expect("non-zero constant"));
164    let session = BenchSession::start_global(path, metadata_from_env(), capacity)?;
165    Ok(BenchInit::Enabled(session))
166}
167
168/// Enables the historical append-only global recorder.
169///
170/// This compatibility API discards write and flush failures and is therefore
171/// unsuitable for a regression gate. Use [`try_init_from_env`] instead.
172///
173/// # Examples
174///
175/// ```no_run
176/// #![allow(deprecated)]
177/// let path: Option<std::path::PathBuf> =
178///     ailloli_ui_bench::init_from_env("artifacts/bench/legacy.jsonl");
179/// let _ = path;
180/// ```
181#[deprecated(
182    since = "0.1.0",
183    note = "use try_init_from_env and retain BenchSession"
184)]
185/// # Examples
186///
187/// ```no_run
188/// #![allow(deprecated)]
189/// let path = ailloli_ui_bench::init_from_env("artifacts/bench/legacy.jsonl");
190/// let _ = path;
191/// ```
192pub fn init_from_env(default_path: &str) -> Option<PathBuf> {
193    if !bench_enabled() {
194        return None;
195    }
196    let path = configured_path(default_path);
197    let recorder = Recorder::new(&path).ok()?;
198    session::install_legacy(recorder).ok()?;
199    record(Event::Marker {
200        ts_ms: now_ms(),
201        name: "ailloli_ui_bench_enabled".to_string(),
202    });
203    Some(path)
204}
205
206/// Resolves the modern/legacy/historical output path or `default_path`.
207///
208/// Empty and whitespace-only overrides are ignored. The path is not
209/// canonicalized or created here.
210fn configured_path(default_path: &str) -> PathBuf {
211    env_value(
212        "AILLOLI_UI_BENCH_PATH",
213        "OCTAVUI_BENCH_PATH",
214        "UI_BENCH_PATH",
215    )
216    .filter(|value| !value.trim().is_empty())
217    .map_or_else(|| PathBuf::from(default_path), PathBuf::from)
218}
219
220/// Scripted benchmark parameters read by integration harnesses.
221///
222/// # Examples
223///
224/// ```
225/// use ailloli_ui_bench::BenchConfig;
226/// let config = BenchConfig::default();
227/// assert_eq!((config.window_w, config.window_h), (1280, 720));
228/// assert_eq!(config.duration_ms, 10_000);
229/// ```
230#[derive(Debug, Clone)]
231pub struct BenchConfig {
232    /// Scenario name; defaults to `default`.
233    pub scenario: String,
234    /// Requested finite positive device-pixel ratio; defaults to `1.0`.
235    pub dpr: f32,
236    /// Requested nonzero physical window width; defaults to 1280.
237    pub window_w: u32,
238    /// Requested nonzero physical window height; defaults to 720.
239    pub window_h: u32,
240    /// Requested nonzero run duration in milliseconds; defaults to 10,000.
241    pub duration_ms: u32,
242}
243
244impl Default for BenchConfig {
245    fn default() -> Self {
246        Self {
247            scenario: "default".to_string(),
248            dpr: 1.0,
249            window_w: 1280,
250            window_h: 720,
251            duration_ms: 10_000,
252        }
253    }
254}
255
256/// Builds [`BenchConfig`] from framework and compatibility environment names.
257///
258/// Invalid, non-finite, nonpositive, or malformed values retain field defaults.
259/// Window syntax is decimal `WIDTHxHEIGHT`; uppercase `X` is not accepted.
260///
261/// # Examples
262///
263/// ```
264/// let config = ailloli_ui_bench::config_from_env();
265/// assert!(config.dpr.is_finite() && config.dpr > 0.0);
266/// assert!(config.window_w > 0 && config.window_h > 0);
267/// ```
268pub fn config_from_env() -> BenchConfig {
269    let mut config = BenchConfig::default();
270    if let Some(scenario) = bench_scenario_from_env() {
271        config.scenario = scenario;
272    }
273    if let Some(value) = env_value("AILLOLI_UI_BENCH_DPR", "OCTAVUI_BENCH_DPR", "BENCH_DPR") {
274        if let Ok(dpr) = value.trim().parse::<f32>() {
275            if dpr.is_finite() && dpr > 0.0 {
276                config.dpr = dpr;
277            }
278        }
279    }
280    if let Some(value) = env_value(
281        "AILLOLI_UI_BENCH_WINDOW",
282        "OCTAVUI_BENCH_WINDOW",
283        "BENCH_WINDOW",
284    ) {
285        if let Some((width, height)) = value.split_once('x') {
286            if let (Ok(width), Ok(height)) =
287                (width.trim().parse::<u32>(), height.trim().parse::<u32>())
288            {
289                if width > 0 && height > 0 {
290                    config.window_w = width;
291                    config.window_h = height;
292                }
293            }
294        }
295    }
296    if let Some(value) = env_value(
297        "AILLOLI_UI_BENCH_DURATION_MS",
298        "OCTAVUI_BENCH_DURATION_MS",
299        "BENCH_DURATION_MS",
300    ) {
301        if let Ok(duration_ms) = value.trim().parse::<u32>() {
302            if duration_ms > 0 {
303                config.duration_ms = duration_ms;
304            }
305        }
306    }
307    config
308}
309
310/// Builds the initial reproducibility metadata snapshot from the environment.
311///
312/// Requested geometry/DPR come from [`config_from_env`]; the operating system
313/// is always populated. Time origin accepts exactly `process_main`, otherwise
314/// defaults to `app_run`. Live backend and observed DPR remain unset until a
315/// host publishes them.
316///
317/// # Examples
318///
319/// ```
320/// let metadata = ailloli_ui_bench::metadata_from_env();
321/// assert_eq!(metadata.operating_system.as_deref(), Some(std::env::consts::OS));
322/// assert!(metadata.window_width.is_some());
323/// ```
324pub fn metadata_from_env() -> RunMetadata {
325    let config = config_from_env();
326    RunMetadata {
327        scenario: Some(config.scenario),
328        phase: bench_phase_from_env(),
329        git_revision: env_value(
330            "AILLOLI_UI_BENCH_GIT_REVISION",
331            "OCTAVUI_BENCH_GIT_REVISION",
332            "BENCH_GIT_REVISION",
333        ),
334        dirty_diff_hash: env_value(
335            "AILLOLI_UI_BENCH_DIRTY_DIFF_HASH",
336            "OCTAVUI_BENCH_DIRTY_DIFF_HASH",
337            "BENCH_DIRTY_DIFF_HASH",
338        ),
339        profile: env_value(
340            "AILLOLI_UI_BENCH_PROFILE",
341            "OCTAVUI_BENCH_PROFILE",
342            "BENCH_PROFILE",
343        ),
344        harness: env_value(
345            "AILLOLI_UI_BENCH_HARNESS",
346            "OCTAVUI_BENCH_HARNESS",
347            "BENCH_HARNESS",
348        ),
349        target: env_value(
350            "AILLOLI_UI_BENCH_TARGET",
351            "OCTAVUI_BENCH_TARGET",
352            "BENCH_TARGET",
353        ),
354        machine: env_value(
355            "AILLOLI_UI_BENCH_MACHINE",
356            "OCTAVUI_BENCH_MACHINE",
357            "BENCH_MACHINE",
358        ),
359        operating_system: Some(std::env::consts::OS.to_string()),
360        winit_version: env_value(
361            "AILLOLI_UI_BENCH_WINIT_VERSION",
362            "OCTAVUI_BENCH_WINIT_VERSION",
363            "BENCH_WINIT_VERSION",
364        ),
365        backend: env_value(
366            "AILLOLI_UI_BENCH_BACKEND",
367            "OCTAVUI_BENCH_BACKEND",
368            "BENCH_BACKEND",
369        ),
370        gpu: env_value("AILLOLI_UI_BENCH_GPU", "OCTAVUI_BENCH_GPU", "BENCH_GPU"),
371        driver: env_value(
372            "AILLOLI_UI_BENCH_DRIVER",
373            "OCTAVUI_BENCH_DRIVER",
374            "BENCH_DRIVER",
375        ),
376        window_width: Some(config.window_w),
377        window_height: Some(config.window_h),
378        scale_factor: Some(f64::from(config.dpr)),
379        warmup_samples: env_u32("WARMUP_SAMPLES"),
380        measured_samples: env_u32("MEASURED_SAMPLES"),
381        time_origin: match env_value(
382            "AILLOLI_UI_BENCH_TIME_ORIGIN",
383            "OCTAVUI_BENCH_TIME_ORIGIN",
384            "BENCH_TIME_ORIGIN",
385        )
386        .as_deref()
387        {
388            Some("process_main") => TimeOrigin::ProcessMain,
389            _ => TimeOrigin::AppRun,
390        },
391        ..RunMetadata::default()
392    }
393}
394
395/// Parses an unsigned environment value across all supported namespaces.
396///
397/// Whitespace is trimmed; invalid or overflowing values return `None`.
398fn env_u32(suffix: &str) -> Option<u32> {
399    env_value(
400        &format!("AILLOLI_UI_BENCH_{suffix}"),
401        &format!("OCTAVUI_BENCH_{suffix}"),
402        &format!("BENCH_{suffix}"),
403    )
404    .and_then(|value| value.trim().parse::<u32>().ok())
405}
406
407/// Scenario name selected through the framework environment namespace.
408///
409/// Empty and whitespace-only names return `None`; retained nonempty names are
410/// not trimmed.
411///
412/// # Examples
413///
414/// ```
415/// let scenario: Option<String> = ailloli_ui_bench::bench_scenario_from_env();
416/// let _ = scenario;
417/// ```
418pub fn bench_scenario_from_env() -> Option<String> {
419    env_value(
420        "AILLOLI_UI_BENCH_SCENARIO",
421        "OCTAVUI_BENCH_SCENARIO",
422        "BENCH_SCENARIO",
423    )
424    .filter(|value| !value.trim().is_empty())
425}
426
427/// Bench phase selected through the framework environment namespace.
428///
429/// Empty and whitespace-only values return `None`.
430///
431/// # Examples
432///
433/// ```
434/// let phase: Option<String> = ailloli_ui_bench::bench_phase_from_env();
435/// let _ = phase;
436/// ```
437pub fn bench_phase_from_env() -> Option<String> {
438    env_value(
439        "AILLOLI_UI_BENCH_PHASE",
440        "OCTAVUI_BENCH_PHASE",
441        "BENCH_PHASE",
442    )
443    .filter(|value| !value.trim().is_empty())
444}
445
446/// Frame count for integration benchmarks (`AILLOLI_UI_BENCH_FRAMES`, default 60).
447///
448/// Invalid, overflowing, or zero values use 60. Legacy namespaces remain lower
449/// priority fallbacks.
450///
451/// # Examples
452///
453/// ```
454/// assert!(ailloli_ui_bench::frames_from_env() > 0);
455/// ```
456pub fn frames_from_env() -> u32 {
457    env_value(
458        "AILLOLI_UI_BENCH_FRAMES",
459        "OCTAVUI_BENCH_FRAMES",
460        "BENCH_FRAMES",
461    )
462    .and_then(|value| value.trim().parse().ok())
463    .filter(|frames| *frames > 0)
464    .unwrap_or(60)
465}
466
467/// Attempts to record a globally correlated event.
468///
469/// `Ok(None)` means that recording is disabled or uses the legacy sink, which
470/// has no correlation identifiers.
471///
472/// # Errors
473///
474/// Returns a typed write error when an active session rejects non-finite data,
475/// has a full/disconnected queue, or has already finished.
476///
477/// # Examples
478///
479/// ```no_run
480/// use ailloli_ui_bench::{try_record, Event, EventContext};
481/// let id = try_record(
482///     Event::Marker { ts_ms: 1, name: "ready".into() },
483///     EventContext::default(),
484/// )?;
485/// let _ = id;
486/// # Ok::<(), ailloli_ui_bench::BenchWriteError>(())
487/// ```
488pub fn try_record(event: Event, context: EventContext) -> Result<Option<EventId>, BenchWriteError> {
489    session::record_global(event, context)
490}
491
492/// Publishes provider metadata learned after startup on the global session.
493/// Returns `Ok(false)` when the recorder is disabled or legacy.
494///
495/// # Errors
496///
497/// Returns a typed error for non-finite metadata, a full/disconnected queue, or
498/// a finished active session.
499///
500/// # Examples
501///
502/// ```no_run
503/// use ailloli_ui_bench::{try_update_metadata, RunMetadata};
504/// let mut metadata = RunMetadata::default();
505/// metadata.renderer_backend = Some("vulkan".into());
506/// let _accepted = try_update_metadata(metadata)?;
507/// # Ok::<(), ailloli_ui_bench::BenchWriteError>(())
508/// ```
509pub fn try_update_metadata(metadata: RunMetadata) -> Result<bool, BenchWriteError> {
510    session::update_global_metadata(metadata)
511}
512
513/// Publishes the effective winit backend and DPR observed from a live window.
514///
515/// Hosts should call this after native window creation, using the backend
516/// selected by the event loop and `Window::scale_factor()` (or provider-neutral
517/// equivalents). This keeps requested benchmark configuration separate from
518/// the environment that actually rendered the run.
519///
520/// # Errors
521///
522/// Non-finite or nonpositive observed scale factors are rejected by an active
523/// session; global queue/lifecycle failures are also propagated.
524///
525/// # Examples
526///
527/// ```no_run
528/// let _accepted = ailloli_ui_bench::try_update_window_observation("wayland", 2.0)?;
529/// # Ok::<(), ailloli_ui_bench::BenchWriteError>(())
530/// ```
531pub fn try_update_window_observation(
532    window_backend: impl Into<String>,
533    observed_scale_factor: f64,
534) -> Result<bool, BenchWriteError> {
535    let metadata = RunMetadata {
536        window_backend: Some(window_backend.into()),
537        observed_scale_factor: Some(observed_scale_factor),
538        ..RunMetadata::default()
539    };
540    try_update_metadata(metadata)
541}
542
543/// Allocates a frame identifier on the global session.
544/// Returns `Ok(None)` when the recorder is disabled or legacy.
545///
546/// # Errors
547///
548/// Returns `Finished` when the installed session has already closed.
549///
550/// # Examples
551///
552/// ```no_run
553/// let frame: Option<ailloli_ui_bench::FrameId> =
554///     ailloli_ui_bench::try_allocate_frame_id()?;
555/// let _ = frame;
556/// # Ok::<(), ailloli_ui_bench::BenchWriteError>(())
557/// ```
558pub fn try_allocate_frame_id() -> Result<Option<FrameId>, BenchWriteError> {
559    session::allocate_global_frame_id()
560}
561
562/// Records an event on the global recorder. This convenience intentionally
563/// ignores errors; gating integrations should call [`try_record`] or use the
564/// retained [`BenchSession`] directly.
565///
566/// # Examples
567///
568/// ```
569/// ailloli_ui_bench::record(ailloli_ui_bench::Event::Marker {
570///     ts_ms: 1,
571///     name: "layout-complete".into(),
572/// });
573/// ```
574pub fn record(event: Event) {
575    let _ = try_record(event, EventContext::default());
576}
577
578/// Records a named metric on the global recorder.
579///
580/// The role is [`MetricRole::Diagnostic`], so this convenience never creates a
581/// release gate. The caller defines the unit through a stable metric name.
582///
583/// # Examples
584///
585/// ```
586/// ailloli_ui_bench::metric("layout_us", 42.0);
587/// ```
588pub fn metric(name: impl Into<String>, value: f64) {
589    metric_with_role(name, value, MetricRole::Diagnostic);
590}
591
592/// Records a named metric with explicit regression behavior.
593///
594/// This convenience discards active-session errors. Use [`try_record`] when a
595/// gate must observe non-finite values or queue overflow.
596///
597/// # Examples
598///
599/// ```
600/// use ailloli_ui_bench::MetricRole;
601/// ailloli_ui_bench::metric_with_role("frame_us", 16_000.0, MetricRole::GatingSteady);
602/// ```
603pub fn metric_with_role(name: impl Into<String>, value: f64, role: MetricRole) {
604    record(Event::Metric {
605        ts_ms: now_ms(),
606        name: name.into(),
607        value,
608        role,
609    });
610}
611
612/// Starts an RAII timing span recorded as a marker on drop.
613///
614/// The marker name is `span:<name>:<elapsed>us`. The span uses monotonic
615/// [`Instant`] time; recording uses the global best-effort convenience path.
616///
617/// # Examples
618///
619/// ```
620/// let span = ailloli_ui_bench::span("layout");
621/// assert!(span.elapsed() >= std::time::Duration::ZERO);
622/// ```
623pub fn span(name: &'static str) -> Span {
624    Span {
625        name,
626        start: Instant::now(),
627    }
628}
629
630/// Scoped timing helper; see [`span`].
631///
632/// # Examples
633///
634/// ```
635/// let timer: ailloli_ui_bench::Span = ailloli_ui_bench::span("paint");
636/// assert!(timer.elapsed() >= std::time::Duration::ZERO);
637/// ```
638pub struct Span {
639    /// Static marker component retained without allocation.
640    name: &'static str,
641    /// Monotonic start time.
642    start: Instant,
643}
644
645impl Span {
646    /// Elapsed time since the span started.
647    ///
648    /// # Examples
649    ///
650    /// ```
651    /// let timer = ailloli_ui_bench::span("render");
652    /// assert!(timer.elapsed() >= std::time::Duration::ZERO);
653    /// ```
654    pub fn elapsed(&self) -> Duration {
655        self.start.elapsed()
656    }
657}
658
659impl Drop for Span {
660    fn drop(&mut self) {
661        record(Event::Marker {
662            ts_ms: now_ms(),
663            name: format!("span:{}:{}us", self.name, self.start.elapsed().as_micros()),
664        });
665    }
666}
667
668/// Returns milliseconds since the Unix epoch for event payload timestamps.
669///
670/// System times before the epoch map to zero rather than panicking.
671fn now_ms() -> u128 {
672    SystemTime::now()
673        .duration_since(UNIX_EPOCH)
674        .unwrap_or_default()
675        .as_millis()
676}