pocketstation 1.0.1

Source-aware desktop audio Session SDK
Documentation
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use std::sync::atomic::{AtomicU64, Ordering};

use crate::capture::CaptureOwnerObservations;
use crate::endpoint::EndpointDriverObservations;
use crate::frame::{EndpointId, RouteId, SourceId, StemId};
use crate::runtime::{
    AsyncOperatorObservations, AsyncOperatorOutputObservations, EdgeObservations,
    GeneratedAudioBridgeObservations, PlanSourceInputObservations, SidecarHostSnapshot,
};

use crate::session::{
    OperatorInstanceId, PolledAudioObservations, SourceInstanceId, SourceRuntimeObservations,
};

/// Point-in-time observations for a session's bounded control-event queue.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionEventQueueObservations {
    pub capacity_event_count: u64,
    pub maximum_event_owned_bytes: u64,
    pub maximum_buffered_owned_bytes: u64,
    pub depth_events: u64,
    pub depth_owned_bytes: u64,
    pub peak_depth_event_count: u64,
    pub peak_depth_owned_bytes: u64,
    pub events_enqueued_total: u64,
    pub events_dropped_total: u64,
    pub events_dropped_oversized_total: u64,
    pub receiver_closed_total: u64,
}

/// Authoritative point-in-time observations for the current Session boundary.
///
/// The snapshot keeps control-event and foreign-audio queue truth together
/// without exposing either counter owner to a language adapter.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionMetricsSnapshot {
    event_queue: SessionEventQueueObservations,
    polled_audio: PolledAudioObservations,
    sources: Box<[SessionSourceMetrics]>,
    external_sources: Box<[SessionExternalSourceMetrics]>,
    routes: Box<[SessionRouteMetrics]>,
    operators: Box<[SessionOperatorMetrics]>,
    derived_routes: Box<[SessionDerivedRouteMetrics]>,
}

impl SessionMetricsSnapshot {
    pub(crate) const fn new(
        event_queue: SessionEventQueueObservations,
        polled_audio: PolledAudioObservations,
        sources: Box<[SessionSourceMetrics]>,
        external_sources: Box<[SessionExternalSourceMetrics]>,
        routes: Box<[SessionRouteMetrics]>,
        operators: Box<[SessionOperatorMetrics]>,
        derived_routes: Box<[SessionDerivedRouteMetrics]>,
    ) -> Self {
        Self {
            event_queue,
            polled_audio,
            sources,
            external_sources,
            routes,
            operators,
            derived_routes,
        }
    }

    pub const fn event_queue(&self) -> SessionEventQueueObservations {
        self.event_queue
    }

    pub const fn polled_audio(&self) -> PolledAudioObservations {
        self.polled_audio
    }

    pub fn source_count(&self) -> usize {
        self.sources.len()
    }

    pub fn source(&self, index: usize) -> Option<&SessionSourceMetrics> {
        self.sources.get(index)
    }

    pub fn external_source_count(&self) -> usize {
        self.external_sources.len()
    }

    pub fn external_source(&self, index: usize) -> Option<&SessionExternalSourceMetrics> {
        self.external_sources.get(index)
    }

    pub fn route_count(&self) -> usize {
        self.routes.len()
    }

    pub fn route(&self, index: usize) -> Option<&SessionRouteMetrics> {
        self.routes.get(index)
    }

    pub fn operator_count(&self) -> usize {
        self.operators.len()
    }

    pub fn operator(&self, index: usize) -> Option<&SessionOperatorMetrics> {
        self.operators.get(index)
    }

    pub fn derived_route_count(&self) -> usize {
        self.derived_routes.len()
    }

    pub fn derived_route(&self, index: usize) -> Option<&SessionDerivedRouteMetrics> {
        self.derived_routes.get(index)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionSourceMetrics {
    pub stem_id: StemId,
    pub capture: CaptureOwnerObservations,
    pub ingress: PlanSourceInputObservations,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionExternalSourceMetrics {
    pub source_instance_id: SourceInstanceId,
    pub source_id: SourceId,
    pub runtime: SourceRuntimeObservations,
}

/// Exact bounded-queue and process-lifecycle accounting for one Session-owned
/// language-neutral sidecar.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionSidecarMetrics {
    pub sidecar_id: u64,
    pub host: SidecarHostSnapshot,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionRouteMetrics {
    pub route_id: RouteId,
    pub endpoint_id: EndpointId,
    pub edge: EdgeObservations,
    pub endpoint: Option<EndpointDriverObservations>,
    pub endpoint_observation_stage: EndpointObservationStage,
    pub endpoint_finalization_failures_total: u64,
}

/// Interval covered by monotonic route counters.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionRouteObservationInterval {
    /// From route start through the instant of the Session snapshot.
    RouteLifetimeToSnapshot,
}

/// Explicit numerator, denominator, interval, and typed reasons for one route.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionRouteDropObservations {
    pub route_id: RouteId,
    pub interval: SessionRouteObservationInterval,
    pub frames_dropped_total: u64,
    pub frames_attempted_total: u64,
    pub receiver_unavailable_drops_total: u64,
    pub queue_full_drops_total: u64,
    pub shared_reference_exhausted_drops_total: u64,
    pub branch_pool_exhausted_drops_total: u64,
    pub invalid_copy_policy_drops_total: u64,
    pub freeze_failed_drops_total: u64,
}

impl SessionRouteDropObservations {
    pub fn drop_rate_pct(self) -> f64 {
        if self.frames_attempted_total == 0 {
            0.0
        } else {
            self.frames_dropped_total as f64 / self.frames_attempted_total as f64 * 100.0
        }
    }
}

/// Common-clock source timestamp to route-receive latency in nanoseconds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionRouteLatencyObservations {
    pub route_id: RouteId,
    pub boundary: SessionRouteLatencyBoundary,
    pub unit: SessionRouteLatencyUnit,
    pub samples_total: u64,
    pub missing_or_incompatible_clock_total: u64,
    pub future_timestamp_total: u64,
    pub p50_ns: u64,
    pub p95_ns: u64,
    pub p99_ns: u64,
    pub max_ns: u64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionRouteLatencyBoundary {
    SourceMonotonicTimestampToRouteReceive,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionRouteLatencyUnit {
    Nanoseconds,
}

impl SessionRouteMetrics {
    pub fn drop_observations(self) -> SessionRouteDropObservations {
        SessionRouteDropObservations {
            route_id: self.route_id,
            interval: SessionRouteObservationInterval::RouteLifetimeToSnapshot,
            frames_dropped_total: self.edge.frames_dropped_total,
            frames_attempted_total: self.edge.frames_attempted_total(),
            receiver_unavailable_drops_total: self.edge.receiver_unavailable_drops_total,
            queue_full_drops_total: self.edge.queue_full_drops_total,
            shared_reference_exhausted_drops_total: self
                .edge
                .shared_reference_exhausted_drops_total,
            branch_pool_exhausted_drops_total: self.edge.branch_pool_exhausted_drops_total,
            invalid_copy_policy_drops_total: self.edge.invalid_copy_policy_drops_total,
            freeze_failed_drops_total: self.edge.freeze_failed_drops_total,
        }
    }

    pub const fn source_to_receive_latency(self) -> SessionRouteLatencyObservations {
        SessionRouteLatencyObservations {
            route_id: self.route_id,
            boundary: SessionRouteLatencyBoundary::SourceMonotonicTimestampToRouteReceive,
            unit: SessionRouteLatencyUnit::Nanoseconds,
            samples_total: self.edge.source_timestamp_to_receive_samples_total,
            missing_or_incompatible_clock_total: self
                .edge
                .source_timestamp_to_receive_missing_total,
            future_timestamp_total: self.edge.source_timestamp_to_receive_future_total,
            p50_ns: self.edge.source_timestamp_to_receive_p50_ns,
            p95_ns: self.edge.source_timestamp_to_receive_p95_ns,
            p99_ns: self.edge.source_timestamp_to_receive_p99_ns,
            max_ns: self.edge.source_timestamp_to_receive_max_ns,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionOperatorInputMetrics {
    pub port_name: String,
    pub edge: EdgeObservations,
}

/// Exact boundedness and lifecycle accounting for one operator PCM output
/// re-entering the Session audio lane.
///
/// This is a Session observation contract. The bridge worker and its queue are
/// deliberately not public extension APIs.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionAudioReentryMetrics {
    operator_instance_id: OperatorInstanceId,
    stem_id: StemId,
    queue_capacity_signals: u64,
    queue_depth_signals: u64,
    queue_peak_signals: u64,
    signals_enqueued_total: u64,
    signals_received_total: u64,
    signals_dropped_total: u64,
    pool_slots: u64,
    frame_capacity_samples: u64,
    maximum_buffered_audio_bytes: u64,
    normalized_total: u64,
    invalid_total: u64,
    shared_audio_rejected_total: u64,
    pool_exhausted_total: u64,
    ingress_rejected_total: u64,
    audio_frames_enqueued_total: u64,
    cancellation_total: u64,
    joined: bool,
}

impl SessionAudioReentryMetrics {
    pub(crate) fn from_bridge(
        operator_instance_id: OperatorInstanceId,
        stem_id: StemId,
        bridge: GeneratedAudioBridgeObservations,
    ) -> Self {
        Self {
            operator_instance_id,
            stem_id,
            queue_capacity_signals: bridge.input_edge.capacity_signals,
            queue_depth_signals: bridge.input_edge.depth_signals,
            queue_peak_signals: bridge.input_edge.peak_depth_signals,
            signals_enqueued_total: bridge.input_edge.enqueued_total,
            signals_received_total: bridge.input_edge.received_total,
            signals_dropped_total: bridge.input_edge.dropped_total,
            pool_slots: bridge.pool_slots,
            frame_capacity_samples: bridge.frame_capacity_samples,
            maximum_buffered_audio_bytes: bridge.maximum_buffered_audio_bytes,
            normalized_total: bridge.normalized_total,
            invalid_total: bridge.invalid_total,
            shared_audio_rejected_total: bridge.shared_audio_rejected_total,
            pool_exhausted_total: bridge.pool_exhausted_total,
            ingress_rejected_total: bridge.ingress_rejected_total,
            audio_frames_enqueued_total: bridge.enqueued_total,
            cancellation_total: bridge.cancellation_total,
            joined: bridge.joined,
        }
    }

    pub const fn operator_instance_id(self) -> OperatorInstanceId {
        self.operator_instance_id
    }

    pub const fn stem_id(self) -> StemId {
        self.stem_id
    }

    pub const fn queue_capacity_signals(self) -> u64 {
        self.queue_capacity_signals
    }

    pub const fn queue_depth_signals(self) -> u64 {
        self.queue_depth_signals
    }

    pub const fn queue_peak_signals(self) -> u64 {
        self.queue_peak_signals
    }

    pub const fn signals_enqueued_total(self) -> u64 {
        self.signals_enqueued_total
    }

    pub const fn signals_received_total(self) -> u64 {
        self.signals_received_total
    }

    pub const fn signals_dropped_total(self) -> u64 {
        self.signals_dropped_total
    }

    pub const fn pool_slots(self) -> u64 {
        self.pool_slots
    }

    pub const fn frame_capacity_samples(self) -> u64 {
        self.frame_capacity_samples
    }

    pub const fn maximum_buffered_audio_bytes(self) -> u64 {
        self.maximum_buffered_audio_bytes
    }

    pub const fn normalized_total(self) -> u64 {
        self.normalized_total
    }

    pub const fn invalid_total(self) -> u64 {
        self.invalid_total
    }

    pub const fn shared_audio_rejected_total(self) -> u64 {
        self.shared_audio_rejected_total
    }

    pub const fn pool_exhausted_total(self) -> u64 {
        self.pool_exhausted_total
    }

    pub const fn ingress_rejected_total(self) -> u64 {
        self.ingress_rejected_total
    }

    pub const fn audio_frames_enqueued_total(self) -> u64 {
        self.audio_frames_enqueued_total
    }

    pub const fn cancellation_total(self) -> u64 {
        self.cancellation_total
    }

    pub const fn joined(self) -> bool {
        self.joined
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionOperatorMetrics {
    pub operator_instance_id: OperatorInstanceId,
    /// Sole counter authority for input delivered by the compiled Session plan.
    ///
    /// `worker.input_*` remains meaningful only for workers fed through the
    /// direct `AsyncOperatorInput` API. Compiled Session operators consume this
    /// plan edge, so callers must use these observations for input accounting.
    pub input_edge: EdgeObservations,
    /// Exact per-port input accounting. `input_edge` is the compatibility
    /// aggregate across this slice.
    pub input_ports: Box<[SessionOperatorInputMetrics]>,
    pub worker: AsyncOperatorObservations,
    pub finalization_failures_total: u64,
}

impl SessionOperatorMetrics {
    pub fn input_port(&self, name: &str) -> Option<&SessionOperatorInputMetrics> {
        self.input_ports.iter().find(|port| port.port_name == name)
    }
    pub const fn input_queue_capacity_frames(&self) -> u64 {
        self.input_edge.queue_capacity_frames
    }

    pub const fn input_queue_depth_frames(&self) -> u64 {
        self.input_edge.queue_depth_frames
    }

    pub const fn input_queue_peak_frames(&self) -> u64 {
        self.input_edge.queue_peak_frames
    }

    pub fn input_attempted_total(&self) -> u64 {
        self.input_edge.frames_attempted_total()
    }

    pub const fn input_enqueued_total(&self) -> u64 {
        self.input_edge.frames_enqueued_total
    }

    pub const fn input_delivered_total(&self) -> u64 {
        self.input_edge.frames_delivered_total
    }

    pub const fn input_dropped_total(&self) -> u64 {
        self.input_edge.frames_dropped_total
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SessionDerivedRouteMetrics {
    pub route_id: RouteId,
    pub endpoint_id: EndpointId,
    pub output: AsyncOperatorOutputObservations,
    pub endpoint: Option<EndpointDriverObservations>,
    pub endpoint_observation_stage: EndpointObservationStage,
    pub endpoint_finalization_failures_total: u64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointObservationStage {
    Unavailable,
    Live,
    Finalized,
}

#[derive(Debug)]
pub(crate) struct SessionEventQueueCounters {
    capacity_event_count: u64,
    maximum_event_owned_bytes: u64,
    maximum_buffered_owned_bytes: u64,
    depth_events: AtomicU64,
    depth_owned_bytes: AtomicU64,
    peak_depth_event_count: AtomicU64,
    peak_depth_owned_bytes: AtomicU64,
    events_enqueued_total: AtomicU64,
    events_dropped_total: AtomicU64,
    events_dropped_oversized_total: AtomicU64,
    receiver_closed_total: AtomicU64,
}

pub(crate) enum SessionEventReservation {
    Reserved,
    Full,
    Oversized,
}

impl SessionEventQueueCounters {
    pub(crate) fn new(capacity_events: usize, maximum_event_owned_bytes: usize) -> Self {
        Self {
            capacity_event_count: capacity_events as u64,
            maximum_event_owned_bytes: maximum_event_owned_bytes as u64,
            maximum_buffered_owned_bytes: capacity_events.saturating_mul(maximum_event_owned_bytes)
                as u64,
            depth_events: AtomicU64::new(0),
            depth_owned_bytes: AtomicU64::new(0),
            peak_depth_event_count: AtomicU64::new(0),
            peak_depth_owned_bytes: AtomicU64::new(0),
            events_enqueued_total: AtomicU64::new(0),
            events_dropped_total: AtomicU64::new(0),
            events_dropped_oversized_total: AtomicU64::new(0),
            receiver_closed_total: AtomicU64::new(0),
        }
    }

    pub(crate) fn reserve_event(&self, owned_bytes: usize) -> SessionEventReservation {
        if owned_bytes as u64 > self.maximum_event_owned_bytes {
            self.events_dropped_total.fetch_add(1, Ordering::Relaxed);
            self.events_dropped_oversized_total
                .fetch_add(1, Ordering::Relaxed);
            return SessionEventReservation::Oversized;
        }
        let mut depth_events = self.depth_events.load(Ordering::Relaxed);
        loop {
            if depth_events >= self.capacity_event_count {
                self.events_dropped_total.fetch_add(1, Ordering::Relaxed);
                return SessionEventReservation::Full;
            }

            match self.depth_events.compare_exchange_weak(
                depth_events,
                depth_events + 1,
                Ordering::AcqRel,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    self.peak_depth_event_count
                        .fetch_max(depth_events + 1, Ordering::Relaxed);
                    let depth_owned_bytes = self
                        .depth_owned_bytes
                        .fetch_add(owned_bytes as u64, Ordering::AcqRel)
                        .saturating_add(owned_bytes as u64);
                    self.peak_depth_owned_bytes
                        .fetch_max(depth_owned_bytes, Ordering::Relaxed);
                    return SessionEventReservation::Reserved;
                }
                Err(observed_depth_events) => depth_events = observed_depth_events,
            }
        }
    }

    pub(crate) fn observe_enqueued(&self) {
        self.events_enqueued_total.fetch_add(1, Ordering::Relaxed);
    }

    pub(crate) fn observe_send_full(&self, owned_bytes: usize) {
        self.cancel_reservation(owned_bytes);
        self.events_dropped_total.fetch_add(1, Ordering::Relaxed);
    }

    pub(crate) fn observe_receiver_closed(&self, owned_bytes: usize) {
        self.cancel_reservation(owned_bytes);
        self.events_dropped_total.fetch_add(1, Ordering::Relaxed);
        self.receiver_closed_total.fetch_add(1, Ordering::Relaxed);
    }

    pub(crate) fn observe_dequeued(&self, owned_bytes: usize) {
        let previous_depth_events = self.depth_events.fetch_sub(1, Ordering::AcqRel);
        debug_assert!(previous_depth_events > 0);
        let previous_depth_owned_bytes = self
            .depth_owned_bytes
            .fetch_sub(owned_bytes as u64, Ordering::AcqRel);
        debug_assert!(previous_depth_owned_bytes >= owned_bytes as u64);
    }

    pub(crate) fn snapshot(&self) -> SessionEventQueueObservations {
        SessionEventQueueObservations {
            capacity_event_count: self.capacity_event_count,
            maximum_event_owned_bytes: self.maximum_event_owned_bytes,
            maximum_buffered_owned_bytes: self.maximum_buffered_owned_bytes,
            depth_events: self.depth_events.load(Ordering::Acquire),
            depth_owned_bytes: self.depth_owned_bytes.load(Ordering::Acquire),
            peak_depth_event_count: self.peak_depth_event_count.load(Ordering::Relaxed),
            peak_depth_owned_bytes: self.peak_depth_owned_bytes.load(Ordering::Relaxed),
            events_enqueued_total: self.events_enqueued_total.load(Ordering::Relaxed),
            events_dropped_total: self.events_dropped_total.load(Ordering::Relaxed),
            events_dropped_oversized_total: self
                .events_dropped_oversized_total
                .load(Ordering::Relaxed),
            receiver_closed_total: self.receiver_closed_total.load(Ordering::Relaxed),
        }
    }

    fn cancel_reservation(&self, owned_bytes: usize) {
        let previous_depth_events = self.depth_events.fetch_sub(1, Ordering::AcqRel);
        debug_assert!(previous_depth_events > 0);
        let previous_depth_owned_bytes = self
            .depth_owned_bytes
            .fetch_sub(owned_bytes as u64, Ordering::AcqRel);
        debug_assert!(previous_depth_owned_bytes >= owned_bytes as u64);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn given_route_snapshot_when_drop_observed_then_rate_has_explicit_denominator_and_reasons() {
        let route = SessionRouteMetrics {
            route_id: RouteId(7),
            endpoint_id: EndpointId(8),
            edge: EdgeObservations {
                frames_enqueued_total: 3,
                frames_dropped_total: 1,
                queue_full_drops_total: 1,
                ..EdgeObservations::default()
            },
            endpoint: None,
            endpoint_observation_stage: EndpointObservationStage::Unavailable,
            endpoint_finalization_failures_total: 0,
        };

        let drops = route.drop_observations();
        assert_eq!(drops.route_id, RouteId(7));
        assert_eq!(drops.frames_dropped_total, 1);
        assert_eq!(drops.frames_attempted_total, 4);
        assert_eq!(drops.queue_full_drops_total, 1);
        assert_eq!(
            drops.interval,
            SessionRouteObservationInterval::RouteLifetimeToSnapshot
        );
        assert!((drops.drop_rate_pct() - 25.0).abs() < f64::EPSILON);
    }

    #[test]
    fn given_route_snapshot_when_latency_observed_then_boundary_units_and_coverage_are_explicit() {
        let route = SessionRouteMetrics {
            route_id: RouteId(7),
            endpoint_id: EndpointId(8),
            edge: EdgeObservations {
                source_timestamp_to_receive_samples_total: 9,
                source_timestamp_to_receive_missing_total: 2,
                source_timestamp_to_receive_future_total: 1,
                source_timestamp_to_receive_p95_ns: 42,
                ..EdgeObservations::default()
            },
            endpoint: None,
            endpoint_observation_stage: EndpointObservationStage::Unavailable,
            endpoint_finalization_failures_total: 0,
        };

        let latency = route.source_to_receive_latency();
        assert_eq!(latency.route_id, RouteId(7));
        assert_eq!(
            latency.boundary,
            SessionRouteLatencyBoundary::SourceMonotonicTimestampToRouteReceive
        );
        assert_eq!(latency.unit, SessionRouteLatencyUnit::Nanoseconds);
        assert_eq!(latency.samples_total, 9);
        assert_eq!(latency.missing_or_incompatible_clock_total, 2);
        assert_eq!(latency.future_timestamp_total, 1);
        assert_eq!(latency.p95_ns, 42);
    }
}