ailloli_ui_bench/
model.rs

1//! Versioned JSONL wire types, stable identifiers, and event correlation.
2//!
3//! Schema version one tolerates unknown JSON fields and event payloads so newer
4//! producers remain inspectable by older readers. IDs are run-local unless a
5//! type explicitly describes a logical host identity.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11/// Version of the JSONL wire schema emitted by this crate.
12///
13/// # Examples
14///
15/// ```
16/// assert_eq!(ailloli_ui_bench::SCHEMA_VERSION, 1);
17/// ```
18pub const SCHEMA_VERSION: u32 = 1;
19
20/// Identifier of one benchmark run.
21///
22/// The value is opaque and serialized as a JSON string; this type does not
23/// reject empty or duplicate caller-controlled identifiers.
24///
25/// # Examples
26///
27/// ```
28/// use ailloli_ui_bench::RunId;
29///
30/// let id = RunId::new("run-42");
31/// assert_eq!(id.as_str(), "run-42");
32/// ```
33#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(transparent)]
35pub struct RunId(String);
36
37impl RunId {
38    /// Creates a run identifier from a caller-controlled stable value.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// use ailloli_ui_bench::RunId;
44    ///
45    /// assert_eq!(RunId::new(String::from("candidate")).as_str(), "candidate");
46    /// ```
47    pub fn new(value: impl Into<String>) -> Self {
48        Self(value.into())
49    }
50
51    /// Returns the serialized identifier.
52    ///
53    /// # Examples
54    ///
55    /// ```
56    /// use ailloli_ui_bench::RunId;
57    ///
58    /// assert_eq!(RunId::new("baseline").as_str(), "baseline");
59    /// ```
60    pub fn as_str(&self) -> &str {
61        &self.0
62    }
63}
64
65/// Monotonic identifier of an event within one run.
66///
67/// Zero is valid, although [`crate::BenchSession`] allocates IDs starting at
68/// one and saturates instead of wrapping at `u64::MAX`.
69///
70/// # Examples
71///
72/// ```
73/// use ailloli_ui_bench::EventId;
74///
75/// assert_eq!(EventId::new(7).get(), 7);
76/// ```
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(transparent)]
79pub struct EventId(u64);
80
81impl EventId {
82    /// Creates an event identifier.
83    ///
84    /// # Examples
85    ///
86    /// ```
87    /// use ailloli_ui_bench::EventId;
88    /// assert_eq!(EventId::new(0).get(), 0);
89    /// ```
90    pub const fn new(value: u64) -> Self {
91        Self(value)
92    }
93
94    /// Returns the numeric identifier.
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// use ailloli_ui_bench::EventId;
100    /// assert_eq!(EventId::new(u64::MAX).get(), u64::MAX);
101    /// ```
102    pub const fn get(self) -> u64 {
103        self.0
104    }
105}
106
107/// Identifier of a rendered frame within one run.
108///
109/// # Examples
110///
111/// ```
112/// use ailloli_ui_bench::FrameId;
113/// assert_eq!(FrameId::new(12).get(), 12);
114/// ```
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
116#[serde(transparent)]
117pub struct FrameId(u64);
118
119impl FrameId {
120    /// Creates a frame identifier.
121    ///
122    /// # Examples
123    ///
124    /// ```
125    /// use ailloli_ui_bench::FrameId;
126    /// assert_eq!(FrameId::new(1).get(), 1);
127    /// ```
128    pub const fn new(value: u64) -> Self {
129        Self(value)
130    }
131
132    /// Returns the numeric identifier.
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use ailloli_ui_bench::FrameId;
138    /// assert_eq!(FrameId::new(99).get(), 99);
139    /// ```
140    pub const fn get(self) -> u64 {
141        self.0
142    }
143}
144
145/// Stable logical window identifier used by benchmark correlation.
146///
147/// # Examples
148///
149/// ```
150/// use ailloli_ui_bench::BenchWindowId;
151/// assert_eq!(BenchWindowId::new("main").as_str(), "main");
152/// ```
153#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(transparent)]
155pub struct BenchWindowId(String);
156
157impl BenchWindowId {
158    /// Creates a logical window identifier.
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// use ailloli_ui_bench::BenchWindowId;
164    /// assert_eq!(BenchWindowId::new(String::from("popup")).as_str(), "popup");
165    /// ```
166    pub fn new(value: impl Into<String>) -> Self {
167        Self(value.into())
168    }
169
170    /// Returns the serialized identifier.
171    ///
172    /// # Examples
173    ///
174    /// ```
175    /// use ailloli_ui_bench::BenchWindowId;
176    /// assert_eq!(BenchWindowId::new("main").as_str(), "main");
177    /// ```
178    pub fn as_str(&self) -> &str {
179        &self.0
180    }
181}
182
183/// Stable logical surface identifier used by benchmark correlation.
184///
185/// # Examples
186///
187/// ```
188/// use ailloli_ui_bench::BenchSurfaceId;
189/// assert_eq!(BenchSurfaceId::new("main-surface").as_str(), "main-surface");
190/// ```
191#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
192#[serde(transparent)]
193pub struct BenchSurfaceId(String);
194
195impl BenchSurfaceId {
196    /// Creates a logical surface identifier.
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use ailloli_ui_bench::BenchSurfaceId;
202    /// assert_eq!(BenchSurfaceId::new(String::from("surface-2")).as_str(), "surface-2");
203    /// ```
204    pub fn new(value: impl Into<String>) -> Self {
205        Self(value.into())
206    }
207
208    /// Returns the serialized identifier.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use ailloli_ui_bench::BenchSurfaceId;
214    /// assert_eq!(BenchSurfaceId::new("surface").as_str(), "surface");
215    /// ```
216    pub fn as_str(&self) -> &str {
217        &self.0
218    }
219}
220
221/// Origin used by elapsed-time measurements in a run.
222///
223/// # Examples
224///
225/// ```
226/// use ailloli_ui_bench::TimeOrigin;
227/// assert_eq!(TimeOrigin::default(), TimeOrigin::AppRun);
228/// ```
229#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(rename_all = "snake_case")]
231pub enum TimeOrigin {
232    /// Initialization happened at the start of the child process.
233    ProcessMain,
234    /// Initialization happened when the application entered its run path.
235    #[default]
236    AppRun,
237}
238
239/// Reproducibility metadata for one benchmark run.
240///
241/// Unknown JSON fields are intentionally tolerated by readers. Use [`Default`]
242/// and mutate the public fields instead of constructing this non-exhaustive
243/// structure as a literal.
244///
245/// Optional values are absent when unknown; empty strings are not normalized.
246/// Width and height are physical window pixels. Scale factors must be finite
247/// and positive when validated by a session or comparison workflow.
248///
249/// # Examples
250///
251/// ```
252/// use ailloli_ui_bench::RunMetadata;
253///
254/// let mut metadata = RunMetadata::default();
255/// metadata.scenario = Some("scroll-tree".into());
256/// metadata.window_width = Some(1280);
257/// assert_eq!(metadata.scenario.as_deref(), Some("scroll-tree"));
258/// ```
259#[non_exhaustive]
260#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
261#[serde(default)]
262pub struct RunMetadata {
263    /// Stable benchmark scenario name, or `None` when unspecified.
264    pub scenario: Option<String>,
265    /// Project phase or experiment label, or `None` when unspecified.
266    pub phase: Option<String>,
267    /// Source revision measured by this run.
268    pub git_revision: Option<String>,
269    /// Digest of uncommitted source changes, when present.
270    pub dirty_diff_hash: Option<String>,
271    /// Build profile such as `release` or `debug`.
272    pub profile: Option<String>,
273    /// Stable identity of the executable or harness which produced the run.
274    pub harness: Option<String>,
275    /// Compilation target used for the measured executable, when known.
276    pub target: Option<String>,
277    /// Stable caller-provided machine identity, when available.
278    ///
279    /// Producers should use an opaque lab identifier rather than a hostname or
280    /// another value which could disclose user information.
281    pub machine: Option<String>,
282    /// Operating-system identity used for run compatibility checks.
283    pub operating_system: Option<String>,
284    /// Winit version used by the measured host, when applicable.
285    pub winit_version: Option<String>,
286    /// Legacy backend field retained for version-one artifacts.
287    ///
288    /// New producers should use [`Self::window_backend`] for the effective
289    /// winit backend and [`Self::renderer_backend`] for the graphics backend.
290    pub backend: Option<String>,
291    /// Effective window-system backend observed by the winit adapter.
292    pub window_backend: Option<String>,
293    /// Effective graphics backend reported by the renderer adapter.
294    pub renderer_backend: Option<String>,
295    /// GPU adapter identity reported by the renderer.
296    pub gpu: Option<String>,
297    /// Graphics driver identity/version reported by the renderer.
298    pub driver: Option<String>,
299    /// Requested window width in physical pixels.
300    pub window_width: Option<u32>,
301    /// Requested window height in physical pixels.
302    pub window_height: Option<u32>,
303    /// Requested logical-to-physical device-pixel ratio.
304    pub scale_factor: Option<f64>,
305    /// Device-pixel ratio read from the live native window.
306    ///
307    /// This is deliberately separate from [`Self::scale_factor`], which is a
308    /// requested/configured value in version-one benchmark artifacts.
309    pub observed_scale_factor: Option<f64>,
310    /// Number of leading samples excluded from regression statistics.
311    pub warmup_samples: Option<u32>,
312    /// Number of samples intended for measured statistics.
313    pub measured_samples: Option<u32>,
314    /// Reference point for every `elapsed_us` value in this run.
315    pub time_origin: TimeOrigin,
316    /// Provider-specific diagnostics which do not warrant a schema revision.
317    pub extensions: BTreeMap<String, serde_json::Value>,
318}
319
320impl RunMetadata {
321    /// Overlays non-empty values from `update` onto this metadata set.
322    ///
323    /// `None` never erases an existing value. Extensions overwrite entries with
324    /// the same key. A legacy `backend` update accompanied by GPU or driver
325    /// metadata is migrated to `renderer_backend` and does not replace the
326    /// original window backend.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use ailloli_ui_bench::RunMetadata;
332    ///
333    /// let mut update = RunMetadata::default();
334    /// update.renderer_backend = Some("vulkan".into());
335    /// // Sessions apply this sparse update without clearing other metadata.
336    /// assert_eq!(update.renderer_backend.as_deref(), Some("vulkan"));
337    /// ```
338    pub(crate) fn apply_update(&mut self, update: &Self) {
339        macro_rules! apply_option {
340            ($field:ident) => {
341                if update.$field.is_some() {
342                    self.$field.clone_from(&update.$field);
343                }
344            };
345        }
346
347        apply_option!(scenario);
348        apply_option!(phase);
349        apply_option!(git_revision);
350        apply_option!(dirty_diff_hash);
351        apply_option!(profile);
352        apply_option!(harness);
353        apply_option!(target);
354        apply_option!(machine);
355        apply_option!(operating_system);
356        apply_option!(winit_version);
357        // Older renderer integrations published their WGPU backend through
358        // `backend` together with GPU/driver metadata. Preserve the original
359        // window backend and migrate that late update into the dedicated
360        // renderer field instead of overwriting Wayland/X11.
361        let inferred_renderer_backend = update.renderer_backend.clone().or_else(|| {
362            if update.gpu.is_some() || update.driver.is_some() {
363                update.backend.clone()
364            } else {
365                None
366            }
367        });
368        if update.backend.is_some() && inferred_renderer_backend.is_none() {
369            self.backend.clone_from(&update.backend);
370        }
371        apply_option!(window_backend);
372        if inferred_renderer_backend.is_some() {
373            self.renderer_backend = inferred_renderer_backend;
374        }
375        apply_option!(gpu);
376        apply_option!(driver);
377        apply_option!(window_width);
378        apply_option!(window_height);
379        apply_option!(scale_factor);
380        apply_option!(observed_scale_factor);
381        apply_option!(warmup_samples);
382        apply_option!(measured_samples);
383        self.extensions.extend(update.extensions.clone());
384    }
385}
386
387/// Classification of a sample for deterministic warmup exclusion.
388///
389/// # Examples
390///
391/// ```
392/// use ailloli_ui_bench::SamplePhase;
393/// assert_eq!(SamplePhase::default(), SamplePhase::Measured);
394/// ```
395#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
396#[serde(rename_all = "snake_case")]
397pub enum SamplePhase {
398    /// Sample used only to warm caches and pipelines.
399    Warmup,
400    /// Sample included in regression statistics.
401    #[default]
402    Measured,
403}
404
405/// Regression role carried by an explicit numeric metric.
406///
407/// Legacy metrics and provider events without a role are diagnostics. This
408/// keeps existing JSONL artifacts readable without accidentally promoting
409/// incidental counters into release gates.
410///
411/// # Examples
412///
413/// ```
414/// use ailloli_ui_bench::MetricRole;
415/// assert_eq!(MetricRole::default(), MetricRole::Diagnostic);
416/// ```
417#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
418#[serde(rename_all = "snake_case")]
419pub enum MetricRole {
420    /// Requires at least 30 measured samples and gates median plus p95.
421    GatingSteady,
422    /// Requires at least five independent measured processes and gates median.
423    GatingColdStart,
424    /// Informational metric requiring only one sample and never blocking.
425    #[default]
426    Diagnostic,
427    /// Correctness counter whose candidate samples must all equal zero.
428    Correctness,
429}
430
431/// Correlation attached to a recorded event.
432///
433/// All identifiers are optional. `presentation_generation` should be present
434/// with `surface_id`; builders set the pair atomically. An empty cause list
435/// means no predecessor was declared. Samples default to measured.
436///
437/// # Examples
438///
439/// ```
440/// use ailloli_ui_bench::{EventContext, FrameId, SamplePhase};
441///
442/// let context = EventContext::default()
443///     .with_frame(FrameId::new(3))
444///     .with_sample_phase(SamplePhase::Warmup);
445/// assert_eq!(context.frame_id, Some(FrameId::new(3)));
446/// assert_eq!(context.sample_phase, SamplePhase::Warmup);
447/// ```
448#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(default)]
450pub struct EventContext {
451    /// Frame containing the event, or `None` for run-level events.
452    pub frame_id: Option<FrameId>,
453    /// Logical host window associated with the event.
454    pub logical_window_id: Option<BenchWindowId>,
455    /// Logical presentation surface associated with the event.
456    pub surface_id: Option<BenchSurfaceId>,
457    /// Surface generation paired with [`Self::surface_id`].
458    pub presentation_generation: Option<u64>,
459    /// Earlier event IDs declared as causal predecessors.
460    pub cause_event_ids: Vec<EventId>,
461    /// Whether a numeric sample is warmup-only or measured.
462    pub sample_phase: SamplePhase,
463}
464
465impl EventContext {
466    /// Associates the event with a frame.
467    ///
468    /// # Examples
469    ///
470    /// ```
471    /// use ailloli_ui_bench::{EventContext, FrameId};
472    /// let context = EventContext::default().with_frame(FrameId::new(4));
473    /// assert_eq!(context.frame_id, Some(FrameId::new(4)));
474    /// ```
475    pub fn with_frame(mut self, frame_id: FrameId) -> Self {
476        self.frame_id = Some(frame_id);
477        self
478    }
479
480    /// Associates the event with a logical window.
481    ///
482    /// # Examples
483    ///
484    /// ```
485    /// use ailloli_ui_bench::{BenchWindowId, EventContext};
486    /// let context = EventContext::default().with_window(BenchWindowId::new("main"));
487    /// assert_eq!(context.logical_window_id.unwrap().as_str(), "main");
488    /// ```
489    pub fn with_window(mut self, window_id: BenchWindowId) -> Self {
490        self.logical_window_id = Some(window_id);
491        self
492    }
493
494    /// Associates the event with a logical surface and presentation generation.
495    ///
496    /// # Examples
497    ///
498    /// ```
499    /// use ailloli_ui_bench::{BenchSurfaceId, EventContext};
500    /// let context = EventContext::default().with_surface(BenchSurfaceId::new("s0"), 2);
501    /// assert_eq!(context.presentation_generation, Some(2));
502    /// ```
503    pub fn with_surface(
504        mut self,
505        surface_id: BenchSurfaceId,
506        presentation_generation: u64,
507    ) -> Self {
508        self.surface_id = Some(surface_id);
509        self.presentation_generation = Some(presentation_generation);
510        self
511    }
512
513    /// Adds a causal predecessor.
514    ///
515    /// Repeated IDs are retained in insertion order.
516    ///
517    /// # Examples
518    ///
519    /// ```
520    /// use ailloli_ui_bench::{EventContext, EventId};
521    /// let context = EventContext::default().caused_by(EventId::new(8));
522    /// assert_eq!(context.cause_event_ids, vec![EventId::new(8)]);
523    /// ```
524    pub fn caused_by(mut self, event_id: EventId) -> Self {
525        self.cause_event_ids.push(event_id);
526        self
527    }
528
529    /// Marks whether this event is a warmup or measured sample.
530    ///
531    /// # Examples
532    ///
533    /// ```
534    /// use ailloli_ui_bench::{EventContext, SamplePhase};
535    /// let context = EventContext::default().with_sample_phase(SamplePhase::Warmup);
536    /// assert_eq!(context.sample_phase, SamplePhase::Warmup);
537    /// ```
538    pub fn with_sample_phase(mut self, sample_phase: SamplePhase) -> Self {
539        self.sample_phase = sample_phase;
540        self
541    }
542}
543
544/// One JSONL event payload.
545///
546/// Timestamps are wall-clock milliseconds since the Unix epoch. Durations are
547/// microseconds. Dimensions and pixel counters use physical pixels unless a
548/// field says otherwise. Numeric metric values must be finite before a session
549/// accepts them.
550///
551/// # Examples
552///
553/// ```
554/// use ailloli_ui_bench::Event;
555///
556/// let event = Event::Metric {
557///     ts_ms: 1,
558///     name: "layout_us".into(),
559///     value: 42.0,
560///     role: ailloli_ui_bench::MetricRole::GatingSteady,
561/// };
562/// assert!(matches!(event, Event::Metric { value: 42.0, .. }));
563/// ```
564#[non_exhaustive]
565#[derive(Debug, Clone, Serialize, Deserialize)]
566#[serde(tag = "kind", rename_all = "snake_case")]
567pub enum Event {
568    /// Named checkpoint (including span end markers).
569    Marker {
570        /// Wall-clock timestamp in milliseconds since the Unix epoch.
571        ts_ms: u128,
572        /// Caller-selected checkpoint name.
573        name: String,
574    },
575
576    /// Window resize queued before GPU apply.
577    ResizePending {
578        /// Wall-clock timestamp in milliseconds since the Unix epoch.
579        ts_ms: u128,
580        /// Pending physical width in pixels.
581        w: u32,
582        /// Pending physical height in pixels.
583        h: u32,
584    },
585    /// Surface resize applied on the GPU path.
586    ResizeApply {
587        /// Wall-clock timestamp in milliseconds since the Unix epoch.
588        ts_ms: u128,
589        /// Applied physical width in pixels.
590        w: u32,
591        /// Applied physical height in pixels.
592        h: u32,
593        /// GPU-path resize duration in microseconds.
594        dur_us: u128,
595    },
596    /// GPU surface configuration.
597    SurfaceConfigure {
598        /// Wall-clock timestamp in milliseconds since the Unix epoch.
599        ts_ms: u128,
600        /// Configured physical width in pixels.
601        w: u32,
602        /// Configured physical height in pixels.
603        h: u32,
604        /// Surface configuration duration in microseconds.
605        dur_us: u128,
606    },
607
608    /// Full frame presented to the swapchain.
609    RenderFrame {
610        /// Wall-clock timestamp in milliseconds since the Unix epoch.
611        ts_ms: u128,
612        /// Complete frame duration in microseconds.
613        dur_us: u128,
614    },
615    /// Failed to acquire the current swapchain texture.
616    GetCurrentTextureErr {
617        /// Wall-clock timestamp in milliseconds since the Unix epoch.
618        ts_ms: u128,
619        /// Redacted diagnostic representation of the acquisition error.
620        err: String,
621    },
622
623    /// Window maximize state toggled.
624    MaximizeToggle {
625        /// Wall-clock timestamp in milliseconds since the Unix epoch.
626        ts_ms: u128,
627        /// `true` when transitioning to maximized state.
628        to: bool,
629    },
630    /// Event loop about to wait; may schedule redraw after resize.
631    AboutToWaitRedraw {
632        /// Wall-clock timestamp in milliseconds since the Unix epoch.
633        ts_ms: u128,
634        /// Whether a queued resize still awaits renderer application.
635        awaiting_resize: bool,
636    },
637    /// Sampled inner window size.
638    WindowInnerSizeSample {
639        /// Wall-clock timestamp in milliseconds since the Unix epoch.
640        ts_ms: u128,
641        /// Observed physical width in pixels.
642        w: u32,
643        /// Observed physical height in pixels.
644        h: u32,
645    },
646
647    /// Structured numeric sample.
648    Metric {
649        /// Wall-clock timestamp in milliseconds since the Unix epoch.
650        ts_ms: u128,
651        /// Stable metric name used to group samples.
652        name: String,
653        /// Finite numeric sample in the unit encoded by `name`/documentation.
654        value: f64,
655        /// Explicit comparison behavior. Missing roles in older artifacts
656        /// deserialize as [`MetricRole::Diagnostic`].
657        #[serde(default)]
658        role: MetricRole,
659    },
660
661    /// One text pipeline frame (layout + paint + render).
662    TextPipelineFrame {
663        /// Wall-clock timestamp in milliseconds since the Unix epoch.
664        ts_ms: u128,
665        /// Text layout duration in microseconds.
666        layout_us: u128,
667        /// Text paint-command generation duration in microseconds.
668        paint_us: u128,
669        /// Text renderer duration in microseconds.
670        render_us: u128,
671        /// Number of text draw commands produced for the frame.
672        draw_text_cmds: u32,
673    },
674
675    /// Glyph atlas cache statistics for one frame.
676    TextAtlasFrame {
677        /// Wall-clock timestamp in milliseconds since the Unix epoch.
678        ts_ms: u128,
679        /// Glyph cache lookup hits this frame.
680        hits: u32,
681        /// Glyph cache lookup misses this frame.
682        misses: u32,
683        /// Glyphs rasterized and uploaded this frame.
684        rasterized: u32,
685        /// Atlas pages reset for reuse this frame.
686        resets: u32,
687        /// Evictions blocked because all candidate pages were pinned.
688        evictions_blocked: u32,
689        /// Glyphs skipped because no atlas allocation was available.
690        glyphs_skipped: u32,
691        /// Atlas pages active after the frame.
692        pages_active: u32,
693    },
694
695    /// Isolated compositor metrics for one surface-backed frame.
696    IsolatedCompositorFrame {
697        /// Wall-clock timestamp in milliseconds since the Unix epoch.
698        ts_ms: u128,
699        /// Scenario label copied into renderer metrics; empty means unspecified.
700        scenario: String,
701        /// Number of isolated offscreen passes rendered.
702        isolated_pass_count: u32,
703        /// Total physical pixels covered by isolated targets.
704        isolated_pixels_total: u64,
705        /// Total physical pixels processed by blur passes.
706        blur_pixels_total: u64,
707        /// Peak bytes retained by the offscreen texture pool.
708        offscreen_peak_bytes: u64,
709        /// Pool leases served by an existing allocation.
710        pool_reuse_hits: u32,
711        /// New offscreen allocations performed this frame.
712        pool_allocs: u32,
713        /// Reuse hits divided by hits plus allocations, in `0.0..=1.0`.
714        pool_reuse_ratio: f64,
715        /// Number of separable blur passes recorded.
716        blur_pass_count: u32,
717        /// Isolated passes that required a stencil attachment.
718        stencil_offscreen_count: u32,
719        /// Total isolated-effect downgrades.
720        downgrade_count: u32,
721        /// Blur radii reduced by policy limits.
722        downgrade_blur_clamped: u32,
723        /// Offscreen surfaces reduced by dimension/pixel limits.
724        downgrade_surface_clamped: u32,
725        /// Isolated passes skipped by the byte budget.
726        downgrade_bytes_skipped: u32,
727        /// Backdrop regions captured from the main framebuffer.
728        backdrop_capture_count: u32,
729        /// Total physical pixels captured for backdrop effects.
730        backdrop_pixels_total: u64,
731        /// Blur passes applied to captured backdrop regions.
732        backdrop_blur_pass_count: u32,
733        /// Backdrop effects skipped by the capture budget.
734        downgrade_backdrop_skipped: u32,
735        /// Destination regions captured for non-normal blending.
736        blend_capture_count: u32,
737        /// Shader blend composites recorded.
738        blend_composite_count: u32,
739        /// Destination-aware blends downgraded by policy limits.
740        downgrade_blend_skipped: u32,
741    },
742}
743
744/// Parsed `run_start` line.
745///
746/// # Examples
747///
748/// ```
749/// use ailloli_ui_bench::{RunId, RunMetadata, RunStartRecord, SCHEMA_VERSION};
750/// let record = RunStartRecord {
751///     schema_version: SCHEMA_VERSION,
752///     run_id: RunId::new("run"),
753///     started_unix_ms: 1,
754///     metadata: RunMetadata::default(),
755/// };
756/// assert_eq!(record.schema_version, 1);
757/// ```
758#[derive(Debug, Clone, Serialize, Deserialize)]
759pub struct RunStartRecord {
760    /// Wire schema version used to encode this record.
761    pub schema_version: u32,
762    /// Run identity shared by every record in the file.
763    pub run_id: RunId,
764    /// Run start in milliseconds since the Unix epoch.
765    pub started_unix_ms: u128,
766    /// Initial reproducibility metadata snapshot.
767    pub metadata: RunMetadata,
768}
769
770/// Parsed `metadata_update` line.
771///
772/// # Examples
773///
774/// ```
775/// use ailloli_ui_bench::{MetadataUpdateRecord, RunId, RunMetadata, SCHEMA_VERSION};
776/// let record = MetadataUpdateRecord {
777///     schema_version: SCHEMA_VERSION,
778///     run_id: RunId::new("run"),
779///     elapsed_us: 10,
780///     metadata: RunMetadata::default(),
781/// };
782/// assert_eq!(record.elapsed_us, 10);
783/// ```
784#[derive(Debug, Clone, Serialize, Deserialize)]
785pub struct MetadataUpdateRecord {
786    /// Wire schema version used to encode this record.
787    pub schema_version: u32,
788    /// Run identity shared by every record in the file.
789    pub run_id: RunId,
790    /// Microseconds since the run's declared [`TimeOrigin`].
791    pub elapsed_us: u128,
792    /// Sparse metadata values overlaid onto earlier metadata.
793    pub metadata: RunMetadata,
794}
795
796/// Parsed correlated event line. The payload remains a JSON value so readers
797/// can retain events introduced by future schema revisions.
798///
799/// # Examples
800///
801/// ```
802/// use ailloli_ui_bench::{BenchEventRecord, EventContext, EventId, RunId, SCHEMA_VERSION};
803/// let record = BenchEventRecord {
804///     schema_version: SCHEMA_VERSION,
805///     run_id: RunId::new("run"),
806///     event_id: EventId::new(1),
807///     elapsed_us: 20,
808///     context: EventContext::default(),
809///     event: serde_json::json!({"kind": "marker", "name": "ready"}),
810/// };
811/// assert_eq!(record.event_id.get(), 1);
812/// ```
813#[derive(Debug, Clone, Serialize, Deserialize)]
814pub struct BenchEventRecord {
815    /// Wire schema version used to encode this record.
816    pub schema_version: u32,
817    /// Run identity shared by every record in the file.
818    pub run_id: RunId,
819    /// Strictly increasing event identifier within the run.
820    pub event_id: EventId,
821    /// Microseconds since the run's declared [`TimeOrigin`].
822    pub elapsed_us: u128,
823    /// Optional frame/window/surface/cause/sample correlation fields.
824    #[serde(flatten)]
825    pub context: EventContext,
826    /// Forward-compatible event object, including its `kind` discriminator.
827    pub event: serde_json::Value,
828}
829
830/// Parsed `run_end` line.
831///
832/// # Examples
833///
834/// ```
835/// use ailloli_ui_bench::{RunEndRecord, RunId, SCHEMA_VERSION};
836/// let record = RunEndRecord {
837///     schema_version: SCHEMA_VERSION,
838///     run_id: RunId::new("run"),
839///     elapsed_us: 100,
840///     valid: true,
841///     dropped_records: 0,
842///     records_written: 3,
843/// };
844/// assert!(record.valid);
845/// ```
846#[derive(Debug, Clone, Serialize, Deserialize)]
847pub struct RunEndRecord {
848    /// Wire schema version used to encode this record.
849    pub schema_version: u32,
850    /// Run identity shared by every record in the file.
851    pub run_id: RunId,
852    /// Microseconds since the run's declared [`TimeOrigin`].
853    pub elapsed_us: u128,
854    /// Whether the run remained suitable for gate comparison.
855    pub valid: bool,
856    /// Records rejected because the bounded writer queue was full.
857    pub dropped_records: u64,
858    /// Records serialized before this terminal record, excluding `run_end`.
859    pub records_written: u64,
860}
861
862/// Internal typed representation serialized into JSONL wire records.
863///
864/// # Examples
865///
866/// ```
867/// // Public readers expose the corresponding tolerant `LogRecord` envelope.
868/// let record = ailloli_ui_bench::LogRecord::Unknown(serde_json::json!({
869///     "record_type": "future"
870/// }));
871/// assert!(matches!(record, ailloli_ui_bench::LogRecord::Unknown(_)));
872/// ```
873#[derive(Debug, Serialize)]
874#[serde(tag = "record_type", rename_all = "snake_case")]
875pub(crate) enum WireRecord {
876    /// Initial metadata and run identity.
877    RunStart(RunStartRecord),
878    /// Sparse late metadata update.
879    MetadataUpdate(MetadataUpdateRecord),
880    /// Correlated event with a forward-compatible payload.
881    Event(BenchEventRecord),
882    /// Terminal validity and writer-count summary.
883    RunEnd(RunEndRecord),
884}