Skip to main content

gemini_adk_rs/live/
telemetry.rs

1//! Lightweight session telemetry — atomic fast-lane counters + periodic aggregation.
2//!
3//! All hot-path operations (counter increments, timestamp recording) are lock-free
4//! and zero-allocation (~1ns per call), so the router records them inline.
5//! Aggregation only happens at snapshot time or at turn boundaries, ensuring no
6//! impact on the latency-sensitive audio pipeline.
7//!
8//! The number a voice product is judged on is **response latency**: the time
9//! from the user's end of speech to the model's first audio byte. It is
10//! recorded per turn into [`LatencyStats`] — last, min, max, mean, the p50/
11//! p90/p99 of recent turns, and a fixed-bucket histogram — and read through
12//! [`SessionTelemetry::latency`] or [`SessionTelemetry::snapshot`].
13
14use std::fmt;
15use std::time::{Duration, Instant};
16
17// Under `--cfg gemini_adk_loom` the counters are loom's model atomics, so the `record`
18// / `stats` protocol below can be checked over every interleaving; the
19// production build uses `std` ones. Only this module switches: the model
20// covers the telemetry lane's counters, nothing else.
21#[cfg(gemini_adk_loom)]
22use loom::sync::atomic::{
23    AtomicBool, AtomicU64,
24    Ordering::{Acquire, Relaxed, Release},
25};
26#[cfg(not(gemini_adk_loom))]
27use std::sync::atomic::{
28    AtomicBool, AtomicU64,
29    Ordering::{Acquire, Relaxed, Release},
30};
31
32use serde::{Deserialize, Serialize};
33use serde_json::json;
34
35/// Upper bounds, in milliseconds, of the response-latency histogram buckets.
36///
37/// A final open bucket collects everything above the last bound. The bounds
38/// are denser where voice products live (150–1000 ms) and coarser beyond.
39pub const LATENCY_BUCKETS_MS: [u64; 17] = [
40    50, 100, 150, 200, 300, 400, 500, 650, 800, 1000, 1300, 1600, 2000, 2500, 3000, 4000, 5000,
41];
42
43/// Number of most-recent samples the percentiles are computed over.
44///
45/// Percentiles are exact over this window (nearest-rank on a sorted copy),
46/// which covers every turn of all but the longest sessions; the histogram
47/// carries the full session.
48pub const LATENCY_RECENT_WINDOW: usize = 256;
49
50const BUCKET_COUNT: usize = LATENCY_BUCKETS_MS.len() + 1;
51
52/// One bucket of the response-latency histogram.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
54pub struct LatencyBucket {
55    /// Inclusive upper bound in milliseconds; `None` for the open top bucket.
56    pub upper_ms: Option<u64>,
57    /// Number of turns whose latency fell in this bucket.
58    pub count: u64,
59}
60
61/// Response-latency distribution for the session so far.
62///
63/// All durations are whole milliseconds. Every field is `0` until the first
64/// turn has been measured (`count == 0`).
65#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
66pub struct LatencyStats {
67    /// Number of measured turns.
68    pub count: u64,
69    /// Latency of the most recent turn.
70    pub last_ms: u64,
71    /// Fastest turn.
72    pub min_ms: u64,
73    /// Slowest turn.
74    pub max_ms: u64,
75    /// Mean over all measured turns.
76    pub mean_ms: u64,
77    /// Median of the most recent [`LATENCY_RECENT_WINDOW`] turns.
78    pub p50_ms: u64,
79    /// 90th percentile of the most recent [`LATENCY_RECENT_WINDOW`] turns.
80    pub p90_ms: u64,
81    /// 99th percentile of the most recent [`LATENCY_RECENT_WINDOW`] turns.
82    pub p99_ms: u64,
83    /// Full-session histogram, one entry per [`LATENCY_BUCKETS_MS`] bound plus
84    /// the open top bucket.
85    pub histogram: Vec<LatencyBucket>,
86}
87
88impl fmt::Display for LatencyStats {
89    /// One line, fit for a log: `turns=12 last=420ms p50=380ms p90=610ms max=900ms`.
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        if self.count == 0 {
92            return write!(f, "turns=0 (no response measured yet)");
93        }
94        write!(
95            f,
96            "turns={} last={}ms p50={}ms p90={}ms p99={}ms min={}ms max={}ms",
97            self.count,
98            self.last_ms,
99            self.p50_ms,
100            self.p90_ms,
101            self.p99_ms,
102            self.min_ms,
103            self.max_ms
104        )
105    }
106}
107
108/// Lock-free per-turn latency recorder: scalars, a histogram, and a ring of
109/// recent samples, all atomics.
110struct LatencyRecorder {
111    last_ns: AtomicU64,
112    sum_ns: AtomicU64,
113    count: AtomicU64,
114    min_ns: AtomicU64,
115    max_ns: AtomicU64,
116    buckets: [AtomicU64; BUCKET_COUNT],
117    recent: [AtomicU64; LATENCY_RECENT_WINDOW],
118    recent_next: AtomicU64,
119}
120
121impl LatencyRecorder {
122    fn new() -> Self {
123        Self {
124            last_ns: AtomicU64::new(0),
125            sum_ns: AtomicU64::new(0),
126            count: AtomicU64::new(0),
127            min_ns: AtomicU64::new(u64::MAX),
128            max_ns: AtomicU64::new(0),
129            buckets: std::array::from_fn(|_| AtomicU64::new(0)),
130            recent: std::array::from_fn(|_| AtomicU64::new(0)),
131            recent_next: AtomicU64::new(0),
132        }
133    }
134
135    /// Record one turn's latency.
136    ///
137    /// `count` is the publication point and is written **last**, with
138    /// [`Release`]: a reader that observes `count == n` (with [`Acquire`], as
139    /// [`stats`](Self::stats) does) sees the scalars and histogram of at
140    /// least `n` samples. The ring is published slot by slot: a slot holds
141    /// `latency + 1` once written and `0` while it is still claimed but
142    /// unwritten, so a reader skips it. With two writers the slot order and
143    /// the `count` order can differ (one claims slot 0, the other claims slot
144    /// 1 and publishes first), which is why the count alone cannot say which
145    /// slots are readable; the loom model in this file checks that.
146    #[inline]
147    fn record(&self, latency_ns: u64) {
148        self.last_ns.store(latency_ns, Relaxed);
149        self.sum_ns.fetch_add(latency_ns, Relaxed);
150        self.min_ns.fetch_min(latency_ns, Relaxed);
151        self.max_ns.fetch_max(latency_ns, Relaxed);
152
153        let ms = latency_ns / 1_000_000;
154        let bucket = LATENCY_BUCKETS_MS
155            .iter()
156            .position(|&upper| ms <= upper)
157            .unwrap_or(BUCKET_COUNT - 1);
158        self.buckets[bucket].fetch_add(1, Relaxed);
159
160        // Ring of recent samples: one atomic slot per turn, index wraps.
161        let slot = self.recent_next.fetch_add(1, Relaxed) as usize % LATENCY_RECENT_WINDOW;
162        // `+ 1` so that an unwritten slot (0) is distinguishable from a
163        // zero-latency sample; `stats` subtracts it. `Release`: a reader that
164        // sees this slot (with `Acquire`) also sees the scalars and the
165        // histogram bucket written above it, so a percentile over the ring
166        // never exceeds the `max` or undercuts the `min` read beside it.
167        self.recent[slot].store(latency_ns.saturating_add(1), Release);
168
169        self.count.fetch_add(1, Release);
170    }
171
172    fn stats(&self) -> LatencyStats {
173        // Acquire pairs with the Release in `record`: every sample counted here
174        // is already visible in the scalars and the histogram.
175        let count = self.count.load(Acquire);
176        let histogram = self
177            .buckets
178            .iter()
179            .enumerate()
180            .map(|(i, b)| LatencyBucket {
181                upper_ms: LATENCY_BUCKETS_MS.get(i).copied(),
182                count: b.load(Relaxed),
183            })
184            .collect();
185        if count == 0 {
186            return LatencyStats {
187                histogram,
188                ..LatencyStats::default()
189            };
190        }
191
192        // The window is every slot a writer has claimed; a slot still at 0
193        // was claimed but not yet written (see `record`) and is skipped, so
194        // a percentile never counts a sample that was not published.
195        let claimed = (self.recent_next.load(Relaxed) as usize).min(LATENCY_RECENT_WINDOW);
196        let mut recent: Vec<u64> = self.recent[..claimed]
197            .iter()
198            .map(|s| s.load(Acquire))
199            .filter(|&s| s != 0)
200            .map(|s| s - 1)
201            .collect();
202        recent.sort_unstable();
203        // Nearest-rank percentile over the sorted recent window.
204        let pct = |p: usize| -> u64 {
205            let rank = (p * recent.len()).div_ceil(100).max(1);
206            recent.get(rank - 1).copied().unwrap_or(0) / 1_000_000
207        };
208
209        LatencyStats {
210            count,
211            last_ms: self.last_ns.load(Relaxed) / 1_000_000,
212            min_ms: self.min_ns.load(Relaxed) / 1_000_000,
213            max_ms: self.max_ns.load(Relaxed) / 1_000_000,
214            mean_ms: self.sum_ns.load(Relaxed) / count / 1_000_000,
215            p50_ms: pct(50),
216            p90_ms: pct(90),
217            p99_ms: pct(99),
218            histogram,
219        }
220    }
221}
222
223/// Zero-overhead telemetry collector for speech-to-speech sessions.
224///
225/// Designed for the three-lane processor model:
226/// - **Fast lane** (sync, <1ms): No telemetry calls — pure audio/text forwarding.
227/// - **Router**: Calls `record_*` methods on every event, in event order.
228///   These use only atomic operations — no allocations, no locks, no syscalls.
229/// - **Control lane** (async): Calls `snapshot()` at turn boundaries to get
230///   aggregated stats as a JSON value ready to send to the browser.
231pub struct SessionTelemetry {
232    start: Instant,
233
234    // ── Audio throughput ──
235    audio_chunks_out: AtomicU64,
236    audio_bytes_out: AtomicU64,
237
238    // ── Interruptions ──
239    interruptions: AtomicU64,
240
241    // ── Response latency tracking ──
242    // Stores nanos-since-session-start for atomic compatibility with Instant.
243    vad_end_ns: AtomicU64,
244    awaiting_response: AtomicBool,
245    /// Timestamp when user sent text (for text-input latency tracking).
246    text_send_ns: AtomicU64,
247    awaiting_text_response: AtomicBool,
248    /// Per-turn response latency: end of user speech (or text send) to the
249    /// model's first output.
250    latency: LatencyRecorder,
251
252    // ── Turn timing ──
253    turn_complete_count: AtomicU64,
254    last_turn_start_ns: AtomicU64,
255    turn_duration_sum_ns: AtomicU64,
256    turn_duration_count: AtomicU64,
257
258    // ── Token usage (from UsageMetadata) ──
259    /// Latest total token count from server.
260    total_token_count: AtomicU64,
261    /// Latest prompt token count from server.
262    prompt_token_count: AtomicU64,
263    /// Latest response token count from server.
264    response_token_count: AtomicU64,
265    /// Latest cached content token count from server.
266    cached_content_token_count: AtomicU64,
267    /// Latest thoughts token count (thinking models).
268    thoughts_token_count: AtomicU64,
269    /// Session totals by modality (`TEXT`, `AUDIO`, ...): prompt and
270    /// response tokens, summed over turns.
271    tokens_by_modality: parking_lot::Mutex<std::collections::BTreeMap<String, [u64; 2]>>,
272}
273
274impl SessionTelemetry {
275    /// Create a new telemetry tracker, starting the session clock.
276    pub fn new() -> Self {
277        Self {
278            start: Instant::now(),
279            audio_chunks_out: AtomicU64::new(0),
280            audio_bytes_out: AtomicU64::new(0),
281            interruptions: AtomicU64::new(0),
282            vad_end_ns: AtomicU64::new(0),
283            awaiting_response: AtomicBool::new(false),
284            text_send_ns: AtomicU64::new(0),
285            awaiting_text_response: AtomicBool::new(false),
286            latency: LatencyRecorder::new(),
287            turn_complete_count: AtomicU64::new(0),
288            last_turn_start_ns: AtomicU64::new(0),
289            turn_duration_sum_ns: AtomicU64::new(0),
290            turn_duration_count: AtomicU64::new(0),
291            total_token_count: AtomicU64::new(0),
292            prompt_token_count: AtomicU64::new(0),
293            response_token_count: AtomicU64::new(0),
294            cached_content_token_count: AtomicU64::new(0),
295            thoughts_token_count: AtomicU64::new(0),
296            tokens_by_modality: parking_lot::Mutex::new(std::collections::BTreeMap::new()),
297        }
298    }
299
300    // ── Atomic methods (~1ns each) ──
301
302    /// Record an outgoing audio chunk. Called from the router.
303    ///
304    /// Returns the response latency when this chunk is the model's first
305    /// output after the user's end of speech (or text send) — once per turn,
306    /// via a CAS so only the first chunk wins.
307    #[inline]
308    pub fn record_audio_out(&self, byte_len: usize) -> Option<Duration> {
309        self.audio_chunks_out.fetch_add(1, Relaxed);
310        self.audio_bytes_out.fetch_add(byte_len as u64, Relaxed);
311
312        // A text send answered with audio counts as a response too.
313        let text = self.record_text_response_latency();
314
315        // Latency: if we're awaiting the model's first byte after VAD end,
316        // record the response latency via CAS (only the first chunk wins).
317        if self
318            .awaiting_response
319            .compare_exchange(true, false, Relaxed, Relaxed)
320            .is_ok()
321        {
322            let now_ns = self.elapsed_ns();
323            let vad_end = self.vad_end_ns.load(Relaxed);
324            if now_ns > vad_end && vad_end > 0 {
325                let latency = now_ns - vad_end;
326                self.latency.record(latency);
327                gemini_genai_rs::telemetry::metrics::record_response_latency(latency as f64 / 1e6);
328                return Some(Duration::from_nanos(latency));
329            }
330        }
331        text
332    }
333
334    /// Record VAD end (user stopped speaking).
335    #[inline]
336    pub fn record_vad_end(&self) {
337        self.vad_end_ns.store(self.elapsed_ns(), Relaxed);
338        self.awaiting_response.store(true, Relaxed);
339    }
340
341    /// Record that user sent a text message (for text-input latency tracking).
342    #[inline]
343    pub fn record_text_send(&self) {
344        self.text_send_ns.store(self.elapsed_ns(), Relaxed);
345        self.awaiting_text_response.store(true, Relaxed);
346    }
347
348    /// Record first model output for text-input latency.
349    /// Call on first TextDelta or AudioData after a text send.
350    #[inline]
351    fn record_text_response_latency(&self) -> Option<Duration> {
352        if self
353            .awaiting_text_response
354            .compare_exchange(true, false, Relaxed, Relaxed)
355            .is_ok()
356        {
357            let now_ns = self.elapsed_ns();
358            let send_ns = self.text_send_ns.load(Relaxed);
359            if now_ns > send_ns && send_ns > 0 {
360                let latency = now_ns - send_ns;
361                self.latency.record(latency);
362                gemini_genai_rs::telemetry::metrics::record_response_latency(latency as f64 / 1e6);
363                return Some(Duration::from_nanos(latency));
364            }
365        }
366        None
367    }
368
369    /// Record first model text output (TextDelta). Tracks text-input latency.
370    ///
371    /// Returns the response latency when this delta is the model's first
372    /// output after a text send.
373    #[inline]
374    pub fn record_text_out(&self) -> Option<Duration> {
375        self.record_text_response_latency()
376    }
377
378    /// Record an interruption (barge-in).
379    #[inline]
380    pub fn record_interruption(&self) {
381        self.interruptions.fetch_add(1, Relaxed);
382    }
383
384    /// Record turn completion for duration tracking.
385    #[inline]
386    pub fn record_turn_complete(&self) {
387        self.turn_complete_count.fetch_add(1, Relaxed);
388        let now = self.elapsed_ns();
389        let turn_start = self.last_turn_start_ns.swap(now, Relaxed);
390        if turn_start > 0 {
391            let duration = now.saturating_sub(turn_start);
392            self.turn_duration_sum_ns.fetch_add(duration, Relaxed);
393            self.turn_duration_count.fetch_add(1, Relaxed);
394        }
395    }
396
397    /// Record token usage from a `UsageMetadata` event.
398    #[inline]
399    pub fn record_usage(
400        &self,
401        total: Option<u32>,
402        prompt: Option<u32>,
403        response: Option<u32>,
404        cached: Option<u32>,
405        thoughts: Option<u32>,
406    ) {
407        if let Some(v) = total {
408            self.total_token_count.store(v as u64, Relaxed);
409        }
410        if let Some(v) = prompt {
411            self.prompt_token_count.store(v as u64, Relaxed);
412        }
413        if let Some(v) = response {
414            self.response_token_count.store(v as u64, Relaxed);
415        }
416        if let Some(v) = cached {
417            self.cached_content_token_count.store(v as u64, Relaxed);
418        }
419        if let Some(v) = thoughts {
420            self.thoughts_token_count.store(v as u64, Relaxed);
421        }
422    }
423
424    /// Add one turn's usage, by modality, to the session totals, and to the
425    /// `gemini_genai_rs_tokens_total` metric. Pass the last usage report of
426    /// the turn: each report covers the turn so far.
427    pub fn record_turn_usage(&self, usage: &gemini_genai_rs::prelude::UsageMetadata) {
428        let mut totals = self.tokens_by_modality.lock();
429        for (index, direction, details) in [
430            (0, "prompt", &usage.prompt_tokens_details),
431            (1, "response", &usage.response_tokens_details),
432        ] {
433            for detail in details {
434                let (Some(modality), Some(count)) = (&detail.modality, detail.token_count) else {
435                    continue;
436                };
437                totals.entry(modality.clone()).or_default()[index] += u64::from(count);
438                gemini_genai_rs::telemetry::metrics::record_tokens(
439                    direction,
440                    modality,
441                    count.into(),
442                );
443            }
444        }
445    }
446
447    /// Mark the beginning of a new turn (e.g., when model starts responding).
448    #[inline]
449    pub fn mark_turn_start(&self) {
450        let now = self.elapsed_ns();
451        // Only set if not already set (first call per turn wins)
452        self.last_turn_start_ns
453            .compare_exchange(0, now, Relaxed, Relaxed)
454            .ok();
455    }
456
457    // ── Aggregation (called at turn boundaries / periodic flush) ──
458
459    /// Per-turn response latency: end of user speech (or text send) to the
460    /// model's first output, as a distribution over the session so far.
461    ///
462    /// Cheap enough to call once per turn (it sorts at most
463    /// [`LATENCY_RECENT_WINDOW`] samples); not for the audio hot path.
464    pub fn latency(&self) -> LatencyStats {
465        self.latency.stats()
466    }
467
468    /// Snapshot all metrics as a JSON value.
469    ///
470    /// The flat `*_response_latency_ms` keys are kept for existing dashboards;
471    /// `response_latency` carries the full [`LatencyStats`] (percentiles and
472    /// histogram included).
473    pub fn snapshot(&self) -> serde_json::Value {
474        let elapsed = self.start.elapsed();
475        let elapsed_secs = elapsed.as_secs_f64();
476
477        let chunks = self.audio_chunks_out.load(Relaxed);
478        let bytes = self.audio_bytes_out.load(Relaxed);
479        let latency = self.latency.stats();
480
481        let turn_count = self.turn_duration_count.load(Relaxed);
482        let turn_complete_count = self.turn_complete_count.load(Relaxed);
483        let avg_turn_ms = self
484            .turn_duration_sum_ns
485            .load(Relaxed)
486            .checked_div(turn_count)
487            .map_or(0, |ns| ns / 1_000_000);
488
489        // Audio throughput (KB/s over session lifetime)
490        let throughput_kbps = if elapsed_secs > 0.0 {
491            (bytes as f64 / 1024.0) / elapsed_secs
492        } else {
493            0.0
494        };
495
496        let total_tokens = self.total_token_count.load(Relaxed);
497        let prompt_tokens = self.prompt_token_count.load(Relaxed);
498        let response_tokens = self.response_token_count.load(Relaxed);
499        let cached_tokens = self.cached_content_token_count.load(Relaxed);
500        let thoughts_tokens = self.thoughts_token_count.load(Relaxed);
501
502        json!({
503            "uptime_secs": elapsed.as_secs(),
504            "audio_chunks_out": chunks,
505            "audio_kbytes_out": bytes / 1024,
506            "audio_throughput_kbps": (throughput_kbps * 10.0).round() / 10.0,
507            "interruptions": self.interruptions.load(Relaxed),
508            "last_response_latency_ms": latency.last_ms,
509            "avg_response_latency_ms": latency.mean_ms,
510            "min_response_latency_ms": latency.min_ms,
511            "max_response_latency_ms": latency.max_ms,
512            "response_count": latency.count,
513            "response_latency": latency,
514            "turn_count": turn_complete_count,
515            "avg_turn_duration_ms": avg_turn_ms,
516            "total_token_count": total_tokens,
517            "prompt_token_count": prompt_tokens,
518            "response_token_count": response_tokens,
519            "cached_content_token_count": cached_tokens,
520            "thoughts_token_count": thoughts_tokens,
521            "tokens_by_modality": self
522                .tokens_by_modality
523                .lock()
524                .iter()
525                .map(|(modality, [prompt, response])| {
526                    (modality.clone(), json!({ "prompt": prompt, "response": response }))
527                })
528                .collect::<serde_json::Map<_, _>>(),
529        })
530    }
531
532    #[inline]
533    fn elapsed_ns(&self) -> u64 {
534        self.start.elapsed().as_nanos() as u64
535    }
536}
537
538impl Default for SessionTelemetry {
539    fn default() -> Self {
540        Self::new()
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547
548    #[test]
549    fn turn_usage_is_summed_by_modality() {
550        let t = SessionTelemetry::new();
551        let usage: gemini_genai_rs::prelude::UsageMetadata = serde_json::from_value(json!({
552            "promptTokenCount": 30,
553            "promptTokensDetails": [
554                { "modality": "AUDIO", "tokenCount": 20 },
555                { "modality": "TEXT", "tokenCount": 10 }
556            ],
557            "responseTokensDetails": [{ "modality": "AUDIO", "tokenCount": 40 }]
558        }))
559        .unwrap();
560        t.record_turn_usage(&usage);
561        t.record_turn_usage(&usage);
562        let snap = t.snapshot();
563        assert_eq!(
564            snap["tokens_by_modality"]["AUDIO"],
565            json!({ "prompt": 40, "response": 80 })
566        );
567        assert_eq!(
568            snap["tokens_by_modality"]["TEXT"],
569            json!({ "prompt": 20, "response": 0 })
570        );
571    }
572
573    #[test]
574    fn new_snapshot_is_zeroed() {
575        let t = SessionTelemetry::new();
576        let snap = t.snapshot();
577        assert_eq!(snap["audio_chunks_out"], 0);
578        assert_eq!(snap["interruptions"], 0);
579        assert_eq!(snap["last_response_latency_ms"], 0);
580        assert_eq!(snap["response_count"], 0);
581        assert_eq!(snap["turn_count"], 0);
582        assert_eq!(snap["response_latency"]["count"], 0);
583        assert_eq!(
584            t.latency(),
585            LatencyStats {
586                histogram: t.latency().histogram.clone(),
587                ..LatencyStats::default()
588            }
589        );
590        assert_eq!(
591            t.latency().to_string(),
592            "turns=0 (no response measured yet)"
593        );
594    }
595
596    #[test]
597    fn audio_counters_accumulate() {
598        let t = SessionTelemetry::new();
599        t.record_audio_out(480);
600        t.record_audio_out(480);
601        t.record_audio_out(480);
602        let snap = t.snapshot();
603        assert_eq!(snap["audio_chunks_out"], 3);
604    }
605
606    #[test]
607    fn interruption_counter() {
608        let t = SessionTelemetry::new();
609        t.record_interruption();
610        t.record_interruption();
611        assert_eq!(t.snapshot()["interruptions"], 2);
612    }
613
614    #[test]
615    fn turn_complete_counter_is_independent_of_latency() {
616        let t = SessionTelemetry::new();
617        t.record_turn_complete();
618        t.record_turn_complete();
619
620        let snap = t.snapshot();
621        assert_eq!(snap["turn_count"], 2);
622        assert_eq!(snap["response_count"], 0);
623    }
624
625    #[test]
626    fn latency_tracking() {
627        let t = SessionTelemetry::new();
628        // Simulate: VAD end → short delay → first audio chunk
629        t.record_vad_end();
630        std::thread::sleep(std::time::Duration::from_millis(10));
631        let first = t.record_audio_out(480);
632        assert!(
633            first.is_some(),
634            "first chunk after VAD end reports the latency"
635        );
636        // Subsequent chunks should not re-record latency
637        assert!(t.record_audio_out(480).is_none());
638        assert!(t.record_audio_out(480).is_none());
639
640        let snap = t.snapshot();
641        assert_eq!(snap["response_count"], 1);
642        // Latency should be >= 10ms (we slept 10ms)
643        assert!(snap["last_response_latency_ms"].as_u64().unwrap() >= 5);
644        assert_eq!(snap["response_latency"]["count"], 1);
645    }
646
647    #[test]
648    fn multiple_turns_average_latency() {
649        let t = SessionTelemetry::new();
650
651        // Turn 1
652        t.record_vad_end();
653        std::thread::sleep(std::time::Duration::from_millis(10));
654        t.record_audio_out(480);
655
656        // Turn 2
657        t.record_vad_end();
658        std::thread::sleep(std::time::Duration::from_millis(10));
659        t.record_audio_out(480);
660
661        let snap = t.snapshot();
662        assert_eq!(snap["response_count"], 2);
663        assert!(snap["avg_response_latency_ms"].as_u64().unwrap() >= 5);
664    }
665
666    #[test]
667    fn text_input_latency_via_text_out() {
668        let t = SessionTelemetry::new();
669        // Simulate: user sends text → delay → model responds with text
670        t.record_text_send();
671        std::thread::sleep(std::time::Duration::from_millis(10));
672        assert!(t.record_text_out().is_some());
673        // Subsequent text outputs should not re-record
674        assert!(t.record_text_out().is_none());
675
676        let snap = t.snapshot();
677        assert_eq!(snap["response_count"], 1);
678        assert!(snap["last_response_latency_ms"].as_u64().unwrap() >= 5);
679    }
680
681    #[test]
682    fn text_input_latency_via_audio_out() {
683        let t = SessionTelemetry::new();
684        // Simulate: user sends text → delay → model responds with audio
685        t.record_text_send();
686        std::thread::sleep(std::time::Duration::from_millis(10));
687        assert!(t.record_audio_out(480).is_some());
688
689        let snap = t.snapshot();
690        // Should record text-send latency (response_count = 1)
691        assert_eq!(snap["response_count"], 1);
692        assert!(snap["last_response_latency_ms"].as_u64().unwrap() >= 5);
693    }
694
695    #[test]
696    fn mixed_voice_and_text_turns() {
697        let t = SessionTelemetry::new();
698
699        // Voice turn
700        t.record_vad_end();
701        std::thread::sleep(std::time::Duration::from_millis(10));
702        t.record_audio_out(480);
703
704        // Text turn
705        t.record_text_send();
706        std::thread::sleep(std::time::Duration::from_millis(10));
707        t.record_text_out();
708
709        let snap = t.snapshot();
710        assert_eq!(snap["response_count"], 2);
711    }
712
713    // ── LatencyRecorder: distribution semantics, fed directly in nanos ──
714
715    fn ms(n: u64) -> u64 {
716        n * 1_000_000
717    }
718
719    #[test]
720    fn recorder_scalars_and_percentiles() {
721        let r = LatencyRecorder::new();
722        for v in [300, 100, 500, 200, 400] {
723            r.record(ms(v));
724        }
725        let s = r.stats();
726        assert_eq!(s.count, 5);
727        assert_eq!(s.last_ms, 400);
728        assert_eq!(s.min_ms, 100);
729        assert_eq!(s.max_ms, 500);
730        assert_eq!(s.mean_ms, 300);
731        // Nearest rank over [100,200,300,400,500]: p50 → rank 3 → 300,
732        // p90 → rank 5 → 500, p99 → rank 5 → 500.
733        assert_eq!(s.p50_ms, 300);
734        assert_eq!(s.p90_ms, 500);
735        assert_eq!(s.p99_ms, 500);
736        assert_eq!(
737            s.to_string(),
738            "turns=5 last=400ms p50=300ms p90=500ms p99=500ms min=100ms max=500ms"
739        );
740    }
741
742    #[test]
743    fn recorder_first_sample_is_visible_to_percentiles() {
744        // A count of 1 must come with a window of 1 — never an empty window
745        // that the nearest-rank index would then read past the end of.
746        let r = LatencyRecorder::new();
747        r.record(ms(420));
748        let s = r.stats();
749        assert_eq!(s.count, 1);
750        assert_eq!((s.p50_ms, s.p90_ms, s.p99_ms), (420, 420, 420));
751        assert_eq!(s.mean_ms, 420);
752    }
753
754    #[test]
755    fn recorder_stats_survives_a_count_without_its_sample() {
756        // The panic this pins: `stats()` gated on `count` but sized its
757        // percentile window from `recent_next`. A count that ran ahead of the
758        // ring — as it did while `record` bumped the count first — left an
759        // empty window that the nearest-rank index then read past the end of.
760        // `stats()` now sizes the window from the same counter it gates on.
761        let r = LatencyRecorder::new();
762        r.count.store(1, Release); // counted, ring slot not yet written
763        let s = r.stats();
764        assert_eq!(s.count, 1);
765        assert_eq!((s.p50_ms, s.p90_ms, s.p99_ms), (0, 0, 0));
766    }
767
768    #[test]
769    fn recorder_snapshots_stay_consistent_under_concurrent_records() {
770        // `stats()` runs on whatever thread the caller likes while the
771        // telemetry lane records; no snapshot may mix samples from different
772        // moments into an impossible summary.
773        use std::sync::Arc;
774        use std::sync::atomic::AtomicBool;
775
776        let r = Arc::new(LatencyRecorder::new());
777        let done = Arc::new(AtomicBool::new(false));
778
779        let reader = {
780            let r = Arc::clone(&r);
781            let done = Arc::clone(&done);
782            std::thread::spawn(move || {
783                while !done.load(Relaxed) {
784                    let s = r.stats();
785                    if s.count > 0 {
786                        assert!(s.p99_ms >= s.p50_ms);
787                        assert!(s.max_ms >= s.p99_ms);
788                        assert!(s.min_ms <= s.max_ms);
789                    }
790                }
791            })
792        };
793
794        for _ in 0..2_000 {
795            r.record(ms(100));
796        }
797        done.store(true, Relaxed);
798        reader.join().expect("reader saw an inconsistent snapshot");
799        assert_eq!(r.stats().count, 2_000);
800    }
801
802    #[test]
803    fn recorder_histogram_buckets_by_upper_bound() {
804        let r = LatencyRecorder::new();
805        r.record(ms(50)); // ≤ 50 → bucket 0 (inclusive bound)
806        r.record(ms(51)); // ≤ 100 → bucket 1
807        r.record(ms(999)); // ≤ 1000 → bucket 9
808        r.record(ms(9_000)); // > 5000 → open top bucket
809        let h = r.stats().histogram;
810        assert_eq!(h.len(), LATENCY_BUCKETS_MS.len() + 1);
811        assert_eq!(
812            h[0],
813            LatencyBucket {
814                upper_ms: Some(50),
815                count: 1
816            }
817        );
818        assert_eq!(
819            h[1],
820            LatencyBucket {
821                upper_ms: Some(100),
822                count: 1
823            }
824        );
825        assert_eq!(
826            h[9],
827            LatencyBucket {
828                upper_ms: Some(1000),
829                count: 1
830            }
831        );
832        assert_eq!(
833            h[h.len() - 1],
834            LatencyBucket {
835                upper_ms: None,
836                count: 1
837            }
838        );
839        assert_eq!(h.iter().map(|b| b.count).sum::<u64>(), 4);
840    }
841
842    #[test]
843    fn recorder_percentiles_use_recent_window_only() {
844        let r = LatencyRecorder::new();
845        // Fill the window with slow turns, then overwrite it entirely with
846        // fast ones: the percentiles follow the recent window, min/max and
847        // the histogram keep the whole session.
848        for _ in 0..LATENCY_RECENT_WINDOW {
849            r.record(ms(2_000));
850        }
851        for _ in 0..LATENCY_RECENT_WINDOW {
852            r.record(ms(200));
853        }
854        let s = r.stats();
855        assert_eq!(s.count, 2 * LATENCY_RECENT_WINDOW as u64);
856        assert_eq!(s.p50_ms, 200);
857        assert_eq!(s.p99_ms, 200);
858        assert_eq!(s.max_ms, 2_000);
859        assert_eq!(s.min_ms, 200);
860        let slow: u64 = s
861            .histogram
862            .iter()
863            .filter(|b| b.upper_ms == Some(2000))
864            .map(|b| b.count)
865            .sum();
866        assert_eq!(slow, LATENCY_RECENT_WINDOW as u64);
867    }
868
869    #[test]
870    fn stats_round_trip_through_json() {
871        let r = LatencyRecorder::new();
872        r.record(ms(420));
873        let s = r.stats();
874        let v = serde_json::to_value(&s).unwrap();
875        assert_eq!(v["p50_ms"], 420);
876        let back: LatencyStats = serde_json::from_value(v).unwrap();
877        assert_eq!(back, s);
878    }
879}
880
881/// Loom models of the telemetry lane's lock-free protocol.
882///
883/// Run with `RUSTFLAGS="--cfg gemini_adk_loom" cargo test -p gemini-adk-rs --lib --release loom_`.
884///
885/// The recorder touches some forty atomics per sample (scalars, the
886/// histogram, the ring), so the unbounded three-thread model does not
887/// finish in CI time; the models run with a preemption bound of two, which
888/// explores every schedule with at most two forced context switches and
889/// found the ring-slot race this file's fix removed.
890///
891/// The invariant: a reader that observes `count == n` (an `Acquire` load)
892/// sees every one of the `n` recorded samples in the ring, the histogram
893/// and the scalar extrema, because each `record` publishes them before its
894/// `Release` increment of `count`. Readers never block writers and writers
895/// never block each other: there is no lock to model, only the ordering.
896#[cfg(all(test, gemini_adk_loom))]
897mod loom_tests {
898    use super::*;
899    use loom::sync::Arc;
900    use loom::thread;
901
902    fn bounded() -> loom::model::Builder {
903        let mut builder = loom::model::Builder::new();
904        builder.preemption_bound = Some(2);
905        builder
906    }
907
908    #[test]
909    fn loom_two_writers_one_reader_count_never_exceeds_visible_samples() {
910        bounded().check(|| {
911            let stats = Arc::new(LatencyRecorder::new());
912            let writers: Vec<_> = [7_000_000u64, 40_000_000u64]
913                .into_iter()
914                .map(|latency| {
915                    let stats = stats.clone();
916                    thread::spawn(move || stats.record(latency))
917                })
918                .collect();
919            let reader = {
920                let stats = stats.clone();
921                thread::spawn(move || {
922                    let snapshot = stats.stats();
923                    // Everything the count promises is already visible.
924                    let in_histogram: u64 =
925                        snapshot.histogram.iter().map(|bucket| bucket.count).sum();
926                    assert!(
927                        in_histogram >= snapshot.count,
928                        "count {} ran ahead of the histogram {in_histogram}",
929                        snapshot.count
930                    );
931                    if snapshot.count > 0 {
932                        assert!(snapshot.min_ms <= snapshot.max_ms);
933                        assert!(snapshot.p99_ms <= snapshot.max_ms);
934                        assert!(snapshot.min_ms <= snapshot.p50_ms);
935                        // A counted sample is a real one, never the ring's
936                        // zero-initialised slot.
937                        assert!(snapshot.p50_ms >= snapshot.min_ms);
938                    }
939                })
940            };
941            for writer in writers {
942                writer.join().unwrap();
943            }
944            reader.join().unwrap();
945            let final_stats = stats.stats();
946            assert_eq!(final_stats.count, 2);
947            assert_eq!(final_stats.min_ms, 7);
948            assert_eq!(final_stats.max_ms, 40);
949        });
950    }
951
952    #[test]
953    fn loom_concurrent_audio_counters_lose_nothing() {
954        bounded().check(|| {
955            let telemetry = Arc::new(SessionTelemetry::new());
956            let threads: Vec<_> = (0..2)
957                .map(|_| {
958                    let telemetry = telemetry.clone();
959                    thread::spawn(move || {
960                        telemetry.record_audio_out(960);
961                        telemetry.record_audio_out(960);
962                    })
963                })
964                .collect();
965            for thread in threads {
966                thread.join().unwrap();
967            }
968            let snapshot = telemetry.snapshot();
969            assert_eq!(snapshot["audio_chunks_out"], 4);
970            assert_eq!(snapshot["audio_kbytes_out"], (4 * 960) / 1024);
971        });
972    }
973}