goose 0.19.1

A load testing framework inspired by Locust.
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
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
//! Compact dashboard snapshot DTO and pure builder.
//!
//! Always compiled (no axum dependency). Used by `MetricsCommand::GetDashboardSnapshot`
//! and later by the HTTP dashboard server.

use super::{
    per_second_calculations, GooseErrorMetricAggregate, GooseMetrics, GooseRequestMetricAggregate,
    GooseRequestMetricTimingData, GooseTransactionErrorMetricAggregate, ScenarioMetricAggregate,
    TransactionMetricAggregate,
};
use chrono::prelude::*;
use serde::Serialize;
use std::collections::HashSet;

/// Maximum per-request rows included in a snapshot table.
pub(crate) const MAX_REQUEST_ROWS: usize = 100;
/// Maximum error rows included in a snapshot table.
pub(crate) const MAX_ERROR_ROWS: usize = 50;
/// Default trailing series window length in seconds (5 minutes).
///
/// Consumed by the dashboard HTTP server when issuing GetDashboardSnapshot.
#[cfg_attr(not(feature = "dashboard"), allow(dead_code))]
pub(crate) const SERIES_WINDOW_SECS: u32 = 300;

/// Wire format version of [`DashboardSnapshot`]. The dashboard client refuses a
/// snapshot with any other version; bump it on a breaking change to the shape.
pub(crate) const SNAPSHOT_VERSION: u32 = 1;

/// Wire format versioned so UI and server can evolve independently.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct DashboardSnapshot {
    pub version: u32,
    pub generated_at: DateTime<Utc>,
    pub goose_version: String,

    pub phase: String,
    /// True while a cancel (Stop, `shutdown`, Ctrl-C) ramps the run down,
    /// until it reaches idle. A test plan's own ramp down leaves it false, so
    /// clients can tell the two `decrease` phases apart.
    pub stopping: bool,
    pub duration_secs: u64,
    /// Users currently running (main-loop active count).
    pub active_users: u64,
    /// Peak concurrent users observed during this run (high-water mark).
    pub maximum_users: u64,
    /// Current test-plan step target — users the attack is increasing or
    /// decreasing toward (not the historical peak).
    pub target_users: u64,
    pub total_users: u64,
    pub hosts: Vec<String>,

    pub aggregate: AggregateMetrics,
    pub requests: Vec<RequestRow>,
    pub errors: Vec<ErrorRow>,
    /// The errors transactions returned, most frequent first, capped at
    /// [`MAX_ERROR_ROWS`].
    pub transaction_errors: Vec<TransactionErrorRow>,
    /// One row per registered scenario, in registration order. Never truncated.
    pub scenarios: Vec<ScenarioRow>,
    /// One row per registered transaction, grouped by scenario, each group in
    /// registration order. Never truncated.
    pub transactions: Vec<TransactionRow>,
    pub series: SeriesWindow,

    pub flags: SnapshotFlags,
    /// The report the run writes: Save report, its folder and paths.
    pub report: SnapshotReport,
    /// The run settings: what the next Start runs, and where the running
    /// test is.
    pub settings: SnapshotSettings,
    /// Time the metrics processor spent draining metrics and building this
    /// snapshot, reported as `last_build_ms` on `/api/v1/health`. Zero when
    /// not built by the processor. Not part of the JSON.
    #[serde(skip)]
    pub build_time: std::time::Duration,
}

/// The report the run writes, as the dashboard's report bar shows it.
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct SnapshotReport {
    /// Save report: write the run's `report.json` and `report.html` into its
    /// folder.
    pub save: bool,
    /// Include graph data: the JSON report holds the per second graph data.
    pub graph_data: bool,
    /// The current or last run's folder, as given, never made absolute;
    /// `null` before the first run, and for a run that has none.
    pub folder: Option<String>,
    /// The `--report-file` paths, which are always written.
    pub paths: Vec<String>,
    /// The run's `--notes`.
    pub notes: Option<String>,
    /// The folder of the last report written into a run's folder at the end
    /// of a run.
    pub last_report: Option<String>,
    /// The name the report routes take for `last_report`; `null` when they
    /// take none, as for a name with a space.
    pub last_report_name: Option<String>,
    /// Why the last report Goose tried to write into the run's folder
    /// failed, or why the run has no folder.
    pub error: Option<String>,
    /// How many reports Goose has written into a run's folder since the
    /// process started, at the end of a run or by Save report now.
    pub writes: u64,
}

/// The run settings, as the dashboard shows them: what the next Start runs,
/// plus where the running test is in its hold. Names are the command line's
/// flags in snake case, durations whole seconds with a `_secs` suffix, and
/// `null` means unset, so Goose's default applies.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct SnapshotSettings {
    /// The `--host` override, or `null`.
    pub host: Option<String>,
    /// The hosts the next Start will load test, one per scenario from
    /// `--host`, else the scenario's host, else the default host, in the
    /// same form, sorted and deduplicated, as the top level `hosts` (which
    /// keeps meaning the current or last run's). A scenario with no host
    /// from any source adds nothing.
    pub hosts: Vec<String>,
    /// The configured user count, `null` only with a test plan. Not
    /// `target_users`, the count the current step ramps toward.
    pub users: Option<u64>,
    pub increase_rate: Option<f64>,
    pub increase_time_secs: Option<u64>,
    pub decrease_rate: Option<f64>,
    pub decrease_time_secs: Option<u64>,
    /// The hold at full users after the ramp up, not the total run time.
    pub run_time_secs: Option<u64>,
    /// The test plan as `--test-plan` takes it, in canonical form: each
    /// step's duration in whole seconds.
    pub test_plan: Option<String>,
    /// Seconds until the hold ends once it has a fixed end, 0 while a ramp
    /// runs past it. `null` in Idle, during the first ramp up, once the
    /// ramp down starts, with no run time, and with a test plan.
    pub hold_ends_in_secs: Option<u64>,
    /// Where the run is: `idle`, `ramp_up`, `hold`, `hold_until_stopped`,
    /// `ramping_down` or `stopping` for a users ramp; `idle`, `test_plan` or
    /// `stopping` for a test plan.
    #[cfg_attr(
        test,
        ts(
            type = "\"idle\" | \"ramp_up\" | \"hold\" | \"hold_until_stopped\" | \"ramping_down\" | \"test_plan\" | \"stopping\""
        )
    )]
    pub stage: String,
}

impl SnapshotSettings {
    /// No settings and an idle stage, for a snapshot built in a test.
    #[cfg(test)]
    pub(crate) fn idle() -> Self {
        SnapshotSettings {
            host: None,
            hosts: Vec::new(),
            users: None,
            increase_rate: None,
            increase_time_secs: None,
            decrease_rate: None,
            decrease_time_secs: None,
            run_time_secs: None,
            test_plan: None,
            hold_ends_in_secs: None,
            stage: "idle".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct AggregateMetrics {
    pub total_requests: u64,
    pub total_failures: u64,
    pub requests_per_second: f64,
    pub failures_per_second: f64,
    pub failure_rate: f64,
    pub response_time_avg_ms: f64,
    pub response_time_min_ms: u64,
    pub response_time_max_ms: u64,
    pub percentile_ms: Percentiles,
    /// The same times to the microsecond, null without times.
    pub response_time_us: Option<MicrosecondTimes>,
    /// True iff coordinated-omission metrics object is present AND has recorded
    /// at least one CO event (or synthetic request).
    pub co_active: bool,
    pub co_adjusted: Option<CoAdjusted>,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct RequestRow {
    pub method: String,
    pub name: String,
    pub request_count: u64,
    pub failure_count: u64,
    pub requests_per_second: f64,
    pub failures_per_second: f64,
    pub response_time_avg_ms: f64,
    pub response_time_min_ms: u64,
    pub response_time_max_ms: u64,
    pub percentile_ms: Percentiles,
    /// The same times to the microsecond, null without times.
    pub response_time_us: Option<MicrosecondTimes>,
    pub status_codes: Vec<(u16, u64)>,
    pub co_adjusted: Option<CoAdjusted>,
    /// True when the response time heatmap can show this request alone:
    /// they are kept for the first 100 request names seen since metrics were
    /// last reset.
    pub has_series: bool,
}

/// Metrics for one registered scenario.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct ScenarioRow {
    /// Goose's own scenario index, counted from 0 in registration order. The
    /// dashboard shows it counted from 1.
    pub scenario_index: u64,
    pub scenario_name: String,
    /// Distinct users that ran this scenario since the last metrics reset,
    /// whether or not they finished a run; not only the users running it now.
    pub users: u64,
    /// Completed passes through the scenario's weighted transactions.
    pub run_count: u64,
    pub runs_per_second: f64,
    pub response_time_avg_ms: f64,
    pub response_time_min_ms: u64,
    pub response_time_max_ms: u64,
    pub percentile_ms: Percentiles,
    /// The same times to the microsecond, all 0 without times.
    pub response_time_us: MicrosecondTimes,
}

/// Metrics for one registered transaction.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct TransactionRow {
    /// Goose's own scenario index, counted from 0 in registration order. The
    /// dashboard shows it counted from 1.
    pub scenario_index: u64,
    pub scenario_name: String,
    /// Goose's own transaction index within its scenario, counted from 0 in
    /// registration order. The dashboard shows it counted from 1.
    pub transaction_index: u64,
    /// Empty when the transaction has no name.
    pub transaction_name: String,
    /// Successful plus failed runs.
    pub run_count: u64,
    pub failure_count: u64,
    pub runs_per_second: f64,
    pub failures_per_second: f64,
    pub response_time_avg_ms: f64,
    pub response_time_min_ms: u64,
    pub response_time_max_ms: u64,
    pub percentile_ms: Percentiles,
    /// The same times to the microsecond, all 0 without times.
    pub response_time_us: MicrosecondTimes,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct ErrorRow {
    pub method: String,
    pub name: String,
    pub error: String,
    pub occurrences: u64,
}

/// One row of the transaction errors table: a transaction and an error it
/// returned.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct TransactionErrorRow {
    /// The transaction's number, `scenario.transaction` counted from 1.
    pub transaction: String,
    pub scenario: String,
    /// The transaction's name, empty when it has none.
    pub name: String,
    pub error: String,
    pub occurrences: u64,
}

/// Trailing per-second aggregate series for dashboard charts.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct SeriesWindow {
    /// First exported bucket index in seconds-from-test-start.
    pub start_second: u64,
    pub rps: Vec<f64>,
    pub fps: Vec<f64>,
    pub users: Vec<u64>,
    pub avg_latency_ms: Vec<f64>,
    /// Response times of all requests by second, for the dashboard's
    /// heatmap. Null when percentiles over time are off.
    pub heatmap: Option<Heatmap>,
}

impl SeriesWindow {
    /// Empty window (no series data recorded yet).
    pub(crate) fn empty() -> Self {
        SeriesWindow {
            start_second: 0,
            rps: Vec::new(),
            fps: Vec::new(),
            users: Vec::new(),
            avg_latency_ms: Vec::new(),
            heatmap: None,
        }
    }
}

/// Response times by second over the trailing window, as counts in Goose's response time buckets. Only the columns that changed since the client's last heatmap are sent: apply them to the columns kept from earlier ones. `since` 0 means every column of the window is here; otherwise a client holding `since` of this `generation` applies the columns, and any other client asks again with its own `heatmap_generation` and `heatmap_since`.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct Heatmap {
    /// Which set of histograms the columns come from. It changes when they
    /// are cleared (metrics reset, or a new test), so a client starts over.
    pub generation: u64,
    /// The newest change these columns include. Send it back as
    /// `heatmap_since` with `heatmap_generation` to get only later changes.
    pub rev: u64,
    /// The `rev` these columns follow on from, or 0 for a whole window.
    pub since: u64,
    /// First second of the window, in seconds from the test start. Columns
    /// before it are dropped.
    pub start_second: u64,
    /// Last second of the window.
    pub end_second: u64,
    /// Seconds from this one on may still be missing their slowest requests,
    /// so they are not drawn yet.
    pub hold_from: u64,
    /// Each row by index, as `[time, lowest, highest]` in microseconds:
    /// the time the row stands for, which is its middle, then the first and
    /// last microsecond the row holds. A longer table replaces a shorter
    /// one; entries never change.
    pub buckets_us: Vec<[u64; 3]>,
    /// The columns that changed, oldest first.
    pub columns: Vec<HeatmapColumn>,
}

/// One second of the heatmap. Bucket counts are flattened pairs, `[index, count, index, count, ...]`, by ascending index, empty buckets left out.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct HeatmapColumn {
    /// The second, from the test start.
    pub second: u64,
    /// Measured response times.
    pub measured: Vec<u64>,
    /// Synthetic times coordinated omission mitigation added to this second.
    /// Empty unless mitigation is on and has recorded an event.
    pub synthetic: Vec<u64>,
}

#[cfg(test)]
impl Heatmap {
    /// The column for `second`, if this heatmap has one.
    pub(crate) fn column(&self, second: u64) -> Option<&HeatmapColumn> {
        self.columns.iter().find(|column| column.second == second)
    }

    /// Requests counted in `second`: measured, then synthetic.
    pub(crate) fn counts(&self, second: u64) -> (u64, u64) {
        self.column(second).map_or((0, 0), |column| {
            (
                HeatmapColumn::total(&column.measured),
                HeatmapColumn::total(&column.synthetic),
            )
        })
    }
}

#[cfg(test)]
impl HeatmapColumn {
    /// The `(index, count)` pairs of flattened bucket counts.
    pub(crate) fn pairs(cells: &[u64]) -> Vec<(u64, u64)> {
        cells.chunks(2).map(|pair| (pair[0], pair[1])).collect()
    }

    /// The sum of flattened bucket counts.
    pub(crate) fn total(cells: &[u64]) -> u64 {
        cells.chunks(2).map(|pair| pair[1]).sum()
    }
}

/// What a client holds of a heatmap: its `generation` and `rev`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct HeatmapCursor {
    pub generation: u64,
    pub rev: u64,
}

/// One request's response time heatmap, the body of `GET /api/v1/series`.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct RequestSeries {
    pub method: String,
    pub name: String,
    pub heatmap: Heatmap,
}

/// Response times including the synthetic times coordinated omission mitigation adds. Present only when mitigation has recorded at least one event.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct CoAdjusted {
    pub response_time_avg_ms: f64,
    pub response_time_max_ms: u64,
    pub percentile_ms: Percentiles,
    /// The same times to the microsecond, null without times.
    pub response_time_us: Option<MicrosecondTimes>,
}

impl CoAdjusted {
    fn from_timing_data(data: &GooseRequestMetricTimingData) -> Self {
        let response_time_us = MicrosecondTimes::of(data);
        CoAdjusted {
            response_time_avg_ms: data.average_ms_or_zero(),
            response_time_max_ms: data.maximum_time_ms() as u64,
            percentile_ms: Percentiles::of(response_time_us.as_ref()),
            response_time_us,
        }
    }
}

/// Response times in microseconds, beside the whole milliseconds of the same
/// row: its fastest, slowest and percentiles.
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct MicrosecondTimes {
    pub min: u64,
    pub max: u64,
    pub p50: u64,
    pub p95: u64,
    pub p99: u64,
}

impl MicrosecondTimes {
    /// `data`'s times in microseconds, `None` without times.
    fn of(data: &GooseRequestMetricTimingData) -> Option<Self> {
        (data.counter > 0).then(|| MicrosecondTimes {
            min: data.minimum_time_us,
            max: data.maximum_time_us,
            p50: data.percentile_us(0.5),
            p95: data.percentile_us(0.95),
            p99: data.percentile_us(0.99),
        })
    }
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct Percentiles {
    pub p50: u64,
    pub p95: u64,
    pub p99: u64,
}

impl Percentiles {
    fn zero() -> Self {
        Percentiles {
            p50: 0,
            p95: 0,
            p99: 0,
        }
    }

    /// The percentiles of `times` in whole milliseconds, truncated; 0
    /// without times.
    fn of(times: Option<&MicrosecondTimes>) -> Self {
        match times {
            Some(times) => Percentiles {
                p50: times.p50 / 1000,
                p95: times.p95 / 1000,
                p99: times.p99 / 1000,
            },
            None => Self::zero(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(test, derive(ts_rs::TS))]
pub(crate) struct SnapshotFlags {
    pub metrics_disabled: bool,
    /// True under `--no-transaction-metrics`, and under `--no-metrics` too;
    /// `transactions` is then empty.
    pub transaction_metrics_disabled: bool,
    /// True under `--no-scenario-metrics`, and under `--no-metrics` too;
    /// `scenarios` is then empty.
    pub scenario_metrics_disabled: bool,
    pub requests_truncated: bool,
    pub errors_truncated: bool,
    pub transaction_errors_truncated: bool,
    pub series_seconds: u32,
    /// True when the dashboard tracks response times by second for its
    /// heatmap: on with `--dashboard` unless `--no-percentiles-over-time` or
    /// `--no-metrics`.
    pub percentiles_over_time: bool,
}

/// Inputs supplied by the metrics processor / main loop when building a snapshot.
pub(crate) struct DashboardSnapshotInput<'a> {
    pub metrics: &'a GooseMetrics,
    pub series: SeriesWindow,
    pub active_users: usize,
    pub maximum_users: usize,
    /// Current plan-step / configured target (see [`DashboardSnapshot::target_users`]).
    pub target_users: usize,
    pub total_users: usize,
    pub phase: String,
    /// See [`DashboardSnapshot::stopping`].
    pub stopping: bool,
    pub series_window_secs: u32,
    pub no_status_codes: bool,
    pub metrics_disabled: bool,
    /// `--no-transaction-metrics`.
    pub no_transaction_metrics: bool,
    /// `--no-scenario-metrics`.
    pub no_scenario_metrics: bool,
    /// See [`DashboardSnapshot::report`].
    pub report: SnapshotReport,
    /// See [`DashboardSnapshot::settings`].
    pub settings: SnapshotSettings,
    /// See [`SnapshotFlags::percentiles_over_time`].
    pub percentiles_over_time: bool,
    /// Keys (`"METHOD name"`) of the requests that have their own latency
    /// series; see [`RequestRow::has_series`].
    pub series_keys: HashSet<&'a str>,
}

/// Build a compact [`DashboardSnapshot`] from live metrics + series window.
pub(crate) fn build_dashboard_snapshot(input: DashboardSnapshotInput<'_>) -> DashboardSnapshot {
    // With `--no-metrics`, document an honest empty state: no tables, no series,
    // and no truncation flags. Runtime still reports phase/user counts.
    if input.metrics_disabled {
        let mut hosts: Vec<String> = input.metrics.hosts.iter().cloned().collect();
        hosts.sort();
        return DashboardSnapshot {
            version: SNAPSHOT_VERSION,
            generated_at: Utc::now(),
            goose_version: env!("CARGO_PKG_VERSION").to_string(),
            phase: input.phase,
            stopping: input.stopping,
            duration_secs: input.metrics.duration as u64,
            active_users: input.active_users as u64,
            maximum_users: input.maximum_users as u64,
            target_users: input.target_users as u64,
            total_users: input.total_users as u64,
            hosts,
            aggregate: AggregateMetrics {
                total_requests: 0,
                total_failures: 0,
                requests_per_second: 0.0,
                failures_per_second: 0.0,
                failure_rate: 0.0,
                response_time_avg_ms: 0.0,
                response_time_min_ms: 0,
                response_time_max_ms: 0,
                percentile_ms: Percentiles::zero(),
                response_time_us: None,
                co_active: false,
                co_adjusted: None,
            },
            requests: Vec::new(),
            errors: Vec::new(),
            transaction_errors: Vec::new(),
            scenarios: Vec::new(),
            transactions: Vec::new(),
            series: SeriesWindow::empty(),
            flags: SnapshotFlags {
                metrics_disabled: true,
                transaction_metrics_disabled: true,
                scenario_metrics_disabled: true,
                requests_truncated: false,
                errors_truncated: false,
                transaction_errors_truncated: false,
                series_seconds: input.series_window_secs,
                percentiles_over_time: false,
            },
            report: input.report,
            settings: input.settings,
            build_time: std::time::Duration::ZERO,
        };
    }

    let duration = input.metrics.duration;

    let mut aggregate_total_count: usize = 0;
    let mut aggregate_fail_count: usize = 0;
    // Every request's measured times together.
    let mut aggregate = GooseRequestMetricTimingData::new(None);

    let co_active = input
        .metrics
        .coordinated_omission_metrics
        .as_ref()
        .map(|m| m.has_events())
        .unwrap_or(false);
    // Adjusted times across every request, built only while mitigation has
    // events. A request without adjusted data contributes its measured times,
    // which for it are the same thing, as in the console and the reports.
    let mut co_aggregate: Option<GooseRequestMetricTimingData> =
        co_active.then(|| GooseRequestMetricTimingData::new(None));

    // Rank by count first; only materialize full table rows for the top N so
    // high request-name cardinality does not pay percentile/status work ~1 Hz
    // for rows the UI never shows.
    let mut request_rank: Vec<(&str, &GooseRequestMetricAggregate, usize)> =
        Vec::with_capacity(input.metrics.requests.len());
    for (key, request) in &input.metrics.requests {
        let total_count = request.success_count + request.fail_count;
        aggregate_total_count += total_count;
        aggregate_fail_count += request.fail_count;
        aggregate.merge(&request.raw_data);
        if let Some(co_aggregate) = co_aggregate.as_mut() {
            co_aggregate.merge(
                request
                    .coordinated_omission_data
                    .as_ref()
                    .unwrap_or(&request.raw_data),
            );
        }
        request_rank.push((key.as_str(), request, total_count));
    }

    request_rank.sort_by(|(_, a, a_count), (_, b, b_count)| {
        b_count
            .cmp(a_count)
            .then_with(|| a.method_label().cmp(b.method_label()))
            .then_with(|| a.path.cmp(&b.path))
    });
    let requests_truncated = request_rank.len() > MAX_REQUEST_ROWS;
    request_rank.truncate(MAX_REQUEST_ROWS);
    let request_rows: Vec<RequestRow> = request_rank
        .into_iter()
        .map(|(key, request, _)| {
            request_row_from_aggregate(
                request,
                duration,
                input.no_status_codes,
                co_active,
                input.series_keys.contains(key),
            )
        })
        .collect();

    let mut error_rank: Vec<&GooseErrorMetricAggregate> = input.metrics.errors.values().collect();
    error_rank.sort_by(|a, b| {
        b.occurrences
            .cmp(&a.occurrences)
            .then_with(|| a.method_label().cmp(b.method_label()))
            .then_with(|| a.name.cmp(&b.name))
            .then_with(|| a.error.cmp(&b.error))
    });
    let errors_truncated = error_rank.len() > MAX_ERROR_ROWS;
    error_rank.truncate(MAX_ERROR_ROWS);
    let error_rows: Vec<ErrorRow> = error_rank
        .into_iter()
        .map(error_row_from_aggregate)
        .collect();

    let mut transaction_error_rank: Vec<&GooseTransactionErrorMetricAggregate> =
        input.metrics.transaction_errors.values().collect();
    transaction_error_rank.sort_by(|a, b| {
        b.occurrences
            .cmp(&a.occurrences)
            .then_with(|| a.scenario_index.cmp(&b.scenario_index))
            .then_with(|| a.transaction_index.cmp(&b.transaction_index))
            .then_with(|| a.error.cmp(&b.error))
    });
    let transaction_errors_truncated = transaction_error_rank.len() > MAX_ERROR_ROWS;
    transaction_error_rank.truncate(MAX_ERROR_ROWS);
    let transaction_error_rows: Vec<TransactionErrorRow> = transaction_error_rank
        .into_iter()
        .map(|error| TransactionErrorRow {
            transaction: error.transaction_number(),
            scenario: error.scenario_name.clone(),
            name: error.transaction_name.clone(),
            error: error.error.clone(),
            occurrences: error.occurrences as u64,
        })
        .collect();

    // Every registered scenario and transaction gets a row: their number is
    // fixed by the load test's code, so there is no cap.
    let scenario_rows: Vec<ScenarioRow> = if input.no_scenario_metrics {
        Vec::new()
    } else {
        input
            .metrics
            .scenarios
            .iter()
            .map(|scenario| scenario_row_from_aggregate(scenario, duration))
            .collect()
    };
    let transaction_rows: Vec<TransactionRow> = if input.no_transaction_metrics {
        Vec::new()
    } else {
        input
            .metrics
            .transactions
            .iter()
            .flatten()
            .map(|transaction| transaction_row_from_aggregate(transaction, duration))
            .collect()
    };

    let (rps, fps) = per_second_calculations(duration, aggregate_total_count, aggregate_fail_count);
    let failure_rate = if aggregate_total_count > 0 {
        aggregate_fail_count as f64 / aggregate_total_count as f64
    } else {
        0.0
    };
    let response_time_avg_ms = aggregate.average_ms_or_zero();
    let response_time_us = MicrosecondTimes::of(&aggregate);

    let mut hosts: Vec<String> = input.metrics.hosts.iter().cloned().collect();
    hosts.sort();

    DashboardSnapshot {
        version: SNAPSHOT_VERSION,
        generated_at: Utc::now(),
        goose_version: env!("CARGO_PKG_VERSION").to_string(),
        phase: input.phase,
        stopping: input.stopping,
        duration_secs: duration as u64,
        active_users: input.active_users as u64,
        maximum_users: input.maximum_users as u64,
        target_users: input.target_users as u64,
        total_users: input.total_users as u64,
        hosts,
        aggregate: AggregateMetrics {
            total_requests: aggregate_total_count as u64,
            total_failures: aggregate_fail_count as u64,
            requests_per_second: rps as f64,
            failures_per_second: fps as f64,
            failure_rate,
            response_time_avg_ms,
            response_time_min_ms: aggregate.minimum_time_ms() as u64,
            response_time_max_ms: aggregate.maximum_time_ms() as u64,
            percentile_ms: Percentiles::of(response_time_us.as_ref()),
            response_time_us,
            co_active,
            co_adjusted: co_aggregate.as_ref().map(CoAdjusted::from_timing_data),
        },
        requests: request_rows,
        errors: error_rows,
        transaction_errors: transaction_error_rows,
        scenarios: scenario_rows,
        transactions: transaction_rows,
        series: input.series,
        flags: SnapshotFlags {
            metrics_disabled: false,
            transaction_metrics_disabled: input.no_transaction_metrics,
            scenario_metrics_disabled: input.no_scenario_metrics,
            requests_truncated,
            errors_truncated,
            transaction_errors_truncated,
            series_seconds: input.series_window_secs,
            percentiles_over_time: input.percentiles_over_time,
        },
        report: input.report,
        settings: input.settings,
        build_time: std::time::Duration::ZERO,
    }
}

fn request_row_from_aggregate(
    request: &GooseRequestMetricAggregate,
    duration: usize,
    no_status_codes: bool,
    co_active: bool,
    has_series: bool,
) -> RequestRow {
    let total_count = request.success_count + request.fail_count;
    let (rps, fps) = per_second_calculations(duration, total_count, request.fail_count);
    let avg = request.raw_data.average_ms_or_zero();
    let response_time_us = MicrosecondTimes::of(&request.raw_data);
    let status_codes = if no_status_codes {
        Vec::new()
    } else {
        let mut codes: Vec<(u16, u64)> = request
            .status_code_counts
            .iter()
            .map(|(&code, &count)| (code, count as u64))
            .collect();
        codes.sort_by_key(|(code, _)| *code);
        codes
    };

    RequestRow {
        method: request.method_label().to_string(),
        name: request.path.clone(),
        request_count: total_count as u64,
        failure_count: request.fail_count as u64,
        requests_per_second: rps as f64,
        failures_per_second: fps as f64,
        response_time_avg_ms: avg,
        response_time_min_ms: request.raw_data.minimum_time_ms() as u64,
        response_time_max_ms: request.raw_data.maximum_time_ms() as u64,
        percentile_ms: Percentiles::of(response_time_us.as_ref()),
        response_time_us,
        status_codes,
        co_adjusted: if co_active {
            request
                .coordinated_omission_data
                .as_ref()
                .map(CoAdjusted::from_timing_data)
        } else {
            None
        },
        has_series,
    }
}

fn scenario_row_from_aggregate(scenario: &ScenarioMetricAggregate, duration: usize) -> ScenarioRow {
    let times = &scenario.run_times;
    let (runs_per_second, _) = per_second_calculations(duration, times.counter, 0);
    let response_time_us = MicrosecondTimes::of(times);
    ScenarioRow {
        scenario_index: scenario.index as u64,
        scenario_name: scenario.name.to_string(),
        users: scenario.users.len() as u64,
        run_count: times.counter as u64,
        runs_per_second: runs_per_second as f64,
        response_time_avg_ms: times.average_ms_or_zero(),
        response_time_min_ms: times.minimum_time_ms() as u64,
        response_time_max_ms: times.maximum_time_ms() as u64,
        percentile_ms: Percentiles::of(response_time_us.as_ref()),
        response_time_us: response_time_us.unwrap_or_default(),
    }
}

fn transaction_row_from_aggregate(
    transaction: &TransactionMetricAggregate,
    duration: usize,
) -> TransactionRow {
    let run_count = transaction.success_count + transaction.fail_count;
    let (runs_per_second, failures_per_second) =
        per_second_calculations(duration, run_count, transaction.fail_count);
    let response_time_us = MicrosecondTimes::of(&transaction.run_times);
    TransactionRow {
        scenario_index: transaction.scenario_index as u64,
        scenario_name: transaction.scenario_name.to_string(),
        transaction_index: transaction.transaction_index as u64,
        transaction_name: transaction
            .transaction_name
            .name_for_transaction()
            .to_string(),
        run_count: run_count as u64,
        failure_count: transaction.fail_count as u64,
        runs_per_second: runs_per_second as f64,
        failures_per_second: failures_per_second as f64,
        response_time_avg_ms: transaction.run_times.average_ms_or_zero(),
        response_time_min_ms: transaction.run_times.minimum_time_ms() as u64,
        response_time_max_ms: transaction.run_times.maximum_time_ms() as u64,
        percentile_ms: Percentiles::of(response_time_us.as_ref()),
        response_time_us: response_time_us.unwrap_or_default(),
    }
}

fn error_row_from_aggregate(error: &GooseErrorMetricAggregate) -> ErrorRow {
    ErrorRow {
        method: error.method_label().to_string(),
        name: error.name.clone(),
        error: error.error.clone(),
        occurrences: error.occurrences as u64,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::goose::{GooseMethod, TransactionName};
    use crate::metrics::coordinated_omission::CoordinatedOmissionMetrics;
    use crate::metrics::GooseCoordinatedOmissionMitigation;
    use crate::metrics::GooseRequestMetricAggregate;
    use std::sync::Arc;
    use std::time::Duration;

    fn empty_metrics() -> GooseMetrics {
        GooseMetrics::default()
    }

    fn make_request(
        path: &str,
        successes: usize,
        failures: usize,
        times: &[(usize, usize)],
    ) -> GooseRequestMetricAggregate {
        let mut agg = GooseRequestMetricAggregate::new(path, GooseMethod::Get, 0, "");
        agg.success_count = successes;
        agg.fail_count = failures;
        for &(time, count) in times {
            for _ in 0..count {
                agg.raw_data.record_time(time as u64);
            }
        }
        agg
    }

    #[test]
    fn builder_empty_metrics() {
        let metrics = empty_metrics();
        let snap = build_dashboard_snapshot(DashboardSnapshotInput {
            metrics: &metrics,
            series: SeriesWindow::empty(),
            active_users: 0,
            maximum_users: 10,
            target_users: 10,
            total_users: 10,
            phase: "idle".to_string(),
            stopping: false,
            series_window_secs: SERIES_WINDOW_SECS,
            no_status_codes: false,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        });
        assert_eq!(snap.version, 1);
        assert_eq!(snap.phase, "idle");
        assert_eq!(snap.maximum_users, 10);
        assert_eq!(snap.target_users, 10);
        assert_eq!(snap.aggregate.total_requests, 0);
        assert!(!snap.aggregate.co_active);
        assert!(snap.requests.is_empty());
        assert!(snap.errors.is_empty());
        assert!(!snap.flags.requests_truncated);
        assert!(!snap.flags.errors_truncated);
        assert_eq!(snap.flags.series_seconds, SERIES_WINDOW_SECS);
    }

    #[test]
    fn builder_caps_request_and_error_rows() {
        let mut metrics = empty_metrics();
        metrics.duration = 10;
        for i in 0..(MAX_REQUEST_ROWS + 25) {
            let path = format!("/path-{i}");
            // Higher index → more requests so sort order is deterministic.
            let count = i + 1;
            metrics.requests.insert(
                format!("GET {path}"),
                make_request(&path, count, 0, &[(10, count)]),
            );
        }
        for i in 0..(MAX_ERROR_ROWS + 10) {
            let key = format!("err-{i}");
            let mut err = GooseErrorMetricAggregate::new(
                GooseMethod::Get,
                format!("/e{i}"),
                format!("error {i}"),
                "",
            );
            err.occurrences = i + 1;
            metrics.errors.insert(key, err);
        }

        let snap = build_dashboard_snapshot(DashboardSnapshotInput {
            metrics: &metrics,
            series: SeriesWindow::empty(),
            active_users: 5,
            maximum_users: 5,
            target_users: 5,
            total_users: 5,
            phase: "maintain".to_string(),
            stopping: false,
            series_window_secs: 60,
            no_status_codes: true,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        });

        assert_eq!(snap.requests.len(), MAX_REQUEST_ROWS);
        assert!(snap.flags.requests_truncated);
        // Top row should be the highest count.
        assert_eq!(
            snap.requests[0].request_count,
            (MAX_REQUEST_ROWS + 25) as u64
        );
        assert!(snap.requests[0].status_codes.is_empty());

        assert_eq!(snap.errors.len(), MAX_ERROR_ROWS);
        assert!(snap.flags.errors_truncated);
        assert_eq!(snap.errors[0].occurrences, (MAX_ERROR_ROWS + 10) as u64);
    }

    #[test]
    fn co_active_requires_events_not_just_enabled() {
        let mut metrics = empty_metrics();
        // Mitigation enabled but zero events → co_active false.
        metrics.coordinated_omission_metrics = Some(CoordinatedOmissionMetrics::new(
            GooseCoordinatedOmissionMitigation::Average,
        ));
        let snap = build_dashboard_snapshot(DashboardSnapshotInput {
            metrics: &metrics,
            series: SeriesWindow::empty(),
            active_users: 0,
            maximum_users: 0,
            target_users: 0,
            total_users: 0,
            phase: "maintain".to_string(),
            stopping: false,
            series_window_secs: 300,
            no_status_codes: false,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        });
        assert!(!snap.aggregate.co_active);

        // Record a CO event → co_active true.
        metrics
            .coordinated_omission_metrics
            .as_mut()
            .unwrap()
            .record_co_event(
                Duration::from_millis(100),
                Duration::from_millis(1000),
                5,
                0,
                "scenario".to_string(),
            );
        let snap = build_dashboard_snapshot(DashboardSnapshotInput {
            metrics: &metrics,
            series: SeriesWindow::empty(),
            active_users: 0,
            maximum_users: 0,
            target_users: 0,
            total_users: 0,
            phase: "maintain".to_string(),
            stopping: false,
            series_window_secs: 300,
            no_status_codes: false,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        });
        assert!(snap.aggregate.co_active);
    }

    fn co_input(metrics: &GooseMetrics) -> DashboardSnapshotInput<'_> {
        DashboardSnapshotInput {
            metrics,
            series: SeriesWindow::empty(),
            active_users: 0,
            maximum_users: 0,
            target_users: 0,
            total_users: 0,
            phase: "maintain".to_string(),
            stopping: false,
            series_window_secs: 300,
            no_status_codes: false,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        }
    }

    /// "/a" has 20 real times of 10 ms and 2 synthetic times of 5000 ms; "/b"
    /// has 10 real times of 20 ms and never needed backfill.
    fn add_co_requests(metrics: &mut GooseMetrics) {
        let mut a = GooseRequestMetricAggregate::new("/a", GooseMethod::Get, 0, "");
        a.success_count = 20;
        for _ in 0..20 {
            a.record_time(10, false);
        }
        a.record_time(5000, true);
        a.record_time(5000, true);
        metrics.requests.insert("GET /a".to_string(), a);
        metrics
            .requests
            .insert("GET /b".to_string(), make_request("/b", 10, 0, &[(20, 10)]));
    }

    fn record_one_co_event(metrics: &mut GooseMetrics) {
        metrics
            .coordinated_omission_metrics
            .as_mut()
            .unwrap()
            .record_co_event(
                Duration::from_millis(100),
                Duration::from_millis(1000),
                5,
                0,
                "scenario".to_string(),
            );
    }

    #[test]
    fn co_adjusted_carries_synthetic_times_and_percentile_ms_stays_measured() {
        let mut metrics = empty_metrics();
        metrics.coordinated_omission_metrics = Some(CoordinatedOmissionMetrics::new(
            GooseCoordinatedOmissionMitigation::Average,
        ));
        record_one_co_event(&mut metrics);
        add_co_requests(&mut metrics);
        let snap = build_dashboard_snapshot(co_input(&metrics));
        assert!(snap.aggregate.co_active);

        // Row "/a": adjusted includes the synthetic times, measured does not.
        let a = snap.requests.iter().find(|r| r.name == "/a").unwrap();
        assert_eq!(a.percentile_ms.p95, 10);
        assert_eq!(a.percentile_ms.p99, 10);
        assert_eq!(a.response_time_avg_ms, 10.0);
        assert_eq!(a.response_time_max_ms, 10);
        let a_co = a.co_adjusted.as_ref().expect("/a has adjusted data");
        assert_eq!(a_co.percentile_ms.p50, 10);
        assert_eq!(a_co.percentile_ms.p95, 5000);
        assert_eq!(a_co.percentile_ms.p99, 5000);
        assert_eq!(a_co.response_time_max_ms, 5000);
        assert!((a_co.response_time_avg_ms - 10_200.0 / 22.0).abs() < 1e-9);

        // Row "/b" never needed backfill, so it has no adjusted values.
        let b = snap.requests.iter().find(|r| r.name == "/b").unwrap();
        assert!(b.co_adjusted.is_none());

        // The aggregate: measured percentiles stay measured.
        assert_eq!(snap.aggregate.percentile_ms.p99, 20);
        assert_eq!(snap.aggregate.response_time_max_ms, 20);
        // Adjusted aggregate: "/a" adjusted times plus "/b" raw times (the
        // fallback), 32 times totalling 10400 ms.
        let agg_co = snap.aggregate.co_adjusted.as_ref().expect("adjusted");
        assert_eq!(agg_co.percentile_ms.p50, 10);
        assert_eq!(agg_co.percentile_ms.p95, 20);
        assert_eq!(agg_co.percentile_ms.p99, 5000);
        assert_eq!(agg_co.response_time_max_ms, 5000);
        assert!((agg_co.response_time_avg_ms - 10_400.0 / 32.0).abs() < 1e-9);
    }

    #[test]
    fn co_adjusted_absent_without_mitigation_events() {
        // Mitigation off.
        let mut metrics = empty_metrics();
        add_co_requests(&mut metrics);
        let snap = build_dashboard_snapshot(co_input(&metrics));
        assert!(snap.aggregate.co_adjusted.is_none());
        assert!(snap.requests.iter().all(|r| r.co_adjusted.is_none()));

        // Mitigation on, no events recorded.
        metrics.coordinated_omission_metrics = Some(CoordinatedOmissionMetrics::new(
            GooseCoordinatedOmissionMitigation::Average,
        ));
        let snap = build_dashboard_snapshot(co_input(&metrics));
        assert!(!snap.aggregate.co_active);
        assert!(snap.aggregate.co_adjusted.is_none());
        assert!(snap.requests.iter().all(|r| r.co_adjusted.is_none()));
    }

    #[test]
    fn builder_aggregates_request_counts_and_percentiles() {
        let mut metrics = empty_metrics();
        metrics.duration = 10;
        metrics
            .requests
            .insert("GET /a".to_string(), make_request("/a", 8, 2, &[(20, 10)]));
        metrics
            .requests
            .insert("GET /b".to_string(), make_request("/b", 5, 0, &[(40, 5)]));

        let snap = build_dashboard_snapshot(DashboardSnapshotInput {
            metrics: &metrics,
            series: SeriesWindow::empty(),
            active_users: 3,
            maximum_users: 10,
            target_users: 10,
            total_users: 10,
            phase: "increase".to_string(),
            stopping: false,
            series_window_secs: 300,
            no_status_codes: false,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        });

        assert_eq!(snap.aggregate.total_requests, 15);
        assert_eq!(snap.aggregate.total_failures, 2);
        assert!((snap.aggregate.requests_per_second - 1.5).abs() < 0.001);
        assert!((snap.aggregate.failure_rate - (2.0 / 15.0)).abs() < 0.0001);
        assert_eq!(snap.requests.len(), 2);
        assert_eq!(snap.requests[0].name, "/a");
        assert_eq!(snap.requests[0].request_count, 10);
        assert_eq!(snap.active_users, 3);
        assert_eq!(snap.target_users, 10);
        assert!(snap.aggregate.response_time_avg_ms > 0.0);
        assert!(snap.aggregate.percentile_ms.p50 > 0);
    }

    #[test]
    fn metrics_disabled_forces_empty_tables_and_series() {
        let mut metrics = empty_metrics();
        metrics.duration = 42;
        metrics.hosts.insert("https://example.com".to_string());
        metrics
            .requests
            .insert("GET /a".to_string(), make_request("/a", 8, 2, &[(20, 10)]));
        let mut err = GooseErrorMetricAggregate::new(
            GooseMethod::Get,
            "/a".to_string(),
            "boom".to_string(),
            "",
        );
        err.occurrences = 3;
        metrics.errors.insert("err".to_string(), err);
        add_scenario_metrics(&mut metrics);

        let series = SeriesWindow {
            start_second: 10,
            rps: vec![1.0, 2.0],
            fps: vec![0.0, 0.5],
            users: vec![1, 2],
            avg_latency_ms: vec![10.0, 20.0],
            heatmap: None,
        };

        let snap = build_dashboard_snapshot(DashboardSnapshotInput {
            metrics: &metrics,
            series,
            active_users: 7,
            maximum_users: 10,
            target_users: 10,
            total_users: 10,
            phase: "maintain".to_string(),
            stopping: true,
            series_window_secs: 120,
            no_status_codes: false,
            metrics_disabled: true,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        });

        assert!(snap.flags.metrics_disabled);
        assert!(!snap.flags.requests_truncated);
        assert!(!snap.flags.errors_truncated);
        assert_eq!(snap.flags.series_seconds, 120);
        assert!(snap.requests.is_empty());
        assert!(snap.errors.is_empty());
        assert!(snap.scenarios.is_empty());
        assert!(snap.transactions.is_empty());
        assert!(snap.flags.transaction_metrics_disabled);
        assert!(snap.flags.scenario_metrics_disabled);
        assert_eq!(snap.series, SeriesWindow::empty());
        assert_eq!(snap.aggregate.total_requests, 0);
        assert_eq!(snap.aggregate.total_failures, 0);
        assert!(!snap.aggregate.co_active);
        // Runtime context is still honest.
        assert_eq!(snap.phase, "maintain");
        assert!(snap.stopping);
        assert_eq!(snap.duration_secs, 42);
        assert_eq!(snap.active_users, 7);
        assert_eq!(snap.target_users, 10);
        assert_eq!(snap.hosts, vec!["https://example.com".to_string()]);
    }

    fn make_transaction(
        scenario_index: usize,
        scenario_name: &str,
        transaction_index: usize,
        transaction_name: &str,
        times: &[(u64, bool)],
    ) -> TransactionMetricAggregate {
        let mut agg = TransactionMetricAggregate::new(
            scenario_index,
            Arc::from(scenario_name),
            transaction_index,
            TransactionName::TransactionOnly(Arc::from(transaction_name)),
        );
        for &(time, success) in times {
            agg.set_time(time, success);
        }
        agg
    }

    fn make_scenario(index: usize, name: &str, runs: &[(u64, usize)]) -> ScenarioMetricAggregate {
        let mut agg = ScenarioMetricAggregate::new(index, Arc::from(name));
        for &(time, user) in runs {
            agg.update(time, user);
        }
        agg
    }

    /// Two scenarios of two transactions each, the second transaction of the
    /// first scenario with failures.
    fn add_scenario_metrics(metrics: &mut GooseMetrics) {
        metrics.scenarios = vec![
            make_scenario(0, "Alpha", &[(100, 0), (200, 1), (300, 0), (400, 1)]),
            make_scenario(1, "Beta", &[(50, 2), (70, 2)]),
        ];
        metrics.transactions = vec![
            vec![
                make_transaction(
                    0,
                    "Alpha",
                    0,
                    "login",
                    &[(10, true), (20, true), (30, true)],
                ),
                make_transaction(
                    0,
                    "Alpha",
                    1,
                    "",
                    &[(40, true), (60, false), (80, false), (100, true)],
                ),
            ],
            vec![
                make_transaction(1, "Beta", 0, "front", &[(5, true)]),
                make_transaction(1, "Beta", 1, "about", &[]),
            ],
        ];
    }

    fn scenario_input(metrics: &GooseMetrics) -> DashboardSnapshotInput<'_> {
        DashboardSnapshotInput {
            metrics,
            series: SeriesWindow::empty(),
            active_users: 3,
            maximum_users: 3,
            target_users: 3,
            total_users: 3,
            phase: "maintain".to_string(),
            stopping: false,
            series_window_secs: SERIES_WINDOW_SECS,
            no_status_codes: false,
            metrics_disabled: false,
            no_transaction_metrics: false,
            no_scenario_metrics: false,
            report: SnapshotReport::default(),
            settings: SnapshotSettings::idle(),
            percentiles_over_time: false,
            series_keys: HashSet::new(),
        }
    }

    #[test]
    fn builder_scenario_and_transaction_rows() {
        let mut metrics = empty_metrics();
        metrics.duration = 4;
        add_scenario_metrics(&mut metrics);
        let snap = build_dashboard_snapshot(scenario_input(&metrics));

        assert!(!snap.flags.scenario_metrics_disabled);
        assert!(!snap.flags.transaction_metrics_disabled);

        let names: Vec<&str> = snap
            .scenarios
            .iter()
            .map(|s| s.scenario_name.as_str())
            .collect();
        assert_eq!(names, vec!["Alpha", "Beta"]);
        let alpha = &snap.scenarios[0];
        assert_eq!(alpha.scenario_index, 0);
        assert_eq!(alpha.users, 2);
        assert_eq!(alpha.run_count, 4);
        assert!((alpha.runs_per_second - 1.0).abs() < 1e-9);
        assert!((alpha.response_time_avg_ms - 250.0).abs() < 1e-9);
        assert_eq!(alpha.response_time_min_ms, 100);
        assert_eq!(alpha.response_time_max_ms, 400);
        // 200 ms is reported as the middle of its bucket, 199.68 ms, which
        // is 199 in whole milliseconds.
        assert_eq!(alpha.percentile_ms.p50, 199);
        // Shown rounded, as 200.
        assert_eq!(alpha.response_time_us.p50, 199_680);
        assert_eq!(
            crate::metrics::format_micros(alpha.response_time_us.p50, true),
            "200"
        );
        assert_eq!(alpha.percentile_ms.p95, 400);
        assert_eq!(alpha.percentile_ms.p99, 400);
        let beta = &snap.scenarios[1];
        assert_eq!(beta.scenario_index, 1);
        assert_eq!(beta.users, 1);
        assert_eq!(beta.run_count, 2);
        assert!((beta.response_time_avg_ms - 60.0).abs() < 1e-9);

        let order: Vec<(u64, u64)> = snap
            .transactions
            .iter()
            .map(|t| (t.scenario_index, t.transaction_index))
            .collect();
        assert_eq!(order, vec![(0, 0), (0, 1), (1, 0), (1, 1)]);

        let login = &snap.transactions[0];
        assert_eq!(login.scenario_name, "Alpha");
        assert_eq!(login.transaction_name, "login");
        assert_eq!(login.run_count, 3);
        assert_eq!(login.failure_count, 0);
        assert!((login.runs_per_second - 0.75).abs() < 1e-6);
        assert_eq!(login.failures_per_second, 0.0);
        assert!((login.response_time_avg_ms - 20.0).abs() < 1e-9);
        assert_eq!(login.response_time_min_ms, 10);
        assert_eq!(login.response_time_max_ms, 30);
        assert_eq!(login.percentile_ms.p50, 20);
        assert_eq!(login.percentile_ms.p99, 30);

        let failing = &snap.transactions[1];
        assert_eq!(failing.transaction_name, "");
        assert_eq!(failing.run_count, 4);
        assert_eq!(failing.failure_count, 2);
        assert!((failing.runs_per_second - 1.0).abs() < 1e-6);
        assert!((failing.failures_per_second - 0.5).abs() < 1e-6);
        assert!((failing.response_time_avg_ms - 70.0).abs() < 1e-9);
        assert_eq!(failing.response_time_min_ms, 40);
        assert_eq!(failing.response_time_max_ms, 100);
        assert_eq!(failing.percentile_ms.p50, 60);
        assert_eq!(failing.percentile_ms.p95, 100);

        let never_run = &snap.transactions[3];
        assert_eq!(never_run.scenario_name, "Beta");
        assert_eq!(never_run.transaction_name, "about");
        assert_eq!(never_run.run_count, 0);
        assert_eq!(never_run.response_time_avg_ms, 0.0);
        assert_eq!(never_run.percentile_ms.p50, 0);
    }

    #[test]
    fn never_run_scenario_serializes_without_null() {
        let mut metrics = empty_metrics();
        metrics.scenarios = vec![make_scenario(0, "Idle", &[])];
        metrics.transactions = vec![vec![make_transaction(0, "Idle", 0, "t", &[])]];
        let snap = build_dashboard_snapshot(scenario_input(&metrics));
        let scenario = &snap.scenarios[0];
        assert_eq!(scenario.run_count, 0);
        assert_eq!(scenario.users, 0);
        assert_eq!(scenario.runs_per_second, 0.0);
        assert_eq!(scenario.response_time_avg_ms, 0.0);
        assert_eq!(scenario.percentile_ms.p50, 0);
        assert_eq!(snap.transactions[0].response_time_avg_ms, 0.0);
        // Only the scenario and transaction rows: other parts of the snapshot
        // hold nulls on purpose (`report`, and `co_adjusted` without events).
        let value = serde_json::to_value(&snap).expect("serialize snapshot");
        for rows in ["scenarios", "transactions"] {
            let json = value[rows].to_string();
            assert!(!json.contains("null"), "{}: {}", rows, json);
        }
    }

    #[test]
    fn no_transaction_metrics_empties_only_transactions() {
        let mut metrics = empty_metrics();
        metrics.duration = 4;
        add_scenario_metrics(&mut metrics);
        let mut input = scenario_input(&metrics);
        input.no_transaction_metrics = true;
        let snap = build_dashboard_snapshot(input);
        assert!(snap.transactions.is_empty());
        assert!(snap.flags.transaction_metrics_disabled);
        assert!(!snap.flags.scenario_metrics_disabled);
        assert!(!snap.flags.metrics_disabled);
        assert_eq!(snap.scenarios.len(), 2);
    }

    #[test]
    fn no_scenario_metrics_empties_only_scenarios() {
        let mut metrics = empty_metrics();
        metrics.duration = 4;
        add_scenario_metrics(&mut metrics);
        let mut input = scenario_input(&metrics);
        input.no_scenario_metrics = true;
        let snap = build_dashboard_snapshot(input);
        assert!(snap.scenarios.is_empty());
        assert!(snap.flags.scenario_metrics_disabled);
        assert!(!snap.flags.transaction_metrics_disabled);
        assert!(!snap.flags.metrics_disabled);
        assert_eq!(snap.transactions.len(), 4);
    }

    /// Committed TypeScript declarations of the snapshot structs, compiled
    /// with the dashboard client (`src/dashboard/static/tsconfig.json`).
    const DASHBOARD_TYPES_PATH: &str = "src/dashboard/static/snapshot.d.ts";

    /// Set to rewrite [`DASHBOARD_TYPES_PATH`] instead of comparing against it.
    const UPDATE_DASHBOARD_TYPES_ENV: &str = "GOOSE_UPDATE_DASHBOARD_TYPES";

    /// TypeScript declarations for every struct in the snapshot, generated by
    /// `ts-rs`. They are global `type` aliases, so every client module in
    /// `src/dashboard/static/src/` uses them without an import. Every `u64`
    /// is emitted as `number`, the type `JSON.parse` yields, rather than
    /// `ts-rs`'s default `bigint`.
    fn dashboard_types_ts() -> String {
        use std::any::TypeId;
        use ts_rs::{TypeVisitor, TS};

        /// Collects the declaration of every struct reachable from the
        /// snapshot, so a new nested struct cannot be left out of the file.
        struct Declarations {
            cfg: ts_rs::Config,
            seen: Vec<TypeId>,
            decls: Vec<String>,
        }
        impl TypeVisitor for Declarations {
            fn visit<T: TS + 'static + ?Sized>(&mut self) {
                // Primitives and std containers have no output path and no
                // declaration of their own.
                if T::output_path().is_none() || self.seen.contains(&TypeId::of::<T>()) {
                    return;
                }
                self.seen.push(TypeId::of::<T>());
                self.decls.push(T::decl(&self.cfg));
                T::visit_dependencies(self);
            }
        }

        let mut declarations = Declarations {
            cfg: ts_rs::Config::new().with_large_int("number"),
            seen: Vec::new(),
            decls: Vec::new(),
        };
        declarations.visit::<DashboardSnapshot>();
        declarations.visit::<RequestSeries>();
        // The derive's visiting order is not stable from one build to the
        // next; sort by type name so the file is.
        declarations.decls.sort();
        let mut out = format!(
            "// Generated from src/metrics/dashboard_snapshot.rs by the unit test\n\
             // `dashboard_types_match_rust`. Do not edit. To regenerate, run:\n\
             //   {UPDATE_DASHBOARD_TYPES_ENV}=1 cargo test --lib dashboard_types_match_rust\n\
             \n\
             /** The only `DashboardSnapshot.version` this client accepts. */\n\
             type DashboardSnapshotVersion = {SNAPSHOT_VERSION};\n"
        );
        for decl in declarations.decls {
            out.push('\n');
            // `ts-rs` leaves a space after the comma ahead of a doc comment.
            for line in decl.lines() {
                out.push_str(line.trim_end());
                out.push('\n');
            }
        }
        out
    }

    #[test]
    fn dashboard_types_match_rust() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(DASHBOARD_TYPES_PATH);
        let generated = dashboard_types_ts();
        if std::env::var_os(UPDATE_DASHBOARD_TYPES_ENV).is_some() {
            // Never let a stray variable turn the CI check into a rewrite.
            assert!(
                std::env::var_os("CI").is_none(),
                "{} must not be set in CI",
                UPDATE_DASHBOARD_TYPES_ENV
            );
            std::fs::write(&path, &generated).expect("write dashboard types");
            return;
        }
        let committed = std::fs::read_to_string(&path).expect("read dashboard types");
        assert!(
            committed == generated,
            "{} does not match the snapshot structs. Regenerate it with \
             `{}=1 cargo test --lib dashboard_types_match_rust`, then type check \
             the client (`npm run check` in src/dashboard/static).\n--- generated ---\n{}",
            DASHBOARD_TYPES_PATH,
            UPDATE_DASHBOARD_TYPES_ENV,
            generated
        );
    }

    #[test]
    fn snapshot_json_comes_from_plain_derives() {
        // snapshot.d.ts describes the JSON only while serde's derive writes it
        // from the fields as declared. ts-rs does not model attributes such as
        // `serialize_with`, and cannot see a hand-written `impl Serialize`, so
        // either could change the JSON without changing the declarations.
        // `serde(` also catches one inside `cfg_attr`. `serde(skip)` is the one
        // exception: ts-rs drops a skipped field too, which
        // `dashboard_types_match_rust` checks.
        let source = include_str!("dashboard_snapshot.rs");
        let structs = source
            .split("\nmod tests {")
            .next()
            .expect("source")
            .replace("#[serde(skip)]", "");
        for pattern in ["serde(", "impl Serialize", "impl serde::Serialize"] {
            assert!(
                !structs.contains(pattern),
                "`{}` in dashboard_snapshot.rs: snapshot.d.ts may no longer \
                 match the JSON; check the generated types by hand",
                pattern
            );
        }
    }
}