sonda 1.2.1

CLI for Sonda — synthetic telemetry generator for testing observability pipelines
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Live progress display for running scenarios.
//!
//! Polls [`ScenarioStats`] via the shared [`RwLock`] at regular intervals and
//! renders updating status lines to stderr. All output goes to stderr so that
//! stdout remains clean for data when the sink is stdout.
//!
//! **TTY mode** (stderr is a terminal): Uses ANSI escape sequences to overwrite
//! progress lines in place, producing a compact, live-updating display.
//!
//! **Non-TTY mode** (stderr is piped or redirected): Emits a static progress
//! line every [`NON_TTY_INTERVAL`] to avoid flooding logs while still showing
//! that the tool is alive.
//!
//! The display is driven by a dedicated monitoring thread spawned via
//! [`ProgressDisplay::start`]. The thread is joined cleanly by
//! [`ProgressDisplay::stop`], which also erases the progress lines in TTY mode
//! so that stop banners print without visual artifacts.

use std::io::{self, IsTerminal, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use owo_colors::OwoColorize;
use owo_colors::Stream::Stderr;

use sonda_core::schedule::stats::ScenarioStats;

/// How often to poll stats and redraw in TTY mode.
const TTY_POLL_INTERVAL: Duration = Duration::from_millis(200);

/// How often to emit a status line in non-TTY mode.
///
/// Kept high to avoid spamming redirected logs or CI output. Each line is
/// self-contained (no ANSI cursor control).
const NON_TTY_INTERVAL: Duration = Duration::from_secs(5);

/// Descriptor for a single scenario being monitored.
///
/// Holds the scenario name, its shared stats arc, and the target rate so the
/// progress display can compute and render meaningful indicators.
struct MonitoredScenario {
    /// Human-readable scenario name (from the config).
    name: String,
    /// Shared stats updated by the runner thread on each tick.
    stats: Arc<RwLock<ScenarioStats>>,
    /// Configured target rate (events per second).
    target_rate: f64,
}

/// A live progress display for one or more running scenarios.
///
/// Created via [`ProgressDisplay::start`], which spawns a background monitoring
/// thread. Call [`ProgressDisplay::stop`] to join the thread and clean up
/// terminal state before printing stop banners.
///
/// The monitoring thread only reads stats via `RwLock::read()`, so it does not
/// contend with the writer (the scenario runner thread). The polling interval
/// is 200ms in TTY mode, which is fast enough for visual feedback but
/// negligible overhead compared to event generation.
pub struct ProgressDisplay {
    /// Thread running the progress polling loop.
    thread: Option<JoinHandle<()>>,
    /// Flag to signal the monitoring thread to stop.
    stop_flag: Arc<AtomicBool>,
}

impl ProgressDisplay {
    /// Start the progress display for the given scenarios.
    ///
    /// Spawns a background thread that polls stats and renders progress lines
    /// to stderr. Returns a [`ProgressDisplay`] handle that must be stopped
    /// before printing stop banners.
    ///
    /// Each tuple contains `(name, stats_arc, target_rate)`.
    ///
    /// # Panics
    ///
    /// Panics if the monitoring thread cannot be spawned (system resource
    /// exhaustion).
    pub fn start(scenarios: Vec<(String, Arc<RwLock<ScenarioStats>>, f64)>) -> Self {
        let stop_flag = Arc::new(AtomicBool::new(false));
        let flag_clone = Arc::clone(&stop_flag);

        let monitored: Vec<MonitoredScenario> = scenarios
            .into_iter()
            .map(|(name, stats, target_rate)| MonitoredScenario {
                name,
                stats,
                target_rate,
            })
            .collect();

        let is_tty = io::stderr().is_terminal();

        let thread = thread::Builder::new()
            .name("sonda-progress".to_string())
            .spawn(move || {
                if is_tty {
                    run_tty_loop(&monitored, &flag_clone);
                } else {
                    run_non_tty_loop(&monitored, &flag_clone);
                }
            })
            .expect("failed to spawn progress monitoring thread");

        ProgressDisplay {
            thread: Some(thread),
            stop_flag,
        }
    }

    /// Stop the progress display and clean up terminal state.
    ///
    /// Signals the monitoring thread to exit, joins it, and in TTY mode erases
    /// the progress lines so that subsequent output (stop banners) starts on a
    /// clean line.
    pub fn stop(mut self) {
        self.stop_flag.store(true, Ordering::SeqCst);
        if let Some(thread) = self.thread.take() {
            // The thread checks the flag every poll interval, so this join
            // completes within one interval plus the time to erase lines.
            let _ = thread.join();
        }
    }
}

impl Drop for ProgressDisplay {
    fn drop(&mut self) {
        // Safety net: if stop() was not called, signal the thread to exit.
        // We cannot join in Drop (would need &mut self and the thread is Option),
        // but at least we signal it so it does not run forever.
        self.stop_flag.store(true, Ordering::SeqCst);
    }
}

/// Read a stats snapshot from the shared lock.
///
/// Returns a default `ScenarioStats` if the lock is poisoned.
fn read_stats(stats: &Arc<RwLock<ScenarioStats>>) -> ScenarioStats {
    match stats.read() {
        Ok(guard) => guard.clone(),
        Err(poisoned) => poisoned.into_inner().clone(),
    }
}

/// Run the TTY progress loop.
///
/// Renders progress lines using ANSI cursor control so they update in place.
/// On each iteration: move cursor up N lines, overwrite each line, flush.
/// On exit: erase all progress lines to leave a clean terminal.
fn run_tty_loop(scenarios: &[MonitoredScenario], stop_flag: &AtomicBool) {
    let mut first_render = true;
    let start = Instant::now();

    while !stop_flag.load(Ordering::SeqCst) {
        thread::sleep(TTY_POLL_INTERVAL);

        // Check again after sleep — avoids one extra render after stop is signalled.
        if stop_flag.load(Ordering::SeqCst) {
            break;
        }

        let elapsed = start.elapsed();
        let mut stderr = io::stderr().lock();

        // Move cursor up to overwrite previous progress lines.
        if !first_render {
            // Move up N lines (one per scenario).
            for _ in 0..scenarios.len() {
                let _ = write!(stderr, "\x1b[A");
            }
        }

        // Render one line per scenario.
        for scenario in scenarios {
            let stats = read_stats(&scenario.stats);
            let line = format_tty_line(&scenario.name, &stats, scenario.target_rate, elapsed);
            // \x1b[2K clears the current line (handles variable-width content).
            let _ = write!(stderr, "\x1b[2K{line}\r\n");
        }

        let _ = stderr.flush();
        first_render = false;
    }

    // Erase progress lines on exit so stop banners print cleanly.
    let mut stderr = io::stderr().lock();
    if !first_render {
        for _ in 0..scenarios.len() {
            let _ = write!(stderr, "\x1b[A\x1b[2K");
        }
    }
    let _ = stderr.flush();
}

/// Run the non-TTY progress loop.
///
/// Emits a self-contained status line every [`NON_TTY_INTERVAL`]. No ANSI
/// escape sequences are used.
fn run_non_tty_loop(scenarios: &[MonitoredScenario], stop_flag: &AtomicBool) {
    let start = Instant::now();
    // Use short sleeps to remain responsive to the stop flag, but only
    // emit output at the non-TTY interval.
    let mut last_emit = Instant::now();

    // Sleep in short increments so we notice the stop flag quickly.
    let check_interval = Duration::from_millis(200);

    while !stop_flag.load(Ordering::SeqCst) {
        thread::sleep(check_interval);

        if stop_flag.load(Ordering::SeqCst) {
            break;
        }

        if last_emit.elapsed() < NON_TTY_INTERVAL {
            continue;
        }

        last_emit = Instant::now();
        let elapsed = start.elapsed();

        for scenario in scenarios {
            let stats = read_stats(&scenario.stats);
            let line = format_non_tty_line(&scenario.name, &stats, scenario.target_rate, elapsed);
            eprintln!("{line}");
        }
    }
}

/// Format a TTY progress line for a single scenario.
///
/// Example: `  ~ cpu_usage  events: 1,234 | rate: 98.5/s | bytes: 12.3 KB | elapsed: 5.2s`
fn format_tty_line(
    name: &str,
    stats: &ScenarioStats,
    target_rate: f64,
    elapsed: Duration,
) -> String {
    let indicator = format_indicator(stats);
    let bold_name = format!("{}", name.if_supports_color(Stderr, |t| t.bold()));
    let pipe = format!("{}", "|".if_supports_color(Stderr, |t| t.dimmed()));

    let events_label = format!("{}", "events:".if_supports_color(Stderr, |t| t.dimmed()));
    let events_value = format_count(stats.total_events);

    let rate_label = format!("{}", "rate:".if_supports_color(Stderr, |t| t.dimmed()));
    let rate_value = format_rate_with_target(stats.current_rate, target_rate);

    let bytes_label = format!("{}", "bytes:".if_supports_color(Stderr, |t| t.dimmed()));
    let bytes_value = format!(
        "{}",
        format_bytes(stats.bytes_emitted).if_supports_color(Stderr, |t| t.cyan())
    );

    let elapsed_label = format!("{}", "elapsed:".if_supports_color(Stderr, |t| t.dimmed()));
    let elapsed_value = format_elapsed(elapsed);

    let window_tag = format_window_tag(stats);

    format!(
        "  {indicator} {bold_name}  {events_label} {events_value} {pipe} {rate_label} {rate_value} {pipe} {bytes_label} {bytes_value} {pipe} {elapsed_label} {elapsed_value}{window_tag}"
    )
}

/// Format a non-TTY progress line for a single scenario.
///
/// Example: `[progress] cpu_usage  events: 1234 | rate: 98.5/s | bytes: 12.3 KB | elapsed: 5.2s`
fn format_non_tty_line(
    name: &str,
    stats: &ScenarioStats,
    target_rate: f64,
    elapsed: Duration,
) -> String {
    let events = stats.total_events;
    let rate = format_rate_plain(stats.current_rate, target_rate);
    let bytes = format_bytes(stats.bytes_emitted);
    let elapsed_str = format_elapsed_plain(elapsed);
    let window = format_window_tag_plain(stats);

    format!(
        "[progress] {name}  events: {events} | rate: {rate} | bytes: {bytes} | elapsed: {elapsed_str}{window}"
    )
}

/// Format the spinning/status indicator character.
///
/// Shows a colored `~` (tilde) as a subtle activity indicator. The color
/// reflects the scenario state: green for normal operation, yellow for
/// gap windows, magenta for burst windows.
fn format_indicator(stats: &ScenarioStats) -> String {
    if stats.in_gap {
        format!("{}", "~".if_supports_color(Stderr, |t| t.yellow()))
    } else if stats.in_burst {
        format!("{}", "~".if_supports_color(Stderr, |t| t.magenta()))
    } else {
        format!("{}", "~".if_supports_color(Stderr, |t| t.green()))
    }
}

/// Format the window state tag (gap, burst, spike) for TTY output.
///
/// Returns an empty string when no special window is active.
fn format_window_tag(stats: &ScenarioStats) -> String {
    let mut tags = Vec::new();
    if stats.in_gap {
        tags.push(format!(
            "{}",
            "[gap]".if_supports_color(Stderr, |t| t.yellow())
        ));
    }
    if stats.in_burst {
        tags.push(format!(
            "{}",
            "[burst]".if_supports_color(Stderr, |t| t.magenta())
        ));
    }
    if stats.in_cardinality_spike {
        tags.push(format!(
            "{}",
            "[spike]".if_supports_color(Stderr, |t| t.red())
        ));
    }
    if tags.is_empty() {
        String::new()
    } else {
        format!(" {}", tags.join(" "))
    }
}

/// Format window state tags for non-TTY output (no ANSI codes).
fn format_window_tag_plain(stats: &ScenarioStats) -> String {
    let mut tags = Vec::new();
    if stats.in_gap {
        tags.push("[gap]");
    }
    if stats.in_burst {
        tags.push("[burst]");
    }
    if stats.in_cardinality_spike {
        tags.push("[spike]");
    }
    if tags.is_empty() {
        String::new()
    } else {
        format!(" {}", tags.join(" "))
    }
}

/// Format the current rate with color feedback relative to the target.
///
/// Green when within 80-120% of target, yellow otherwise.
fn format_rate_with_target(current: f64, target: f64) -> String {
    let rate_str = format!("{:.1}/s", current);
    let ratio = if target > 0.0 { current / target } else { 1.0 };

    if (0.8..=1.2).contains(&ratio) {
        format!("{}", rate_str.if_supports_color(Stderr, |t| t.green()))
    } else {
        format!("{}", rate_str.if_supports_color(Stderr, |t| t.yellow()))
    }
}

/// Format a rate value for non-TTY output (no ANSI codes).
fn format_rate_plain(current: f64, _target: f64) -> String {
    format!("{:.1}/s", current)
}

/// Format an event count with thousand separators for readability.
fn format_count(n: u64) -> String {
    if n < 1_000 {
        return format!("{}", n.if_supports_color(Stderr, |t| t.green()));
    }

    // Format with commas: 1,234,567
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, ch) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(ch);
    }
    let formatted: String = result.chars().rev().collect();
    format!("{}", formatted.if_supports_color(Stderr, |t| t.green()))
}

/// Format elapsed time as a human-readable string.
fn format_elapsed(elapsed: Duration) -> String {
    let secs = elapsed.as_secs_f64();
    if secs < 60.0 {
        format!("{secs:.1}s")
    } else if secs < 3600.0 {
        let mins = (secs / 60.0).floor() as u64;
        let remaining = secs - (mins as f64 * 60.0);
        format!("{mins}m{remaining:.0}s")
    } else {
        let hours = (secs / 3600.0).floor() as u64;
        let remaining_mins = ((secs - hours as f64 * 3600.0) / 60.0).floor() as u64;
        format!("{hours}h{remaining_mins}m")
    }
}

/// Format elapsed time for non-TTY output (plain text).
fn format_elapsed_plain(elapsed: Duration) -> String {
    format_elapsed(elapsed)
}

/// Format a byte count as a human-readable string with appropriate units.
fn format_bytes(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * 1024;
    const GB: u64 = 1024 * 1024 * 1024;

    if bytes < KB {
        format!("{bytes} B")
    } else if bytes < MB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else if bytes < GB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    }
}

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

    // -----------------------------------------------------------------------
    // format_bytes: all unit thresholds
    // -----------------------------------------------------------------------

    #[test]
    fn format_bytes_zero() {
        assert_eq!(format_bytes(0), "0 B");
    }

    #[test]
    fn format_bytes_below_kb() {
        assert_eq!(format_bytes(500), "500 B");
    }

    #[test]
    fn format_bytes_one_kb() {
        assert_eq!(format_bytes(1024), "1.0 KB");
    }

    #[test]
    fn format_bytes_one_mb() {
        assert_eq!(format_bytes(1_048_576), "1.0 MB");
    }

    #[test]
    fn format_bytes_one_gb() {
        assert_eq!(format_bytes(1_073_741_824), "1.0 GB");
    }

    // -----------------------------------------------------------------------
    // format_elapsed: time formatting
    // -----------------------------------------------------------------------

    #[test]
    fn format_elapsed_seconds_only() {
        let d = Duration::from_secs_f64(5.3);
        assert_eq!(format_elapsed(d), "5.3s");
    }

    #[test]
    fn format_elapsed_minutes_and_seconds() {
        let d = Duration::from_secs(90);
        assert_eq!(format_elapsed(d), "1m30s");
    }

    #[test]
    fn format_elapsed_hours_and_minutes() {
        let d = Duration::from_secs(3661);
        assert_eq!(format_elapsed(d), "1h1m");
    }

    #[test]
    fn format_elapsed_zero() {
        let d = Duration::ZERO;
        assert_eq!(format_elapsed(d), "0.0s");
    }

    #[test]
    fn format_elapsed_exactly_one_minute() {
        let d = Duration::from_secs(60);
        assert_eq!(format_elapsed(d), "1m0s");
    }

    #[test]
    fn format_elapsed_exactly_one_hour() {
        let d = Duration::from_secs(3600);
        assert_eq!(format_elapsed(d), "1h0m");
    }

    // -----------------------------------------------------------------------
    // format_count: thousand separators
    // -----------------------------------------------------------------------

    /// Helper that strips ANSI escape codes for testing formatted counts.
    fn strip_ansi(s: &str) -> String {
        let mut result = String::new();
        let mut in_escape = false;
        for ch in s.chars() {
            if ch == '\x1b' {
                in_escape = true;
            } else if in_escape {
                if ch.is_ascii_alphabetic() {
                    in_escape = false;
                }
            } else {
                result.push(ch);
            }
        }
        result
    }

    #[test]
    fn format_count_small_number() {
        let s = strip_ansi(&format_count(42));
        assert_eq!(s, "42");
    }

    #[test]
    fn format_count_thousands() {
        let s = strip_ansi(&format_count(1234));
        assert_eq!(s, "1,234");
    }

    #[test]
    fn format_count_millions() {
        let s = strip_ansi(&format_count(1_234_567));
        assert_eq!(s, "1,234,567");
    }

    #[test]
    fn format_count_zero() {
        let s = strip_ansi(&format_count(0));
        assert_eq!(s, "0");
    }

    #[test]
    fn format_count_exactly_one_thousand() {
        let s = strip_ansi(&format_count(1000));
        assert_eq!(s, "1,000");
    }

    // -----------------------------------------------------------------------
    // format_window_tag_plain: window state tags
    // -----------------------------------------------------------------------

    #[test]
    fn window_tag_plain_no_windows_active() {
        let stats = ScenarioStats::default();
        assert_eq!(format_window_tag_plain(&stats), "");
    }

    #[test]
    fn window_tag_plain_gap_active() {
        // `ScenarioStats` is `#[non_exhaustive]` across the crate boundary,
        // so struct-literal construction is forbidden here. Start from
        // `Default::default()` and set the fields the test cares about.
        let mut stats = ScenarioStats::default();
        stats.in_gap = true;
        assert_eq!(format_window_tag_plain(&stats), " [gap]");
    }

    #[test]
    fn window_tag_plain_burst_active() {
        let mut stats = ScenarioStats::default();
        stats.in_burst = true;
        assert_eq!(format_window_tag_plain(&stats), " [burst]");
    }

    #[test]
    fn window_tag_plain_spike_active() {
        let mut stats = ScenarioStats::default();
        stats.in_cardinality_spike = true;
        assert_eq!(format_window_tag_plain(&stats), " [spike]");
    }

    #[test]
    fn window_tag_plain_multiple_windows_active() {
        let mut stats = ScenarioStats::default();
        stats.in_burst = true;
        stats.in_cardinality_spike = true;
        assert_eq!(format_window_tag_plain(&stats), " [burst] [spike]");
    }

    // -----------------------------------------------------------------------
    // format_rate_plain: rate formatting
    // -----------------------------------------------------------------------

    #[test]
    fn format_rate_plain_normal_rate() {
        assert_eq!(format_rate_plain(99.5, 100.0), "99.5/s");
    }

    #[test]
    fn format_rate_plain_zero_rate() {
        assert_eq!(format_rate_plain(0.0, 100.0), "0.0/s");
    }

    // -----------------------------------------------------------------------
    // format_non_tty_line: complete line formatting
    // -----------------------------------------------------------------------

    #[test]
    fn non_tty_line_contains_scenario_name() {
        let mut stats = ScenarioStats::default();
        stats.total_events = 42;
        stats.bytes_emitted = 1024;
        stats.current_rate = 10.0;
        let line = format_non_tty_line("cpu_usage", &stats, 10.0, Duration::from_secs(5));
        assert!(
            line.contains("cpu_usage"),
            "line must contain scenario name"
        );
        assert!(
            line.contains("[progress]"),
            "line must contain [progress] prefix"
        );
        assert!(line.contains("42"), "line must contain event count");
    }

    #[test]
    fn non_tty_line_shows_window_state() {
        let mut stats = ScenarioStats::default();
        stats.in_burst = true;
        let line = format_non_tty_line("test", &stats, 10.0, Duration::from_secs(1));
        assert!(
            line.contains("[burst]"),
            "line must show burst window state"
        );
    }

    // -----------------------------------------------------------------------
    // ProgressDisplay: lifecycle
    // -----------------------------------------------------------------------

    #[test]
    fn progress_display_starts_and_stops_cleanly() {
        let stats = Arc::new(RwLock::new(ScenarioStats::default()));
        let display = ProgressDisplay::start(vec![("test".to_string(), stats, 10.0)]);
        // Give the thread a moment to start.
        thread::sleep(Duration::from_millis(50));
        display.stop();
        // If we get here without hanging, the lifecycle works.
    }

    #[test]
    fn progress_display_handles_multiple_scenarios() {
        let stats1 = Arc::new(RwLock::new(ScenarioStats::default()));
        let stats2 = Arc::new(RwLock::new(ScenarioStats::default()));
        let display = ProgressDisplay::start(vec![
            ("scenario-1".to_string(), stats1, 10.0),
            ("scenario-2".to_string(), stats2, 20.0),
        ]);
        thread::sleep(Duration::from_millis(50));
        display.stop();
    }

    #[test]
    fn progress_display_drop_signals_stop_without_panic() {
        let stats = Arc::new(RwLock::new(ScenarioStats::default()));
        let display = ProgressDisplay::start(vec![("drop-test".to_string(), stats, 10.0)]);
        // Drop without calling stop() — should not panic.
        drop(display);
        // Give the thread a moment to notice the flag.
        thread::sleep(Duration::from_millis(300));
    }

    #[test]
    fn progress_display_reads_updated_stats() {
        let stats = Arc::new(RwLock::new(ScenarioStats::default()));
        let stats_writer = Arc::clone(&stats);
        let display = ProgressDisplay::start(vec![("live-test".to_string(), stats, 100.0)]);

        // Simulate the runner updating stats.
        {
            let mut s = stats_writer.write().expect("lock must not be poisoned");
            s.total_events = 500;
            s.bytes_emitted = 4096;
            s.current_rate = 95.0;
        }

        // Give the display a moment to poll.
        thread::sleep(Duration::from_millis(300));
        display.stop();
        // The test passes if no panics occurred during read.
    }

    // -----------------------------------------------------------------------
    // Contract: ProgressDisplay is Send
    // -----------------------------------------------------------------------

    #[test]
    fn progress_display_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<ProgressDisplay>();
    }
}