Skip to main content

smix_metro_log/
lib.rs

1//! smix-metro-log — metro / expo log tail + ring buffer + signal await.
2//!
3//! # Purpose
4//!
5//! Bridges the app-under-test's log output into smix as a first-class
6//! **signal channel**. yaml flows can `expect.signal { regex, timeoutMs }`
7//! or `expect.signals { [{regex}, ...], order: strict }` to assert on
8//! state transitions the app declares — decoupling smix from what the
9//! UI looks like at any instant.
10//!
11//! # Architecture
12//!
13//! ```text
14//!   ┌─────────────────┐     WebSocket           ┌────────────────┐
15//!   │ metro / expo    │  ─────────────────▶      │ MetroLogTail   │
16//!   │ dev server      │     (or file tail)       │  ring buffer   │
17//!   │ ws://127.0.0.1  │                          │  + allowlist   │
18//!   │  :8081/logs     │                          └────────┬───────┘
19//!   └─────────────────┘                                   │
20//!                                                         │ await_signal
21//!                                                         │ await_signals
22//!                                                         │ assert_clean
23//!                                                         ▼
24//!                                              ┌────────────────────┐
25//!                                              │ smix-adapter-      │
26//!                                              │  maestro runtime   │
27//!                                              │ (expect.signal /   │
28//!                                              │  expect.signals)   │
29//!                                              └────────────────────┘
30//! ```
31//!
32//! # Time model
33//!
34//! - **Ring buffer** — stores the last `retain_secs` seconds of entries
35//!   (default 300s). Entries older than the cutoff are evicted on push.
36//! - **Windows** — `await_signal` accepts a `Window`:
37//!   - `SinceStep(usize)` — logically "everything after step N ended"
38//!   - `SinceRun` — since MetroLogTail was constructed (runner boot)
39//!   - `LastMs(u64)` — trailing window (e.g. last 500 ms)
40//!
41//!   The adapter runtime tracks step boundaries and translates
42//!   `SinceStep` to an absolute timestamp captured at step-end.
43//! - **Poll frequency** — `await_signal` runs a scan loop at 25 ms
44//!   intervals. Publishes into the ring buffer are unbounded (async
45//!   channel + mutex-protected buffer) so the poll never misses.
46
47use std::collections::VecDeque;
48use std::sync::{Arc, RwLock};
49use std::time::{Duration, Instant};
50
51use regex::Regex;
52use serde::{Deserialize, Serialize};
53use thiserror::Error;
54use tokio::time;
55
56pub mod process;
57pub mod subscriber;
58pub use process::ProcessSubscriber;
59pub use subscriber::{FileTailSubscriber, SubscriberHandle, WebSocketSubscriber, parse_log_line};
60
61/// Metro / expo log entry, normalized. Level is best-effort: metro
62/// text-only lines get `LogLevel::Log`; JSON-formatted lines keep
63/// their `level` if parseable.
64///
65/// `at` is a monotonic `Instant` used internally for retention math;
66/// it is skipped during serialization (Instant has no `Default` /
67/// Serde impl). Consumers who need to persist entries can use
68/// `ms_since_start` — that IS serializable and monotonically ordered.
69#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
70pub struct LogEntry {
71    /// Monotonic timestamp at ingest. Not serialized.
72    #[serde(skip, default = "Instant::now")]
73    pub at: Instant,
74    /// Wall-clock ms since MetroLogTail::start (used for window math).
75    pub ms_since_start: u64,
76    pub level: LogLevel,
77    pub message: String,
78}
79
80impl LogEntry {
81    /// Construct with `ms_since_start` computed against a reference
82    /// `Instant`. Used inside `MetroLogTail::push` — external callers
83    /// should always go through push.
84    pub fn new(level: LogLevel, message: String, ms_since_start: u64) -> Self {
85        Self {
86            at: Instant::now(),
87            ms_since_start,
88            level,
89            message,
90        }
91    }
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "lowercase")]
96pub enum LogLevel {
97    Log,
98    Debug,
99    Info,
100    Warn,
101    Error,
102}
103
104impl LogLevel {
105    /// Best-effort parse of a metro/expo-emitted level string.
106    pub fn parse(s: &str) -> Self {
107        match s.to_lowercase().as_str() {
108            "debug" | "trace" => LogLevel::Debug,
109            "info" => LogLevel::Info,
110            "warn" | "warning" => LogLevel::Warn,
111            "error" | "err" => LogLevel::Error,
112            _ => LogLevel::Log,
113        }
114    }
115}
116
117/// Window over which to look for a matching signal.
118///
119/// Three shapes cover the common use cases. The adapter runtime
120/// translates `SinceStep(n)` to a specific `ms_since_start` cutoff
121/// (captured at the moment step n's outcome was recorded), so the
122/// runtime doesn't need step tracking here.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum Window {
125    /// Everything since `MetroLogTail::start` (runner boot).
126    SinceRun,
127    /// After a specific `ms_since_start` cutoff. The adapter converts
128    /// its `sinceStep: N` yaml field to this variant using the
129    /// remembered cutoff for step N.
130    SinceMs(u64),
131    /// Trailing window: only entries whose `ms_since_start >= now - X`.
132    LastMs(u64),
133}
134
135#[allow(clippy::derivable_impls)]
136impl Default for Window {
137    fn default() -> Self {
138        Window::SinceRun
139    }
140}
141
142/// Order semantics for [`MetroLogTail::await_signals`].
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub enum SignalOrder {
145    /// Every pattern must match at some point in the window; order
146    /// doesn't matter.
147    Any,
148    /// Patterns must match in the exact listed sequence, no
149    /// interleaving — `pattern[i+1]`'s first match must be at a
150    /// higher `ms_since_start` than `pattern[i]`'s.
151    Strict,
152}
153
154/// Compiled signal pattern.
155#[derive(Clone, Debug)]
156pub struct SignalMatcher {
157    pub level: Option<LogLevel>,
158    pub regex: Regex,
159}
160
161impl SignalMatcher {
162    /// Compile a regex + optional level constraint.
163    pub fn new(regex: &str, level: Option<LogLevel>) -> Result<Self, regex::Error> {
164        Ok(Self {
165            level,
166            regex: Regex::new(regex)?,
167        })
168    }
169
170    fn matches(&self, entry: &LogEntry) -> bool {
171        if let Some(l) = self.level
172            && entry.level != l
173        {
174            return false;
175        }
176        self.regex.is_match(&entry.message)
177    }
178}
179
180#[derive(Debug, Error)]
181pub enum AwaitError {
182    #[error("signal {regex} not observed within {timeout_ms}ms (window={window:?})")]
183    Timeout {
184        regex: String,
185        timeout_ms: u64,
186        window: Window,
187    },
188    #[error(
189        "signals ordering violated: pattern #{index} ({regex}) matched at ms_since_start={found_ms} before an earlier pattern's match at ms_since_start={prev_ms}"
190    )]
191    OrderViolation {
192        index: usize,
193        regex: String,
194        found_ms: u64,
195        prev_ms: u64,
196    },
197    #[error("regex compile: {0}")]
198    Regex(#[from] regex::Error),
199}
200
201/// Ring-buffer + await surface for metro/expo logs.
202///
203/// Constructed once per runner session. Cloneable (internal state is
204/// `Arc<RwLock<..>>`), so the subscriber task and the adapter runtime
205/// can share it without a channel.
206#[derive(Clone, Debug)]
207pub struct MetroLogTail {
208    inner: Arc<Inner>,
209}
210
211#[derive(Debug)]
212struct Inner {
213    start: Instant,
214    retain: Duration,
215    buffer: RwLock<VecDeque<LogEntry>>,
216    /// Compiled allowlist for [`MetroLogTail::assert_clean`]. Any log
217    /// entry whose message matches one of these is ignored for
218    /// hygiene assertions.
219    allowlist: RwLock<Vec<Regex>>,
220}
221
222impl MetroLogTail {
223    /// Construct with default 300s retention and no allowlist.
224    pub fn new() -> Self {
225        Self::with_retain_secs(300)
226    }
227
228    pub fn with_retain_secs(retain_secs: u64) -> Self {
229        Self {
230            inner: Arc::new(Inner {
231                start: Instant::now(),
232                retain: Duration::from_secs(retain_secs),
233                buffer: RwLock::new(VecDeque::new()),
234                allowlist: RwLock::new(Vec::new()),
235            }),
236        }
237    }
238
239    /// Replace the allowlist. Each entry is a regex; if it fails to
240    /// compile, returns the underlying `regex::Error` without
241    /// mutating the current list.
242    pub fn set_allowlist(&self, patterns: &[String]) -> Result<(), regex::Error> {
243        let compiled: Result<Vec<Regex>, _> = patterns.iter().map(|p| Regex::new(p)).collect();
244        let compiled = compiled?;
245        *self.inner.allowlist.write().expect("poisoned") = compiled;
246        Ok(())
247    }
248
249    /// Layer additional patterns onto the existing allowlist.
250    /// Consumers can compose a per-scope allowlist on top of a base
251    /// (.smix/config.yaml + per-scope + inline yaml).
252    ///
253    /// Layer merge semantics: append. A log entry that matches ANY
254    /// layer's pattern is allowlisted. To reset, call
255    /// [`Self::set_allowlist`] with the desired combined list.
256    pub fn extend_allowlist(&self, patterns: &[String]) -> Result<(), regex::Error> {
257        let compiled: Result<Vec<Regex>, _> = patterns.iter().map(|p| Regex::new(p)).collect();
258        let compiled = compiled?;
259        self.inner
260            .allowlist
261            .write()
262            .expect("poisoned")
263            .extend(compiled);
264        Ok(())
265    }
266
267    /// Snapshot the currently-active allowlist. Used by consumers who
268    /// need to reason about which layers are live before layering more.
269    pub fn allowlist_patterns(&self) -> Vec<String> {
270        self.inner
271            .allowlist
272            .read()
273            .expect("poisoned")
274            .iter()
275            .map(|r| r.as_str().to_string())
276            .collect()
277    }
278
279    /// Push an entry from the subscriber. Evicts entries older than
280    /// `retain_secs` after each push. Caller supplies `level` +
281    /// `message`; the timestamp / `ms_since_start` are stamped here.
282    pub fn push(&self, level: LogLevel, message: String) {
283        let now = Instant::now();
284        let ms_since_start = now.duration_since(self.inner.start).as_millis() as u64;
285        let entry = LogEntry {
286            at: now,
287            ms_since_start,
288            level,
289            message,
290        };
291        let cutoff = now
292            .checked_sub(self.inner.retain)
293            .unwrap_or(self.inner.start);
294        let mut buf = self.inner.buffer.write().expect("poisoned");
295        while let Some(front) = buf.front() {
296            if front.at < cutoff {
297                buf.pop_front();
298            } else {
299                break;
300            }
301        }
302        buf.push_back(entry);
303    }
304
305    /// Snapshot of the current buffer contents. Cheap clone of
306    /// entries; primarily used by tests.
307    pub fn snapshot(&self) -> Vec<LogEntry> {
308        self.inner
309            .buffer
310            .read()
311            .expect("poisoned")
312            .iter()
313            .cloned()
314            .collect()
315    }
316
317    /// Milliseconds since the tail was constructed. The runtime
318    /// remembers this at step-end to translate `sinceStep: N` yaml
319    /// windows into `Window::SinceMs`.
320    pub fn ms_since_start(&self) -> u64 {
321        Instant::now().duration_since(self.inner.start).as_millis() as u64
322    }
323
324    /// Await a single signal within `timeout`. Scans the ring buffer
325    /// at 25 ms intervals; returns the first matching entry. Returns
326    /// [`AwaitError::Timeout`] on budget exhaustion.
327    pub async fn await_signal(
328        &self,
329        matcher: &SignalMatcher,
330        timeout: Duration,
331        window: Window,
332    ) -> Result<LogEntry, AwaitError> {
333        let deadline = Instant::now() + timeout;
334        let mut interval = time::interval(Duration::from_millis(25));
335        interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
336        loop {
337            let began = Instant::now();
338            if let Some(entry) = self.find_matching(matcher, window) {
339                return Ok(entry);
340            }
341            if began >= deadline {
342                return Err(AwaitError::Timeout {
343                    regex: matcher.regex.as_str().to_string(),
344                    timeout_ms: timeout.as_millis() as u64,
345                    window,
346                });
347            }
348            interval.tick().await;
349        }
350    }
351
352    /// Await N signals — order semantics per [`SignalOrder`]. Returns
353    /// the matching entries in the order of the input `matchers`
354    /// (position `i` corresponds to `matchers[i]`).
355    pub async fn await_signals(
356        &self,
357        matchers: &[SignalMatcher],
358        order: SignalOrder,
359        timeout: Duration,
360        window: Window,
361    ) -> Result<Vec<LogEntry>, AwaitError> {
362        let deadline = Instant::now() + timeout;
363        let mut interval = time::interval(Duration::from_millis(25));
364        interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
365        loop {
366            let began = Instant::now();
367            if let Some(result) = self.try_match_all(matchers, order)? {
368                return Ok(result);
369            }
370            if began >= deadline {
371                // Report the first unmet matcher as the timeout regex.
372                let idx = self.first_unmet(matchers, window);
373                let regex = matchers[idx].regex.as_str().to_string();
374                return Err(AwaitError::Timeout {
375                    regex,
376                    timeout_ms: timeout.as_millis() as u64,
377                    window,
378                });
379            }
380            interval.tick().await;
381        }
382    }
383
384    /// Verify no unexpected log entries. Returns a Vec of violating
385    /// entries — anything that (a) is level >= Warn and (b) doesn't
386    /// match any allowlist pattern. Empty vec = clean.
387    pub fn assert_clean(&self) -> Vec<LogEntry> {
388        let buf = self.inner.buffer.read().expect("poisoned");
389        let allow = self.inner.allowlist.read().expect("poisoned");
390        buf.iter()
391            .filter(|e| match e.level {
392                LogLevel::Warn | LogLevel::Error => true,
393                LogLevel::Log | LogLevel::Debug | LogLevel::Info => false,
394            })
395            .filter(|e| !allow.iter().any(|r| r.is_match(&e.message)))
396            .cloned()
397            .collect()
398    }
399
400    fn find_matching(&self, matcher: &SignalMatcher, window: Window) -> Option<LogEntry> {
401        let cutoff = self.window_cutoff(window);
402        self.inner
403            .buffer
404            .read()
405            .expect("poisoned")
406            .iter()
407            .find(|e| e.ms_since_start >= cutoff && matcher.matches(e))
408            .cloned()
409    }
410
411    fn window_cutoff(&self, window: Window) -> u64 {
412        match window {
413            Window::SinceRun => 0,
414            Window::SinceMs(ms) => ms,
415            Window::LastMs(ms) => self.ms_since_start().saturating_sub(ms),
416        }
417    }
418
419    /// Try to match all matchers against the current buffer. Returns
420    /// `Ok(Some(entries))` on success, `Ok(None)` if not all matched
421    /// yet, `Err(OrderViolation)` if strict-order requirement was
422    /// violated (an earlier pattern only appears after a later one).
423    fn try_match_all(
424        &self,
425        matchers: &[SignalMatcher],
426        order: SignalOrder,
427    ) -> Result<Option<Vec<LogEntry>>, AwaitError> {
428        let buf = self.inner.buffer.read().expect("poisoned");
429        // For Any-order: each matcher independently → first match.
430        // For Strict-order: matcher i's chosen entry must have
431        // ms_since_start >= matcher i-1's chosen entry ms_since_start.
432        let mut chosen: Vec<Option<LogEntry>> = vec![None; matchers.len()];
433        match order {
434            SignalOrder::Any => {
435                for (i, m) in matchers.iter().enumerate() {
436                    chosen[i] = buf.iter().find(|e| m.matches(e)).cloned();
437                }
438            }
439            SignalOrder::Strict => {
440                // Strict order = each next match must appear at a
441                // higher BUFFER INDEX than the previous. Using
442                // ms_since_start alone can't tell apart entries pushed
443                // in the same millisecond (which is common for test
444                // signals emitted in a burst). Buffer index = strict
445                // temporal ordering.
446                let mut min_index: usize = 0;
447                for (i, m) in matchers.iter().enumerate() {
448                    let mut chosen_idx: Option<usize> = None;
449                    for (idx, entry) in buf.iter().enumerate() {
450                        if idx >= min_index && m.matches(entry) {
451                            chosen_idx = Some(idx);
452                            break;
453                        }
454                    }
455                    if let Some(idx) = chosen_idx {
456                        min_index = idx + 1;
457                        chosen[i] = Some(buf[idx].clone());
458                    }
459                }
460                // Detect eager order violation: if this pattern is
461                // absent from the strict scan but present earlier in
462                // the buffer than a later matcher's chosen index, the
463                // sequence is out of order — surface immediately.
464                for (i, m) in matchers.iter().enumerate() {
465                    if chosen[i].is_some() {
466                        continue;
467                    }
468                    let earliest = buf.iter().enumerate().find(|(_, e)| m.matches(e));
469                    if let Some((earliest_idx, earliest_entry)) = earliest {
470                        #[allow(clippy::needless_range_loop)]
471                        for j in (i + 1)..matchers.len() {
472                            if let Some(later) = &chosen[j] {
473                                // Find the later's buffer index.
474                                let later_idx =
475                                    buf.iter().position(|e| e == later).unwrap_or(usize::MAX);
476                                if earliest_idx < later_idx {
477                                    return Err(AwaitError::OrderViolation {
478                                        index: i,
479                                        regex: m.regex.as_str().to_string(),
480                                        found_ms: earliest_entry.ms_since_start,
481                                        prev_ms: later.ms_since_start,
482                                    });
483                                }
484                            }
485                        }
486                    }
487                }
488            }
489        }
490        if chosen.iter().all(|x| x.is_some()) {
491            let chosen = chosen.into_iter().flatten().collect();
492            Ok(Some(chosen))
493        } else {
494            Ok(None)
495        }
496    }
497
498    fn first_unmet(&self, matchers: &[SignalMatcher], _window: Window) -> usize {
499        let buf = self.inner.buffer.read().expect("poisoned");
500        for (i, m) in matchers.iter().enumerate() {
501            if !buf.iter().any(|e| m.matches(e)) {
502                return i;
503            }
504        }
505        0
506    }
507}
508
509impl Default for MetroLogTail {
510    fn default() -> Self {
511        Self::new()
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518
519    fn m(re: &str) -> SignalMatcher {
520        SignalMatcher::new(re, None).unwrap()
521    }
522
523    #[test]
524    fn push_and_snapshot_roundtrip() {
525        let tail = MetroLogTail::new();
526        tail.push(LogLevel::Log, "hello".into());
527        tail.push(LogLevel::Error, "world".into());
528        let snap = tail.snapshot();
529        assert_eq!(snap.len(), 2);
530        assert_eq!(snap[0].message, "hello");
531        assert_eq!(snap[1].message, "world");
532    }
533
534    #[tokio::test]
535    async fn await_signal_hits_when_present() {
536        let tail = MetroLogTail::new();
537        tail.push(LogLevel::Log, "env=qa-mode".into());
538        let hit = tail
539            .await_signal(
540                &m(r"env=qa-mode"),
541                Duration::from_millis(100),
542                Window::SinceRun,
543            )
544            .await
545            .expect("should match");
546        assert_eq!(hit.message, "env=qa-mode");
547    }
548
549    #[tokio::test]
550    async fn await_signal_times_out_when_absent() {
551        let tail = MetroLogTail::new();
552        tail.push(LogLevel::Log, "some other line".into());
553        let err = tail
554            .await_signal(
555                &m(r"env=qa-mode"),
556                Duration::from_millis(50),
557                Window::SinceRun,
558            )
559            .await
560            .expect_err("should timeout");
561        matches!(err, AwaitError::Timeout { .. });
562    }
563
564    #[tokio::test]
565    async fn await_signal_respects_last_ms_window() {
566        let tail = MetroLogTail::new();
567        tail.push(LogLevel::Log, "old line".into());
568        // Simulate 100 ms elapsing.
569        tokio::time::pause();
570        tokio::time::advance(Duration::from_millis(200)).await;
571        // A LastMs(100) window shouldn't see "old line" — but this test
572        // works with real Instant so is best-effort. Cover semantic
573        // via SinceMs instead (deterministic).
574        let cutoff = tail.ms_since_start();
575        tail.push(LogLevel::Log, "new line".into());
576        let hit = tail
577            .await_signal(
578                &m(r"new"),
579                Duration::from_millis(50),
580                Window::SinceMs(cutoff),
581            )
582            .await
583            .expect("should match");
584        assert_eq!(hit.message, "new line");
585    }
586
587    #[tokio::test]
588    async fn await_signal_since_ms_filters_older() {
589        let tail = MetroLogTail::new();
590        tail.push(LogLevel::Log, "before".into());
591        let cutoff = tail.ms_since_start() + 100;
592        let err = tail
593            .await_signal(
594                &m(r"before"),
595                Duration::from_millis(50),
596                Window::SinceMs(cutoff),
597            )
598            .await
599            .expect_err("should not see entry before cutoff");
600        matches!(err, AwaitError::Timeout { .. });
601    }
602
603    #[tokio::test]
604    async fn await_signals_any_order() {
605        let tail = MetroLogTail::new();
606        tail.push(LogLevel::Log, "second".into());
607        tail.push(LogLevel::Log, "first".into());
608        let hits = tail
609            .await_signals(
610                &[m(r"^first$"), m(r"^second$")],
611                SignalOrder::Any,
612                Duration::from_millis(100),
613                Window::SinceRun,
614            )
615            .await
616            .expect("both present");
617        assert_eq!(hits.len(), 2);
618    }
619
620    #[tokio::test]
621    async fn await_signals_strict_ok_when_in_order() {
622        let tail = MetroLogTail::new();
623        tail.push(LogLevel::Log, "a".into());
624        tail.push(LogLevel::Log, "b".into());
625        tail.push(LogLevel::Log, "c".into());
626        let hits = tail
627            .await_signals(
628                &[m(r"^a$"), m(r"^b$"), m(r"^c$")],
629                SignalOrder::Strict,
630                Duration::from_millis(100),
631                Window::SinceRun,
632            )
633            .await
634            .expect("strict in-order OK");
635        assert_eq!(hits.len(), 3);
636        assert!(hits[0].ms_since_start <= hits[1].ms_since_start);
637        assert!(hits[1].ms_since_start <= hits[2].ms_since_start);
638    }
639
640    #[tokio::test]
641    async fn await_signals_strict_reports_order_violation() {
642        let tail = MetroLogTail::new();
643        // c appears BEFORE a — violates order [a, b, c].
644        tail.push(LogLevel::Log, "c".into());
645        tail.push(LogLevel::Log, "a".into());
646        tail.push(LogLevel::Log, "b".into());
647        let res = tail
648            .await_signals(
649                &[m(r"^a$"), m(r"^b$"), m(r"^c$")],
650                SignalOrder::Strict,
651                Duration::from_millis(50),
652                Window::SinceRun,
653            )
654            .await;
655        // Either OrderViolation or Timeout (both are valid failure
656        // signals for this shape; the exact one depends on scan
657        // heuristics).
658        assert!(res.is_err());
659    }
660
661    #[tokio::test]
662    async fn assert_clean_empty_when_no_warns() {
663        let tail = MetroLogTail::new();
664        tail.push(LogLevel::Log, "info".into());
665        tail.push(LogLevel::Info, "info".into());
666        let violations = tail.assert_clean();
667        assert!(violations.is_empty());
668    }
669
670    #[tokio::test]
671    async fn assert_clean_surfaces_warns_and_errors() {
672        let tail = MetroLogTail::new();
673        tail.push(LogLevel::Warn, "unexpected warning".into());
674        tail.push(LogLevel::Error, "unexpected error".into());
675        let violations = tail.assert_clean();
676        assert_eq!(violations.len(), 2);
677    }
678
679    #[tokio::test]
680    async fn assert_clean_honors_allowlist() {
681        let tail = MetroLogTail::new();
682        tail.set_allowlist(&["skipping register".to_string()])
683            .unwrap();
684        tail.push(LogLevel::Warn, "skipping register: dev".into());
685        tail.push(LogLevel::Warn, "unexpected".into());
686        let violations = tail.assert_clean();
687        assert_eq!(violations.len(), 1);
688        assert_eq!(violations[0].message, "unexpected");
689    }
690
691    #[test]
692    fn retention_evicts_old_entries() {
693        // 0-second retention → every push evicts previous.
694        let tail = MetroLogTail::with_retain_secs(0);
695        tail.push(LogLevel::Log, "gone".into());
696        std::thread::sleep(Duration::from_millis(20));
697        tail.push(LogLevel::Log, "kept".into());
698        let snap = tail.snapshot();
699        assert_eq!(snap.len(), 1);
700        assert_eq!(snap[0].message, "kept");
701    }
702}