pi_agent_rust 0.5.1

Native AI coding agent CLI - Rust port of Pi Agent
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
//! Shared performance-build metadata helpers for benchmark tooling.
//!
//! These helpers keep profile and allocator reporting consistent across
//! benchmark binaries, regression tests, and shell harnesses.

use serde::Deserialize;
use sha2::{Digest as _, Sha256};
use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::io::Read as _;
use std::path::{Path, PathBuf};

/// Environment variable that overrides benchmark build-profile metadata.
pub const BENCH_BUILD_PROFILE_ENV: &str = "PI_BENCH_BUILD_PROFILE";

/// Environment variable that requests an allocator label for benchmark runs.
pub const BENCH_ALLOCATOR_ENV: &str = "PI_BENCH_ALLOCATOR";

/// Release binary-size budget (MB) shared by perf regression and budget gates.
///
/// Raised 22.0 → 26.0 on 2026-08-16 with the FrankenSQLite cutover
/// (bd-oc1wu): the pure-Rust engine replaces libsqlite3-sys C code and costs
/// ~5.6 MiB of compiled core (parser/planner/VDBE/MVCC/pager) that LTO cannot
/// remove. Reclaim tracked in the follow-up size bead before tightening.
/// Raised 26.0 → 48.0 on 2026-08-21 for the v0.3.0 capability wave (BPE
/// token tables, LSP/DAP bridges, MCP client, eval kernels, web tools);
/// bd tracker holds the re-trim investigation.
pub const BINARY_SIZE_RELEASE_BUDGET_MB: f64 = 48.0;

/// Cargo profile family embedded by `build.rs` (`PROFILE`; custom release-derived
/// profiles are reported by Cargo as `release`).
pub const COMPILED_PROFILE_FAMILY: &str = env!("PI_BUILD_PROFILE_FAMILY");

/// Cargo optimization level embedded by `build.rs` (`OPT_LEVEL`).
pub const COMPILED_OPT_LEVEL: &str = env!("PI_BUILD_OPT_LEVEL");

/// Cargo debug-info switch embedded by `build.rs` (`DEBUG`).
pub const COMPILED_DEBUG: &str = env!("PI_BUILD_DEBUG");

/// Sorted, comma-separated package feature set embedded by `build.rs`.
pub const COMPILED_FEATURES_CSV: &str = env!("PI_BUILD_FEATURES");

/// Exact package feature set for the canonical shipping/system PiJS perf lane.
pub const CANONICAL_PIJS_PERF_FEATURES: &[&str] = &[
    "clipboard",
    "image",
    "image-resize",
    "sqlite-sessions",
    "wasm-host",
];

/// Versioned name for the authoritative Cargo build fingerprint contract.
pub const BUILD_FINGERPRINT_CONTRACT: &str = "cargo_build_fingerprint.v1";

/// Release-binary size measurement control emitted by the perf orchestrator.
pub const BINARY_SIZE_MEASUREMENT_SCHEMA: &str = "pi.perf.binary_size_measurement.v1";

/// Idle-process RSS measurement control consumed by the release budget gate.
pub const IDLE_RSS_MEASUREMENT_SCHEMA: &str = "pi.perf.idle_rss_measurement.v1";

/// Criterion cold-load measurement control emitted by the perf orchestrator.
pub const COLD_LOAD_MEASUREMENT_SCHEMA: &str = "pi.perf.cold_load_measurement.v1";

/// A measurement control can be absent, malformed, or valid-but-too-noisy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MeasurementControlError {
    Missing(PathBuf),
    Invalid(String),
    Noisy { observed: u8, maximum: u8 },
}

impl fmt::Display for MeasurementControlError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing(path) => write!(
                formatter,
                "measurement control is missing: {}",
                path.display()
            ),
            Self::Invalid(detail) => write!(formatter, "invalid measurement control: {detail}"),
            Self::Noisy { observed, maximum } => write!(
                formatter,
                "measurement control noise_score={observed} exceeds maximum={maximum}"
            ),
        }
    }
}

/// Verified release-binary size input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedBinarySizeMeasurement {
    pub control_path: PathBuf,
    pub control_sha256: String,
    pub source_commit: String,
    pub correlation_id: String,
    pub binary_path: PathBuf,
    pub binary_sha256: String,
    pub size_bytes: u64,
}

/// Verified Criterion cold-load input and its environment fingerprint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedColdLoadMeasurement {
    pub control_path: PathBuf,
    pub control_sha256: String,
    pub source_commit: String,
    pub correlation_id: String,
    pub artifact_path: PathBuf,
    pub artifact_sha256: String,
    pub bench_env_sha256: String,
    pub governor: String,
    pub aslr: String,
    pub thp: String,
    pub noise_score: u8,
}

/// Verified idle-process RSS input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedIdleRssMeasurement {
    pub control_path: PathBuf,
    pub control_sha256: String,
    pub source_commit: String,
    pub correlation_id: String,
    pub pid: u32,
    pub process_name: String,
    pub allocator: String,
    pub binary_path: PathBuf,
    pub binary_sha256: String,
    pub rss_bytes: u64,
    pub sample_count: usize,
    pub rss_spread_bytes: u64,
    pub settle_ms: u64,
    pub bench_env_sha256: String,
    pub governor: String,
    pub noise_score: u8,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct BinarySizeMeasurementControl {
    schema: String,
    generated_at: String,
    run_id: String,
    correlation_id: String,
    source_commit: String,
    source_dirty: bool,
    binary_path: String,
    binary_sha256: String,
    size_bytes: u64,
    cargo_profile: String,
    compiled_profile_family: String,
    compiled_opt_level: String,
    strip: bool,
    profile_source: String,
    build_command: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ColdLoadMeasurementControl {
    schema: String,
    generated_at: String,
    run_id: String,
    correlation_id: String,
    source_commit: String,
    source_dirty: bool,
    benchmark_exit_code: i32,
    max_noise_score: u8,
    bench_env_source: String,
    status: String,
    reason: Option<String>,
    bench_env: Option<BenchEnvMeasurementControl>,
    #[serde(default)]
    bench_env_sha256: Option<String>,
    measurements: BTreeMap<String, ColdLoadArtifactControl>,
}

#[derive(Debug, Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct BenchEnvMeasurementControl {
    os: String,
    arch: String,
    cpu_brand: String,
    cpu_cores: usize,
    mem_total_mb: u64,
    governor: String,
    turbo_boost: String,
    aslr: String,
    thp: String,
    noise_score: u8,
    config_hash: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ColdLoadArtifactControl {
    #[serde(rename = "artifact_path")]
    path: String,
    #[serde(rename = "artifact_sha256")]
    sha256: String,
    #[serde(rename = "artifact_size_bytes")]
    size_bytes: u64,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct IdleRssMeasurementControl {
    schema: String,
    generated_at: String,
    run_id: String,
    correlation_id: String,
    source_commit: String,
    source_dirty: bool,
    pid: u32,
    process_name: String,
    allocator: String,
    binary_path: String,
    binary_sha256: String,
    rss_bytes: u64,
    idle_state: String,
    cargo_profile: String,
    build_command: String,
    sample_count: usize,
    samples: Vec<IdleRssSampleControl>,
    rss_spread_bytes: u64,
    settle_ms: u64,
    bench_env_source: String,
    bench_env: BenchEnvMeasurementControl,
    bench_env_sha256: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct IdleRssSampleControl {
    pid: u32,
    process_name: String,
    rss_bytes: u64,
}

/// Independent build assertions carried by benchmark provenance.
#[derive(Debug, Clone, Copy)]
pub struct BenchmarkBuildVerification {
    pub executable_profile: bool,
    pub build_fingerprint: bool,
    pub build_profile: bool,
}

/// Inputs covered by the benchmark provenance configuration hash.
#[derive(Debug, Clone, Copy)]
pub struct BenchmarkProvenance<'a> {
    pub source_commit: &'a str,
    pub source_dirty: bool,
    pub build_profile: &'a str,
    pub executable_build_profile: &'a str,
    pub verification: BenchmarkBuildVerification,
    pub build_fingerprint_contract: &'a str,
    pub compiled_profile_family: &'a str,
    pub compiled_opt_level: &'a str,
    pub compiled_debug: &'a str,
    pub compiled_features: &'a [&'a str],
    pub binary_path: &'a str,
    pub binary_sha256: &'a str,
    pub debug_assertions: bool,
}

/// Effective allocator compiled into the current binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AllocatorKind {
    /// The platform/system allocator.
    System,
    /// `tikv-jemallocator` via the `jemalloc` Cargo feature.
    Jemalloc,
}

impl AllocatorKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::System => "system",
            Self::Jemalloc => "jemalloc",
        }
    }
}

/// Benchmark allocator selection metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AllocatorSelection {
    /// Requested allocator token (normalized).
    pub requested: String,
    /// Source of `requested` (`env` or `default`).
    pub requested_source: &'static str,
    /// Effective allocator compiled into this binary.
    pub effective: AllocatorKind,
    /// Optional explanation when request/effective do not match.
    pub fallback_reason: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RequestedAllocator {
    Auto,
    System,
    Jemalloc,
    Unknown,
}

/// Returns the allocator compiled into the current binary.
#[must_use]
pub const fn compiled_allocator() -> AllocatorKind {
    if cfg!(all(
        feature = "jemalloc",
        any(target_os = "linux", target_os = "macos")
    )) {
        AllocatorKind::Jemalloc
    } else {
        AllocatorKind::System
    }
}

/// Resolves benchmark allocator metadata from [`BENCH_ALLOCATOR_ENV`].
#[must_use]
pub fn resolve_bench_allocator() -> AllocatorSelection {
    let raw_value = std::env::var(BENCH_ALLOCATOR_ENV).ok();
    resolve_bench_allocator_from(raw_value.as_deref())
}

/// Resolves benchmark allocator metadata from an optional raw token.
#[must_use]
pub fn resolve_bench_allocator_from(raw_value: Option<&str>) -> AllocatorSelection {
    let requested_raw = raw_value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map_or_else(|| "auto".to_string(), str::to_ascii_lowercase);
    let requested_source = if raw_value
        .map(str::trim)
        .is_some_and(|value| !value.is_empty())
    {
        "env"
    } else {
        "default"
    };

    let requested_kind = match requested_raw.as_str() {
        "auto" | "default" => RequestedAllocator::Auto,
        "system" | "native" => RequestedAllocator::System,
        "jemalloc" | "je" => RequestedAllocator::Jemalloc,
        _ => RequestedAllocator::Unknown,
    };

    let effective = compiled_allocator();
    let fallback_reason = match requested_kind {
        RequestedAllocator::System if effective == AllocatorKind::Jemalloc => {
            Some("system requested but binary was built with --features jemalloc".to_string())
        }
        RequestedAllocator::Jemalloc if effective != AllocatorKind::Jemalloc => {
            Some("jemalloc requested but this target/build uses the system allocator".to_string())
        }
        RequestedAllocator::Unknown => Some(format!(
            "unknown allocator '{requested_raw}'; using compiled allocator '{}'",
            effective.as_str()
        )),
        RequestedAllocator::Auto | RequestedAllocator::System | RequestedAllocator::Jemalloc => {
            None
        }
    };

    let requested = match requested_kind {
        RequestedAllocator::System => "system".to_string(),
        RequestedAllocator::Jemalloc => "jemalloc".to_string(),
        RequestedAllocator::Auto => "auto".to_string(),
        RequestedAllocator::Unknown => requested_raw,
    };

    AllocatorSelection {
        requested,
        requested_source,
        effective,
        fallback_reason,
    }
}

/// Detects the benchmark build profile for reporting.
#[must_use]
pub fn detect_build_profile() -> String {
    let env_profile = std::env::var(BENCH_BUILD_PROFILE_ENV).ok();
    let current_exe = std::env::current_exe().ok();
    detect_build_profile_from(
        env_profile.as_deref(),
        current_exe.as_deref(),
        cfg!(debug_assertions),
    )
}

/// Detects build profile with injectable dependencies for tests.
#[must_use]
pub fn detect_build_profile_from(
    env_profile: Option<&str>,
    current_exe: Option<&Path>,
    debug_assertions: bool,
) -> String {
    if let Some(value) = env_profile.map(str::trim).filter(|value| !value.is_empty()) {
        return value.to_string();
    }

    if let Some(profile) = current_exe.and_then(profile_from_target_path) {
        return profile;
    }

    if debug_assertions {
        "debug".to_string()
    } else {
        "release".to_string()
    }
}

/// Returns the sorted package features compiled into this binary.
#[must_use]
pub fn compiled_feature_set() -> Vec<&'static str> {
    if COMPILED_FEATURES_CSV.is_empty() {
        Vec::new()
    } else {
        COMPILED_FEATURES_CSV.split(',').collect()
    }
}

/// Returns whether Cargo's authoritative build settings match the custom
/// `perf` profile fingerprint.
///
/// The profile's directory name is deliberately not trusted because Cargo
/// reports release-inheriting custom profiles through `PROFILE=release`.
#[must_use]
pub fn has_canonical_perf_build_fingerprint() -> bool {
    matches_canonical_perf_build_fingerprint(
        COMPILED_PROFILE_FAMILY,
        COMPILED_OPT_LEVEL,
        COMPILED_DEBUG,
    )
}

/// Checks an injected Cargo build fingerprint against the canonical `perf`
/// settings. This is public so evidence consumers and tests use one contract.
#[must_use]
pub fn matches_canonical_perf_build_fingerprint(
    profile_family: &str,
    opt_level: &str,
    debug: &str,
) -> bool {
    profile_family == "release" && opt_level == "3" && debug == "true"
}

/// Returns whether this binary has the exact package features used by the
/// canonical shipping/system PiJS performance lane.
#[must_use]
pub fn has_canonical_pijs_perf_features() -> bool {
    matches_canonical_pijs_perf_features(&compiled_feature_set())
}

/// Checks an injected sorted feature set against the canonical shipping/system
/// PiJS lane.
///
/// `image-resize` also enables the package's implicit `image` feature, so both
/// are intentionally present.
#[must_use]
pub fn matches_canonical_pijs_perf_features(features: &[&str]) -> bool {
    features == CANONICAL_PIJS_PERF_FEATURES
}

/// Computes the lowercase SHA-256 digest of a file without loading it all into
/// memory.
pub fn sha256_file(path: &Path) -> std::io::Result<String> {
    let mut file = std::fs::File::open(path)?;
    let mut hasher = Sha256::new();
    let mut buffer = [0_u8; 8 * 1024];
    loop {
        let read = file.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(crate::package_manager::hex_encode(&hasher.finalize()))
}

fn sha256_bytes(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    crate::package_manager::hex_encode(&hasher.finalize())
}

fn read_measurement_control<T: serde::de::DeserializeOwned>(
    path: &Path,
) -> Result<(PathBuf, String, T), MeasurementControlError> {
    let metadata = match std::fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Err(MeasurementControlError::Missing(path.to_path_buf()));
        }
        Err(error) => {
            return Err(MeasurementControlError::Invalid(format!(
                "cannot inspect {}: {error}",
                path.display()
            )));
        }
    };
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(MeasurementControlError::Invalid(format!(
            "{} must be a regular non-symlink file",
            path.display()
        )));
    }
    let canonical_path = std::fs::canonicalize(path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot canonicalize {}: {error}", path.display()))
    })?;
    let bytes = std::fs::read(&canonical_path).map_err(|error| {
        MeasurementControlError::Invalid(format!(
            "cannot read {}: {error}",
            canonical_path.display()
        ))
    })?;
    let control = serde_json::from_slice(&bytes).map_err(|error| {
        MeasurementControlError::Invalid(format!(
            "{} is not the exact expected JSON document: {error}",
            canonical_path.display()
        ))
    })?;
    Ok((canonical_path, sha256_bytes(&bytes), control))
}

fn validate_control_lineage(
    generated_at: &str,
    run_id: &str,
    correlation_id: &str,
    source_commit: &str,
    source_dirty: bool,
) -> Result<(), MeasurementControlError> {
    if chrono::DateTime::parse_from_rfc3339(generated_at).is_err() {
        return Err(MeasurementControlError::Invalid(
            "generated_at must be an RFC3339 timestamp".to_string(),
        ));
    }
    if run_id.is_empty() || run_id != correlation_id {
        return Err(MeasurementControlError::Invalid(
            "run_id and correlation_id must be the same non-empty value".to_string(),
        ));
    }
    if source_commit.len() != 40
        || !source_commit
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
        || source_commit.bytes().all(|byte| byte == b'0')
    {
        return Err(MeasurementControlError::Invalid(
            "source_commit must be a full lowercase nonzero Git SHA-1".to_string(),
        ));
    }
    if source_dirty {
        return Err(MeasurementControlError::Invalid(
            "source_dirty must be false for release-budget evidence".to_string(),
        ));
    }
    Ok(())
}

fn canonical_regular_path(path: &Path, field: &str) -> Result<PathBuf, MeasurementControlError> {
    if !path.is_absolute() {
        return Err(MeasurementControlError::Invalid(format!(
            "{field} must be absolute"
        )));
    }
    let metadata = std::fs::symlink_metadata(path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot inspect {field}: {error}"))
    })?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(MeasurementControlError::Invalid(format!(
            "{field} must identify a regular non-symlink file"
        )));
    }
    let canonical = std::fs::canonicalize(path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot canonicalize {field}: {error}"))
    })?;
    if canonical != path {
        return Err(MeasurementControlError::Invalid(format!(
            "{field} must already be canonical"
        )));
    }
    Ok(canonical)
}

fn measurement_artifact_path(
    claimed_path: &str,
    relocated_path: Option<&Path>,
    required_claimed_suffix: &Path,
    field: &str,
) -> Result<PathBuf, MeasurementControlError> {
    let claimed_path = PathBuf::from(claimed_path);
    if !claimed_path.is_absolute()
        || claimed_path.components().any(|component| {
            matches!(
                component,
                std::path::Component::CurDir | std::path::Component::ParentDir
            )
        })
    {
        return Err(MeasurementControlError::Invalid(format!(
            "{field} must claim an absolute normalized producer path"
        )));
    }
    if !claimed_path.ends_with(required_claimed_suffix) {
        return Err(MeasurementControlError::Invalid(format!(
            "{field} must end with the required producer path {}",
            required_claimed_suffix.display()
        )));
    }
    relocated_path.map_or_else(
        || canonical_regular_path(&claimed_path, field),
        |relocated_path| canonical_regular_path(relocated_path, field),
    )
}

fn validate_isolated_cold_load_producer_path(
    claimed_path: &str,
    extension: &str,
) -> Result<(), MeasurementControlError> {
    let path = Path::new(claimed_path);
    let components = path
        .components()
        .filter_map(|component| match component {
            std::path::Component::Normal(value) => value.to_str(),
            _ => None,
        })
        .collect::<Vec<_>>();
    let suffix = [
        "criterion_extensions",
        "ext_load_init",
        "load_init_cold",
        extension,
        "new",
        "estimates.json",
    ];
    if components.len() < suffix.len() + 3 {
        return Err(MeasurementControlError::Invalid(
            "artifact_path must identify an isolated criterion_extensions producer".to_string(),
        ));
    }
    let suffix_start = components.len() - suffix.len();
    let run_instance_id = components[suffix_start - 1];
    if components[suffix_start - 3] != "criterion"
        || components[suffix_start - 2] != "pi-perf-runs"
        || run_instance_id.len() != 64
        || !run_instance_id
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
        || components[suffix_start..] != suffix
    {
        return Err(MeasurementControlError::Invalid(format!(
            "artifact_path must identify criterion/pi-perf-runs/<run-instance>/criterion_extensions/ext_load_init/load_init_cold/{extension}/new/estimates.json"
        )));
    }
    Ok(())
}

fn validate_sha256(value: &str, field: &str) -> Result<(), MeasurementControlError> {
    if value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
    {
        return Ok(());
    }
    Err(MeasurementControlError::Invalid(format!(
        "{field} must be 64 lowercase hexadecimal characters"
    )))
}

/// Verify that the size input names and hashes the exact release binary and
/// proves the shipping profile's size-oriented Cargo settings.
pub fn verify_binary_size_measurement_control(
    control_path: &Path,
) -> Result<VerifiedBinarySizeMeasurement, MeasurementControlError> {
    verify_binary_size_measurement_control_with_relocated_artifact(control_path, None)
}

/// Verify a release-binary control while reading the measured bytes from a
/// digest-identical relocated evidence package.
///
/// The control's producer path is
/// preserved as provenance and must remain an absolute normalized path.
pub fn verify_binary_size_measurement_control_with_relocated_artifact(
    control_path: &Path,
    relocated_binary_path: Option<&Path>,
) -> Result<VerifiedBinarySizeMeasurement, MeasurementControlError> {
    let (control_path, control_sha256, control): (_, _, BinarySizeMeasurementControl) =
        read_measurement_control(control_path)?;
    if control.schema != BINARY_SIZE_MEASUREMENT_SCHEMA {
        return Err(MeasurementControlError::Invalid(format!(
            "schema must equal {BINARY_SIZE_MEASUREMENT_SCHEMA}"
        )));
    }
    validate_control_lineage(
        &control.generated_at,
        &control.run_id,
        &control.correlation_id,
        &control.source_commit,
        control.source_dirty,
    )?;
    if control.cargo_profile != "release"
        || control.compiled_profile_family != "release"
        || control.compiled_opt_level != "z"
        || !control.strip
        || control.profile_source != "Cargo.toml#profile.release"
        || control.build_command != "cargo build --bin pi --release"
    {
        return Err(MeasurementControlError::Invalid(
            "release binary must prove profile=release, opt-level=z, strip=true, and the canonical build command"
                .to_string(),
        ));
    }
    validate_sha256(&control.binary_sha256, "binary_sha256")?;
    let binary_path = measurement_artifact_path(
        &control.binary_path,
        relocated_binary_path,
        Path::new("release/pi"),
        "binary_path",
    )?;
    let metadata = std::fs::metadata(&binary_path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot inspect binary_path: {error}"))
    })?;
    if control.size_bytes == 0 || metadata.len() != control.size_bytes {
        return Err(MeasurementControlError::Invalid(format!(
            "size_bytes does not match binary_path (claimed={}, observed={})",
            control.size_bytes,
            metadata.len()
        )));
    }
    let observed_sha256 = sha256_file(&binary_path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot hash binary_path: {error}"))
    })?;
    if observed_sha256 != control.binary_sha256 {
        return Err(MeasurementControlError::Invalid(format!(
            "binary_sha256 does not match binary_path (claimed={}, observed={observed_sha256})",
            control.binary_sha256
        )));
    }
    Ok(VerifiedBinarySizeMeasurement {
        control_path,
        control_sha256,
        source_commit: control.source_commit,
        correlation_id: control.correlation_id,
        binary_path,
        binary_sha256: control.binary_sha256,
        size_bytes: control.size_bytes,
    })
}

/// Verify one extension's Criterion cold-load estimate against the exact
/// `benches/bench_env.rs` fingerprint captured by the same orchestrator run.
pub fn verify_cold_load_measurement_control(
    control_path: &Path,
    extension: &str,
) -> Result<VerifiedColdLoadMeasurement, MeasurementControlError> {
    verify_cold_load_measurement_control_with_relocated_artifact(control_path, extension, None)
}

/// Verify a cold-load control against an inventory-bound relocated Criterion
/// estimate while retaining the producer's absolute artifact path in the
/// control document.
pub fn verify_cold_load_measurement_control_with_relocated_artifact(
    control_path: &Path,
    extension: &str,
    relocated_artifact_path: Option<&Path>,
) -> Result<VerifiedColdLoadMeasurement, MeasurementControlError> {
    let (control_path, control_sha256, control): (_, _, ColdLoadMeasurementControl) =
        read_measurement_control(control_path)?;
    if control.schema != COLD_LOAD_MEASUREMENT_SCHEMA {
        return Err(MeasurementControlError::Invalid(format!(
            "schema must equal {COLD_LOAD_MEASUREMENT_SCHEMA}"
        )));
    }
    validate_control_lineage(
        &control.generated_at,
        &control.run_id,
        &control.correlation_id,
        &control.source_commit,
        control.source_dirty,
    )?;
    if control.benchmark_exit_code != 0
        || control.status != "verified"
        || control.reason.is_some()
        || control.bench_env_source != "benches/bench_env.rs"
        || control.max_noise_score != 0
    {
        return Err(MeasurementControlError::Invalid(
            "cold-load control must be a successful verified benches/bench_env.rs run with max_noise_score=0"
                .to_string(),
        ));
    }
    let bench_env = control
        .bench_env
        .ok_or_else(|| MeasurementControlError::Invalid("bench_env must be present".to_string()))?;
    let claimed_bench_env_sha256 = control.bench_env_sha256.ok_or_else(|| {
        MeasurementControlError::Invalid("bench_env_sha256 must be present".to_string())
    })?;
    validate_sha256(&claimed_bench_env_sha256, "bench_env_sha256")?;
    let bench_env = verify_bench_env_measurement(
        bench_env,
        &claimed_bench_env_sha256,
        control.max_noise_score,
    )?;
    let measurement = control.measurements.get(extension).ok_or_else(|| {
        MeasurementControlError::Invalid(format!(
            "measurements must contain extension {extension:?}"
        ))
    })?;
    validate_sha256(&measurement.sha256, "artifact_sha256")?;
    validate_isolated_cold_load_producer_path(&measurement.path, extension)?;
    let required_suffix = PathBuf::from(format!(
        "criterion_extensions/ext_load_init/load_init_cold/{extension}/new/estimates.json"
    ));
    let artifact_path = measurement_artifact_path(
        &measurement.path,
        relocated_artifact_path,
        &required_suffix,
        "artifact_path",
    )?;
    let artifact_metadata = std::fs::metadata(&artifact_path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot inspect artifact_path: {error}"))
    })?;
    if measurement.size_bytes == 0 || artifact_metadata.len() != measurement.size_bytes {
        return Err(MeasurementControlError::Invalid(format!(
            "artifact_size_bytes does not match artifact_path (claimed={}, observed={})",
            measurement.size_bytes,
            artifact_metadata.len()
        )));
    }
    let observed_artifact_sha256 = sha256_file(&artifact_path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot hash artifact_path: {error}"))
    })?;
    if observed_artifact_sha256 != measurement.sha256 {
        return Err(MeasurementControlError::Invalid(format!(
            "artifact_sha256 does not match artifact_path (claimed={}, observed={observed_artifact_sha256})",
            measurement.sha256
        )));
    }
    Ok(VerifiedColdLoadMeasurement {
        control_path,
        control_sha256,
        source_commit: control.source_commit,
        correlation_id: control.correlation_id,
        artifact_path,
        artifact_sha256: measurement.sha256.clone(),
        bench_env_sha256: claimed_bench_env_sha256,
        governor: bench_env.governor,
        aslr: bench_env.aslr,
        thp: bench_env.thp,
        noise_score: bench_env.noise_score,
    })
}

fn verify_bench_env_measurement(
    bench_env: BenchEnvMeasurementControl,
    claimed_sha256: &str,
    max_noise_score: u8,
) -> Result<BenchEnvMeasurementControl, MeasurementControlError> {
    if bench_env.os.is_empty()
        || bench_env.arch.is_empty()
        || bench_env.cpu_brand.is_empty()
        || bench_env.cpu_cores == 0
        || bench_env.mem_total_mb == 0
        || bench_env.governor.is_empty()
        || bench_env.turbo_boost.is_empty()
        || bench_env.aslr.is_empty()
        || bench_env.thp.is_empty()
    {
        return Err(MeasurementControlError::Invalid(
            "bench_env fields must be complete and non-empty".to_string(),
        ));
    }
    validate_sha256(&bench_env.config_hash, "bench_env.config_hash")?;
    let bench_env_value = serde_json::to_value(&bench_env).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot serialize bench_env: {error}"))
    })?;
    let bench_env_bytes = serde_json::to_vec(&bench_env_value).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot canonicalize bench_env: {error}"))
    })?;
    let observed_sha256 = sha256_bytes(&bench_env_bytes);
    if claimed_sha256 != observed_sha256 {
        return Err(MeasurementControlError::Invalid(format!(
            "bench_env_sha256 mismatch (claimed={claimed_sha256}, observed={observed_sha256})"
        )));
    }
    if bench_env.noise_score > max_noise_score {
        return Err(MeasurementControlError::Noisy {
            observed: bench_env.noise_score,
            maximum: max_noise_score,
        });
    }
    Ok(bench_env)
}

fn verify_idle_rss_samples(
    control: &IdleRssMeasurementControl,
) -> Result<(), MeasurementControlError> {
    if control.sample_count < 5 || control.sample_count != control.samples.len() {
        return Err(MeasurementControlError::Invalid(
            "idle RSS control requires sample_count >= 5 matching samples length".to_string(),
        ));
    }
    if !(100..=10_000).contains(&control.settle_ms) {
        return Err(MeasurementControlError::Invalid(
            "idle RSS settle_ms must be in 100..=10000".to_string(),
        ));
    }
    let mut unique_pids = HashSet::with_capacity(control.samples.len());
    let mut min_rss_bytes = u64::MAX;
    let mut max_rss_bytes = 0u64;
    for sample in &control.samples {
        if sample.pid == 0
            || sample.process_name != "pi"
            || sample.rss_bytes == 0
            || !unique_pids.insert(sample.pid)
        {
            return Err(MeasurementControlError::Invalid(
                "idle RSS samples require unique pid>0, process_name=pi, and rss_bytes>0"
                    .to_string(),
            ));
        }
        min_rss_bytes = min_rss_bytes.min(sample.rss_bytes);
        max_rss_bytes = max_rss_bytes.max(sample.rss_bytes);
    }
    if control.rss_bytes != max_rss_bytes
        || control.rss_spread_bytes != max_rss_bytes.saturating_sub(min_rss_bytes)
        || !control.samples.iter().any(|sample| {
            sample.pid == control.pid
                && sample.process_name == control.process_name
                && sample.rss_bytes == control.rss_bytes
        })
    {
        return Err(MeasurementControlError::Invalid(
            "idle RSS aggregate must identify the maximum sample and exact max-minus-min spread"
                .to_string(),
        ));
    }
    Ok(())
}

/// Verify that idle RSS was sampled from a real `pi` process and remains
/// bound to the exact measured executable and allocator.
pub fn verify_idle_rss_measurement_control(
    control_path: &Path,
) -> Result<VerifiedIdleRssMeasurement, MeasurementControlError> {
    verify_idle_rss_measurement_control_with_relocated_artifact(control_path, None)
}

/// Verify an idle-RSS control while resolving its measured executable from an
/// inventory-bound relocated evidence package.
pub fn verify_idle_rss_measurement_control_with_relocated_artifact(
    control_path: &Path,
    relocated_binary_path: Option<&Path>,
) -> Result<VerifiedIdleRssMeasurement, MeasurementControlError> {
    let (control_path, control_sha256, control): (_, _, IdleRssMeasurementControl) =
        read_measurement_control(control_path)?;
    if control.schema != IDLE_RSS_MEASUREMENT_SCHEMA {
        return Err(MeasurementControlError::Invalid(format!(
            "schema must equal {IDLE_RSS_MEASUREMENT_SCHEMA}"
        )));
    }
    validate_control_lineage(
        &control.generated_at,
        &control.run_id,
        &control.correlation_id,
        &control.source_commit,
        control.source_dirty,
    )?;
    if control.pid == 0
        || control.process_name != "pi"
        || !matches!(control.allocator.as_str(), "system" | "jemalloc")
        || control.rss_bytes == 0
        || control.idle_state != "startup_before_user_input"
        || control.cargo_profile != "release"
        || control.build_command != "cargo build --bin pi --release"
    {
        return Err(MeasurementControlError::Invalid(
            "idle RSS control requires a release-built pi process, a known allocator, rss_bytes>0, and the startup_before_user_input boundary"
                .to_string(),
        ));
    }
    verify_idle_rss_samples(&control)?;
    if control.bench_env_source != "benches/bench_env.rs" {
        return Err(MeasurementControlError::Invalid(
            "idle RSS bench_env_source must equal benches/bench_env.rs".to_string(),
        ));
    }
    validate_sha256(&control.bench_env_sha256, "bench_env_sha256")?;
    let bench_env = verify_bench_env_measurement(control.bench_env, &control.bench_env_sha256, 7)?;
    validate_sha256(&control.binary_sha256, "binary_sha256")?;
    let binary_path = measurement_artifact_path(
        &control.binary_path,
        relocated_binary_path,
        Path::new("release/pi"),
        "binary_path",
    )?;
    if binary_path.file_name().and_then(|name| name.to_str()) != Some("pi") {
        return Err(MeasurementControlError::Invalid(
            "idle RSS binary_path must identify the pi executable".to_string(),
        ));
    }
    let observed_binary_sha256 = sha256_file(&binary_path).map_err(|error| {
        MeasurementControlError::Invalid(format!("cannot hash binary_path: {error}"))
    })?;
    if observed_binary_sha256 != control.binary_sha256 {
        return Err(MeasurementControlError::Invalid(format!(
            "binary_sha256 does not match binary_path (claimed={}, observed={observed_binary_sha256})",
            control.binary_sha256
        )));
    }
    Ok(VerifiedIdleRssMeasurement {
        control_path,
        control_sha256,
        source_commit: control.source_commit,
        correlation_id: control.correlation_id,
        pid: control.pid,
        process_name: control.process_name,
        allocator: control.allocator,
        binary_path,
        binary_sha256: control.binary_sha256,
        rss_bytes: control.rss_bytes,
        sample_count: control.sample_count,
        rss_spread_bytes: control.rss_spread_bytes,
        settle_ms: control.settle_ms,
        bench_env_sha256: control.bench_env_sha256,
        governor: bench_env.governor,
        noise_score: bench_env.noise_score,
    })
}

/// Hashes asserted build/source/binary provenance as compact canonical JSON.
///
/// Evidence producers and consumers share this helper so field omissions or
/// serialization-order drift fail closed.
#[must_use]
pub fn benchmark_provenance_config_hash(provenance: &BenchmarkProvenance<'_>) -> String {
    let canonical = serde_json::json!({
        "binary_path": provenance.binary_path,
        "binary_sha256": provenance.binary_sha256,
        "build_fingerprint_contract": provenance.build_fingerprint_contract,
        "build_fingerprint_verified": provenance.verification.build_fingerprint,
        "build_profile": provenance.build_profile,
        "build_profile_verified": provenance.verification.build_profile,
        "compiled_debug": provenance.compiled_debug,
        "compiled_features": provenance.compiled_features,
        "compiled_opt_level": provenance.compiled_opt_level,
        "compiled_profile_family": provenance.compiled_profile_family,
        "debug_assertions": provenance.debug_assertions,
        "executable_build_profile": provenance.executable_build_profile,
        "executable_profile_verified": provenance.verification.executable_profile,
        "source_commit": provenance.source_commit,
        "source_dirty": provenance.source_dirty,
    });
    let bytes = serde_json::to_vec(&canonical)
        .expect("benchmark provenance contains only JSON-serializable primitives");
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    crate::package_manager::hex_encode(&hasher.finalize())
}

/// Attempts to derive the Cargo profile from an executable artifact layout.
///
/// This works with both the default `target/` directory and arbitrary
/// `CARGO_TARGET_DIR` values. Example/test artifacts live one level below the
/// profile in `examples/` or `deps/`; ordinary binaries live directly below it.
#[must_use]
pub fn profile_from_target_path(path: &Path) -> Option<String> {
    let artifact_parent = path.parent()?;
    let artifact_parent_name = artifact_parent.file_name()?.to_str()?;
    let profile_dir = if matches!(artifact_parent_name, "deps" | "examples") {
        artifact_parent.parent()?
    } else {
        artifact_parent
    };
    let candidate = profile_dir.file_name()?.to_str()?.trim();
    if candidate.is_empty() {
        return None;
    }

    Some(candidate.to_string())
}

/// Create a normalized target-relative output directory without traversing a
/// symlink.
///
/// RCH only returns selected subtrees beneath the active Cargo target,
/// so benchmark producers use this helper to place evidence in a supported
/// return path without trusting a controller-absolute environment value.
pub fn prepare_target_output_dir(target_dir: &Path, subdir: &Path) -> Result<PathBuf, String> {
    if subdir.as_os_str().is_empty()
        || subdir.is_absolute()
        || !subdir
            .components()
            .all(|component| matches!(component, std::path::Component::Normal(_)))
    {
        return Err(format!(
            "target output subdir must be a non-empty, normalized relative path: {}",
            subdir.display()
        ));
    }

    std::fs::create_dir_all(target_dir)
        .map_err(|error| format!("create CARGO_TARGET_DIR {}: {error}", target_dir.display()))?;
    let canonical_target = std::fs::canonicalize(target_dir).map_err(|error| {
        format!(
            "canonicalize CARGO_TARGET_DIR {}: {error}",
            target_dir.display()
        )
    })?;
    let output_dir = target_dir.join(subdir);
    let mut candidate = target_dir.to_path_buf();
    for component in subdir.components() {
        let std::path::Component::Normal(part) = component else {
            return Err(format!(
                "target output subdir contains an invalid component: {}",
                subdir.display()
            ));
        };
        candidate.push(part);
        let metadata = match std::fs::symlink_metadata(&candidate) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                std::fs::create_dir(&candidate).map_err(|create_error| {
                    format!(
                        "create target output component {}: {create_error}",
                        candidate.display()
                    )
                })?;
                std::fs::symlink_metadata(&candidate).map_err(|inspect_error| {
                    format!(
                        "inspect created target output component {}: {inspect_error}",
                        candidate.display()
                    )
                })?
            }
            Err(error) => {
                return Err(format!(
                    "inspect target output component {}: {error}",
                    candidate.display()
                ));
            }
        };
        if metadata.file_type().is_symlink() {
            return Err(format!(
                "target output subdir must not traverse a symlink: {}",
                candidate.display()
            ));
        }
        if !metadata.is_dir() {
            return Err(format!(
                "target output component is not a directory: {}",
                candidate.display()
            ));
        }
    }

    let canonical_output = std::fs::canonicalize(&output_dir).map_err(|error| {
        format!(
            "canonicalize target output subdir {}: {error}",
            output_dir.display()
        )
    })?;
    if !canonical_output.starts_with(&canonical_target) {
        return Err(format!(
            "target output subdir escapes CARGO_TARGET_DIR: {}",
            canonical_output.display()
        ));
    }
    Ok(canonical_output)
}

#[cfg(test)]
mod tests {
    use super::{
        AllocatorKind, BENCH_ALLOCATOR_ENV, BenchmarkBuildVerification, BenchmarkProvenance,
        MeasurementControlError, benchmark_provenance_config_hash, detect_build_profile_from,
        matches_canonical_perf_build_fingerprint, matches_canonical_pijs_perf_features,
        profile_from_target_path, resolve_bench_allocator_from,
        verify_binary_size_measurement_control,
        verify_binary_size_measurement_control_with_relocated_artifact,
        verify_cold_load_measurement_control,
        verify_cold_load_measurement_control_with_relocated_artifact,
        verify_idle_rss_measurement_control,
        verify_idle_rss_measurement_control_with_relocated_artifact,
    };
    use std::path::Path;

    const TEST_SOURCE_COMMIT: &str = "1234567890abcdef1234567890abcdef12345678";

    fn write_json(path: &Path, value: &serde_json::Value) {
        std::fs::write(
            path,
            serde_json::to_vec(value).expect("serialize test control"),
        )
        .expect("write test control");
    }

    #[test]
    fn binary_size_control_binds_exact_release_binary_and_profile() {
        let temp = tempfile::tempdir().expect("create test directory");
        // The verifier binds controls to the producer path `release/pi`.
        let binary_path = temp.path().join("release").join("pi");
        std::fs::create_dir_all(binary_path.parent().expect("release dir"))
            .expect("create release dir");
        std::fs::write(&binary_path, b"shipping release binary").expect("write release binary");
        let binary_path = std::fs::canonicalize(binary_path).expect("canonical binary path");
        let binary_sha256 = super::sha256_file(&binary_path).expect("hash release binary");
        let control_path = temp.path().join("binary-size.json");
        let control = serde_json::json!({
            "schema": super::BINARY_SIZE_MEASUREMENT_SCHEMA,
            "generated_at": "2026-08-24T00:00:00Z",
            "run_id": "test-run",
            "correlation_id": "test-run",
            "source_commit": TEST_SOURCE_COMMIT,
            "source_dirty": false,
            "binary_path": binary_path,
            "binary_sha256": binary_sha256,
            "size_bytes": 23,
            "cargo_profile": "release",
            "compiled_profile_family": "release",
            "compiled_opt_level": "z",
            "strip": true,
            "profile_source": "Cargo.toml#profile.release",
            "build_command": "cargo build --bin pi --release"
        });
        write_json(&control_path, &control);

        let verified = verify_binary_size_measurement_control(&control_path)
            .expect("valid release-binary control");
        assert_eq!(verified.size_bytes, 23);

        let relocated_binary_path = temp.path().join("relocated/pi");
        std::fs::create_dir_all(relocated_binary_path.parent().expect("relocated parent"))
            .expect("create relocated binary directory");
        std::fs::write(&relocated_binary_path, b"shipping release binary")
            .expect("write relocated release binary");
        let relocated_binary_path = std::fs::canonicalize(relocated_binary_path)
            .expect("canonicalize relocated release binary");
        let mut relocated_control = control;
        relocated_control["binary_path"] =
            serde_json::json!("/unavailable/producer/target/release/pi");
        let relocated_control_path = temp.path().join("binary-size-relocated.json");
        write_json(&relocated_control_path, &relocated_control);
        assert!(verify_binary_size_measurement_control(&relocated_control_path).is_err());
        let relocated = verify_binary_size_measurement_control_with_relocated_artifact(
            &relocated_control_path,
            Some(&relocated_binary_path),
        )
        .expect("relocated binary bytes satisfy the producer control");
        assert_eq!(relocated.binary_path, relocated_binary_path);

        relocated_control["binary_path"] =
            serde_json::json!("/unavailable/producer/target/debug/pi");
        write_json(&relocated_control_path, &relocated_control);
        let wrong_suffix = verify_binary_size_measurement_control_with_relocated_artifact(
            &relocated_control_path,
            Some(&relocated_binary_path),
        )
        .expect_err("digest-identical relocated bytes must not excuse a non-release producer path");
        assert!(
            wrong_suffix
                .to_string()
                .contains("binary_path must end with the required producer path release/pi")
        );

        std::fs::write(&binary_path, b"tampered release binary").expect("tamper release binary");
        assert!(matches!(
            verify_binary_size_measurement_control(&control_path),
            Err(MeasurementControlError::Invalid(_))
        ));
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn cold_load_control_rejects_noisy_or_tampered_criterion_input() {
        let temp = tempfile::tempdir().expect("create test directory");
        let run_instance_id = "a".repeat(64);
        let artifact_path = temp
            .path()
            .join("criterion/pi-perf-runs")
            .join(&run_instance_id)
            .join("criterion_extensions/ext_load_init/load_init_cold/hello/new/estimates.json");
        std::fs::create_dir_all(artifact_path.parent().expect("Criterion estimate parent"))
            .expect("create Criterion estimate directory");
        std::fs::write(&artifact_path, br#"{"mean":{"point_estimate":1000000}}"#)
            .expect("write Criterion estimate");
        let artifact_path = std::fs::canonicalize(artifact_path).expect("canonical Criterion path");
        let artifact_sha256 = super::sha256_file(&artifact_path).expect("hash Criterion estimate");
        let bench_env = serde_json::json!({
            "os": "linux",
            "arch": "x86_64",
            "cpu_brand": "fixture cpu",
            "cpu_cores": 8,
            "mem_total_mb": 16384,
            "governor": "performance",
            "turbo_boost": "disabled",
            "aslr": "enabled",
            "thp": "never",
            "noise_score": 0,
            "config_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        });
        let bench_env_sha256 = super::sha256_bytes(
            &serde_json::to_vec(&bench_env).expect("serialize benchmark environment"),
        );
        let control_path = temp.path().join("cold-load.json");
        let mut control = serde_json::json!({
            "schema": super::COLD_LOAD_MEASUREMENT_SCHEMA,
            "generated_at": "2026-08-24T00:00:00Z",
            "run_id": "test-run",
            "correlation_id": "test-run",
            "source_commit": TEST_SOURCE_COMMIT,
            "source_dirty": false,
            "benchmark_exit_code": 0,
            "max_noise_score": 0,
            "bench_env_source": "benches/bench_env.rs",
            "status": "verified",
            "reason": null,
            "bench_env": bench_env,
            "bench_env_sha256": bench_env_sha256,
            "measurements": {
                "hello": {
                    "artifact_path": artifact_path,
                    "artifact_sha256": artifact_sha256,
                    "artifact_size_bytes": 35
                }
            }
        });
        write_json(&control_path, &control);

        verify_cold_load_measurement_control(&control_path, "hello")
            .expect("quiet, bound Criterion control");

        let relocated_artifact_path = temp.path().join("relocated/estimates.json");
        std::fs::create_dir_all(relocated_artifact_path.parent().expect("relocated parent"))
            .expect("create relocated Criterion directory");
        std::fs::write(
            &relocated_artifact_path,
            br#"{"mean":{"point_estimate":1000000}}"#,
        )
        .expect("write relocated Criterion estimate");
        let relocated_artifact_path = std::fs::canonicalize(relocated_artifact_path)
            .expect("canonicalize relocated Criterion estimate");
        let mut relocated_control = control.clone();
        relocated_control["measurements"]["hello"]["artifact_path"] = serde_json::json!(format!(
            "/unavailable/producer/target/criterion/pi-perf-runs/{run_instance_id}/criterion_extensions/ext_load_init/load_init_cold/hello/new/estimates.json"
        ));
        let relocated_control_path = temp.path().join("cold-load-relocated.json");
        write_json(&relocated_control_path, &relocated_control);
        assert!(verify_cold_load_measurement_control(&relocated_control_path, "hello").is_err());
        let relocated = verify_cold_load_measurement_control_with_relocated_artifact(
            &relocated_control_path,
            "hello",
            Some(&relocated_artifact_path),
        )
        .expect("relocated Criterion bytes satisfy the producer control");
        assert_eq!(relocated.artifact_path, relocated_artifact_path);

        relocated_control["measurements"]["hello"]["artifact_path"] = serde_json::json!(format!(
            "/unavailable/producer/target/criterion/pi-perf-runs/{run_instance_id}/criterion_extensions/ext_load_init/load_init_cold/pirate/new/estimates.json"
        ));
        write_json(&relocated_control_path, &relocated_control);
        assert!(
            verify_cold_load_measurement_control_with_relocated_artifact(
                &relocated_control_path,
                "hello",
                Some(&relocated_artifact_path),
            )
            .is_err(),
            "digest-identical relocated bytes must not excuse the wrong producer suffix"
        );

        control["bench_env"]["noise_score"] = serde_json::json!(1);
        let noisy_env_sha256 = super::sha256_bytes(
            &serde_json::to_vec(&control["bench_env"]).expect("serialize noisy environment"),
        );
        control["bench_env_sha256"] = serde_json::json!(noisy_env_sha256);
        write_json(&control_path, &control);
        assert_eq!(
            verify_cold_load_measurement_control(&control_path, "hello"),
            Err(MeasurementControlError::Noisy {
                observed: 1,
                maximum: 0
            })
        );

        control["bench_env"]["noise_score"] = serde_json::json!(0);
        let quiet_env_sha256 = super::sha256_bytes(
            &serde_json::to_vec(&control["bench_env"]).expect("serialize quiet environment"),
        );
        control["bench_env_sha256"] = serde_json::json!(quiet_env_sha256);
        write_json(&control_path, &control);
        std::fs::write(&artifact_path, br#"{"mean":{"point_estimate":2000000}}"#)
            .expect("tamper Criterion estimate");
        assert!(matches!(
            verify_cold_load_measurement_control(&control_path, "hello"),
            Err(MeasurementControlError::Invalid(_))
        ));
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn idle_rss_control_binds_pi_process_allocator_and_executable() {
        let temp = tempfile::tempdir().expect("create test directory");
        // The verifier binds controls to the producer path `release/pi`.
        let binary_path = temp.path().join("release").join("pi");
        std::fs::create_dir_all(binary_path.parent().expect("release dir"))
            .expect("create release dir");
        std::fs::write(&binary_path, b"measured pi executable").expect("write Pi executable");
        let binary_path = std::fs::canonicalize(binary_path).expect("canonical Pi path");
        let binary_sha256 = super::sha256_file(&binary_path).expect("hash Pi executable");
        let control_path = temp.path().join("idle-rss.json");
        let bench_env = serde_json::json!({
            "os": "Linux",
            "arch": "x86_64",
            "cpu_brand": "fixture cpu",
            "cpu_cores": 8,
            "mem_total_mb": 16_384,
            "governor": "performance",
            "turbo_boost": "disabled",
            "aslr": "full",
            "thp": "never",
            "noise_score": 1,
            "config_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        });
        let typed_bench_env: super::BenchEnvMeasurementControl =
            serde_json::from_value(bench_env.clone()).expect("parse benchmark environment");
        let bench_env_sha256 = super::sha256_bytes(
            &serde_json::to_vec(
                &serde_json::to_value(&typed_bench_env).expect("normalize benchmark environment"),
            )
            .expect("serialize benchmark environment"),
        );
        let mut control = serde_json::json!({
            "schema": super::IDLE_RSS_MEASUREMENT_SCHEMA,
            "generated_at": "2026-08-24T00:00:00Z",
            "run_id": "test-run",
            "correlation_id": "test-run",
            "source_commit": TEST_SOURCE_COMMIT,
            "source_dirty": false,
            "pid": 4242,
            "process_name": "pi",
            "allocator": "system",
            "binary_path": binary_path,
            "binary_sha256": binary_sha256,
            "rss_bytes": 1_572_864,
            "idle_state": "startup_before_user_input",
            "cargo_profile": "release",
            "build_command": "cargo build --bin pi --release",
            "sample_count": 5,
            "samples": [
                {"pid": 4240, "process_name": "pi", "rss_bytes": 1_048_576},
                {"pid": 4241, "process_name": "pi", "rss_bytes": 1_179_648},
                {"pid": 4242, "process_name": "pi", "rss_bytes": 1_572_864},
                {"pid": 4243, "process_name": "pi", "rss_bytes": 1_310_720},
                {"pid": 4244, "process_name": "pi", "rss_bytes": 1_441_792}
            ],
            "rss_spread_bytes": 524_288,
            "settle_ms": 1_000,
            "bench_env_source": "benches/bench_env.rs",
            "bench_env": bench_env,
            "bench_env_sha256": bench_env_sha256
        });
        write_json(&control_path, &control);

        let verified =
            verify_idle_rss_measurement_control(&control_path).expect("valid idle RSS control");
        assert_eq!(verified.pid, 4242);
        assert_eq!(verified.sample_count, 5);
        assert_eq!(verified.rss_spread_bytes, 524_288);

        let relocated_binary_path = temp.path().join("relocated/pi");
        std::fs::create_dir_all(relocated_binary_path.parent().expect("relocated parent"))
            .expect("create relocated idle-RSS binary directory");
        std::fs::write(&relocated_binary_path, b"measured pi executable")
            .expect("write relocated idle-RSS binary");
        let relocated_binary_path = std::fs::canonicalize(relocated_binary_path)
            .expect("canonicalize relocated idle-RSS binary");
        let mut relocated_control = control.clone();
        relocated_control["binary_path"] =
            serde_json::json!("/unavailable/producer/target/release/pi");
        let relocated_control_path = temp.path().join("idle-rss-relocated.json");
        write_json(&relocated_control_path, &relocated_control);
        assert!(verify_idle_rss_measurement_control(&relocated_control_path).is_err());
        let relocated = verify_idle_rss_measurement_control_with_relocated_artifact(
            &relocated_control_path,
            Some(&relocated_binary_path),
        )
        .expect("relocated idle-RSS binary bytes satisfy the producer control");
        assert_eq!(relocated.binary_path, relocated_binary_path);

        relocated_control["binary_path"] =
            serde_json::json!("/unavailable/producer/target/debug/pi");
        write_json(&relocated_control_path, &relocated_control);
        let wrong_suffix = verify_idle_rss_measurement_control_with_relocated_artifact(
            &relocated_control_path,
            Some(&relocated_binary_path),
        )
        .expect_err("digest-identical relocated bytes must not excuse a non-release producer path");
        assert!(
            wrong_suffix
                .to_string()
                .contains("binary_path must end with the required producer path release/pi")
        );

        control["process_name"] = serde_json::json!("cargo-test");
        write_json(&control_path, &control);
        assert!(matches!(
            verify_idle_rss_measurement_control(&control_path),
            Err(MeasurementControlError::Invalid(_))
        ));

        control["process_name"] = serde_json::json!("pi");
        control["sample_count"] = serde_json::json!(4);
        control["samples"] = serde_json::json!([
            {"pid": 4240, "process_name": "pi", "rss_bytes": 1_048_576},
            {"pid": 4241, "process_name": "pi", "rss_bytes": 1_179_648},
            {"pid": 4242, "process_name": "pi", "rss_bytes": 1_572_864},
            {"pid": 4243, "process_name": "pi", "rss_bytes": 1_310_720}
        ]);
        write_json(&control_path, &control);
        assert!(matches!(
            verify_idle_rss_measurement_control(&control_path),
            Err(MeasurementControlError::Invalid(_))
        ));

        control["sample_count"] = serde_json::json!(5);
        control["samples"] = serde_json::json!([
            {"pid": 4240, "process_name": "pi", "rss_bytes": 1_048_576},
            {"pid": 4241, "process_name": "pi", "rss_bytes": 1_179_648},
            {"pid": 4242, "process_name": "pi", "rss_bytes": 1_572_864},
            {"pid": 4243, "process_name": "pi", "rss_bytes": 1_310_720},
            {"pid": 4244, "process_name": "pi", "rss_bytes": 1_441_792}
        ]);
        control["bench_env_sha256"] = serde_json::json!("0".repeat(64));
        write_json(&control_path, &control);
        assert!(matches!(
            verify_idle_rss_measurement_control(&control_path),
            Err(MeasurementControlError::Invalid(_))
        ));
    }

    #[test]
    fn detect_build_profile_prefers_env_override() {
        let profile = detect_build_profile_from(Some("perf"), None, true);
        assert_eq!(profile, "perf");
    }

    #[test]
    fn detect_build_profile_from_target_path_detects_profile() {
        let path = Path::new("/tmp/repo/target/perf/pijs_workload");
        let profile = detect_build_profile_from(None, Some(path), true);
        assert_eq!(profile, "perf");
    }

    #[test]
    fn detect_build_profile_falls_back_to_debug_or_release() {
        assert_eq!(detect_build_profile_from(None, None, true), "debug");
        assert_eq!(detect_build_profile_from(None, None, false), "release");
    }

    #[test]
    fn profile_from_target_path_detects_release_deps_binary() {
        let path = Path::new("/tmp/repo/target/release/deps/pijs_workload-abc123");
        assert_eq!(profile_from_target_path(path).as_deref(), Some("release"));
    }

    #[test]
    fn profile_from_target_path_detects_perf_example_binary() {
        let path = Path::new("/tmp/repo/target/perf/examples/pijs_workload");
        assert_eq!(profile_from_target_path(path).as_deref(), Some("perf"));
    }

    #[test]
    fn profile_from_target_path_detects_cross_target_perf_example_binary() {
        let path =
            Path::new("/tmp/repo/target/x86_64-unknown-linux-gnu/perf/examples/pijs_workload");
        assert_eq!(profile_from_target_path(path).as_deref(), Some("perf"));
    }

    #[test]
    fn profile_from_target_path_does_not_misclassify_moved_binary_as_perf() {
        let path = Path::new("/tmp/repo/pijs_workload");
        let derived = profile_from_target_path(path);
        assert_eq!(derived.as_deref(), Some("repo"));
        assert_ne!(derived.as_deref(), Some("perf"));
    }

    #[test]
    fn profile_from_target_path_uses_direct_artifact_parent_as_profile_hint() {
        let path = Path::new("/tmp/repo/bin/pijs_workload");
        assert_eq!(profile_from_target_path(path).as_deref(), Some("bin"));
    }

    #[test]
    fn profile_from_target_path_supports_arbitrary_cargo_target_dir() {
        let path = Path::new("/tmp/pi-build/perf/examples/pijs_workload");
        assert_eq!(profile_from_target_path(path).as_deref(), Some("perf"));
    }

    #[test]
    fn canonical_perf_fingerprint_distinguishes_perf_from_release() {
        assert!(matches_canonical_perf_build_fingerprint(
            "release", "3", "true"
        ));
        assert!(!matches_canonical_perf_build_fingerprint(
            "release", "z", "false"
        ));
        assert!(!matches_canonical_perf_build_fingerprint(
            "release", "3", "false"
        ));
        assert!(!matches_canonical_perf_build_fingerprint(
            "perf", "3", "true"
        ));
    }

    #[test]
    fn canonical_pijs_features_include_transitively_enabled_image_feature() {
        let canonical = [
            "clipboard",
            "image",
            "image-resize",
            "sqlite-sessions",
            "wasm-host",
        ];
        assert!(matches_canonical_pijs_perf_features(&canonical));

        let missing_implicit_image = ["clipboard", "image-resize", "sqlite-sessions", "wasm-host"];
        assert!(!matches_canonical_pijs_perf_features(
            &missing_implicit_image
        ));
    }

    #[test]
    fn benchmark_provenance_hash_binds_every_asserted_field() {
        let features = ["clipboard", "image"];
        let canonical = BenchmarkProvenance {
            source_commit: "0123456789abcdef0123456789abcdef01234567",
            source_dirty: false,
            build_profile: "perf",
            executable_build_profile: "perf",
            verification: BenchmarkBuildVerification {
                executable_profile: true,
                build_fingerprint: true,
                build_profile: true,
            },
            build_fingerprint_contract: "cargo_build_fingerprint.v1",
            compiled_profile_family: "release",
            compiled_opt_level: "3",
            compiled_debug: "true",
            compiled_features: &features,
            binary_path: "/tmp/pi-build/perf/examples/pijs_workload",
            binary_sha256: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            debug_assertions: false,
        };
        let first = benchmark_provenance_config_hash(&canonical);
        assert_eq!(first, benchmark_provenance_config_hash(&canonical));

        let dirty = BenchmarkProvenance {
            source_dirty: true,
            ..canonical
        };
        assert_ne!(first, benchmark_provenance_config_hash(&dirty));
        assert_eq!(first.len(), 64);
    }

    #[test]
    fn allocator_unknown_token_fails_closed_to_compiled_allocator() {
        let resolved = resolve_bench_allocator_from(Some("weird"));
        assert_eq!(resolved.requested, "weird");
        assert_eq!(resolved.requested_source, "env");
        assert_eq!(resolved.effective, super::compiled_allocator());
        assert!(resolved.fallback_reason.is_some());
    }

    #[test]
    fn allocator_auto_defaults_to_compiled_allocator() {
        let resolved = resolve_bench_allocator_from(None);
        assert_eq!(resolved.requested, "auto");
        assert_eq!(resolved.requested_source, "default");
        assert_eq!(resolved.effective, super::compiled_allocator());
        assert!(resolved.fallback_reason.is_none());
    }

    #[test]
    fn allocator_jemalloc_request_reports_compile_time_mismatch() {
        let resolved = resolve_bench_allocator_from(Some("jemalloc"));
        assert_eq!(resolved.requested, "jemalloc");
        if super::compiled_allocator() == AllocatorKind::Jemalloc {
            assert_eq!(resolved.effective, AllocatorKind::Jemalloc);
            assert!(resolved.fallback_reason.is_none());
        } else {
            assert_eq!(resolved.effective, AllocatorKind::System);
            assert!(
                resolved.fallback_reason.is_some(),
                "{BENCH_ALLOCATOR_ENV}=jemalloc should report fallback without compiled jemalloc"
            );
        }
    }

    #[test]
    fn allocator_system_request_reports_compile_time_mismatch() {
        let resolved = resolve_bench_allocator_from(Some("system"));
        assert_eq!(resolved.requested, "system");
        if super::compiled_allocator() == AllocatorKind::Jemalloc {
            assert_eq!(resolved.effective, AllocatorKind::Jemalloc);
            assert!(resolved.fallback_reason.is_some());
        } else {
            assert_eq!(resolved.effective, AllocatorKind::System);
            assert!(resolved.fallback_reason.is_none());
        }
    }

    // ── Property tests ──

    mod proptest_perf_build {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn resolve_allocator_effective_is_always_compiled(
                raw_value in prop::option::of("[a-z]{0,20}"),
            ) {
                let resolved = resolve_bench_allocator_from(raw_value.as_deref());
                assert!(
                    resolved.effective == super::super::compiled_allocator(),
                    "effective allocator must always be compiled allocator"
                );
            }

            #[test]
            fn resolve_allocator_known_tokens_have_no_unknown_fallback(
                token in prop::sample::select(vec![
                    "auto", "default", "system", "native", "jemalloc", "je",
                ]),
            ) {
                let resolved = resolve_bench_allocator_from(Some(token));
                // Known tokens never produce "unknown allocator" fallback
                if let Some(reason) = &resolved.fallback_reason {
                    assert!(
                        !reason.starts_with("unknown allocator"),
                        "known token '{token}' should not produce unknown fallback: {reason}"
                    );
                }
            }

            #[test]
            fn resolve_allocator_unknown_tokens_always_have_fallback(
                token in "[a-z]{3,10}".prop_filter(
                    "must not be known",
                    |t| !matches!(t.as_str(), "auto" | "default" | "system" | "native" | "jemalloc" | "je"),
                ),
            ) {
                let resolved = resolve_bench_allocator_from(Some(&token));
                assert!(
                    resolved.fallback_reason.is_some(),
                    "unknown token '{token}' must produce a fallback reason"
                );
                assert!(
                    resolved.requested == token,
                    "unknown token should be passed through as-is"
                );
            }

            #[test]
            fn resolve_allocator_empty_or_whitespace_defaults_to_auto(
                value in prop::sample::select(vec!["", " ", "  ", "\t"]),
            ) {
                let resolved = resolve_bench_allocator_from(Some(value));
                assert!(
                    resolved.requested == "auto",
                    "empty/whitespace should default to 'auto', got '{}'",
                    resolved.requested,
                );
                assert_eq!(resolved.requested_source, "default");
            }

            #[test]
            fn resolve_allocator_none_defaults_to_auto(_dummy in Just(())) {
                let resolved = resolve_bench_allocator_from(None);
                assert_eq!(resolved.requested, "auto");
                assert_eq!(resolved.requested_source, "default");
                assert!(resolved.fallback_reason.is_none());
            }

            #[test]
            fn profile_from_target_path_uses_artifact_parent_for_custom_target_dirs(
                dir in "[a-z]{1,10}",
                binary in "[a-z_]{1,10}",
            ) {
                let path_str = format!("/{dir}/{binary}");
                let path = Path::new(&path_str);
                assert!(
                    profile_from_target_path(path).as_deref() == Some(dir.as_str()),
                    "direct artifact should use its parent as profile: {path_str}"
                );
            }

            #[test]
            fn profile_from_target_path_extracts_profile(
                profile in "[a-z]{3,10}",
                binary in "[a-z_]{3,10}",
            ) {
                let path_str = format!("/repo/target/{profile}/{binary}");
                let path = Path::new(&path_str);
                let result = profile_from_target_path(path);
                assert!(
                    result == Some(profile.clone()),
                    "expected Some(\"{profile}\"), got {result:?} for path {path_str}"
                );
            }

            #[test]
            fn detect_build_profile_env_overrides_all(
                env_val in "[a-z]{1,15}",
            ) {
                let result = detect_build_profile_from(
                    Some(&env_val),
                    Some(Path::new("/target/release/bin")),
                    true,
                );
                assert!(
                    result == env_val,
                    "env override should take priority: expected '{env_val}', got '{result}'"
                );
            }

            #[test]
            fn allocator_kind_as_str_is_stable(
                kind in prop::sample::select(vec![
                    AllocatorKind::System,
                    AllocatorKind::Jemalloc,
                ]),
            ) {
                let s1 = kind.as_str();
                let s2 = kind.as_str();
                assert!(s1 == s2, "as_str must be deterministic");
                assert!(
                    s1 == "system" || s1 == "jemalloc",
                    "as_str must return known value: {s1}"
                );
            }
        }
    }
}