subms 0.5.1

The sub-millisecond perf harness for Rust. Zero-dependency std-only library that records timed samples per stage, computes percentiles, supports coordinated-omission correction, runs scale sweeps, and emits a stable JSON contract. Byte-equivalent to the Java sibling com.submillisecond:subms.
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
//! Shared bench helpers. Pipeline:
//!
//! ```text
//! recipe -> SubMsPerfHarness -> SubMsBenchSummary -> { print, assert, JSON }
//! ```
//!
//! [`summarize`] turns the raw harness into a typed [`SubMsBenchSummary`].
//! [`print_summary`], [`assert_p99_under`], and [`summary_to_json`] are
//! presenters / asserters on top of that data; none of them recompute stats.
//!
//! The Java sibling ships the same surface (`SubMsBench.summarize`,
//! `SubMsBench.printSummary`, `SubMsBench.summaryToJson`) with byte-equivalent
//! output, so tooling can consume either runtime interchangeably.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::{self, Write};

use crate::{
    SubMsBenchDiff, SubMsBenchParams, SubMsBenchSummary, SubMsBenchSweep, SubMsMetricDiff,
    SubMsPerfHarness, SubMsRecipe, SubMsStageDiff, SubMsStageSummary, stats,
};

// ---------------------------------------------------------------------
// Summarise (structured)
// ---------------------------------------------------------------------

/// Build a [`SubMsBenchSummary`] from the harness. Includes the downsampled
/// (max-500) chronological per-stage timeline. Order matches stage
/// registration.
pub fn summarize(h: &SubMsPerfHarness) -> SubMsBenchSummary {
    summarize_internal(h, /*include_samples*/ true, /*skip_warmup*/ 0)
}

/// Same as [`summarize`] but drops the per-stage sample arrays. Use when you
/// only need count + percentiles + mean.
pub fn summarize_lean(h: &SubMsPerfHarness) -> SubMsBenchSummary {
    summarize_internal(h, /*include_samples*/ false, /*skip_warmup*/ 0)
}

/// Same as [`summarize`] but discards the first `skip_warmup` samples per
/// stage before computing percentiles + mean + stddev. Use when the
/// recipe can't insert a pre-pass warmup itself (e.g. a JIT- or cache-
/// cold first ~1k operations would skew p99).
///
/// `samples_ns` in the output reflects the trimmed timeline.
pub fn summarize_skipping(h: &SubMsPerfHarness, skip_warmup: usize) -> SubMsBenchSummary {
    summarize_internal(h, /*include_samples*/ true, skip_warmup)
}

/// Slice each stage's chronological sample buffer into `window` equal-sized
/// chunks and produce a [`SubMsBenchSummary`] per chunk. Useful for
/// rolling-window p99 analysis - "how did p99 evolve across the run?"
///
/// Windows are sample-count-based, not wall-clock-based, since the harness
/// doesn't record per-sample timestamps. For wall-clock windows, ensure
/// the workload runs at a roughly steady rate; then the i-th window
/// approximates the i-th time slice.
///
/// Returns an empty vector if the harness has zero stages.
pub fn summarize_windowed(h: &SubMsPerfHarness, window: usize) -> Vec<SubMsBenchSummary> {
    let window = window.max(1);
    // Find the longest stage; that determines how many windows we emit.
    let max_len = h
        .stages()
        .iter()
        .map(|s| s.samples().len())
        .max()
        .unwrap_or(0);
    if max_len == 0 {
        return Vec::new();
    }
    let n_windows = max_len.div_ceil(window);
    let mut out = Vec::with_capacity(n_windows);
    for w in 0..n_windows {
        let start = w * window;
        let stages = h
            .stages()
            .iter()
            .map(|s| {
                let samples = s.samples();
                let end = (start + window).min(samples.len());
                let slice = if start < samples.len() {
                    &samples[start..end]
                } else {
                    &[][..]
                };
                summarize_stage(s.name(), slice, /*include_samples*/ false)
            })
            .collect();
        out.push(SubMsBenchSummary {
            workload: h.workload().to_string(),
            lang: h.lang().to_string(),
            timestamp: h.timestamp(),
            inputs: {
                let mut m = clone_map(h.inputs());
                m.insert("__window_index".to_string(), w.to_string());
                m.insert("__window_size".to_string(), window.to_string());
                m
            },
            meta: clone_map(h.meta()),
            stages,
        });
    }
    out
}

// percentile_sweep moved to `crate::stats::percentile_sweep`. Recipes
// previously importing it from this module can keep using `subms::percentile_sweep`
// via the top-level re-export.

fn summarize_internal(
    h: &SubMsPerfHarness,
    include_samples: bool,
    skip_warmup: usize,
) -> SubMsBenchSummary {
    let stages = h
        .stages()
        .iter()
        .map(|s| {
            let trimmed = if skip_warmup > 0 && s.samples().len() > skip_warmup {
                &s.samples()[skip_warmup..]
            } else {
                s.samples()
            };
            summarize_stage(s.name(), trimmed, include_samples)
        })
        .collect();
    SubMsBenchSummary {
        workload: h.workload().to_string(),
        lang: h.lang().to_string(),
        timestamp: h.timestamp(),
        inputs: clone_map(h.inputs()),
        meta: clone_map(h.meta()),
        stages,
    }
}

fn summarize_stage(name: &str, chronological: &[u64], include_samples: bool) -> SubMsStageSummary {
    let mut sorted = chronological.to_vec();
    sorted.sort_unstable();
    let samples_ns = if include_samples {
        Some(downsample(chronological))
    } else {
        None
    };
    SubMsStageSummary {
        name: name.to_string(),
        count: sorted.len(),
        p50_ns: stats::percentile(&sorted, 0.50),
        p99_ns: stats::percentile(&sorted, 0.99),
        p999_ns: stats::percentile(&sorted, 0.999),
        max_ns: sorted.last().copied().unwrap_or(0),
        mean_ns: stats::mean(chronological),
        stddev_ns: stats::stddev(chronological),
        cdf_buckets_ns: stats::cdf_buckets(chronological),
        jitter_score: stats::jitter_score(chronological),
        samples_ns,
    }
}

/// Evenly-spaced downsample to at most 500 points, chronological order preserved.
pub(crate) fn downsample(chronological: &[u64]) -> Vec<u64> {
    let n = chronological.len();
    if n == 0 {
        return Vec::new();
    }
    let step = (n / 500).max(1);
    chronological.iter().copied().step_by(step).collect()
}

fn clone_map(src: &BTreeMap<String, String>) -> BTreeMap<String, String> {
    src.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
}

// ---------------------------------------------------------------------
// Print (presenter)
// ---------------------------------------------------------------------

/// Print a fixed-width percentile table for every stage in the summary, in
/// registration order. Byte-equivalent to Java's `SubMsBench.printSummary`.
pub fn print_summary<W: Write>(s: &SubMsBenchSummary, out: &mut W) -> io::Result<()> {
    writeln!(
        out,
        "  {:<9}  {:>9}  {:>9}  {:>9}  {:>9}  {:>9}",
        "stage", "p50", "p99", "p99.9", "max", "mean"
    )?;
    for stage in &s.stages {
        writeln!(
            out,
            "  {:<9}  {:>9}  {:>9}  {:>9}  {:>9}  {:>9}",
            stage.name,
            format_ns(stage.p50_ns),
            format_ns(stage.p99_ns),
            format_ns(stage.p999_ns),
            format_ns(stage.max_ns),
            format_ns(stage.mean_ns),
        )?;
    }
    Ok(())
}

/// Compact unit-aware ns formatter. Sub-microsecond stays in ns; sub-millisecond
/// goes to us with one decimal; everything else is ms to two decimals. Matches
/// Java's `SubMsBench.formatNs`.
pub fn format_ns(ns: u64) -> String {
    if ns < 1_000 {
        format!("{}ns", ns)
    } else if ns < 1_000_000 {
        format!("{:.1}us", ns as f64 / 1_000.0)
    } else {
        format!("{:.2}ms", ns as f64 / 1_000_000.0)
    }
}

// ---------------------------------------------------------------------
// Assert
// ---------------------------------------------------------------------

/// A single stage-level p99 assertion.
#[derive(Debug, Clone, Copy)]
pub struct SubMsBenchAssertion {
    /// Stage name as registered with the harness.
    pub stage: &'static str,
    /// Upper bound, ns.
    pub p99_ns_max: u64,
}

/// Accept either a [`SubMsBenchSummary`] (recommended) or a
/// [`SubMsPerfHarness`] (back-compat). Used by [`assert_p99_under`].
pub trait SubMsAssertionTarget {
    fn lookup_p99_ns(&self, stage: &str) -> Option<u64>;
}

impl SubMsAssertionTarget for SubMsBenchSummary {
    fn lookup_p99_ns(&self, stage: &str) -> Option<u64> {
        self.stage(stage).map(|s| s.p99_ns)
    }
}

impl SubMsAssertionTarget for SubMsPerfHarness {
    fn lookup_p99_ns(&self, stage: &str) -> Option<u64> {
        let st = self.stage_by_name(stage)?;
        let mut sorted = st.samples().to_vec();
        sorted.sort_unstable();
        Some(stats::percentile(&sorted, 0.99))
    }
}

/// `Err` on the first stage that exceeds its p99 bound (or is missing).
/// Accepts either a summary or the raw harness.
pub fn assert_p99_under<T: SubMsAssertionTarget + ?Sized>(
    target: &T,
    assertions: &[SubMsBenchAssertion],
) -> Result<(), String> {
    for a in assertions {
        let p99 = target
            .lookup_p99_ns(a.stage)
            .ok_or_else(|| format!("stage '{}' not found", a.stage))?;
        if p99 > a.p99_ns_max {
            return Err(format!(
                "stage '{}' p99 = {} ns exceeded limit {} ns",
                a.stage, p99, a.p99_ns_max
            ));
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------
// Run
// ---------------------------------------------------------------------

/// Alias of [`crate::recipe::benchmark`]; matches Java's `Bench.runBench`.
pub fn run_bench<R: SubMsRecipe + ?Sized>(
    recipe: &R,
    params: &SubMsBenchParams,
) -> SubMsPerfHarness {
    crate::recipe::benchmark(recipe, params)
}

/// Run a contended workload `iterations_per_thread` times on `threads`
/// threads and discard the timings. The standard way to warm up
/// recipes whose hot path runs under multi-producer contention: serial
/// warmup compiles the function under uncontended cache-line traffic,
/// which doesn't expose the JIT / branch predictor to the actual
/// contended pattern the timed loop uses. Without this pre-pass the
/// first 1-2k samples in the timed loop run "cold" under contention
/// and inflate p99 by 3-5x.
///
/// `work` is invoked once per iteration on each thread with the
/// `(thread_id, iteration)` pair.
pub fn contended_warmup<F>(threads: usize, iterations_per_thread: usize, work: F)
where
    F: Fn(usize, usize) + Send + Sync + 'static + Copy,
{
    let mut handles = Vec::with_capacity(threads);
    for tid in 0..threads {
        handles.push(std::thread::spawn(move || {
            for i in 0..iterations_per_thread {
                work(tid, i);
            }
        }));
    }
    for h in handles {
        h.join().expect("contended_warmup thread");
    }
}

// ---------------------------------------------------------------------
// JSON (presenter)
// ---------------------------------------------------------------------

/// Serialise the summary to the standard subms JSON shape. Byte-equivalent
/// to Java's `SubMsBench.summaryToJson`.
pub fn summary_to_json<W: Write>(s: &SubMsBenchSummary, out: &mut W) -> io::Result<()> {
    let mut buf = String::with_capacity(64 * 1024);
    append_summary_json(&mut buf, s);
    out.write_all(buf.as_bytes())?;
    out.write_all(b"\n")?;
    Ok(())
}

pub(crate) fn append_summary_json(out: &mut String, s: &SubMsBenchSummary) {
    out.push('{');
    json_kv_str(out, "workload", &s.workload);
    out.push(',');
    json_kv_str(out, "lang", &s.lang);
    out.push(',');
    json_kv_str(out, "timestamp", &s.timestamp);
    out.push(',');
    out.push_str("\"inputs\":");
    json_map(out, &s.inputs);
    out.push(',');
    out.push_str("\"meta\":");
    json_map(out, &s.meta);
    out.push(',');
    out.push_str("\"stages\":{");
    for (i, stage) in s.stages.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        json_str(out, &stage.name);
        out.push(':');
        stage_json(out, stage);
    }
    out.push_str("}}");
}

fn stage_json(out: &mut String, stage: &SubMsStageSummary) {
    out.push('{');
    let _ = write!(out, "\"count\":{},", stage.count);
    let _ = write!(out, "\"p50_ns\":{},", stage.p50_ns);
    let _ = write!(out, "\"p99_ns\":{},", stage.p99_ns);
    let _ = write!(out, "\"p999_ns\":{},", stage.p999_ns);
    let _ = write!(out, "\"max_ns\":{},", stage.max_ns);
    let _ = write!(out, "\"mean_ns\":{},", stage.mean_ns);
    let _ = write!(out, "\"stddev_ns\":{},", stage.stddev_ns);
    let _ = write!(out, "\"jitter_score\":{:.4},", stage.jitter_score);
    out.push_str("\"cdf_buckets_ns\":[");
    for (i, c) in stage.cdf_buckets_ns.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        let _ = write!(out, "{}", c);
    }
    out.push_str("],");
    out.push_str("\"samples_ns\":[");
    if let Some(samples) = &stage.samples_ns {
        for (i, x) in samples.iter().enumerate() {
            if i > 0 {
                out.push(',');
            }
            let _ = write!(out, "{}", x);
        }
    }
    out.push_str("]}");
}

fn json_str(out: &mut String, s: &str) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

fn json_kv_str(out: &mut String, k: &str, v: &str) {
    json_str(out, k);
    out.push(':');
    json_str(out, v);
}

fn json_map(out: &mut String, m: &BTreeMap<String, String>) {
    out.push('{');
    for (i, (k, v)) in m.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        json_kv_str(out, k, v);
    }
    out.push('}');
}

// ---------------------------------------------------------------------
// Sweep (multi-run varied-input pipeline)
// ---------------------------------------------------------------------

/// Run the recipe once per element of `params_list`, summarise each run, and
/// bundle the summaries into a [`SubMsBenchSweep`]. `varied_input_key` should
/// name the input that differs across runs (typically `"entries"`); pass
/// `None` to leave it unset.
pub fn run_sweep<R: SubMsRecipe + ?Sized>(
    recipe: &R,
    params_list: &[SubMsBenchParams],
    varied_input_key: Option<&str>,
) -> SubMsBenchSweep {
    let runs = params_list
        .iter()
        .map(|p| summarize(&run_bench(recipe, p)))
        .collect();
    SubMsBenchSweep {
        workload: recipe.name().to_string(),
        lang: "rust".to_string(),
        varied_input_key: varied_input_key.map(|s| s.to_string()),
        runs,
    }
}

/// Bundle pre-computed summaries (e.g. captured separately) into a sweep. All
/// summaries should share a workload; the first summary's workload is used.
pub fn summarize_sweep(
    summaries: Vec<SubMsBenchSummary>,
    varied_input_key: Option<&str>,
) -> SubMsBenchSweep {
    assert!(
        !summaries.is_empty(),
        "summarize_sweep requires at least one run"
    );
    SubMsBenchSweep {
        workload: summaries[0].workload.clone(),
        lang: summaries[0].lang.clone(),
        varied_input_key: varied_input_key.map(|s| s.to_string()),
        runs: summaries,
    }
}

/// Print a pivoted percentile table per stage: one block per stage, one row
/// per run, labelled by the varied input value (or by ordinal if no varied
/// key was supplied). Byte-equivalent to Java's `SubMsBench.printSweep`.
pub fn print_sweep<W: Write>(sweep: &SubMsBenchSweep, out: &mut W) -> io::Result<()> {
    if sweep.runs.is_empty() {
        writeln!(out, "(empty sweep)")?;
        return Ok(());
    }
    let first = &sweep.runs[0];
    let header_label = sweep.varied_input_key.as_deref().unwrap_or("run");
    for stage in &first.stages {
        writeln!(out, "stage: {}", stage.name)?;
        writeln!(
            out,
            "  {:<15}  {:>9}  {:>9}  {:>9}  {:>9}  {:>9}  {:>9}",
            header_label, "count", "p50", "p99", "p99.9", "max", "mean"
        )?;
        for (i, run) in sweep.runs.iter().enumerate() {
            let label = match &sweep.varied_input_key {
                Some(k) => run
                    .inputs
                    .get(k)
                    .cloned()
                    .unwrap_or_else(|| "?".to_string()),
                None => format!("run {}", i + 1),
            };
            match run.stage(&stage.name) {
                None => writeln!(out, "  {:<15}  (stage missing)", label)?,
                Some(s) => writeln!(
                    out,
                    "  {:<15}  {:>9}  {:>9}  {:>9}  {:>9}  {:>9}  {:>9}",
                    label,
                    s.count,
                    format_ns(s.p50_ns),
                    format_ns(s.p99_ns),
                    format_ns(s.p999_ns),
                    format_ns(s.max_ns),
                    format_ns(s.mean_ns)
                )?,
            }
        }
        writeln!(out)?;
    }
    Ok(())
}

/// Emit a JSON array of run-summaries, identical shape to
/// on-disk `perf/<lang>.json`. Byte-equivalent to Java's
/// `SubMsBench.sweepToJson`.
pub fn sweep_to_json<W: Write>(sweep: &SubMsBenchSweep, out: &mut W) -> io::Result<()> {
    let mut buf = String::with_capacity(64 * 1024);
    buf.push('[');
    for (i, run) in sweep.runs.iter().enumerate() {
        if i > 0 {
            buf.push(',');
        }
        append_summary_json(&mut buf, run);
    }
    buf.push(']');
    out.write_all(buf.as_bytes())?;
    out.write_all(b"\n")?;
    Ok(())
}

// ---------------------------------------------------------------------
// Diff (baseline vs candidate regression detection)
// ---------------------------------------------------------------------

/// Default percent above which a stage's metric is considered a regression for
/// the subms-perf-gate CI workflow. Matches Java's
/// `SubMsBench.DEFAULT_REGRESSION_THRESHOLD_PCT`.
pub const DEFAULT_REGRESSION_THRESHOLD_PCT: f64 = 10.0;

/// Build a typed diff between two summaries using the default 10 % threshold.
pub fn diff_summary(baseline: &SubMsBenchSummary, candidate: &SubMsBenchSummary) -> SubMsBenchDiff {
    diff_summary_with(baseline, candidate, DEFAULT_REGRESSION_THRESHOLD_PCT)
}

/// Same as [`diff_summary`] but caller specifies the regression threshold.
pub fn diff_summary_with(
    baseline: &SubMsBenchSummary,
    candidate: &SubMsBenchSummary,
    regression_threshold_pct: f64,
) -> SubMsBenchDiff {
    let baseline_names: Vec<&str> = baseline.stages.iter().map(|s| s.name.as_str()).collect();
    let candidate_names: std::collections::BTreeSet<&str> =
        candidate.stages.iter().map(|s| s.name.as_str()).collect();

    let mut stage_diffs = Vec::new();
    for cand in &candidate.stages {
        if let Some(base) = baseline.stage(&cand.name) {
            stage_diffs.push(diff_stage(base, cand));
        }
    }

    let candidate_name_set: std::collections::BTreeSet<&str> = candidate_names.clone();
    let baseline_name_set: std::collections::BTreeSet<&str> =
        baseline_names.iter().copied().collect();
    let baseline_only: Vec<String> = baseline_names
        .iter()
        .filter(|n| !candidate_name_set.contains(*n))
        .map(|s| s.to_string())
        .collect();
    let candidate_only: Vec<String> = candidate
        .stages
        .iter()
        .map(|s| s.name.clone())
        .filter(|n| !baseline_name_set.contains(n.as_str()))
        .collect();

    SubMsBenchDiff {
        baseline_workload: baseline.workload.clone(),
        candidate_workload: candidate.workload.clone(),
        lang: candidate.lang.clone(),
        stages: stage_diffs,
        baseline_only_stages: baseline_only,
        candidate_only_stages: candidate_only,
        regression_threshold_pct,
    }
}

fn diff_stage(baseline: &SubMsStageSummary, candidate: &SubMsStageSummary) -> SubMsStageDiff {
    let metrics = vec![
        metric_diff("p50", baseline.p50_ns, candidate.p50_ns),
        metric_diff("p99", baseline.p99_ns, candidate.p99_ns),
        metric_diff("p99.9", baseline.p999_ns, candidate.p999_ns),
        metric_diff("max", baseline.max_ns, candidate.max_ns),
        metric_diff("mean", baseline.mean_ns, candidate.mean_ns),
    ];
    let worst = metrics
        .iter()
        .filter(|m| m.delta_pct.is_finite())
        .map(|m| m.delta_pct)
        .fold(0.0_f64, f64::max);
    SubMsStageDiff {
        stage: baseline.name.clone(),
        metrics,
        worst_regression_pct: worst,
    }
}

fn metric_diff(name: &str, baseline: u64, candidate: u64) -> SubMsMetricDiff {
    let delta_ns = candidate as i64 - baseline as i64;
    let delta_pct = if baseline == 0 {
        if candidate == 0 { 0.0 } else { f64::INFINITY }
    } else {
        (100.0 * delta_ns as f64) / baseline as f64
    };
    SubMsMetricDiff {
        metric: name.to_string(),
        baseline_ns: baseline,
        candidate_ns: candidate,
        delta_ns,
        delta_pct,
    }
}

/// Print a regression-table view of the diff. Byte-equivalent to Java's
/// `SubMsBench.printDiff`.
pub fn print_diff<W: Write>(diff: &SubMsBenchDiff, out: &mut W) -> io::Result<()> {
    writeln!(
        out,
        "diff: {} vs {} ({})  threshold=+{:.1}%",
        diff.baseline_workload, diff.candidate_workload, diff.lang, diff.regression_threshold_pct
    )?;
    writeln!(
        out,
        "  {:<12}  {:<7}  {:>9}  {:>9}  {:>9}  {:>9}  verdict",
        "stage", "metric", "baseline", "candidate", "delta", "%delta"
    )?;
    for stage in &diff.stages {
        for m in &stage.metrics {
            let pct_str = if m.delta_pct.is_finite() {
                format!("{:+.1}%", m.delta_pct)
            } else {
                "+inf%".to_string()
            };
            let verdict = if m.delta_pct.is_finite() && m.delta_pct > diff.regression_threshold_pct
            {
                "REGRESSED"
            } else {
                "ok"
            };
            let abs = m.delta_ns.unsigned_abs();
            let delta_str = if m.delta_ns >= 0 {
                format!("+{}", format_ns(abs))
            } else {
                format!("-{}", format_ns(abs))
            };
            writeln!(
                out,
                "  {:<12}  {:<7}  {:>9}  {:>9}  {:>9}  {:>9}  {}",
                stage.stage,
                m.metric,
                format_ns(m.baseline_ns),
                format_ns(m.candidate_ns),
                delta_str,
                pct_str,
                verdict,
            )?;
        }
    }
    if !diff.baseline_only_stages.is_empty() {
        writeln!(
            out,
            "  stages only in baseline:  {}",
            diff.baseline_only_stages.join(", ")
        )?;
    }
    if !diff.candidate_only_stages.is_empty() {
        writeln!(
            out,
            "  stages only in candidate: {}",
            diff.candidate_only_stages.join(", ")
        )?;
    }
    Ok(())
}

/// Emit the diff as a single JSON object for downstream CI tooling.
/// Byte-equivalent to Java's `SubMsBench.diffToJson`.
pub fn diff_to_json<W: Write>(diff: &SubMsBenchDiff, out: &mut W) -> io::Result<()> {
    let mut buf = String::with_capacity(8 * 1024);
    append_diff_json(&mut buf, diff);
    out.write_all(buf.as_bytes())?;
    out.write_all(b"\n")?;
    Ok(())
}

fn append_diff_json(out: &mut String, diff: &SubMsBenchDiff) {
    out.push('{');
    json_kv_str(out, "baseline_workload", &diff.baseline_workload);
    out.push(',');
    json_kv_str(out, "candidate_workload", &diff.candidate_workload);
    out.push(',');
    json_kv_str(out, "lang", &diff.lang);
    out.push(',');
    let _ = write!(
        out,
        "\"regression_threshold_pct\":{},",
        diff.regression_threshold_pct
    );
    let _ = write!(out, "\"has_regression\":{},", diff.has_regression());
    out.push_str("\"stages\":[");
    for (i, s) in diff.stages.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push('{');
        json_kv_str(out, "stage", &s.stage);
        out.push(',');
        let _ = write!(
            out,
            "\"worst_regression_pct\":{},",
            json_number(s.worst_regression_pct)
        );
        out.push_str("\"metrics\":[");
        for (j, m) in s.metrics.iter().enumerate() {
            if j > 0 {
                out.push(',');
            }
            out.push('{');
            json_kv_str(out, "metric", &m.metric);
            out.push(',');
            let _ = write!(out, "\"baseline_ns\":{},", m.baseline_ns);
            let _ = write!(out, "\"candidate_ns\":{},", m.candidate_ns);
            let _ = write!(out, "\"delta_ns\":{},", m.delta_ns);
            let _ = write!(out, "\"delta_pct\":{}", json_number(m.delta_pct));
            out.push('}');
        }
        out.push_str("]}");
    }
    out.push_str("],");
    out.push_str("\"baseline_only_stages\":[");
    for (i, n) in diff.baseline_only_stages.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        json_str(out, n);
    }
    out.push_str("],");
    out.push_str("\"candidate_only_stages\":[");
    for (i, n) in diff.candidate_only_stages.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        json_str(out, n);
    }
    out.push_str("]}");
}

/// Render a finite f64 as a JSON number; non-finite values become `null`
/// (JSON has no inf/NaN literal).
fn json_number(d: f64) -> String {
    if d.is_finite() {
        d.to_string()
    } else {
        "null".to_string()
    }
}

// percentile is INTERNAL ONLY. Recipes don't reach for it directly;
// they read the percentile fields off `SubMsStageSummary`. External
// consumers wanting a standalone percentile fn pull in `subms-stats`.

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

    #[test]
    fn percentile_empty_is_zero() {
        assert_eq!(stats::percentile(&[], 0.5), 0);
    }

    #[test]
    fn percentile_single_value() {
        assert_eq!(stats::percentile(&[42], 0.0), 42);
        assert_eq!(stats::percentile(&[42], 0.5), 42);
        assert_eq!(stats::percentile(&[42], 1.0), 42);
    }

    #[test]
    fn percentile_known_distribution() {
        let v: Vec<u64> = (1..=100).collect();
        assert_eq!(stats::percentile(&v, 0.50), 51);
        assert_eq!(stats::percentile(&v, 0.99), 100);
        assert_eq!(stats::percentile(&v, 0.999), 100);
        assert_eq!(stats::percentile(&v, 1.0), 100);
    }

    struct FixedSubMsRecipe;
    impl SubMsRecipe for FixedSubMsRecipe {
        fn name(&self) -> &str {
            "fixed-recipe"
        }
        fn run(&self, h: &mut SubMsPerfHarness, _params: &SubMsBenchParams) {
            let s = h.stage("step", 4);
            s.record(100);
            s.record(200);
            s.record(300);
            s.record(400);
        }
    }

    #[test]
    fn run_bench_drives_recipe_through_harness() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let stage = h.stage_by_name("step").expect("step recorded");
        assert_eq!(stage.samples().len(), 4);
    }

    #[test]
    fn summarize_populates_percentiles_and_samples() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let s = summarize(&h);
        assert_eq!(s.stages.len(), 1);
        let st = &s.stages[0];
        assert_eq!(st.name, "step");
        assert_eq!(st.count, 4);
        assert_eq!(st.p50_ns, 300);
        assert_eq!(st.p99_ns, 400);
        assert_eq!(st.max_ns, 400);
        assert_eq!(st.mean_ns, 250);
        assert_eq!(st.samples_ns.as_ref().unwrap().len(), 4);
    }

    #[test]
    fn summarize_lean_drops_samples() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let s = summarize_lean(&h);
        assert!(s.stages[0].samples_ns.is_none());
    }

    #[test]
    fn assert_p99_under_passes_when_below_limit() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let s = summarize_lean(&h);
        assert_p99_under(
            &s,
            &[SubMsBenchAssertion {
                stage: "step",
                p99_ns_max: 400,
            }],
        )
        .expect("p99=400 should satisfy max=400");
    }

    #[test]
    fn assert_p99_under_errors_when_above_limit() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let s = summarize_lean(&h);
        let err = assert_p99_under(
            &s,
            &[SubMsBenchAssertion {
                stage: "step",
                p99_ns_max: 399,
            }],
        )
        .unwrap_err();
        assert!(err.contains("step"));
        assert!(err.contains("400"));
        assert!(err.contains("399"));
    }

    #[test]
    fn assert_p99_under_errors_when_stage_missing() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let s = summarize_lean(&h);
        let err = assert_p99_under(
            &s,
            &[SubMsBenchAssertion {
                stage: "ghost",
                p99_ns_max: 1,
            }],
        )
        .unwrap_err();
        assert!(err.contains("ghost"));
        assert!(err.contains("not found"));
    }

    #[test]
    fn format_ns_uses_three_unit_tiers() {
        assert_eq!(format_ns(0), "0ns");
        assert_eq!(format_ns(999), "999ns");
        assert_eq!(format_ns(1_000), "1.0us");
        assert_eq!(format_ns(36_000), "36.0us");
        assert_eq!(format_ns(999_999), "1000.0us");
        assert_eq!(format_ns(1_000_000), "1.00ms");
        assert_eq!(format_ns(3_590_000), "3.59ms");
    }

    #[test]
    fn run_sweep_runs_recipe_once_per_params_set() {
        let params = vec![
            SubMsBenchParams {
                entries: 4,
                warmup: 0,
                seed: 0,
            },
            SubMsBenchParams {
                entries: 4,
                warmup: 0,
                seed: 1,
            },
        ];
        let sweep = run_sweep(&FixedSubMsRecipe, &params, Some("seed"));
        assert_eq!(sweep.runs.len(), 2);
        assert_eq!(sweep.varied_input_key.as_deref(), Some("seed"));
        // Both runs hit the fixed recipe's "step" stage.
        assert_eq!(sweep.runs[0].stages[0].name, "step");
        assert_eq!(sweep.runs[1].stages[0].name, "step");
    }

    #[test]
    fn summarize_sweep_bundles_existing_summaries() {
        let p = SubMsBenchParams::default();
        let a = summarize(&run_bench(&FixedSubMsRecipe, &p));
        let b = summarize(&run_bench(&FixedSubMsRecipe, &p));
        let sweep = summarize_sweep(vec![a, b], Some("entries"));
        assert_eq!(sweep.runs.len(), 2);
        assert_eq!(sweep.workload, "fixed-recipe");
        assert_eq!(sweep.lang, "rust");
    }

    #[test]
    fn print_sweep_pivots_by_stage_and_labels_rows() {
        let params = vec![
            SubMsBenchParams {
                entries: 4,
                warmup: 0,
                seed: 0,
            },
            SubMsBenchParams {
                entries: 4,
                warmup: 0,
                seed: 0,
            },
        ];
        let sweep = run_sweep(&FixedSubMsRecipe, &params, None);
        let mut buf = Vec::new();
        print_sweep(&sweep, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("stage: step"));
        assert!(out.contains("run 1"));
        assert!(out.contains("run 2"));
    }

    #[test]
    fn sweep_to_json_emits_array() {
        let params = vec![
            SubMsBenchParams {
                entries: 4,
                warmup: 0,
                seed: 0,
            },
            SubMsBenchParams {
                entries: 4,
                warmup: 0,
                seed: 0,
            },
        ];
        let sweep = run_sweep(&FixedSubMsRecipe, &params, Some("seed"));
        let mut buf = Vec::new();
        sweep_to_json(&sweep, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.starts_with('['));
        assert!(out.contains("\"workload\":\"fixed-recipe\""));
        assert!(out.contains("\"stages\":{"));
    }

    // ---- diff tests -----------------------------------------------------

    struct ExplicitRecipe {
        values: Vec<u64>,
    }
    impl SubMsRecipe for ExplicitRecipe {
        fn name(&self) -> &str {
            "explicit"
        }
        fn run(&self, h: &mut SubMsPerfHarness, _p: &SubMsBenchParams) {
            let s = h.stage("put", self.values.len());
            for v in &self.values {
                s.record(*v);
            }
        }
    }

    #[test]
    fn diff_summary_computes_per_metric_deltas() {
        let p = SubMsBenchParams::default();
        let base = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![100, 200, 300, 400],
            },
            &p,
        ));
        let cand = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![110, 220, 330, 440],
            },
            &p,
        ));
        let d = diff_summary(&base, &cand);
        assert_eq!(d.stages.len(), 1);
        let put = &d.stages[0];
        for m in &put.metrics {
            assert!(
                (m.delta_pct - 10.0).abs() < 1e-9,
                "{}: {}",
                m.metric,
                m.delta_pct
            );
        }
        assert!((put.worst_regression_pct - 10.0).abs() < 1e-9);
    }

    #[test]
    fn diff_summary_flags_regression_above_threshold() {
        let p = SubMsBenchParams::default();
        let base = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![100, 200, 300, 400],
            },
            &p,
        ));
        let cand = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![200, 400, 600, 800],
            },
            &p,
        ));
        let d = diff_summary_with(&base, &cand, 50.0);
        assert!(d.has_regression());
        assert_eq!(d.worst_stage().unwrap().stage, "put");
    }

    #[test]
    fn diff_summary_does_not_flag_when_all_improved() {
        let p = SubMsBenchParams::default();
        let base = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![200, 400, 600, 800],
            },
            &p,
        ));
        let cand = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![100, 200, 300, 400],
            },
            &p,
        ));
        let d = diff_summary_with(&base, &cand, 10.0);
        assert!(!d.has_regression());
    }

    #[test]
    fn print_diff_emits_table_with_verdict_column() {
        let p = SubMsBenchParams::default();
        let base = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![100, 200, 300, 400],
            },
            &p,
        ));
        let cand = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![200, 400, 600, 800],
            },
            &p,
        ));
        let d = diff_summary_with(&base, &cand, 50.0);
        let mut buf = Vec::new();
        print_diff(&d, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("stage"));
        assert!(out.contains("verdict"));
        assert!(out.contains("REGRESSED"));
    }

    #[test]
    fn diff_to_json_emits_expected_keys() {
        let p = SubMsBenchParams::default();
        let base = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![100, 200, 300, 400],
            },
            &p,
        ));
        let cand = summarize_lean(&run_bench(
            &ExplicitRecipe {
                values: vec![110, 220, 330, 440],
            },
            &p,
        ));
        let d = diff_summary_with(&base, &cand, 5.0);
        let mut buf = Vec::new();
        diff_to_json(&d, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("\"has_regression\":true"));
        assert!(out.contains("\"stages\":["));
        assert!(out.contains("\"metric\":\"p99\""));
        assert!(out.contains("\"delta_pct\""));
    }

    #[test]
    fn print_summary_produces_aligned_table() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&FixedSubMsRecipe, &p);
        let s = summarize_lean(&h);
        let mut buf = Vec::new();
        print_summary(&s, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("stage"));
        assert!(out.contains("p99"));
        assert!(out.contains("step"));
    }

    // ------------------------------------------------------------
    // 0.5.0 additions: summarize_windowed, cdf_buckets_ns/jitter_score
    // JSON round-trip
    // ------------------------------------------------------------

    /// Recipe that records 100 samples into one stage so summarize_windowed
    /// has enough data for multiple buckets.
    struct ManySamplesRecipe;
    impl SubMsRecipe for ManySamplesRecipe {
        fn name(&self) -> &str {
            "many-samples"
        }
        fn run(&self, h: &mut SubMsPerfHarness, _params: &SubMsBenchParams) {
            let s = h.stage("op", 100);
            for i in 0..100 {
                // Linearly increasing values - first window will have lower
                // p99 than later windows, so summarize_windowed should
                // show monotonic non-decreasing p99 across windows.
                s.record((i + 1) * 100);
            }
        }
    }

    #[test]
    fn summarize_windowed_splits_into_correct_number_of_buckets() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&ManySamplesRecipe, &p);
        let windows = summarize_windowed(&h, 20);
        // 100 samples / 20-per-window = 5 windows
        assert_eq!(windows.len(), 5);
        // Each window records the bucket index in inputs.
        for (i, w) in windows.iter().enumerate() {
            assert_eq!(
                w.inputs.get("__window_index").map(String::as_str),
                Some(i.to_string().as_str())
            );
            assert_eq!(
                w.inputs.get("__window_size").map(String::as_str),
                Some("20")
            );
        }
    }

    #[test]
    fn summarize_windowed_p99_monotonic_for_monotonic_input() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&ManySamplesRecipe, &p);
        let windows = summarize_windowed(&h, 25);
        let p99s: Vec<u64> = windows.iter().map(|w| w.stages[0].p99_ns).collect();
        // Monotonic non-decreasing p99 since the recipe records
        // i*100 increasing values across the run.
        for pair in p99s.windows(2) {
            assert!(
                pair[1] >= pair[0],
                "p99 not monotonic: {} -> {}",
                pair[0],
                pair[1]
            );
        }
    }

    #[test]
    fn summarize_windowed_empty_harness_returns_empty_vec() {
        // A harness with no stages.
        let h = SubMsPerfHarness::new("empty", "rust");
        let windows = summarize_windowed(&h, 10);
        assert!(windows.is_empty());
    }

    #[test]
    fn summarize_windowed_zero_window_treated_as_one() {
        let p = SubMsBenchParams::default();
        let h = run_bench(&ManySamplesRecipe, &p);
        // Window size 0 should be normalised to 1; expect 100 windows.
        let windows = summarize_windowed(&h, 0);
        assert_eq!(windows.len(), 100);
    }

    #[test]
    fn summary_to_json_emits_cdf_buckets_ns_field() {
        let p = SubMsBenchParams::default();
        let s = summarize(&run_bench(&FixedSubMsRecipe, &p));
        let mut buf = Vec::new();
        summary_to_json(&s, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            out.contains("\"cdf_buckets_ns\":["),
            "summary JSON must include cdf_buckets_ns: {}",
            out
        );
    }

    #[test]
    fn summary_to_json_emits_jitter_score_field() {
        let p = SubMsBenchParams::default();
        let s = summarize(&run_bench(&FixedSubMsRecipe, &p));
        let mut buf = Vec::new();
        summary_to_json(&s, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            out.contains("\"jitter_score\":"),
            "summary JSON must include jitter_score: {}",
            out
        );
    }

    #[test]
    fn summary_to_json_emits_stddev_ns_field() {
        let p = SubMsBenchParams::default();
        let s = summarize(&run_bench(&FixedSubMsRecipe, &p));
        let mut buf = Vec::new();
        summary_to_json(&s, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(
            out.contains("\"stddev_ns\":"),
            "summary JSON must include stddev_ns: {}",
            out
        );
    }

    #[test]
    fn summarize_populates_cdf_buckets_64_long() {
        let p = SubMsBenchParams::default();
        let s = summarize(&run_bench(&FixedSubMsRecipe, &p));
        assert_eq!(s.stages[0].cdf_buckets_ns.len(), 64);
        // Total bucket count should equal the sample count.
        let total: u64 = s.stages[0].cdf_buckets_ns.iter().sum();
        assert_eq!(total as usize, s.stages[0].count);
    }

    #[test]
    fn summarize_populates_jitter_score_in_unit_interval() {
        let p = SubMsBenchParams::default();
        let s = summarize(&run_bench(&FixedSubMsRecipe, &p));
        let jit = s.stages[0].jitter_score;
        assert!(
            (0.0..=1.0).contains(&jit),
            "jitter_score out of [0, 1]: {}",
            jit
        );
    }
}