shardline 1.0.0

Self-hosted Shardline CAS server and operator CLI for Git/Xet storage workflows.
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
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
mod concurrent;
mod e2e;
mod ingest;
mod sparse;

use std::{
    fs as std_fs,
    io::{Error as IoError, ErrorKind},
    num::{NonZeroUsize, TryFromIntError},
    path::{Path, PathBuf},
    thread,
    time::Duration,
};

use bytes::Bytes;
use serde::{Deserialize, Serialize};
use shardline_protocol::{RepositoryProvider, RepositoryScope, TokenClaimsError};
use shardline_server::{BenchmarkBackend, ServerConfig, ServerConfigError, ServerError};
use thiserror::Error;
use tokio::fs;

pub(crate) use e2e::run_bench_iteration;
pub(crate) use ingest::run_ingest_bench_iteration;
pub(crate) use sparse::{
    build_base_asset, build_concurrent_ingest_upload_cases, build_concurrent_upload_cases,
    build_cross_repository_assets, build_mutation_range, build_sparse_update,
};

#[cfg(test)]
pub(crate) const DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS: usize = 64;

/// Latency measurements for a single benchmark iteration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LatencyMetrics {
    /// Initial upload latency in microseconds.
    pub initial_upload_micros: u64,
    /// Sparse-update upload latency in microseconds.
    pub sparse_update_upload_micros: u64,
    /// Latest-version download latency in microseconds.
    pub latest_download_micros: u64,
    /// Previous-version download latency in microseconds.
    pub previous_download_micros: u64,
    /// Ranged reconstruction-planning latency in microseconds.
    pub ranged_reconstruction_micros: u64,
    /// Concurrent latest-download wall-clock latency in microseconds.
    pub concurrent_latest_download_micros: u64,
    /// Concurrent upload wall-clock latency in microseconds.
    pub concurrent_upload_micros: u64,
    /// Cross-repository upload latency in microseconds.
    pub cross_repository_upload_micros: u64,
    /// Cold reconstruction-cache fill latency in microseconds.
    pub cached_latest_reconstruction_cold_micros: u64,
    /// Hot reconstruction-cache hit latency in microseconds.
    pub cached_latest_reconstruction_hot_micros: u64,
}

/// Byte-count measurements for a single benchmark iteration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ByteMetrics {
    /// Total bytes uploaded in this iteration.
    pub uploaded_bytes: u64,
    /// Total bytes downloaded in this iteration.
    pub downloaded_bytes: u64,
    /// Serialized cached reconstruction response bytes measured in this iteration.
    pub cached_reconstruction_response_bytes: u64,
    /// Whether the hot cached reconstruction avoided the backend loader.
    pub cached_latest_reconstruction_cache_hit: bool,
    /// Bytes downloaded by concurrent latest-download workers.
    pub concurrent_downloaded_bytes: u64,
    /// Bytes uploaded by concurrent upload workers.
    pub concurrent_uploaded_bytes: u64,
    /// New bytes written by concurrent upload workers.
    pub concurrent_newly_stored_bytes: u64,
    /// New bytes written to storage in this iteration.
    pub newly_stored_bytes: u64,
    /// New bytes written during the cross-repository upload.
    pub cross_repository_newly_stored_bytes: u64,
}

/// Chunk-count measurements for a single benchmark iteration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChunkMetrics {
    /// Number of chunks inserted during the initial upload.
    pub initial_inserted_chunks: u64,
    /// Number of chunks inserted during the sparse update.
    pub sparse_update_inserted_chunks: u64,
    /// Number of chunks reused during the sparse update.
    pub sparse_update_reused_chunks: u64,
    /// Number of chunks inserted during concurrent uploads.
    pub concurrent_upload_inserted_chunks: u64,
    /// Number of chunks reused during concurrent uploads.
    pub concurrent_upload_reused_chunks: u64,
    /// Number of chunks inserted during the cross-repository upload.
    pub cross_repository_inserted_chunks: u64,
    /// Number of chunks reused during the cross-repository upload.
    pub cross_repository_reused_chunks: u64,
}

/// Process timing measurements for a single benchmark iteration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TimingMetrics {
    /// Total process CPU time consumed while executing this iteration workload.
    pub process_cpu_micros: u64,
    /// Average CPU cores consumed during this iteration, in per-mille cores.
    pub process_cpu_cores_per_mille: u64,
    /// Fraction of host CPU capacity consumed during this iteration, in per-mille.
    pub process_host_utilization_per_mille: u64,
}

/// Inventory snapshot at the end of a single benchmark iteration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct InventoryMetrics {
    /// Chunk object count after the iteration completes.
    pub chunk_objects: u64,
    /// Chunk object bytes after the iteration completes.
    pub chunk_bytes: u64,
    /// Visible file-record count after the iteration completes.
    pub visible_files: u64,
}

/// One benchmark iteration report.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BenchIterationReport {
    /// Iteration number starting at one.
    pub iteration: u32,
    /// Storage root used for this isolated iteration.
    pub storage_dir: PathBuf,
    /// Latency measurements for this iteration.
    pub latency: LatencyMetrics,
    /// Byte-count measurements for this iteration.
    pub bytes: ByteMetrics,
    /// Chunk-count measurements for this iteration.
    pub chunks: ChunkMetrics,
    /// Process timing measurements for this iteration.
    pub timing: TimingMetrics,
    /// Inventory snapshot at the end of this iteration.
    pub inventory: InventoryMetrics,
}

/// Aggregate benchmark report.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BenchReport {
    /// Focused benchmark scenario.
    pub scenario: BenchScenario,
    /// Backend target exercised by this report.
    pub deployment_target: BenchDeploymentTarget,
    /// Metadata backend selected for this run.
    pub metadata_backend: String,
    /// Immutable object-storage backend selected for this run.
    pub object_backend: String,
    /// Scope of the reported inventory counters.
    pub inventory_scope: BenchInventoryScope,
    /// Root directory that contains isolated iteration stores.
    pub storage_dir: PathBuf,
    /// Number of benchmark iterations.
    pub iterations: u32,
    /// Chunk size used for all iterations.
    pub chunk_size_bytes: u64,
    /// Concurrency used for concurrent benchmark sub-scenarios.
    pub concurrency: u32,
    /// Maximum upload chunks processed in parallel per upload.
    pub upload_max_in_flight_chunks: u64,
    /// Base asset size used for all iterations.
    pub base_bytes: u64,
    /// Mutation window size used for all iterations.
    pub mutated_bytes: u64,
    /// CPU threads available to the benchmark process.
    pub available_parallelism: u64,
    /// Average latency measurements across iterations.
    pub latency: LatencyMetrics,
    /// Average throughput measurements across iterations.
    pub throughput: BenchThroughputMetrics,
    /// Average process timing measurements across iterations.
    pub timing: TimingMetrics,
    /// Inventory totals across all iterations.
    pub totals: BenchTotals,
    /// Per-iteration detail.
    pub iterations_detail: Vec<BenchIterationReport>,
}

/// Average throughput measurements in the aggregate report.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BenchThroughputMetrics {
    /// Average initial upload throughput in bytes per second.
    pub average_initial_upload_bytes_per_second: u64,
    /// Average sparse-update upload throughput in bytes per second.
    pub average_sparse_update_upload_bytes_per_second: u64,
    /// Average latest-download throughput in bytes per second.
    pub average_latest_download_bytes_per_second: u64,
    /// Average previous-download throughput in bytes per second.
    pub average_previous_download_bytes_per_second: u64,
    /// Average concurrent latest-download throughput in bytes per second.
    pub average_concurrent_latest_download_bytes_per_second: u64,
    /// Average concurrent upload throughput in bytes per second.
    pub average_concurrent_upload_bytes_per_second: u64,
    /// Average cross-repository upload throughput in bytes per second.
    pub average_cross_repository_upload_bytes_per_second: u64,
    /// Average hot cached-reconstruction throughput in bytes per second.
    pub average_cached_latest_reconstruction_hit_bytes_per_second: u64,
}

/// Totals across all iterations in the aggregate report.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BenchTotals {
    /// Concurrent latest-download scaling efficiency in per-mille, where 1000 is ideal linear scaling.
    pub concurrent_latest_download_scaling_per_mille: u64,
    /// Concurrent upload scaling efficiency in per-mille, where 1000 is ideal linear scaling.
    pub concurrent_upload_scaling_per_mille: u64,
    /// Total uploaded bytes across all iterations.
    pub total_uploaded_bytes: u64,
    /// Total downloaded bytes across all iterations.
    pub total_downloaded_bytes: u64,
    /// Total serialized cached reconstruction response bytes across all iterations.
    pub total_cached_reconstruction_response_bytes: u64,
    /// Number of iterations whose second reconstruction lookup hit cache.
    pub cache_hit_iterations: u64,
    /// Total bytes downloaded across all concurrent latest-download runs.
    pub total_concurrent_downloaded_bytes: u64,
    /// Total bytes uploaded across all concurrent upload runs.
    pub total_concurrent_uploaded_bytes: u64,
    /// Total newly stored bytes across all concurrent upload runs.
    pub total_concurrent_newly_stored_bytes: u64,
    /// Total newly stored bytes across all iterations.
    pub total_newly_stored_bytes: u64,
    /// Total chunks inserted across all initial uploads.
    pub total_initial_inserted_chunks: u64,
    /// Total chunks inserted across all sparse updates.
    pub total_sparse_update_inserted_chunks: u64,
    /// Total chunks reused across all sparse updates.
    pub total_sparse_update_reused_chunks: u64,
    /// Total chunks inserted across all concurrent upload runs.
    pub total_concurrent_upload_inserted_chunks: u64,
    /// Total chunks reused across all concurrent upload runs.
    pub total_concurrent_upload_reused_chunks: u64,
    /// Total chunks inserted across all cross-repository upload runs.
    pub total_cross_repository_inserted_chunks: u64,
    /// Total chunks reused across all cross-repository upload runs.
    pub total_cross_repository_reused_chunks: u64,
    /// Total newly stored bytes across all cross-repository upload runs.
    pub total_cross_repository_newly_stored_bytes: u64,
}

impl BenchReport {
    pub fn print_summary(&self) {
        println!("mode: e2e");
        println!("deployment_target: {}", self.deployment_target.as_str());
        println!("metadata_backend: {}", self.metadata_backend);
        println!("object_backend: {}", self.object_backend);
        println!("inventory_scope: {}", self.inventory_scope.as_str());
        println!("scenario: {}", self.scenario.as_str());
        if self.scenario == BenchScenario::Full {
            println!("scenario: sparse-update");
            println!("scenario: concurrent-latest-download");
            println!("scenario: concurrent-upload");
            println!("scenario: cross-repository-upload");
            println!("scenario: cached-latest-reconstruction");
        }
        println!("storage_dir: {}", self.storage_dir.display());
        println!("iterations: {}", self.iterations);
        println!("concurrency: {}", self.concurrency);
        println!(
            "upload_max_in_flight_chunks: {}",
            self.upload_max_in_flight_chunks
        );
        println!("chunk_size_bytes: {}", self.chunk_size_bytes);
        println!("base_bytes: {}", self.base_bytes);
        println!("mutated_bytes: {}", self.mutated_bytes);
        println!("available_parallelism: {}", self.available_parallelism);
        println!(
            "average_initial_upload_micros: {}",
            self.latency.initial_upload_micros
        );
        println!(
            "average_sparse_update_upload_micros: {}",
            self.latency.sparse_update_upload_micros
        );
        println!(
            "average_latest_download_micros: {}",
            self.latency.latest_download_micros
        );
        println!(
            "average_previous_download_micros: {}",
            self.latency.previous_download_micros
        );
        println!(
            "average_ranged_reconstruction_micros: {}",
            self.latency.ranged_reconstruction_micros
        );
        println!(
            "average_concurrent_latest_download_micros: {}",
            self.latency.concurrent_latest_download_micros
        );
        println!(
            "average_concurrent_upload_micros: {}",
            self.latency.concurrent_upload_micros
        );
        println!(
            "average_cross_repository_upload_micros: {}",
            self.latency.cross_repository_upload_micros
        );
        println!(
            "average_cached_latest_reconstruction_cold_micros: {}",
            self.latency.cached_latest_reconstruction_cold_micros
        );
        println!(
            "average_cached_latest_reconstruction_hot_micros: {}",
            self.latency.cached_latest_reconstruction_hot_micros
        );
        println!(
            "average_process_cpu_micros: {}",
            self.timing.process_cpu_micros
        );
        println!(
            "average_process_cpu_cores_per_mille: {}",
            self.timing.process_cpu_cores_per_mille
        );
        println!(
            "average_process_host_utilization_per_mille: {}",
            self.timing.process_host_utilization_per_mille
        );
        println!(
            "average_initial_upload_bytes_per_second: {}",
            self.throughput.average_initial_upload_bytes_per_second
        );
        println!(
            "average_sparse_update_upload_bytes_per_second: {}",
            self.throughput
                .average_sparse_update_upload_bytes_per_second
        );
        println!(
            "average_latest_download_bytes_per_second: {}",
            self.throughput.average_latest_download_bytes_per_second
        );
        println!(
            "average_previous_download_bytes_per_second: {}",
            self.throughput.average_previous_download_bytes_per_second
        );
        println!(
            "average_concurrent_latest_download_bytes_per_second: {}",
            self.throughput
                .average_concurrent_latest_download_bytes_per_second
        );
        println!(
            "average_concurrent_upload_bytes_per_second: {}",
            self.throughput.average_concurrent_upload_bytes_per_second
        );
        println!(
            "average_cross_repository_upload_bytes_per_second: {}",
            self.throughput
                .average_cross_repository_upload_bytes_per_second
        );
        println!(
            "average_cached_latest_reconstruction_hit_bytes_per_second: {}",
            self.throughput
                .average_cached_latest_reconstruction_hit_bytes_per_second
        );
        println!(
            "concurrent_latest_download_scaling_per_mille: {}",
            self.totals.concurrent_latest_download_scaling_per_mille
        );
        println!(
            "concurrent_upload_scaling_per_mille: {}",
            self.totals.concurrent_upload_scaling_per_mille
        );
        println!("total_uploaded_bytes: {}", self.totals.total_uploaded_bytes);
        println!(
            "total_downloaded_bytes: {}",
            self.totals.total_downloaded_bytes
        );
        println!(
            "total_cached_reconstruction_response_bytes: {}",
            self.totals.total_cached_reconstruction_response_bytes
        );
        println!("cache_hit_iterations: {}", self.totals.cache_hit_iterations);
        println!(
            "total_concurrent_downloaded_bytes: {}",
            self.totals.total_concurrent_downloaded_bytes
        );
        println!(
            "total_concurrent_uploaded_bytes: {}",
            self.totals.total_concurrent_uploaded_bytes
        );
        println!(
            "total_newly_stored_bytes: {}",
            self.totals.total_newly_stored_bytes
        );
        println!(
            "total_concurrent_newly_stored_bytes: {}",
            self.totals.total_concurrent_newly_stored_bytes
        );
        println!(
            "total_cross_repository_newly_stored_bytes: {}",
            self.totals.total_cross_repository_newly_stored_bytes
        );
        println!(
            "total_initial_inserted_chunks: {}",
            self.totals.total_initial_inserted_chunks
        );
        println!(
            "total_sparse_update_inserted_chunks: {}",
            self.totals.total_sparse_update_inserted_chunks
        );
        println!(
            "total_sparse_update_reused_chunks: {}",
            self.totals.total_sparse_update_reused_chunks
        );
        println!(
            "total_concurrent_upload_inserted_chunks: {}",
            self.totals.total_concurrent_upload_inserted_chunks
        );
        println!(
            "total_concurrent_upload_reused_chunks: {}",
            self.totals.total_concurrent_upload_reused_chunks
        );
        println!(
            "total_cross_repository_inserted_chunks: {}",
            self.totals.total_cross_repository_inserted_chunks
        );
        println!(
            "total_cross_repository_reused_chunks: {}",
            self.totals.total_cross_repository_reused_chunks
        );
        if let Some(last) = self.iterations_detail.last() {
            println!(
                "last_iteration_chunk_objects: {}",
                last.inventory.chunk_objects
            );
            println!("last_iteration_chunk_bytes: {}", last.inventory.chunk_bytes);
            println!(
                "last_iteration_visible_files: {}",
                last.inventory.visible_files
            );
        }
    }
}

/// One zero-storage ingest benchmark iteration report.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct IngestBenchIterationReport {
    /// Iteration number starting at one.
    pub iteration: u32,
    /// Initial upload latency in microseconds.
    pub initial_upload_micros: u64,
    /// Sparse-update upload latency in microseconds.
    pub sparse_update_upload_micros: u64,
    /// Concurrent upload wall-clock latency in microseconds.
    pub concurrent_upload_micros: u64,
    /// Total bytes processed by uploads in this iteration.
    pub uploaded_bytes: u64,
    /// Bytes processed by concurrent upload workers.
    pub concurrent_uploaded_bytes: u64,
    /// Chunks processed by the initial upload.
    pub initial_inserted_chunks: u64,
    /// Chunks processed by the sparse update upload.
    pub sparse_update_inserted_chunks: u64,
    /// Chunks processed by concurrent upload workers.
    pub concurrent_upload_inserted_chunks: u64,
    /// Process CPU time consumed by the timed concurrent upload window.
    pub concurrent_upload_process_cpu_micros: u64,
    /// Average CPU cores consumed during the timed concurrent upload window, in per-mille cores.
    pub concurrent_upload_process_cpu_cores_per_mille: u64,
    /// Fraction of host CPU capacity consumed by the timed concurrent upload window, in per-mille.
    pub concurrent_upload_process_host_utilization_per_mille: u64,
    /// Total process CPU time consumed while executing this iteration workload.
    pub process_cpu_micros: u64,
    /// Average CPU cores consumed during this iteration, in per-mille cores.
    pub process_cpu_cores_per_mille: u64,
    /// Fraction of host CPU capacity consumed during this iteration, in per-mille.
    pub process_host_utilization_per_mille: u64,
}

/// Aggregate zero-storage ingest benchmark report.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct IngestBenchReport {
    /// Focused benchmark scenario.
    pub scenario: BenchScenario,
    /// Number of benchmark iterations.
    pub iterations: u32,
    /// Chunk size used for all iterations.
    pub chunk_size_bytes: u64,
    /// Concurrency used for concurrent upload sub-scenarios.
    pub concurrency: u32,
    /// Maximum upload chunks processed in parallel per upload.
    pub upload_max_in_flight_chunks: u64,
    /// Base asset size used for all iterations.
    pub base_bytes: u64,
    /// Mutation window size used for all iterations.
    pub mutated_bytes: u64,
    /// CPU threads available to the benchmark process.
    pub available_parallelism: u64,
    /// Average initial upload latency in microseconds.
    pub average_initial_upload_micros: u64,
    /// Average sparse-update upload latency in microseconds.
    pub average_sparse_update_upload_micros: u64,
    /// Average concurrent upload latency in microseconds.
    pub average_concurrent_upload_micros: u64,
    /// Average initial upload throughput in bytes per second.
    pub average_initial_upload_bytes_per_second: u64,
    /// Average sparse-update upload throughput in bytes per second.
    pub average_sparse_update_upload_bytes_per_second: u64,
    /// Average concurrent upload throughput in bytes per second.
    pub average_concurrent_upload_bytes_per_second: u64,
    /// Average process CPU time consumed by timed concurrent upload windows.
    pub average_concurrent_upload_process_cpu_micros: u64,
    /// Average CPU cores consumed by timed concurrent upload windows, in per-mille cores.
    pub average_concurrent_upload_process_cpu_cores_per_mille: u64,
    /// Average fraction of host CPU capacity consumed by timed concurrent upload windows, in per-mille.
    pub average_concurrent_upload_process_host_utilization_per_mille: u64,
    /// Average process CPU time consumed per iteration.
    pub average_process_cpu_micros: u64,
    /// Average CPU cores consumed per iteration, in per-mille cores.
    pub average_process_cpu_cores_per_mille: u64,
    /// Average fraction of host CPU capacity consumed per iteration, in per-mille.
    pub average_process_host_utilization_per_mille: u64,
    /// Concurrent upload scaling efficiency in per-mille, where 1000 is ideal linear scaling.
    pub concurrent_upload_scaling_per_mille: u64,
    /// Total processed bytes across all iterations.
    pub total_uploaded_bytes: u64,
    /// Total bytes processed across all concurrent upload runs.
    pub total_concurrent_uploaded_bytes: u64,
    /// Total chunks processed across all initial uploads.
    pub total_initial_inserted_chunks: u64,
    /// Total chunks processed across all sparse updates.
    pub total_sparse_update_inserted_chunks: u64,
    /// Total chunks processed across all concurrent upload runs.
    pub total_concurrent_upload_inserted_chunks: u64,
    /// Per-iteration detail.
    pub iterations_detail: Vec<IngestBenchIterationReport>,
}

impl IngestBenchReport {
    pub fn print_summary(&self) {
        println!("mode: ingest");
        println!("scenario: {}", self.scenario.as_str());
        if self.scenario == BenchScenario::Full {
            println!("scenario: sparse-update");
            println!("scenario: concurrent-upload");
        }
        println!("iterations: {}", self.iterations);
        println!("concurrency: {}", self.concurrency);
        println!(
            "upload_max_in_flight_chunks: {}",
            self.upload_max_in_flight_chunks
        );
        println!("chunk_size_bytes: {}", self.chunk_size_bytes);
        println!("base_bytes: {}", self.base_bytes);
        println!("mutated_bytes: {}", self.mutated_bytes);
        println!("available_parallelism: {}", self.available_parallelism);
        println!(
            "average_initial_upload_micros: {}",
            self.average_initial_upload_micros
        );
        println!(
            "average_sparse_update_upload_micros: {}",
            self.average_sparse_update_upload_micros
        );
        println!(
            "average_concurrent_upload_micros: {}",
            self.average_concurrent_upload_micros
        );
        println!(
            "average_initial_upload_bytes_per_second: {}",
            self.average_initial_upload_bytes_per_second
        );
        println!(
            "average_sparse_update_upload_bytes_per_second: {}",
            self.average_sparse_update_upload_bytes_per_second
        );
        println!(
            "average_concurrent_upload_bytes_per_second: {}",
            self.average_concurrent_upload_bytes_per_second
        );
        println!(
            "average_concurrent_upload_process_cpu_micros: {}",
            self.average_concurrent_upload_process_cpu_micros
        );
        println!(
            "average_concurrent_upload_process_cpu_cores_per_mille: {}",
            self.average_concurrent_upload_process_cpu_cores_per_mille
        );
        println!(
            "average_concurrent_upload_process_host_utilization_per_mille: {}",
            self.average_concurrent_upload_process_host_utilization_per_mille
        );
        println!(
            "average_process_cpu_micros: {}",
            self.average_process_cpu_micros
        );
        println!(
            "average_process_cpu_cores_per_mille: {}",
            self.average_process_cpu_cores_per_mille
        );
        println!(
            "average_process_host_utilization_per_mille: {}",
            self.average_process_host_utilization_per_mille
        );
        println!(
            "concurrent_upload_scaling_per_mille: {}",
            self.concurrent_upload_scaling_per_mille
        );
        println!("total_uploaded_bytes: {}", self.total_uploaded_bytes);
        println!(
            "total_concurrent_uploaded_bytes: {}",
            self.total_concurrent_uploaded_bytes
        );
        println!(
            "total_initial_inserted_chunks: {}",
            self.total_initial_inserted_chunks
        );
        println!(
            "total_sparse_update_inserted_chunks: {}",
            self.total_sparse_update_inserted_chunks
        );
        println!(
            "total_concurrent_upload_inserted_chunks: {}",
            self.total_concurrent_upload_inserted_chunks
        );
    }
}

/// Supported benchmark scenarios.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum BenchScenario {
    /// Run the full benchmark suite.
    Full,
    /// Measure only the initial upload hot path.
    InitialUpload,
    /// Measure only the sparse-update upload hot path.
    SparseUpdateUpload,
    /// Measure reconstruction of the latest version into full file bytes.
    LatestDownload,
    /// Measure reconstruction of a previous version into full file bytes.
    PreviousDownload,
    /// Measure ranged reconstruction planning for a logical file byte range.
    RangedReconstruction,
    /// Measure concurrent latest-version downloads.
    ConcurrentLatestDownload,
    /// Measure concurrent uploads with chunk reuse.
    ConcurrentUpload,
    /// Measure cross-repository dedupe reuse during upload.
    CrossRepositoryUpload,
    /// Measure hot reconstruction served from the memory cache after a cold fill.
    CachedLatestReconstruction,
}

impl BenchScenario {
    /// Returns the stable CLI/documentation name.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::InitialUpload => "initial-upload",
            Self::SparseUpdateUpload => "sparse-update-upload",
            Self::LatestDownload => "latest-download",
            Self::PreviousDownload => "previous-download",
            Self::RangedReconstruction => "ranged-reconstruction",
            Self::ConcurrentLatestDownload => "concurrent-latest-download",
            Self::ConcurrentUpload => "concurrent-upload",
            Self::CrossRepositoryUpload => "cross-repository-upload",
            Self::CachedLatestReconstruction => "cached-latest-reconstruction",
        }
    }

    #[must_use]
    pub(crate) const fn supports_ingest(self) -> bool {
        matches!(
            self,
            Self::Full | Self::InitialUpload | Self::SparseUpdateUpload | Self::ConcurrentUpload
        )
    }
}

/// Supported end-to-end benchmark deployment targets.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum BenchDeploymentTarget {
    /// Create a fresh local SQLite and local-object-store deployment under `--storage-dir`.
    IsolatedLocal,
    /// Use the active `SHARDLINE_*` runtime config, with per-run benchmark namespacing.
    Configured,
}

impl BenchDeploymentTarget {
    /// Returns the stable kebab-case target name used in reports.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::IsolatedLocal => "isolated-local",
            Self::Configured => "configured",
        }
    }
}

/// Scope of the inventory counters recorded in the benchmark report.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum BenchInventoryScope {
    /// Inventory counters reflect only the benchmark's isolated local store.
    Isolated,
    /// Inventory counters may combine isolated and shared adapters.
    Mixed,
    /// Inventory counters come from shared configured adapters.
    BackendGlobal,
}

impl BenchInventoryScope {
    /// Returns the stable kebab-case inventory scope name used in reports.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Isolated => "isolated",
            Self::Mixed => "mixed",
            Self::BackendGlobal => "backend-global",
        }
    }
}

/// Benchmark execution parameters.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct BenchConfig {
    /// End-to-end backend target.
    pub deployment_target: BenchDeploymentTarget,
    /// Focused benchmark scenario.
    pub scenario: BenchScenario,
    /// Number of benchmark iterations to run.
    pub iterations: u32,
    /// Number of concurrent workers used by concurrent sub-scenarios.
    pub concurrency: u32,
    /// Maximum upload chunks processed in parallel per upload.
    pub upload_max_in_flight_chunks: usize,
    /// Chunk size in bytes used by the benchmark backend.
    pub chunk_size_bytes: usize,
    /// Logical size of the benchmark asset in bytes.
    pub base_bytes: usize,
    /// Number of bytes changed in the sparse-update step.
    pub mutated_bytes: usize,
}

#[derive(Debug, Clone)]
pub(crate) struct ConcurrentUploadCase {
    pub(crate) file_id: String,
    pub(crate) expected_bytes: Bytes,
}

#[derive(Debug, Clone)]
pub(crate) struct BenchFixture<'asset> {
    pub(crate) chunk_size: NonZeroUsize,
    pub(crate) upload_max_in_flight_chunks: NonZeroUsize,
    pub(crate) concurrency: u32,
    pub(crate) base: Bytes,
    pub(crate) updated: Bytes,
    pub(crate) ranged_reconstruction: ByteRange,
    pub(crate) concurrent_upload_cases: &'asset [ConcurrentUploadCase],
    pub(crate) cross_repository_base: Bytes,
    pub(crate) cross_repository_updated: Bytes,
}

#[derive(Debug, Clone)]
pub(crate) struct IngestBenchScenario<'asset> {
    pub(crate) chunk_size: NonZeroUsize,
    pub(crate) upload_max_in_flight_chunks: NonZeroUsize,
    pub(crate) concurrent_upload_cases: &'asset [ConcurrentIngestUploadCase],
    pub(crate) base: Bytes,
    pub(crate) updated: Bytes,
}

#[derive(Debug, Clone)]
pub(crate) struct ConcurrentIngestUploadCase {
    pub(crate) file_id: String,
    pub(crate) body: Bytes,
}

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct TimedConcurrentIngestUpload {
    pub(crate) elapsed_micros: u64,
    pub(crate) uploaded_bytes: u64,
    pub(crate) inserted_chunks: u64,
    pub(crate) process_cpu_micros: u64,
    pub(crate) process_cpu_cores_per_mille: u64,
    pub(crate) process_host_utilization_per_mille: u64,
}

#[derive(Debug, Clone)]
pub(crate) enum BenchBackendSetup {
    IsolatedLocal,
    Configured(Box<ServerConfig>),
}

/// Benchmark runtime failure.
#[derive(Debug, Error)]
pub enum BenchRuntimeError {
    /// The benchmark chunk size must be positive.
    #[error("benchmark chunk size must be greater than zero")]
    ZeroChunkSize,
    /// The benchmark iteration count must be positive.
    #[error("benchmark iteration count must be greater than zero")]
    ZeroIterations,
    /// The benchmark concurrency must be positive.
    #[error("benchmark concurrency must be greater than zero")]
    ZeroConcurrency,
    /// Upload chunk parallelism must be positive.
    #[error("benchmark upload-max-in-flight-chunks must be greater than zero")]
    ZeroUploadMaxInFlightChunks,
    /// The mutation window must be positive.
    #[error("benchmark mutated-bytes must be greater than zero")]
    ZeroMutatedBytes,
    /// The mutation window cannot exceed the asset size.
    #[error("benchmark mutated-bytes must not exceed base-bytes")]
    MutatedBytesExceedBaseBytes,
    /// The chosen benchmark scenario is not supported by the selected mode.
    #[error("benchmark scenario is not supported by the selected mode")]
    UnsupportedScenarioForMode,
    /// Filesystem access failed.
    #[error(transparent)]
    Io(#[from] IoError),
    /// Numeric conversion exceeded the supported range.
    #[error(transparent)]
    NumericConversion(#[from] TryFromIntError),
    /// Backend operation failed.
    #[error(transparent)]
    Server(#[from] ServerError),
    /// Loading runtime configuration failed.
    #[error(transparent)]
    ServerConfig(#[from] ServerConfigError),
    /// Repository scope construction failed.
    #[error(transparent)]
    TokenClaims(#[from] TokenClaimsError),
    /// The run root path did not contain a valid final path component.
    #[error("benchmark run root did not produce a stable namespace")]
    MissingRunNamespace,
    /// The iteration loop did not report backend names.
    #[error("benchmark iterations did not report backend names")]
    MissingBenchmarkBackendNames,
    /// The ranged reconstruction request did not produce reconstruction terms.
    #[error("ranged reconstruction did not return any reconstruction terms")]
    EmptyRangedReconstruction,
    /// The latest download payload differed from the uploaded sparse update.
    #[error("latest download did not match updated asset bytes")]
    LatestDownloadMismatch,
    /// The previous download payload differed from the uploaded base asset.
    #[error("previous download did not match initial asset bytes")]
    PreviousDownloadMismatch,
    /// The left scoped repository download differed from the seeded asset.
    #[error("cross-repository left download did not match seeded asset bytes")]
    CrossRepositoryLeftDownloadMismatch,
    /// The right scoped repository download differed from the updated asset.
    #[error("cross-repository right download did not match updated asset bytes")]
    CrossRepositoryRightDownloadMismatch,
    /// The cross-repository upload did not reuse stored chunks.
    #[error("cross-repository upload did not reuse any chunks")]
    CrossRepositoryUploadWithoutReusedChunks,
    /// A concurrent latest download returned unexpected bytes.
    #[error("concurrent latest download did not match updated asset bytes")]
    ConcurrentLatestDownloadMismatch,
    /// A concurrent upload verification download returned unexpected bytes.
    #[error("concurrent upload verification download did not match uploaded bytes")]
    ConcurrentUploadVerificationMismatch,
    /// Concurrent upload chunk selection failed.
    #[error("concurrent upload chunk selection failed")]
    ConcurrentUploadChunkSelectionFailed,
    /// Calculating a chunk start overflowed.
    #[error("chunk start overflowed")]
    ChunkStartOverflow,
    /// Calculating a chunk end overflowed.
    #[error("chunk end overflowed")]
    ChunkEndOverflow,
    /// Calculating a chunk window underflowed.
    #[error("chunk window underflowed")]
    ChunkWindowUnderflow,
    /// Calculating a worker mutation window overflowed.
    #[error("worker mutation window overflowed")]
    WorkerMutationWindowOverflow,
    /// Calculating a worker mutation window selected an invalid slice.
    #[error("worker mutation window was out of bounds")]
    WorkerMutationWindowOutOfBounds,
    /// Calculating worker byte deltas overflowed.
    #[error("worker delta overflowed")]
    WorkerDeltaOverflow,
    /// A benchmark divisor was zero.
    #[error("benchmark divisor was zero")]
    BenchmarkDivisorZero,
    /// Calculating a sparse mutation window overflowed.
    #[error("mutation window overflowed")]
    MutationWindowOverflow,
    /// Calculating a sparse mutation window selected an invalid slice.
    #[error("mutation window was out of bounds")]
    MutationWindowOutOfBounds,
    /// Calculating a sparse mutation byte range overflowed.
    #[error("mutation range overflowed")]
    MutationRangeOverflow,
    /// Constructing a sparse mutation byte range failed.
    #[error("mutation range was invalid")]
    MutationRangeInvalid(#[source] shardline_protocol::RangeError),
    /// Building the cross-repository fixture overflowed.
    #[error("cross-repository asset overflowed")]
    CrossRepositoryAssetOverflow,
    /// Building the cross-repository fixture selected an invalid middle chunk.
    #[error("cross-repository middle chunk was out of bounds")]
    CrossRepositoryMiddleChunkOutOfBounds,
    /// A `u64` benchmark counter overflowed.
    #[error("benchmark counter overflowed u64")]
    BenchmarkCounterU64Overflow,
    /// A `u32` benchmark counter overflowed.
    #[error("benchmark counter overflowed u32")]
    BenchmarkCounterU32Overflow,
    /// A spawned benchmark task failed to join.
    #[error("benchmark task failed to join")]
    BenchmarkTaskJoin(#[from] tokio::task::JoinError),
}

impl BenchBackendSetup {
    pub(crate) async fn create_backend(
        &self,
        root: PathBuf,
        chunk_size: NonZeroUsize,
        upload_max_in_flight_chunks: NonZeroUsize,
        benchmark_namespace: &str,
    ) -> Result<BenchmarkBackend, BenchRuntimeError> {
        match self {
            Self::IsolatedLocal => Ok(BenchmarkBackend::isolated_local(
                root,
                "http://127.0.0.1:8080".to_owned(),
                chunk_size,
                upload_max_in_flight_chunks,
            )
            .await?),
            Self::Configured(config) => {
                let configured = config
                    .as_ref()
                    .clone()
                    .with_root_dir(root)
                    .with_chunk_size(chunk_size)
                    .with_upload_max_in_flight_chunks(upload_max_in_flight_chunks);
                Ok(BenchmarkBackend::from_config(
                    &configured,
                    configured.root_dir().to_path_buf(),
                    benchmark_namespace,
                )
                .await?)
            }
        }
    }
}

/// Runs the local sparse-update benchmark suite.
///
/// # Errors
///
/// Returns [`BenchRuntimeError`] when the benchmark parameters are invalid, storage
/// roots cannot be created, or the backend violates the expected sparse-update flow.
pub async fn run_bench(
    storage_dir: &Path,
    config: BenchConfig,
) -> Result<BenchReport, BenchRuntimeError> {
    let deployment_target = config.deployment_target;
    let scenario = config.scenario;
    let iterations = config.iterations;
    let concurrency = config.concurrency;
    let upload_max_in_flight_chunks = config.upload_max_in_flight_chunks;
    let chunk_size_bytes = config.chunk_size_bytes;
    let base_bytes = config.base_bytes;
    let mutated_bytes = config.mutated_bytes;

    if iterations == 0 {
        return Err(BenchRuntimeError::ZeroIterations);
    }
    if concurrency == 0 {
        return Err(BenchRuntimeError::ZeroConcurrency);
    }
    if upload_max_in_flight_chunks == 0 {
        return Err(BenchRuntimeError::ZeroUploadMaxInFlightChunks);
    }
    if chunk_size_bytes == 0 {
        return Err(BenchRuntimeError::ZeroChunkSize);
    }
    if mutated_bytes == 0 {
        return Err(BenchRuntimeError::ZeroMutatedBytes);
    }
    if mutated_bytes > base_bytes {
        return Err(BenchRuntimeError::MutatedBytesExceedBaseBytes);
    }

    fs::create_dir_all(storage_dir).await?;
    let run_root = allocate_bench_run_root(storage_dir).await?;
    fs::create_dir_all(&run_root).await?;

    let base = build_base_asset(base_bytes)?;
    let updated = build_sparse_update(&base, mutated_bytes)?;
    let chunk_size = NonZeroUsize::new(chunk_size_bytes).ok_or(BenchRuntimeError::ZeroChunkSize)?;
    let upload_max_in_flight_chunks = NonZeroUsize::new(upload_max_in_flight_chunks)
        .ok_or(BenchRuntimeError::ZeroUploadMaxInFlightChunks)?;
    let backend_setup = match deployment_target {
        BenchDeploymentTarget::IsolatedLocal => BenchBackendSetup::IsolatedLocal,
        BenchDeploymentTarget::Configured => BenchBackendSetup::Configured(Box::new(
            ServerConfig::from_env()?
                .with_chunk_size(chunk_size)
                .with_upload_max_in_flight_chunks(upload_max_in_flight_chunks),
        )),
    };
    let concurrent_upload_cases =
        build_concurrent_upload_cases(&updated, mutated_bytes, chunk_size.get(), concurrency)?;
    let (cross_repository_base, cross_repository_updated) =
        build_cross_repository_assets(chunk_size.get())?;

    let fixture = BenchFixture {
        chunk_size,
        upload_max_in_flight_chunks,
        concurrency,
        base: Bytes::from(base),
        updated: Bytes::from(updated),
        ranged_reconstruction: build_mutation_range(base_bytes, mutated_bytes)?,
        concurrent_upload_cases: &concurrent_upload_cases,
        cross_repository_base: Bytes::from(cross_repository_base),
        cross_repository_updated: Bytes::from(cross_repository_updated),
    };
    let run_namespace = run_root
        .file_name()
        .and_then(|component| component.to_str())
        .ok_or(BenchRuntimeError::MissingRunNamespace)?
        .to_owned();

    let mut detail = Vec::with_capacity(usize::try_from(iterations)?);
    let mut benchmark_backend_names: Option<(String, String)> = None;
    let mut total_initial_upload_micros = 0_u64;
    let mut total_sparse_update_upload_micros = 0_u64;
    let mut total_latest_download_micros = 0_u64;
    let mut total_previous_download_micros = 0_u64;
    let mut total_ranged_reconstruction_micros = 0_u64;
    let mut total_concurrent_latest_download_micros = 0_u64;
    let mut total_concurrent_upload_micros = 0_u64;
    let mut total_cross_repository_upload_micros = 0_u64;
    let mut total_cached_latest_reconstruction_cold_micros = 0_u64;
    let mut total_cached_latest_reconstruction_hot_micros = 0_u64;
    let mut total_uploaded_bytes = 0_u64;
    let mut total_downloaded_bytes = 0_u64;
    let mut total_cached_reconstruction_response_bytes = 0_u64;
    let mut total_concurrent_downloaded_bytes = 0_u64;
    let mut total_concurrent_uploaded_bytes = 0_u64;
    let mut total_concurrent_newly_stored_bytes = 0_u64;
    let mut total_cross_repository_newly_stored_bytes = 0_u64;
    let mut total_newly_stored_bytes = 0_u64;
    let mut total_initial_inserted_chunks = 0_u64;
    let mut total_sparse_update_inserted_chunks = 0_u64;
    let mut total_sparse_update_reused_chunks = 0_u64;
    let mut total_concurrent_upload_inserted_chunks = 0_u64;
    let mut total_concurrent_upload_reused_chunks = 0_u64;
    let mut total_cross_repository_inserted_chunks = 0_u64;
    let mut total_cross_repository_reused_chunks = 0_u64;
    let mut total_process_cpu_micros = 0_u64;
    let mut total_process_cpu_cores_per_mille = 0_u64;
    let mut total_process_host_utilization_per_mille = 0_u64;
    let mut cache_hit_iterations = 0_u64;

    for index in 0..iterations {
        let iteration_number = checked_add_u32(index, 1)?;
        let iteration_root = run_root.join(format!("iteration-{index:04}"));

        let (report, metadata_backend, object_backend) = run_bench_iteration(
            iteration_number,
            iteration_root,
            &run_namespace,
            fixture.clone(),
            scenario,
            &backend_setup,
        )
        .await?;
        if benchmark_backend_names.is_none() {
            benchmark_backend_names = Some((metadata_backend, object_backend));
        }

        total_initial_upload_micros = checked_add_u64(
            total_initial_upload_micros,
            report.latency.initial_upload_micros,
        )?;
        total_sparse_update_upload_micros = checked_add_u64(
            total_sparse_update_upload_micros,
            report.latency.sparse_update_upload_micros,
        )?;
        total_latest_download_micros = checked_add_u64(
            total_latest_download_micros,
            report.latency.latest_download_micros,
        )?;
        total_previous_download_micros = checked_add_u64(
            total_previous_download_micros,
            report.latency.previous_download_micros,
        )?;
        total_ranged_reconstruction_micros = checked_add_u64(
            total_ranged_reconstruction_micros,
            report.latency.ranged_reconstruction_micros,
        )?;
        total_concurrent_latest_download_micros = checked_add_u64(
            total_concurrent_latest_download_micros,
            report.latency.concurrent_latest_download_micros,
        )?;
        total_concurrent_upload_micros = checked_add_u64(
            total_concurrent_upload_micros,
            report.latency.concurrent_upload_micros,
        )?;
        total_cross_repository_upload_micros = checked_add_u64(
            total_cross_repository_upload_micros,
            report.latency.cross_repository_upload_micros,
        )?;
        total_cached_latest_reconstruction_cold_micros = checked_add_u64(
            total_cached_latest_reconstruction_cold_micros,
            report.latency.cached_latest_reconstruction_cold_micros,
        )?;
        total_cached_latest_reconstruction_hot_micros = checked_add_u64(
            total_cached_latest_reconstruction_hot_micros,
            report.latency.cached_latest_reconstruction_hot_micros,
        )?;
        total_uploaded_bytes = checked_add_u64(total_uploaded_bytes, report.bytes.uploaded_bytes)?;
        total_downloaded_bytes =
            checked_add_u64(total_downloaded_bytes, report.bytes.downloaded_bytes)?;
        total_cached_reconstruction_response_bytes = checked_add_u64(
            total_cached_reconstruction_response_bytes,
            report.bytes.cached_reconstruction_response_bytes,
        )?;
        total_concurrent_downloaded_bytes = checked_add_u64(
            total_concurrent_downloaded_bytes,
            report.bytes.concurrent_downloaded_bytes,
        )?;
        total_concurrent_uploaded_bytes = checked_add_u64(
            total_concurrent_uploaded_bytes,
            report.bytes.concurrent_uploaded_bytes,
        )?;
        total_concurrent_newly_stored_bytes = checked_add_u64(
            total_concurrent_newly_stored_bytes,
            report.bytes.concurrent_newly_stored_bytes,
        )?;
        total_cross_repository_newly_stored_bytes = checked_add_u64(
            total_cross_repository_newly_stored_bytes,
            report.bytes.cross_repository_newly_stored_bytes,
        )?;
        total_newly_stored_bytes =
            checked_add_u64(total_newly_stored_bytes, report.bytes.newly_stored_bytes)?;
        total_initial_inserted_chunks = checked_add_u64(
            total_initial_inserted_chunks,
            report.chunks.initial_inserted_chunks,
        )?;
        total_sparse_update_inserted_chunks = checked_add_u64(
            total_sparse_update_inserted_chunks,
            report.chunks.sparse_update_inserted_chunks,
        )?;
        total_sparse_update_reused_chunks = checked_add_u64(
            total_sparse_update_reused_chunks,
            report.chunks.sparse_update_reused_chunks,
        )?;
        total_concurrent_upload_inserted_chunks = checked_add_u64(
            total_concurrent_upload_inserted_chunks,
            report.chunks.concurrent_upload_inserted_chunks,
        )?;
        total_concurrent_upload_reused_chunks = checked_add_u64(
            total_concurrent_upload_reused_chunks,
            report.chunks.concurrent_upload_reused_chunks,
        )?;
        total_cross_repository_inserted_chunks = checked_add_u64(
            total_cross_repository_inserted_chunks,
            report.chunks.cross_repository_inserted_chunks,
        )?;
        total_cross_repository_reused_chunks = checked_add_u64(
            total_cross_repository_reused_chunks,
            report.chunks.cross_repository_reused_chunks,
        )?;
        total_process_cpu_micros =
            checked_add_u64(total_process_cpu_micros, report.timing.process_cpu_micros)?;
        total_process_cpu_cores_per_mille = checked_add_u64(
            total_process_cpu_cores_per_mille,
            report.timing.process_cpu_cores_per_mille,
        )?;
        total_process_host_utilization_per_mille = checked_add_u64(
            total_process_host_utilization_per_mille,
            report.timing.process_host_utilization_per_mille,
        )?;
        cache_hit_iterations = checked_add_u64(
            cache_hit_iterations,
            if report.bytes.cached_latest_reconstruction_cache_hit {
                1
            } else {
                0
            },
        )?;
        detail.push(report);
    }

    let iterations_u64 = u64::from(iterations);
    let base_bytes_u64 = u64::try_from(base_bytes)?;
    let chunk_size_bytes_u64 = u64::try_from(chunk_size_bytes)?;
    let measured_initial_upload_bytes = checked_mul_u64(
        base_bytes_u64,
        measured_iteration_count(total_initial_upload_micros, iterations_u64),
    )?;
    let measured_sparse_update_upload_bytes = checked_mul_u64(
        base_bytes_u64,
        measured_iteration_count(total_sparse_update_upload_micros, iterations_u64),
    )?;
    let measured_latest_download_bytes = checked_mul_u64(
        base_bytes_u64,
        measured_iteration_count(total_latest_download_micros, iterations_u64),
    )?;
    let measured_previous_download_bytes = checked_mul_u64(
        base_bytes_u64,
        measured_iteration_count(total_previous_download_micros, iterations_u64),
    )?;
    let cross_repository_asset_bytes = checked_mul_u64(chunk_size_bytes_u64, 3)?;
    let measured_cross_repository_upload_bytes = checked_mul_u64(
        cross_repository_asset_bytes,
        measured_iteration_count(total_cross_repository_upload_micros, iterations_u64),
    )?;
    let initial_upload_bytes_per_second =
        throughput_bytes_per_second(measured_initial_upload_bytes, total_initial_upload_micros);
    let sparse_update_upload_bytes_per_second = throughput_bytes_per_second(
        measured_sparse_update_upload_bytes,
        total_sparse_update_upload_micros,
    );
    let latest_download_bytes_per_second =
        throughput_bytes_per_second(measured_latest_download_bytes, total_latest_download_micros);
    let concurrent_latest_download_bytes_per_second = throughput_bytes_per_second(
        total_concurrent_downloaded_bytes,
        total_concurrent_latest_download_micros,
    );
    let concurrent_upload_bytes_per_second = throughput_bytes_per_second(
        total_concurrent_uploaded_bytes,
        total_concurrent_upload_micros,
    );
    let available_parallelism = available_parallelism_u64();
    let (metadata_backend, object_backend) =
        benchmark_backend_names.ok_or(BenchRuntimeError::MissingBenchmarkBackendNames)?;
    Ok(BenchReport {
        scenario,
        deployment_target,
        metadata_backend: metadata_backend.clone(),
        object_backend: object_backend.clone(),
        inventory_scope: inventory_scope(&metadata_backend, &object_backend),
        storage_dir: run_root,
        iterations,
        chunk_size_bytes: chunk_size_bytes_u64,
        concurrency,
        upload_max_in_flight_chunks: u64::try_from(upload_max_in_flight_chunks.get())?,
        base_bytes: base_bytes_u64,
        mutated_bytes: u64::try_from(mutated_bytes)?,
        available_parallelism,
        latency: LatencyMetrics {
            initial_upload_micros: checked_average_u64(
                total_initial_upload_micros,
                iterations_u64,
            )?,
            sparse_update_upload_micros: checked_average_u64(
                total_sparse_update_upload_micros,
                iterations_u64,
            )?,
            latest_download_micros: checked_average_u64(
                total_latest_download_micros,
                iterations_u64,
            )?,
            previous_download_micros: checked_average_u64(
                total_previous_download_micros,
                iterations_u64,
            )?,
            ranged_reconstruction_micros: checked_average_u64(
                total_ranged_reconstruction_micros,
                iterations_u64,
            )?,
            concurrent_latest_download_micros: checked_average_u64(
                total_concurrent_latest_download_micros,
                iterations_u64,
            )?,
            concurrent_upload_micros: checked_average_u64(
                total_concurrent_upload_micros,
                iterations_u64,
            )?,
            cross_repository_upload_micros: checked_average_u64(
                total_cross_repository_upload_micros,
                iterations_u64,
            )?,
            cached_latest_reconstruction_cold_micros: checked_average_u64(
                total_cached_latest_reconstruction_cold_micros,
                iterations_u64,
            )?,
            cached_latest_reconstruction_hot_micros: checked_average_u64(
                total_cached_latest_reconstruction_hot_micros,
                iterations_u64,
            )?,
        },
        throughput: BenchThroughputMetrics {
            average_initial_upload_bytes_per_second: initial_upload_bytes_per_second,
            average_sparse_update_upload_bytes_per_second: sparse_update_upload_bytes_per_second,
            average_latest_download_bytes_per_second: latest_download_bytes_per_second,
            average_previous_download_bytes_per_second: throughput_bytes_per_second(
                measured_previous_download_bytes,
                total_previous_download_micros,
            ),
            average_concurrent_latest_download_bytes_per_second:
                concurrent_latest_download_bytes_per_second,
            average_concurrent_upload_bytes_per_second: concurrent_upload_bytes_per_second,
            average_cross_repository_upload_bytes_per_second: throughput_bytes_per_second(
                measured_cross_repository_upload_bytes,
                total_cross_repository_upload_micros,
            ),
            average_cached_latest_reconstruction_hit_bytes_per_second: throughput_bytes_per_second(
                total_cached_reconstruction_response_bytes,
                total_cached_latest_reconstruction_hot_micros,
            ),
        },
        timing: TimingMetrics {
            process_cpu_micros: checked_average_u64(total_process_cpu_micros, iterations_u64)?,
            process_cpu_cores_per_mille: checked_average_u64(
                total_process_cpu_cores_per_mille,
                iterations_u64,
            )?,
            process_host_utilization_per_mille: checked_average_u64(
                total_process_host_utilization_per_mille,
                iterations_u64,
            )?,
        },
        totals: BenchTotals {
            concurrent_latest_download_scaling_per_mille: scaling_per_mille(
                concurrent_latest_download_bytes_per_second,
                latest_download_bytes_per_second,
                concurrency,
            ),
            concurrent_upload_scaling_per_mille: scaling_per_mille(
                concurrent_upload_bytes_per_second,
                sparse_update_upload_bytes_per_second,
                concurrency,
            ),
            total_uploaded_bytes,
            total_downloaded_bytes,
            total_cached_reconstruction_response_bytes,
            cache_hit_iterations,
            total_concurrent_downloaded_bytes,
            total_concurrent_uploaded_bytes,
            total_concurrent_newly_stored_bytes,
            total_cross_repository_newly_stored_bytes,
            total_newly_stored_bytes,
            total_initial_inserted_chunks,
            total_sparse_update_inserted_chunks,
            total_sparse_update_reused_chunks,
            total_concurrent_upload_inserted_chunks,
            total_concurrent_upload_reused_chunks,
            total_cross_repository_inserted_chunks,
            total_cross_repository_reused_chunks,
        },
        iterations_detail: detail,
    })
}

/// Runs the zero-storage upload-ingest benchmark suite.
///
/// # Errors
///
/// Returns [`BenchRuntimeError`] when parameters are invalid or the ingest path fails.
pub async fn run_ingest_bench(config: BenchConfig) -> Result<IngestBenchReport, BenchRuntimeError> {
    let scenario = config.scenario;
    let iterations = config.iterations;
    let concurrency = config.concurrency;
    let upload_max_in_flight_chunks = config.upload_max_in_flight_chunks;
    let chunk_size_bytes = config.chunk_size_bytes;
    let base_bytes = config.base_bytes;
    let mutated_bytes = config.mutated_bytes;

    if !scenario.supports_ingest() {
        return Err(BenchRuntimeError::UnsupportedScenarioForMode);
    }
    if iterations == 0 {
        return Err(BenchRuntimeError::ZeroIterations);
    }
    if concurrency == 0 {
        return Err(BenchRuntimeError::ZeroConcurrency);
    }
    if upload_max_in_flight_chunks == 0 {
        return Err(BenchRuntimeError::ZeroUploadMaxInFlightChunks);
    }
    if chunk_size_bytes == 0 {
        return Err(BenchRuntimeError::ZeroChunkSize);
    }
    if mutated_bytes == 0 {
        return Err(BenchRuntimeError::ZeroMutatedBytes);
    }
    if mutated_bytes > base_bytes {
        return Err(BenchRuntimeError::MutatedBytesExceedBaseBytes);
    }

    let base = build_base_asset(base_bytes)?;
    let updated = build_sparse_update(&base, mutated_bytes)?;
    let chunk_size = NonZeroUsize::new(chunk_size_bytes).ok_or(BenchRuntimeError::ZeroChunkSize)?;
    let upload_max_in_flight_chunks = NonZeroUsize::new(upload_max_in_flight_chunks)
        .ok_or(BenchRuntimeError::ZeroUploadMaxInFlightChunks)?;
    let concurrent_upload_cases = build_concurrent_ingest_upload_cases(
        &updated,
        mutated_bytes,
        chunk_size.get(),
        concurrency,
    )?;
    let fixture = IngestBenchScenario {
        chunk_size,
        upload_max_in_flight_chunks,
        concurrent_upload_cases: &concurrent_upload_cases,
        base: Bytes::from(base),
        updated: Bytes::from(updated),
    };

    let mut detail = Vec::with_capacity(usize::try_from(iterations)?);
    let mut total_initial_upload_micros = 0_u64;
    let mut total_sparse_update_upload_micros = 0_u64;
    let mut total_concurrent_upload_micros = 0_u64;
    let mut total_uploaded_bytes = 0_u64;
    let mut total_concurrent_uploaded_bytes = 0_u64;
    let mut total_initial_inserted_chunks = 0_u64;
    let mut total_sparse_update_inserted_chunks = 0_u64;
    let mut total_concurrent_upload_inserted_chunks = 0_u64;
    let mut total_concurrent_upload_process_cpu_micros = 0_u64;
    let mut total_concurrent_upload_process_cpu_cores_per_mille = 0_u64;
    let mut total_concurrent_upload_process_host_utilization_per_mille = 0_u64;
    let mut total_process_cpu_micros = 0_u64;
    let mut total_process_cpu_cores_per_mille = 0_u64;
    let mut total_process_host_utilization_per_mille = 0_u64;

    for index in 0..iterations {
        let iteration_number = checked_add_u32(index, 1)?;
        let report = run_ingest_bench_iteration(iteration_number, &fixture, scenario).await?;
        total_initial_upload_micros =
            checked_add_u64(total_initial_upload_micros, report.initial_upload_micros)?;
        total_sparse_update_upload_micros = checked_add_u64(
            total_sparse_update_upload_micros,
            report.sparse_update_upload_micros,
        )?;
        total_concurrent_upload_micros = checked_add_u64(
            total_concurrent_upload_micros,
            report.concurrent_upload_micros,
        )?;
        total_uploaded_bytes = checked_add_u64(total_uploaded_bytes, report.uploaded_bytes)?;
        total_concurrent_uploaded_bytes = checked_add_u64(
            total_concurrent_uploaded_bytes,
            report.concurrent_uploaded_bytes,
        )?;
        total_initial_inserted_chunks = checked_add_u64(
            total_initial_inserted_chunks,
            report.initial_inserted_chunks,
        )?;
        total_sparse_update_inserted_chunks = checked_add_u64(
            total_sparse_update_inserted_chunks,
            report.sparse_update_inserted_chunks,
        )?;
        total_concurrent_upload_inserted_chunks = checked_add_u64(
            total_concurrent_upload_inserted_chunks,
            report.concurrent_upload_inserted_chunks,
        )?;
        total_concurrent_upload_process_cpu_micros = checked_add_u64(
            total_concurrent_upload_process_cpu_micros,
            report.concurrent_upload_process_cpu_micros,
        )?;
        total_concurrent_upload_process_cpu_cores_per_mille = checked_add_u64(
            total_concurrent_upload_process_cpu_cores_per_mille,
            report.concurrent_upload_process_cpu_cores_per_mille,
        )?;
        total_concurrent_upload_process_host_utilization_per_mille = checked_add_u64(
            total_concurrent_upload_process_host_utilization_per_mille,
            report.concurrent_upload_process_host_utilization_per_mille,
        )?;
        total_process_cpu_micros =
            checked_add_u64(total_process_cpu_micros, report.process_cpu_micros)?;
        total_process_cpu_cores_per_mille = checked_add_u64(
            total_process_cpu_cores_per_mille,
            report.process_cpu_cores_per_mille,
        )?;
        total_process_host_utilization_per_mille = checked_add_u64(
            total_process_host_utilization_per_mille,
            report.process_host_utilization_per_mille,
        )?;
        detail.push(report);
    }

    let iterations_u64 = u64::from(iterations);
    let base_bytes_u64 = u64::try_from(base_bytes)?;
    let initial_upload_bytes_per_second = throughput_bytes_per_second(
        checked_mul_u64(
            base_bytes_u64,
            measured_iteration_count(total_initial_upload_micros, iterations_u64),
        )?,
        total_initial_upload_micros,
    );
    let sparse_update_upload_bytes_per_second = throughput_bytes_per_second(
        checked_mul_u64(
            base_bytes_u64,
            measured_iteration_count(total_sparse_update_upload_micros, iterations_u64),
        )?,
        total_sparse_update_upload_micros,
    );
    let concurrent_upload_bytes_per_second = throughput_bytes_per_second(
        total_concurrent_uploaded_bytes,
        total_concurrent_upload_micros,
    );
    let available_parallelism = available_parallelism_u64();
    Ok(IngestBenchReport {
        scenario,
        iterations,
        chunk_size_bytes: u64::try_from(chunk_size_bytes)?,
        concurrency,
        upload_max_in_flight_chunks: u64::try_from(upload_max_in_flight_chunks.get())?,
        base_bytes: base_bytes_u64,
        mutated_bytes: u64::try_from(mutated_bytes)?,
        available_parallelism,
        average_initial_upload_micros: checked_average_u64(
            total_initial_upload_micros,
            iterations_u64,
        )?,
        average_sparse_update_upload_micros: checked_average_u64(
            total_sparse_update_upload_micros,
            iterations_u64,
        )?,
        average_concurrent_upload_micros: checked_average_u64(
            total_concurrent_upload_micros,
            iterations_u64,
        )?,
        average_initial_upload_bytes_per_second: initial_upload_bytes_per_second,
        average_sparse_update_upload_bytes_per_second: sparse_update_upload_bytes_per_second,
        average_concurrent_upload_bytes_per_second: concurrent_upload_bytes_per_second,
        average_concurrent_upload_process_cpu_micros: checked_average_u64(
            total_concurrent_upload_process_cpu_micros,
            iterations_u64,
        )?,
        average_concurrent_upload_process_cpu_cores_per_mille: checked_average_u64(
            total_concurrent_upload_process_cpu_cores_per_mille,
            iterations_u64,
        )?,
        average_concurrent_upload_process_host_utilization_per_mille: checked_average_u64(
            total_concurrent_upload_process_host_utilization_per_mille,
            iterations_u64,
        )?,
        average_process_cpu_micros: checked_average_u64(total_process_cpu_micros, iterations_u64)?,
        average_process_cpu_cores_per_mille: checked_average_u64(
            total_process_cpu_cores_per_mille,
            iterations_u64,
        )?,
        average_process_host_utilization_per_mille: checked_average_u64(
            total_process_host_utilization_per_mille,
            iterations_u64,
        )?,
        concurrent_upload_scaling_per_mille: scaling_per_mille(
            concurrent_upload_bytes_per_second,
            sparse_update_upload_bytes_per_second,
            concurrency,
        ),
        total_uploaded_bytes,
        total_concurrent_uploaded_bytes,
        total_initial_inserted_chunks,
        total_sparse_update_inserted_chunks,
        total_concurrent_upload_inserted_chunks,
        iterations_detail: detail,
    })
}

pub(crate) async fn allocate_bench_run_root(
    storage_dir: &Path,
) -> Result<PathBuf, BenchRuntimeError> {
    let mut index = 0_u32;
    loop {
        let candidate = storage_dir.join(format!("run-{index:04}"));
        match fs::metadata(&candidate).await {
            Ok(_metadata) => {}
            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(candidate),
            Err(error) => return Err(BenchRuntimeError::Io(error)),
        }
        index = checked_add_u32(index, 1)?;
    }
}

pub(crate) fn iteration_namespace(run_namespace: &str, iteration: u32) -> String {
    format!("{run_namespace}-iteration-{iteration:04}")
}

pub(crate) fn namespaced_file_id(namespace: &str, file_id: &str) -> String {
    format!("{namespace}-{file_id}")
}

pub(crate) fn build_iteration_repository_scopes(
    namespace: &str,
) -> Result<(RepositoryScope, RepositoryScope), BenchRuntimeError> {
    let left_owner = format!("bench-left-{namespace}");
    let right_owner = format!("bench-right-{namespace}");
    let scope_left = RepositoryScope::new(
        RepositoryProvider::Generic,
        &left_owner,
        "assets",
        Some("main"),
    )?;
    let scope_right = RepositoryScope::new(
        RepositoryProvider::Generic,
        &right_owner,
        "assets",
        Some("main"),
    )?;
    Ok((scope_left, scope_right))
}

pub(crate) fn inventory_scope(metadata_backend: &str, object_backend: &str) -> BenchInventoryScope {
    match (metadata_backend, object_backend) {
        ("local", "local") => BenchInventoryScope::Isolated,
        ("postgres", "s3") => BenchInventoryScope::BackendGlobal,
        _ => BenchInventoryScope::Mixed,
    }
}

pub(crate) fn duration_micros(duration: Duration) -> Result<u64, BenchRuntimeError> {
    u64::try_from(duration.as_micros()).map_err(BenchRuntimeError::from)
}

pub(crate) fn checked_add_u64(left: u64, right: u64) -> Result<u64, BenchRuntimeError> {
    left.checked_add(right)
        .ok_or(BenchRuntimeError::BenchmarkCounterU64Overflow)
}

pub(crate) fn checked_add_u32(left: u32, right: u32) -> Result<u32, BenchRuntimeError> {
    left.checked_add(right)
        .ok_or(BenchRuntimeError::BenchmarkCounterU32Overflow)
}

pub(crate) fn checked_average_u64(total: u64, count: u64) -> Result<u64, BenchRuntimeError> {
    total
        .checked_div(count)
        .ok_or(BenchRuntimeError::BenchmarkDivisorZero)
}

pub(crate) fn checked_mul_u64(left: u64, right: u64) -> Result<u64, BenchRuntimeError> {
    left.checked_mul(right)
        .ok_or(BenchRuntimeError::BenchmarkCounterU64Overflow)
}

pub(crate) const fn measured_iteration_count(total_micros: u64, iterations: u64) -> u64 {
    if total_micros == 0 { 0 } else { iterations }
}

pub(crate) fn throughput_bytes_per_second(bytes: u64, micros: u64) -> u64 {
    if bytes == 0 || micros == 0 {
        return 0;
    }

    bytes
        .saturating_mul(1_000_000)
        .checked_div(micros)
        .unwrap_or(u64::MAX)
}

const SCHEDSTAT_PATH: &str = "/proc/self/schedstat";
const TASK_SCHEDSTAT_DIR_PATH: &str = "/proc/self/task";

pub(crate) fn available_parallelism_u64() -> u64 {
    thread::available_parallelism()
        .map(usize::from)
        .ok()
        .and_then(|value| u64::try_from(value).ok())
        .unwrap_or(1)
}

pub(crate) fn capture_process_cpu_micros() -> u64 {
    let Ok(entries) = std_fs::read_dir(TASK_SCHEDSTAT_DIR_PATH) else {
        return read_schedstat_runtime_micros(Path::new(SCHEDSTAT_PATH));
    };

    let mut total_runtime_micros = 0_u64;
    for entry in entries {
        let Ok(entry) = entry else {
            continue;
        };
        let runtime_micros = read_schedstat_runtime_micros(&entry.path().join("schedstat"));
        total_runtime_micros = total_runtime_micros.saturating_add(runtime_micros);
    }

    if total_runtime_micros == 0 {
        read_schedstat_runtime_micros(Path::new(SCHEDSTAT_PATH))
    } else {
        total_runtime_micros
    }
}

fn read_schedstat_runtime_micros(path: &Path) -> u64 {
    let Ok(schedstat) = std_fs::read_to_string(path) else {
        return 0;
    };
    let Some(runtime_nanos) = schedstat.split_ascii_whitespace().next() else {
        return 0;
    };
    let Ok(runtime_nanos) = runtime_nanos.parse::<u64>() else {
        return 0;
    };

    runtime_nanos / 1_000
}

pub(crate) fn ratio_per_mille(numerator: u64, denominator: u64) -> u64 {
    if numerator == 0 || denominator == 0 {
        return 0;
    }

    let scaled = u128::from(numerator)
        .checked_mul(1_000)
        .and_then(|value| value.checked_div(u128::from(denominator)))
        .unwrap_or_else(|| u128::from(u64::MAX));
    u64::try_from(scaled).unwrap_or(u64::MAX)
}

pub(crate) fn host_utilization_per_mille(
    cpu_micros: u64,
    wall_micros: u64,
    available_parallelism: u64,
) -> u64 {
    if cpu_micros == 0 || wall_micros == 0 || available_parallelism == 0 {
        return 0;
    }

    let denominator = u128::from(wall_micros)
        .checked_mul(u128::from(available_parallelism))
        .unwrap_or_else(|| u128::from(u64::MAX));
    if denominator == 0 {
        return 0;
    }

    let scaled = u128::from(cpu_micros)
        .checked_mul(1_000)
        .and_then(|value| value.checked_div(denominator))
        .unwrap_or_else(|| u128::from(u64::MAX));
    u64::try_from(scaled).unwrap_or(u64::MAX)
}

pub(crate) fn scaling_per_mille(
    aggregate_throughput: u64,
    single_throughput: u64,
    concurrency: u32,
) -> u64 {
    if aggregate_throughput == 0 || single_throughput == 0 || concurrency == 0 {
        return 0;
    }

    aggregate_throughput
        .saturating_mul(1_000)
        .checked_div(single_throughput)
        .and_then(|value| value.checked_div(u64::from(concurrency)))
        .unwrap_or(u64::MAX)
}

use shardline_protocol::ByteRange;

#[cfg(test)]
mod tests {
    use super::{
        BenchConfig, BenchDeploymentTarget, BenchInventoryScope, BenchRuntimeError, BenchScenario,
        DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS, available_parallelism_u64, build_base_asset,
        build_concurrent_upload_cases, build_sparse_update, host_utilization_per_mille,
        ratio_per_mille, run_bench, run_ingest_bench,
    };

    #[test]
    fn sparse_update_changes_only_requested_window() {
        let base = build_base_asset(128);
        assert!(base.is_ok());
        let Ok(base) = base else {
            return;
        };

        let updated = build_sparse_update(&base, 16);
        assert!(updated.is_ok());
        let Ok(updated) = updated else {
            return;
        };

        let changed = base
            .iter()
            .zip(&updated)
            .filter(|(left, right)| left != right)
            .count();
        assert_eq!(changed, 16);
    }

    #[test]
    fn concurrent_upload_cases_mutate_deterministic_chunk_windows() {
        let base = build_base_asset(12);
        assert!(base.is_ok());
        let Ok(base) = base else {
            return;
        };

        let cases = build_concurrent_upload_cases(&base, 4, 4, 3);
        assert!(cases.is_ok());
        let Ok(cases) = cases else {
            return;
        };

        assert_eq!(cases.len(), 3);
        let first = cases.first().map(|case| &case.expected_bytes);
        let second = cases.get(1).map(|case| &case.expected_bytes);
        let third = cases.get(2).map(|case| &case.expected_bytes);
        assert!(first.is_some());
        assert!(second.is_some());
        assert!(third.is_some());
        let Some(first) = first else {
            return;
        };
        let Some(second) = second else {
            return;
        };
        let Some(third) = third else {
            return;
        };
        assert_ne!(first, &base);
        assert_ne!(second, &base);
        assert_ne!(third, &base);
        assert_ne!(first, second);
    }

    #[test]
    fn ratio_helpers_report_expected_cpu_usage() {
        assert_eq!(ratio_per_mille(0, 10), 0);
        assert_eq!(ratio_per_mille(500, 1_000), 500);
        assert_eq!(ratio_per_mille(2_000, 1_000), 2_000);
        assert_eq!(host_utilization_per_mille(2_000, 1_000, 4), 500);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bench_reports_sparse_update_and_concurrent_metrics() {
        let storage = tempfile::tempdir();
        assert!(storage.is_ok());
        let Ok(storage) = storage else {
            return;
        };

        let report = run_bench(
            storage.path(),
            BenchConfig {
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                iterations: 1,
                concurrency: 2,
                upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
                chunk_size_bytes: 4,
                base_bytes: 12,
                mutated_bytes: 4,
            },
        )
        .await;
        assert!(report.is_ok());
        let Ok(report) = report else {
            return;
        };

        assert_eq!(report.iterations, 1);
        assert_eq!(
            report.deployment_target,
            BenchDeploymentTarget::IsolatedLocal
        );
        assert_eq!(report.metadata_backend, "local");
        assert_eq!(report.object_backend, "local");
        assert_eq!(report.inventory_scope, BenchInventoryScope::Isolated);
        assert_eq!(report.concurrency, 2);
        assert_eq!(report.available_parallelism, available_parallelism_u64());
        assert_eq!(report.iterations_detail.len(), 1);
        let iteration = report.iterations_detail.first();
        assert!(iteration.is_some());
        let Some(iteration) = iteration else {
            return;
        };
        assert_eq!(iteration.chunks.initial_inserted_chunks, 3);
        assert_eq!(iteration.chunks.sparse_update_inserted_chunks, 1);
        assert_eq!(iteration.chunks.sparse_update_reused_chunks, 2);
        assert_eq!(iteration.chunks.concurrent_upload_inserted_chunks, 2);
        assert_eq!(iteration.chunks.concurrent_upload_reused_chunks, 4);
        assert_eq!(iteration.bytes.concurrent_newly_stored_bytes, 8);
        assert_eq!(iteration.bytes.concurrent_uploaded_bytes, 24);
        assert_eq!(iteration.bytes.concurrent_downloaded_bytes, 24);
        assert_eq!(iteration.chunks.cross_repository_inserted_chunks, 1);
        assert_eq!(iteration.chunks.cross_repository_reused_chunks, 2);
        assert_eq!(iteration.bytes.cross_repository_newly_stored_bytes, 4);
        assert_eq!(iteration.bytes.newly_stored_bytes, 40);
        assert_eq!(report.totals.total_sparse_update_reused_chunks, 2);
        assert_eq!(report.totals.total_concurrent_upload_inserted_chunks, 2);
        assert_eq!(report.totals.total_concurrent_upload_reused_chunks, 4);
        assert_eq!(report.totals.total_concurrent_newly_stored_bytes, 8);
        assert_eq!(report.totals.total_cross_repository_inserted_chunks, 1);
        assert_eq!(report.totals.total_cross_repository_reused_chunks, 2);
        assert_eq!(report.totals.total_cross_repository_newly_stored_bytes, 4);
        assert!(
            iteration.timing.process_cpu_cores_per_mille
                >= iteration.timing.process_host_utilization_per_mille
        );
        assert!(
            report.timing.process_cpu_cores_per_mille
                >= report.timing.process_host_utilization_per_mille
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bench_reuses_requested_storage_root_by_allocating_new_run_directories() {
        let storage = tempfile::tempdir();
        assert!(storage.is_ok());
        let Ok(storage) = storage else {
            return;
        };

        let first = run_bench(
            storage.path(),
            BenchConfig {
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                iterations: 1,
                concurrency: 1,
                upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
                chunk_size_bytes: 4,
                base_bytes: 12,
                mutated_bytes: 4,
            },
        )
        .await;
        assert!(first.is_ok());
        let Ok(first) = first else {
            return;
        };
        let second = run_bench(
            storage.path(),
            BenchConfig {
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                iterations: 1,
                concurrency: 1,
                upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
                chunk_size_bytes: 4,
                base_bytes: 12,
                mutated_bytes: 4,
            },
        )
        .await;
        assert!(second.is_ok());
        let Ok(second) = second else {
            return;
        };

        assert_ne!(first.storage_dir, second.storage_dir);
        assert!(first.storage_dir.starts_with(storage.path()));
        assert!(second.storage_dir.starts_with(storage.path()));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bench_rejects_mutation_window_larger_than_asset() {
        let storage = tempfile::tempdir();
        assert!(storage.is_ok());
        let Ok(storage) = storage else {
            return;
        };

        let report = run_bench(
            storage.path(),
            BenchConfig {
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                iterations: 1,
                concurrency: 1,
                upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
                chunk_size_bytes: 4,
                base_bytes: 8,
                mutated_bytes: 16,
            },
        )
        .await;
        assert!(matches!(
            report,
            Err(BenchRuntimeError::MutatedBytesExceedBaseBytes)
        ));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bench_rejects_zero_concurrency() {
        let storage = tempfile::tempdir();
        assert!(storage.is_ok());
        let Ok(storage) = storage else {
            return;
        };

        let report = run_bench(
            storage.path(),
            BenchConfig {
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::Full,
                iterations: 1,
                concurrency: 0,
                upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
                chunk_size_bytes: 4,
                base_bytes: 8,
                mutated_bytes: 4,
            },
        )
        .await;
        assert!(matches!(report, Err(BenchRuntimeError::ZeroConcurrency)));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ingest_bench_reports_upload_metrics() {
        let report = run_ingest_bench(BenchConfig {
            deployment_target: BenchDeploymentTarget::IsolatedLocal,
            scenario: BenchScenario::Full,
            iterations: 1,
            concurrency: 2,
            upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
            chunk_size_bytes: 4,
            base_bytes: 12,
            mutated_bytes: 4,
        })
        .await;
        assert!(report.is_ok());
        let Ok(report) = report else {
            return;
        };

        assert_eq!(report.iterations, 1);
        assert_eq!(report.concurrency, 2);
        assert_eq!(report.available_parallelism, available_parallelism_u64());
        assert_eq!(report.total_initial_inserted_chunks, 3);
        assert_eq!(report.total_sparse_update_inserted_chunks, 3);
        assert_eq!(report.total_concurrent_upload_inserted_chunks, 6);
        assert_eq!(report.total_concurrent_uploaded_bytes, 24);
        assert!(
            report.average_process_cpu_cores_per_mille
                >= report.average_process_host_utilization_per_mille
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn bench_can_focus_on_cross_repository_upload() {
        let storage = tempfile::tempdir();
        assert!(storage.is_ok());
        let Ok(storage) = storage else {
            return;
        };

        let report = run_bench(
            storage.path(),
            BenchConfig {
                deployment_target: BenchDeploymentTarget::IsolatedLocal,
                scenario: BenchScenario::CrossRepositoryUpload,
                iterations: 1,
                concurrency: 2,
                upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
                chunk_size_bytes: 4,
                base_bytes: 12,
                mutated_bytes: 4,
            },
        )
        .await;
        assert!(report.is_ok());
        let Ok(report) = report else {
            return;
        };

        assert_eq!(report.scenario, BenchScenario::CrossRepositoryUpload);
        assert_eq!(report.latency.initial_upload_micros, 0);
        assert_eq!(report.latency.sparse_update_upload_micros, 0);
        assert_eq!(report.latency.latest_download_micros, 0);
        assert_eq!(report.latency.previous_download_micros, 0);
        assert_eq!(report.latency.concurrent_upload_micros, 0);
        assert_eq!(report.totals.total_uploaded_bytes, 12);
        assert_eq!(report.totals.total_cross_repository_inserted_chunks, 1);
        assert_eq!(report.totals.total_cross_repository_reused_chunks, 2);
        assert_eq!(report.totals.total_cross_repository_newly_stored_bytes, 4);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn ingest_bench_rejects_unsupported_download_focus() {
        let report = run_ingest_bench(BenchConfig {
            deployment_target: BenchDeploymentTarget::IsolatedLocal,
            scenario: BenchScenario::LatestDownload,
            iterations: 1,
            concurrency: 2,
            upload_max_in_flight_chunks: DEFAULT_BENCH_UPLOAD_MAX_IN_FLIGHT_CHUNKS,
            chunk_size_bytes: 4,
            base_bytes: 12,
            mutated_bytes: 4,
        })
        .await;
        assert!(matches!(
            report,
            Err(BenchRuntimeError::UnsupportedScenarioForMode)
        ));
    }
}