memseek-test 0.26.0

Scenario-based async load testing framework with HTTP helpers, HDR histogram latency reports and graceful shutdown
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
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
708
709
710
711
712
713
714
715
716
717
use std::{
    borrow::Cow,
    collections::{BTreeMap, HashMap},
    fmt::{Display, Formatter, Result, Write as _},
    time::Duration,
};

use crate::{invariant::InvariantViolation, recorder::Recorder};

#[derive(Debug)]
pub struct ScenarioReport {
    pub name: Cow<'static, str>,
    /// 该场景的执行并发度(Manager 分配的任务数)。
    pub concurrency: u64,
    pub times: u64,
    /// 各任务耗时之和(含 setup),`merge` 累加;与墙钟 `elapsed` 不同
    pub total: Duration,
    /// 场景墙钟耗时(Manager 从分发任务到全部结束),用于 RPS 计算
    pub elapsed: Duration,
    pub avg: Duration,
    pub min: Duration,
    pub max: Duration,
    pub p50: Duration,
    pub p95: Duration,
    pub p99: Duration,

    pub validate_success: u64,
    pub validate_failures: u64,

    /// 各任务 `setup` 尝试耗时之和(含超时重试的每次尝试;与墙钟口径不同)
    pub setup_total: Duration,
    /// 各轮 `validate` 耗时之和
    pub validate_total: Duration,
    /// 各次 `teardown` 耗时之和
    pub teardown_total: Duration,
    /// 收尾成功/失败次数(失败不进 `failures`,也不影响通过率)
    pub teardown_success: u64,
    pub teardown_failures: u64,

    pub success: u64,
    pub failures: u64,
    /// 超时类软失败数(单独统计,不加剧失败率)
    pub timeouts: u64,
    pub error_map: HashMap<Cow<'static, str>, u64>,
    /// 错误携带的 HTTP 状态码计数(见 [`crate::ScenarioError::status_code`])。
    pub status_counts: BTreeMap<u16, u64>,

    /// 全局对账(`Scenario::reconcile`)发现的失败项。
    /// 与 `failures` / `timeouts` / `validate_failures` 分开统计,
    /// 不影响单轮通过率,由调用方单独判定。
    pub invariant_failures: Vec<InvariantViolation>,
    /// 全局对账耗时(不计入 `elapsed` / RPS)。
    pub reconcile_total: Duration,

    /// 该场景是否因优雅关闭(停止信号)提前结束
    pub interrupted: bool,
}

impl ScenarioReport {
    pub fn from_recorder(
        name: impl Into<Cow<'static, str>>,
        mut recorder: Recorder,
        concurrency: u64,
        elapsed: Duration,
    ) -> Self {
        Self {
            name: name.into(),
            concurrency,
            times: recorder.times(),
            total: recorder.total(),
            elapsed,
            avg: recorder.avg(),
            min: recorder.min(),
            max: recorder.max(),
            p50: recorder.p50(),
            p95: recorder.p95(),
            p99: recorder.p99(),

            validate_success: recorder.validate_success,
            validate_failures: recorder.validate_failures,

            setup_total: recorder.setup_total,
            validate_total: recorder.validate_total,
            teardown_total: recorder.teardown_total,
            teardown_success: recorder.teardown_success,
            teardown_failures: recorder.teardown_failures,

            success: recorder.success,
            failures: recorder.failures,
            timeouts: recorder.timeouts,
            error_map: recorder.error_map,
            status_counts: recorder.status_counts,
            invariant_failures: Vec::new(),
            reconcile_total: Duration::ZERO,
            interrupted: recorder.interrupted,
        }
    }
}

impl Display for ScenarioReport {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        writeln!(f, "Scenario: {}", self.name)?;
        writeln!(f, "  Times: {}", self.times)?;
        writeln!(f, "  Concurrency: {}", self.concurrency)?;
        writeln!(f, "  Total: {}", fmt_duration(self.total))?;
        writeln!(f, "  RPS:   {}", fmt_rps(self.times, self.elapsed))?;
        writeln!(f, "  Min:  {}", fmt_duration(self.min))?;
        writeln!(f, "  Avg:  {}", fmt_duration(self.avg))?;
        writeln!(f, "  Max:  {}", fmt_duration(self.max))?;
        writeln!(f, "  P50:  {}", fmt_duration(self.p50))?;
        writeln!(f, "  P95:  {}", fmt_duration(self.p95))?;
        writeln!(f, "  P99:  {}", fmt_duration(self.p99))?;

        writeln!(f, "  Validate Success:  {}", self.validate_success)?;
        writeln!(f, "  Validate Failures: {}", self.validate_failures)?;
        // 阶段耗时与收尾计数仅在用到对应阶段时输出(未实现时不打扰输出)
        if self.setup_total > Duration::ZERO {
            writeln!(f, "  Setup Total:    {}", fmt_duration(self.setup_total))?;
        }
        if self.validate_total > Duration::ZERO {
            writeln!(f, "  Validate Total: {}", fmt_duration(self.validate_total))?;
        }
        if self.teardown_success + self.teardown_failures > 0 {
            writeln!(f, "  Teardown Total: {}", fmt_duration(self.teardown_total))?;
            writeln!(
                f,
                "  Teardown: {} ok / {} fail",
                self.teardown_success, self.teardown_failures,
            )?;
        }
        if self.reconcile_total > Duration::ZERO {
            writeln!(f, "  Reconcile: {}", fmt_duration(self.reconcile_total))?;
        }
        if !self.invariant_failures.is_empty() {
            writeln!(f, "  Invariants: {} failed", self.invariant_failures.len())?;
            for violation in &self.invariant_failures {
                writeln!(f, "    {violation}")?;
            }
        }
        let (status_4xx, status_5xx) = status_class_counts(&self.status_counts);
        if status_4xx + status_5xx > 0 {
            writeln!(f, "  Status: 4xx {status_4xx} | 5xx {status_5xx}")?;
        }

        writeln!(f, "  Success: {}", self.success)?;
        writeln!(f, "  Failures: {}", self.failures)?;
        writeln!(f, "  Timeouts: {}", self.timeouts)?;
        if self.interrupted {
            writeln!(f, "  Interrupted: true (graceful shutdown)")?;
        }

        if !self.error_map.is_empty() {
            writeln!(f, "  Errors:")?;

            for (kind, count) in &self.error_map {
                writeln!(f, "    {kind}: {count}")?;
            }
        }

        Ok(())
    }
}

/// 可视化报告渲染选项
#[derive(Debug, Clone, Copy)]
pub struct ReportOptions {
    /// 是否启用 ANSI 颜色。默认关闭,可用 `report_with` 显式开启
    pub color: bool,
    /// 条形图宽度(字符数)
    pub bar_width: usize,
}

impl Default for ReportOptions {
    fn default() -> Self {
        Self {
            color: false,
            bar_width: 20,
        }
    }
}

/// 可视化报告入口:让单个场景与多个场景统一支持 `.report()` / `.report_with()` 调用。
///
/// `Vec<ScenarioReport>` 通过本 crate 的 `impl Report for Vec<ScenarioReport>`
/// 直接可用,`&[ScenarioReport]` 亦可。
pub trait Report {
    /// 渲染为可视化文本(使用默认选项:颜色关闭)
    fn report(&self) -> String;

    /// 以自定义选项渲染为可视化文本
    fn report_with(&self, options: ReportOptions) -> String;

    /// 渲染为带 ANSI 颜色的可视化文本(条形图宽度使用默认值)
    fn report_with_color(&self) -> String {
        self.report_with(ReportOptions {
            color: true,
            ..ReportOptions::default()
        })
    }
}

impl Report for ScenarioReport {
    fn report(&self) -> String {
        render_single(self, &ReportOptions::default())
    }

    fn report_with(&self, options: ReportOptions) -> String {
        render_single(self, &options)
    }
}

impl Report for [ScenarioReport] {
    fn report(&self) -> String {
        render_many(self, &ReportOptions::default())
    }

    fn report_with(&self, options: ReportOptions) -> String {
        render_many(self, &options)
    }
}

impl Report for Vec<ScenarioReport> {
    fn report(&self) -> String {
        self.as_slice().report()
    }

    fn report_with(&self, options: ReportOptions) -> String {
        self.as_slice().report_with(options)
    }
}

// ---------- 渲染内核 ----------

/// 有效通过轮数:`run` 成功且业务校验(validate)通过。
/// validate 失败的轮次虽然计入 `success`(HTTP/业务请求本身成功),
/// 但断言未通过,不能视为通过。
/// 收尾(teardown)失败单独计数,不影响这里的通过口径。
fn passed_rounds(success: u64, validate_failures: u64) -> u64 {
    success.saturating_sub(validate_failures)
}

/// error 明细的分母:四类失败事件之和(每类都会写入 `error_map`,可对账)。
fn error_events(r: &ScenarioReport) -> u64 {
    r.failures + r.timeouts + r.validate_failures + r.teardown_failures
}

fn render_single(r: &ScenarioReport, o: &ReportOptions) -> String {
    let mut out = String::new();

    writeln!(
        out,
        "{}",
        paint("============= Scenario =============", "1;36", o.color)
    )
    .unwrap();
    writeln!(out, "{}", paint(&format!("  {}", r.name), "1", o.color)).unwrap();
    writeln!(
        out,
        "{}",
        paint("====================================", "1;36", o.color)
    )
    .unwrap();

    // Success 指有效通过(含 validate):run 成功但断言失败的轮次另见 Validate 行
    let passed = passed_rounds(r.success, r.validate_failures);
    // 百分比分母 = 已产生结果的轮次(含超时软失败),保证各行占比可对账
    let denom = r.times + r.timeouts;
    let success_rate = rate_of(passed, denom);
    let fail_rate = rate_of(r.failures, denom);
    let timeout_rate = rate_of(r.timeouts, denom);

    writeln!(out, "Requests : {}", r.times).unwrap();
    writeln!(out, "Concurrent: {}", r.concurrency).unwrap();
    writeln!(out, "Total    : {}", fmt_duration(r.total)).unwrap();
    writeln!(out, "RPS      : {}", fmt_rps(r.times, r.elapsed)).unwrap();
    writeln!(
        out,
        "Success  : {} ({:.1}%) {}",
        passed,
        success_rate * 100.0,
        paint(rate_label(success_rate), rate_color(success_rate), o.color),
    )
    .unwrap();
    writeln!(out, "Failures : {} ({:.1}%)", r.failures, fail_rate * 100.0,).unwrap();
    writeln!(
        out,
        "Timeout  : {} ({:.1}%)",
        r.timeouts,
        timeout_rate * 100.0,
    )
    .unwrap();
    writeln!(
        out,
        "Validate : {} ok / {} fail",
        r.validate_success, r.validate_failures,
    )
    .unwrap();
    if r.teardown_success + r.teardown_failures > 0 {
        writeln!(
            out,
            "Cleanup  : {} ok / {} fail",
            r.teardown_success, r.teardown_failures,
        )
        .unwrap();
    }
    if r.reconcile_total > Duration::ZERO {
        writeln!(
            out,
            "Reconcile: {} (after all tasks)",
            fmt_duration(r.reconcile_total),
        )
        .unwrap();
    }
    let (status_4xx, status_5xx) = status_class_counts(&r.status_counts);
    if status_4xx + status_5xx > 0 {
        writeln!(out, "Status   : 4xx {status_4xx} | 5xx {status_5xx}").unwrap();
    }
    if !r.invariant_failures.is_empty() {
        writeln!(
            out,
            "{}",
            paint(
                &format!("Invariants: {} failed", r.invariant_failures.len()),
                "31",
                o.color,
            )
        )
        .unwrap();
        for violation in &r.invariant_failures {
            writeln!(out, "  - {violation}").unwrap();
        }
    }
    // 各阶段耗时合计:跨任务累加(可与墙钟 elapsed 重叠),
    // 用于解释 RPS 与 Total 的差距;未用到任何阶段时不输出。
    let stage_total = r.setup_total + r.validate_total + r.teardown_total;
    if stage_total > Duration::ZERO {
        writeln!(
            out,
            "Stages   : setup {} | validate {} | teardown {} (summed over tasks)",
            fmt_duration(r.setup_total),
            fmt_duration(r.validate_total),
            fmt_duration(r.teardown_total),
        )
        .unwrap();
    }
    if r.interrupted {
        writeln!(
            out,
            "{}",
            paint("Interrupted: yes (graceful shutdown)", "33", o.color)
        )
        .unwrap();
    }

    if r.times > 0 {
        let max_ns = r.max.as_nanos().max(1) as f64;
        writeln!(out).unwrap();
        writeln!(out, "Latency (relative to max):").unwrap();
        // 默认不展示 Min/Max,聚焦均值与分位数;
        // 完整统计(含 Min/Max)仍在 ScenarioReport 字段与 Display 中可用。
        for (label, d) in [
            ("Avg", r.avg),
            ("P50", r.p50),
            ("P95", r.p95),
            ("P99", r.p99),
        ] {
            let frac = d.as_nanos() as f64 / max_ns;
            writeln!(
                out,
                "  {:<4} {} {}",
                label,
                bar(frac, o.bar_width),
                fmt_duration(d),
            )
            .unwrap();
        }
    }

    if !r.error_map.is_empty() {
        writeln!(out).unwrap();
        writeln!(out, "Errors:").unwrap();

        // 明细包含 run 失败、超时、validate 失败与收尾失败;分母为全部失败事件数,保证占比对账
        let mut errs: Vec<_> = r.error_map.iter().collect();
        errs.sort_by(|a, b| b.1.cmp(a.1));
        let denom = error_events(r).max(1) as f64;
        for (kind, count) in errs {
            let frac = *count as f64 / denom;
            writeln!(
                out,
                "  {:<24} {} {} ({:.1}%)",
                kind,
                bar(frac, o.bar_width),
                count,
                frac * 100.0,
            )
            .unwrap();
        }
    }

    out
}

fn render_many(reports: &[ScenarioReport], o: &ReportOptions) -> String {
    let mut out = String::new();

    if reports.is_empty() {
        return paint("No reports.", "33", o.color);
    }

    // ---- 总览 ----
    let total_times: u64 = reports.iter().map(|r| r.times).sum();
    let total_success: u64 = reports.iter().map(|r| r.success).sum();
    let total_failures: u64 = reports.iter().map(|r| r.failures).sum();
    let total_timeouts: u64 = reports.iter().map(|r| r.timeouts).sum();
    let total_validate_success: u64 = reports.iter().map(|r| r.validate_success).sum();
    let total_validate_failures: u64 = reports.iter().map(|r| r.validate_failures).sum();
    let total_teardown_success: u64 = reports.iter().map(|r| r.teardown_success).sum();
    let total_teardown_failures: u64 = reports.iter().map(|r| r.teardown_failures).sum();
    let total_setup: Duration = reports.iter().map(|r| r.setup_total).sum();
    let total_validate: Duration = reports.iter().map(|r| r.validate_total).sum();
    let total_teardown: Duration = reports.iter().map(|r| r.teardown_total).sum();
    let total_total: Duration = reports.iter().map(|r| r.total).sum();
    let total_invariant_failures: usize = reports.iter().map(|r| r.invariant_failures.len()).sum();
    let (total_4xx, total_5xx) = reports.iter().fold((0, 0), |(a4, a5), r| {
        let (s4, s5) = status_class_counts(&r.status_counts);
        (a4 + s4, a5 + s5)
    });
    // 多场景由 Manager 串行执行,汇总墙钟 = 各场景 elapsed 之和
    let total_elapsed: Duration = reports.iter().map(|r| r.elapsed).sum();
    // 有效通过:run 成功且 validate 通过,汇总与 Overall 均以此为准
    let total_passed = total_success.saturating_sub(total_validate_failures);

    // 并发度:各场景一致时显示单值,不一致时显示范围
    let first_concurrency = reports[0].concurrency;
    let concurrency_label = if reports.iter().all(|r| r.concurrency == first_concurrency) {
        first_concurrency.to_string()
    } else {
        let min = reports.iter().map(|r| r.concurrency).min().unwrap();
        let max = reports.iter().map(|r| r.concurrency).max().unwrap();
        format!("{min}-{max}")
    };
    let avg: Duration = if total_times > 0 {
        let num: u128 = reports
            .iter()
            .map(|r| r.avg.as_nanos() * r.times as u128)
            .sum();
        Duration::from_nanos((num / total_times as u128) as u64)
    } else {
        Duration::ZERO
    };
    let total_rate = rate_of(total_passed, total_times);
    // 汇总百分比分母同样含超时软失败,保证对账
    let total_denom = total_times + total_timeouts;
    let total_timeout_rate = rate_of(total_timeouts, total_denom);

    writeln!(
        out,
        "{}",
        paint("============== Summary ==============", "1;36", o.color)
    )
    .unwrap();
    writeln!(out, "Scenarios : {}", reports.len()).unwrap();
    writeln!(out, "Concurrent : {concurrency_label}").unwrap();
    writeln!(out, "Requests  : {}", total_times).unwrap();
    writeln!(out, "Total     : {}", fmt_duration(total_total)).unwrap();
    writeln!(out, "RPS       : {}", fmt_rps(total_times, total_elapsed)).unwrap();
    writeln!(out, "Avg       : {}", fmt_duration(avg)).unwrap();
    writeln!(
        out,
        "Success   : {} ({:.1}%) {}",
        total_passed,
        total_rate * 100.0,
        paint(rate_label(total_rate), rate_color(total_rate), o.color),
    )
    .unwrap();
    writeln!(out, "Failures  : {}", total_failures).unwrap();
    writeln!(
        out,
        "Timeout   : {} ({:.1}%)",
        total_timeouts,
        total_timeout_rate * 100.0,
    )
    .unwrap();
    writeln!(
        out,
        "Validate  : {} ok / {} fail",
        total_validate_success, total_validate_failures,
    )
    .unwrap();
    if total_teardown_success + total_teardown_failures > 0 {
        writeln!(
            out,
            "Cleanup   : {} ok / {} fail",
            total_teardown_success, total_teardown_failures,
        )
        .unwrap();
    }
    if total_invariant_failures > 0 {
        writeln!(
            out,
            "{}",
            paint(
                &format!("Invariants: {total_invariant_failures} failed"),
                "31",
                o.color,
            )
        )
        .unwrap();
    }
    if total_4xx + total_5xx > 0 {
        writeln!(out, "Status    : 4xx {total_4xx} | 5xx {total_5xx}").unwrap();
    }
    // 各阶段耗时合计(跨任务累加,可与墙钟重叠);未用到任何阶段时不输出
    if total_setup + total_validate + total_teardown > Duration::ZERO {
        writeln!(
            out,
            "Stages    : setup {} | validate {} | teardown {} (summed over tasks)",
            fmt_duration(total_setup),
            fmt_duration(total_validate),
            fmt_duration(total_teardown),
        )
        .unwrap();
    }
    let interrupted_count = reports.iter().filter(|r| r.interrupted).count();
    if interrupted_count > 0 {
        writeln!(
            out,
            "{}",
            paint(
                &format!(
                    "Interrupted: {interrupted_count}/{} scenarios (graceful shutdown)",
                    reports.len()
                ),
                "33",
                o.color,
            )
        )
        .unwrap();
    }
    writeln!(
        out,
        "Overall   : {} {}",
        bar(total_rate, o.bar_width),
        paint(rate_label(total_rate), rate_color(total_rate), o.color),
    )
    .unwrap();

    // ---- 逐场景表格 ----
    writeln!(out).unwrap();
    writeln!(out, "{}", paint("---- Per-scenario ----", "1;36", o.color)).unwrap();

    let name_w = reports
        .iter()
        .map(|r| r.name.len())
        .max()
        .unwrap_or(0)
        .max(4);

    let header = format!(
        "{:<name_w$} {:>8} {:>10} {:>10} {:>8} {:>10} {:>10} {:>12}",
        "Name",
        "Times",
        "Success",
        "Failures",
        "Rate",
        "Avg",
        "P95",
        "Validate",
        name_w = name_w,
    );
    writeln!(out, "{}", paint(&header, "36", o.color)).unwrap();

    for r in reports {
        // Rate 为有效通过率:run 成功且 validate 通过
        let rate = rate_of(passed_rounds(r.success, r.validate_failures), r.times);
        writeln!(
            out,
            "{:<name_w$} {:>8} {:>10} {:>10} {:>8} {:>10} {:>10} {:>12}",
            r.name,
            r.times,
            r.success,
            r.failures,
            format!("{:.1}%", rate * 100.0),
            fmt_duration(r.avg),
            fmt_duration(r.p95),
            format!("{}/{}", r.validate_success, r.validate_failures),
            name_w = name_w,
        )
        .unwrap();
    }

    // ---- 错误明细 ----
    let err_rows: Vec<_> = reports.iter().filter(|r| !r.error_map.is_empty()).collect();
    if !err_rows.is_empty() {
        writeln!(out).unwrap();
        writeln!(out, "{}", paint("---- Errors ----", "1;36", o.color)).unwrap();

        for r in err_rows {
            writeln!(out, "{}", paint(&format!("  {}.", r.name), "1", o.color)).unwrap();

            // 明细包含 run 失败、超时、validate 失败与收尾失败;分母为全部失败事件数,保证占比对账
            let mut errs: Vec<_> = r.error_map.iter().collect();
            errs.sort_by(|a, b| b.1.cmp(a.1));
            let denom = error_events(r).max(1) as f64;
            for (kind, count) in errs {
                let frac = *count as f64 / denom;
                writeln!(
                    out,
                    "    {:<24} {} {} ({:.1}%)",
                    kind,
                    bar(frac, o.bar_width),
                    count,
                    frac * 100.0,
                )
                .unwrap();
            }
        }
    }

    // ---- 对账失败明细 ----
    let invariant_rows: Vec<_> = reports
        .iter()
        .filter(|r| !r.invariant_failures.is_empty())
        .collect();
    if !invariant_rows.is_empty() {
        writeln!(out).unwrap();
        writeln!(
            out,
            "{}",
            paint("---- Invariant failures ----", "1;36", o.color)
        )
        .unwrap();

        for r in invariant_rows {
            writeln!(out, "{}", paint(&format!("  {}.", r.name), "1", o.color)).unwrap();
            for violation in &r.invariant_failures {
                writeln!(out, "    - {violation}").unwrap();
            }
        }
    }

    out
}

/// 按 4xx / 5xx 聚合状态码计数(其它状态码忽略)。
fn status_class_counts(counts: &BTreeMap<u16, u64>) -> (u64, u64) {
    counts
        .iter()
        .fold((0, 0), |(c4, c5), (code, count)| match code {
            400..=499 => (c4 + count, c5),
            500..=599 => (c4, c5 + count),
            _ => (c4, c5),
        })
}

// ---------- 渲染辅助 ----------

/// 是否启用颜色的判定:由 `ReportOptions::color` 显式控制。
/// 默认关闭颜色,保证输出可预测、可直接写入日志/文件;
/// 需要彩色时用 `report_with(ReportOptions { color: true, .. })`。
pub(crate) fn paint(s: &str, code: &str, enabled: bool) -> String {
    if enabled {
        format!("\x1b[{code}m{s}\x1b[0m")
    } else {
        s.to_string()
    }
}

fn rate_of(passed: u64, total: u64) -> f64 {
    if total == 0 {
        0.0
    } else {
        passed as f64 / total as f64
    }
}

fn rate_color(rate: f64) -> &'static str {
    if rate >= 0.99 {
        "32" // 绿
    } else if rate >= 0.90 {
        "33" // 黄
    } else {
        "31" // 红
    }
}

fn rate_label(rate: f64) -> &'static str {
    if rate >= 0.99 {
        "OK"
    } else if rate >= 0.90 {
        "WARN"
    } else {
        "BAD"
    }
}

/// 生成 ASCII 条形图,`fraction` 为 0.0 ~ 1.0
pub(crate) fn bar(fraction: f64, width: usize) -> String {
    let width = width.max(1);
    let filled = (fraction.clamp(0.0, 1.0) * width as f64).round() as usize;
    format!("{}{}", "█".repeat(filled), "░".repeat(width - filled))
}

/// 可读化 Duration:一律以毫秒(ms)为单位,便于跨场景对比。
pub(crate) fn fmt_duration(d: Duration) -> String {
    format!("{:.2}ms", d.as_nanos() as f64 / 1e6)
}

/// 每秒请求数(RPS):总请求数 / 墙钟耗时,保留两位小数。
pub(crate) fn fmt_rps(times: u64, elapsed: Duration) -> String {
    let secs = elapsed.as_secs_f64();
    if secs <= 0.0 {
        return "0.00".to_string();
    }
    format!("{:.2}", times as f64 / secs)
}