gras 2.0.1

A Genetic Programming framework for Neural Architecture Search in Rust
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
//! On-disk run state: `engine.json` is the header, `nets/<hash>.json` the snapshots.

use std::collections::HashMap;
use std::path::Path;

use flodl::tensor::Result;
use serde::{Deserialize, Serialize};

use crate::engine::config::RaceConfig;
use crate::graph::topology::{Topology, TopologyOptions};
use crate::utils::error::EngineError;
use crate::utils::fitness::{Direction, FitnessLabel, Metric};
use crate::utils::seed::topo_hash;

// ── Run header (engine.json) ───────────────────────────────────────────────

/// The run's **complete** configuration, serialized into `engine.json` under
/// `"config"` — the single source of truth; the file alone reproduces the run.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ConfigSnapshot {
    /// Population size the race held constant.
    pub pop_size: usize,
    /// Steps between population checkpoints.
    pub checkpoint_every: usize,
    /// Share of the population each channel replaces per clock; `0.0` = off.
    #[serde(default)]
    pub crossover_share: f32,
    #[serde(default)]
    pub mutation_share: f32,
    /// Crossover replacement policy (`"worst"` | `"random"`). Crossover-only —
    /// mutation channel has its own knob, recorded just below.
    pub crossover_cull_policy: String,
    /// Mutation replacement policy (`"worst"` | `"random"`), the channel's
    /// own knob — it decides which net a fresh immigrant replaces, so a reader cannot reconstruct
    #[serde(default = "default_mutation_cull_policy")]
    pub mutation_cull_policy: String,
    /// Top-k live nets saved as champions at stop.
    #[serde(default)]
    pub champion_count: usize,
    /// Crossover operator pool (`"one_point"`/`"uniform"`); empty ⇒ both.
    pub crossover_ops_pool: Vec<String>,
    /// Crossover parent-selection method, as its `Display` label (`"roulette"` /
    /// `"tournament(size=3)"`).
    #[serde(default)]
    pub crossover_selection: String,
    /// Stop budget as configured (`None` = no limit). Duplicated at the header root;
    /// this copy is authoritative.
    #[serde(default)]
    pub max_steps: Option<usize>,
    /// Whether a pluggable `custom_stop` closure was installed. The closure
    /// code, not data, so only its presence is recordable.
    pub has_custom_stop: bool,
    /// Per-step verbosity (`"none"` | `"summ"` | `"minimal"`).
    pub log_level: String,
    /// Whether the run wrote the `telemetry.jsonl` event sidecar
    /// (`#[serde(default)]` so pre-knob `engine.json` files still load).
    #[serde(default)]
    pub trace_file: bool,
    /// Problem-space target (`"tabular"` | `"onecimage"` | `"threecimage"` |
    /// `"nlp"` | `"rl"`).
    pub mode: String,
    /// Effective shared-stream geometry after the trainer's `stream_shape()` override.
    /// `None` in modes with no shared stream (RL).
    pub batch_size: Option<usize>,
    /// Effective eval batch size (`None` when the mode has no shared stream).
    pub eval_batch_size: Option<usize>,
    /// Per-net fitness smoothing window (K).
    pub smoothing_window: usize,
    /// How the smoothing window was averaged into the ranking centre (`set_fitness_mean_type`:
    /// `"arithmetic"` | `"signed_log"` | `"median"`).
    #[serde(default)]
    pub mean_type: String,
    /// Metrics that feed the ranking (`set_selection_metric`): label + weight, in ranking order.
    /// Empty = fitness only, which is every header written before the knob.
    #[serde(default)]
    pub selection_metrics: Vec<crate::utils::fitness::SelectionMetric>,
    /// Device the run executed on (`"cpu"` | `"cuda:0"`).
    pub device: String,
    /// Whether the lossless per-step `metrics.csv` was written.
    pub csv_export: bool,
    /// Whether optimizer state rode the checkpoint (see `RaceConfig::save_optim`).
    #[serde(default)]
    pub save_optim: bool,
    /// Human label for the experiment (`set_run_name`), verbatim. Purely
    /// informative — never affects the results folder name.
    pub run_name: Option<String>,
    /// Lottery floor `p_min`: the worst net's chance of a ticket each clock.
    #[serde(default)]
    pub train_merit_p_min: f32,
    /// Lottery ceiling `p_max`: the best net's chance of a ticket each clock.
    #[serde(default = "default_p_max")]
    pub train_merit_p_max: f32,
    /// The lottery's legs, e.g. `most_fit_fewest_updates` (`""` = the default).
    #[serde(default)]
    pub train_ticket: String,
    /// LEARN-ONLY lottery (`set_ticket_learn_only`): `true` = a lost ticket costs the weight update, not the clock (the net acts and is measured anyway). `default` = `false`…
    #[serde(default)]
    pub train_merit_learn_only: bool,
    /// `true` = rank only on readings from the weights the net holds now.
    #[serde(default)]
    pub policy_scoped_fitness: bool,
    /// ANTI-CHAMPION dump (`set_worst_save_topology`): `true` writes the `spent`-ranked nets'
    /// markdown at stop. `default` = `false` for every header written before the knob.
    #[serde(default)]
    pub worst_save_topology: bool,
    /// Fitter parent as the crossover base (`set_crossover_fitter_base`): `true` (the default)
    /// orders both drawn parents best-first, so the child keeps the BETTER one's skeleton.
    #[serde(default)]
    pub crossover_fitter_base: bool,
    /// Chance each inherited gene is re-drawn on a crossover child.
    #[serde(default)]
    pub drift_prob: f32,
    /// Write the champions' topology markdown at stop.
    #[serde(default = "default_true")]
    pub champion_save_topology: bool,
    /// Novelty floor `d_min` for a mutation draw (`set_mutation_novelty_min`). Replay-relevant:
    /// `0.0` is what a header written before the gate recorded.
    #[serde(default)]
    pub mutation_novelty_min: f32,
    /// Candidates one mutation may spend clearing that floor (`set_mutation_novelty_draws`).
    #[serde(default)]
    pub mutation_novelty_draws: usize,
    /// Mutation probation steps: cull-immunity for an immigrant until it has spent k UPDATES
    /// (`U`), not clocks. Replay-relevant.
    #[serde(default)]
    pub mutation_probation_steps: usize,
    /// Crossover probation steps: cull-immunity for a crossover child until it has spent k UPDATES
    /// (`U`). Replay-relevant.
    #[serde(default)]
    pub crossover_probation_steps: usize,
    /// INIT PROBATION (`set_pop_init_probation_steps`): opening clocks with no culls or births.
    #[serde(default)]
    pub init_probation_steps: usize,
    /// Extra real updates one clock may run to recover a falling net (`0` = off).
    #[serde(default)]
    pub recovery_retries: usize,
    /// Recovery tolerance: the fraction of the standing a reading may lose before a rescue. A
    /// header written before the knob reads `0.0` (every drop triggers). Replay-relevant.
    #[serde(default)]
    pub recovery_tolerance: f32,
    /// Recovery retry DRAW (`set_pop_recovery_same_seed`): `true` = a retry repeats the clock's own train draw.
    #[serde(default = "default_true")]
    pub recovery_same_seed: bool,
    /// The input feature-split policy the run drew masks from (`"split_exclusive"` /
    /// `"split_random"`); `None` = no split
    #[serde(default)]
    pub feature_split: Option<String>,
    /// The feature-split POOL the run drew newborn splits from, in draw order (`"none"`,
    /// `"split_random"`, `"split_exclusive"`).
    #[serde(default)]
    pub feature_split_pool: Vec<String>,
    /// Seed the first founders from the newest compatible previous run.
    #[serde(default)]
    pub champion_previous_load: bool,
    /// Where that run is looked up: a run dir or a dir of run dirs (`None` = `results/`).
    #[serde(default)]
    pub champion_previous_dir: Option<String>,
    /// One-line identity of the binary that produced the run (version, profile, exe
    /// path, build time). Diagnostics
    #[serde(default)]
    pub build: String,
}

impl ConfigSnapshot {
    /// Capture every knob from a run's config plus the effective stream shape
    /// (`None`/`None` for modes with no shared stream — see the fields).
    pub fn from_config(
        cfg: &RaceConfig,
        batch_size: Option<usize>,
        eval_batch_size: Option<usize>,
    ) -> Self {
        let split_pool = cfg.feature_split_pool_names();
        // One policy is also recorded on the single-value field, so readers written
        // before the pool (and the Python tests that assert on it) keep working.
        let split_single = if split_pool.len() == 1 {
            Some(split_pool[0].clone())
        } else {
            None
        };
        ConfigSnapshot {
            pop_size: cfg.pop_size,
            checkpoint_every: cfg.checkpoint_every,
            crossover_share: cfg.crossover_share,
            mutation_share: cfg.mutation_share,
            crossover_cull_policy: cfg.crossover_cull_policy.to_string(),
            mutation_cull_policy: cfg.mutation_cull_policy.to_string(),
            champion_count: cfg.champion_count,
            crossover_ops_pool: cfg.crossover_ops_pool.clone(),
            crossover_selection: cfg.crossover_selection.to_string(),
            mutation_novelty_min: cfg.mutation_novelty_min,
            mutation_novelty_draws: cfg.mutation_novelty_draws,
            max_steps: cfg.max_steps,
            has_custom_stop: cfg.custom_stop.is_some(),
            log_level: format!("{:?}", cfg.log_level).to_lowercase(),
            trace_file: cfg.trace_file,
            mode: format!("{:?}", cfg.mode).to_lowercase(),
            batch_size,
            eval_batch_size,
            smoothing_window: cfg.smoothing_window,
            mean_type: cfg.mean_type.to_string(),
            selection_metrics: cfg.selection_metrics.clone(),
            device: if cfg!(feature = "cuda") {
                "cuda:0"
            } else {
                "cpu"
            }
            .to_string(),
            csv_export: cfg.csv_export,
            save_optim: cfg.save_optim,
            run_name: cfg.run_name.clone(),
            train_merit_p_min: cfg.train_merit_p_min,
            train_merit_p_max: cfg.train_merit_p_max,
            train_ticket: cfg.train_ticket.to_string(),
            train_merit_learn_only: cfg.train_merit_learn_only,
            policy_scoped_fitness: cfg.policy_scoped_fitness,
            worst_save_topology: cfg.worst_save_topology,
            crossover_fitter_base: cfg.crossover_fitter_base,
            champion_previous_load: cfg.champion_previous_load,
            champion_previous_dir: cfg
                .champion_previous_dir
                .as_ref()
                .map(|p| p.display().to_string()),
            champion_save_topology: cfg.champion_save_topology,
            mutation_probation_steps: cfg.mutation_probation_steps,
            crossover_probation_steps: cfg.crossover_probation_steps,
            init_probation_steps: cfg.init_probation_steps,
            recovery_retries: cfg.recovery_retries,
            recovery_tolerance: cfg.recovery_tolerance,
            recovery_same_seed: cfg.recovery_same_seed,
            feature_split: split_single,
            feature_split_pool: split_pool,
            drift_prob: cfg.drift_prob,
            build: crate::engine::format::build_stamp(),
        }
    }
}

/// Which previous experiment this run's founder batch was seeded from — the inheritance
/// receipt (informational; the copied topology is recorded per net like any founder).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SeedSourceRecord {
    /// The source run's id (its `results/<id>` directory name).
    pub source_run_id: String,
    /// Directory the source was read from (as resolved).
    pub source_dir: String,
    /// The source run's rank-1 net at its final table — the one copied first.
    pub champion_hash: String,
    /// That champion's parameter count (the tie-break key).
    #[serde(default)]
    pub champion_params: Option<i64>,
    /// Every founder reinstated here, best first (`[0]` = `champion_hash`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub elite_hashes: Vec<String>,
}

/// The reproducible run header, serialized as `engine.json`. Overwritten
/// reproducibility-affecting config changes; the seed receipt is preserved.
#[derive(Clone, Debug, Serialize)]
pub struct RunHeader {
    /// User-visible run id (directory name or CLI-chosen label).
    pub run_id: String,
    /// Mode (`"tabular"` | `"rl"`) at the header root, so a resume need not read the config.
    #[serde(default)]
    pub engine_mode: Option<String>,
    /// Dataset directory the run was launched from (one-argument resume). `None`
    /// RL runs and on headers written before this field existed.
    #[serde(default)]
    pub data_dir: Option<String>,
    /// Single deterministic root for the whole run; generated and recorded when no seed
    /// is given, so an interrupted run can be resumed exactly.
    pub run_seed: u64,
    /// Fitness label used for ranking (e.g. `"f1"`, `"cross_entropy"`).
    pub fitness_label: FitnessLabel,
    /// Whether lower or higher fitness is better.
    pub fitness_direction: Direction,
    /// Dataset dims the run was launched with (informational; the stream
    /// derives its pool from the actual dataset on disk).
    pub input_dim: usize,
    /// Output dimension the run was built
    pub output_dim: usize,
    /// Topology template + GP-pool knobs the run was launched
    pub topology_options: TopologyOptions,
    /// Hidden-dim sampling range.
    pub hidden_dim_pool: String,
    /// Hidden-dim stride used when sampling.
    pub hidden_dim_stride: usize,
    /// Combine/activation/standardize pools actually used by the run.
    pub combine_op_pool: Vec<String>,
    /// Activation pool the run drew
    pub activation_pool: Vec<String>,
    /// Standardize-op pool the run drew
    pub standardize_op_pool: Vec<String>,
    /// Informative (non-ranking) metrics configured for the run; their labels determine
    /// the extra per-net metric columns.
    pub informative_metrics: Vec<String>,
    /// Stop criteria / budgets. The scheduler honors them and `config` carries
    /// authoritative copy; the stopped-by fact is in `history.csv` / the stop banner.
    pub max_steps: Option<usize>,
    /// When the run was started (wall clock), for human-readability.
    pub started_at: Option<String>,
    /// Train/eval split ratio recorded for the run.
    pub train_eval_split_ratio: Option<f32>,
    /// The EVAL-PERMUTATION era length, in clocks, as the run actually used
    #[serde(default)]
    pub eval_era_every: Option<usize>,
    /// Cumulative culls at the last stop — restored on resume so the cull budget
    /// continues. `0` on legacy files.
    #[serde(default)]
    pub culls: usize,
    /// Accumulated wall-clock seconds at the last stop — restored on resume as the base
    /// offset. `0` on legacy files.
    #[serde(default)]
    pub run_elapsed_secs: u64,
    /// Children born per step clock at the last stop (same-clock siblings get
    /// distinct child seeds). Restored on resume; empty on legacy files.
    #[serde(default)]
    pub children_born_at_clock: std::collections::HashMap<usize, usize>,
    /// Data layout: `None` = single-pool seeded split; `Some(n)` = explicit two-role layout
    /// `n` RANKING-pool rows after the train rows.
    #[serde(default)]
    pub explicit_test_rows: Option<usize>,
    /// Which subdirectory the run RANKED on: `"val"` (train/val/test), `"test"` (train/test)
    /// `None` (one pool, split by `eval_share`).
    #[serde(default)]
    pub eval_split: Option<String>,
    /// EXAM rows: the one dataset the race never reads.
    #[serde(default)]
    pub exam_rows: Option<usize>,
    /// The run's complete configuration (see [`ConfigSnapshot`]).
    /// authoritative settings record — `engine.json` alone reproduces a run.
    #[serde(default)]
    pub config: ConfigSnapshot,
    /// The training scheme's self-description from `Trainer::describe()` — persisted
    /// verbatim, never interpreted. `None` on legacy files.
    #[serde(default)]
    pub trainer: Option<serde_json::Value>,
    /// The previous experiment this run's founder batch was seeded from (see
    /// [`SeedSourceRecord`]). `None` = an all-random batch: nothing was inherited.
    #[serde(default)]
    pub run_topology_source: Option<SeedSourceRecord>,
    /// What the run DID to its population (see [`RunAccounting`]). Written
    /// stop; absent on a running or legacy run.
    #[serde(default)]
    pub accounting: Option<RunAccounting>,
}

/// The run's tally of what its evolution actually did — births, deaths and what the roll
/// batches bought. Counters of the WRITING process; the frontier is the cross-session record.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunAccounting {
    /// Every net this process created: the initial batch plus each insert.
    pub born: usize,
    /// Initial-batch split: random founders vs nets inherited from a previous
    /// run's `champions.json` (`created_from = seed:<run>:<hash>`).
    pub founders: usize,
    /// Founders that came from an inherited run.
    pub inherited_founders: usize,
    /// Nets born from an evolution roll, by channel.
    pub crossover_children: usize,
    /// UNIFORM-crossover exchange totals: births that reported a count, genes the operator flipped,
    /// and genes it compared.
    #[serde(default)]
    pub uniform_cx_births: usize,
    /// Genes taken from the other parent, summed over those births.
    #[serde(default)]
    pub uniform_cx_swaps: usize,
    /// Aligned genes compared, summed over those births.
    #[serde(default)]
    pub uniform_cx_pairs: usize,
    /// Random immigrants inserted.
    pub immigrants: usize,
    /// Culls by the slot they freed — `crossover` (any policy: `crossover-random`,
    /// `crossover-unfed`, …) or `immigrant-slot`; the two parts sum to this total.
    pub culls: usize,
    /// Culls that freed a slot for a crossover child.
    pub culls_crossover: usize,
    /// Culls that freed a slot for a mutation immigrant.
    pub culls_immigrant: usize,
    /// Crossover roll batch: rolls offered/fired, attempts made, rolls discarded after
    /// retry budget.
    pub crossover_rolls: usize,
    /// Crossover rolls that fired.
    pub crossover_fired: usize,
    /// Crossover generate attempts made.
    pub crossover_attempts: usize,
    /// Crossover rolls discarded after the retry budget.
    pub crossover_discarded: usize,
    /// Mutation roll batch: rolls offered, rolls that fired and built
    /// immigrant, and rolls the hard shield refused (no cull-eligible victim).
    pub mutation_rolls: usize,
    /// Mutation rolls that fired.
    pub mutation_fired: usize,
    /// Mutation rolls skipped by the shield (no cullable victim).
    pub mutation_blocked: usize,
    /// Clocks whose whole roll batch was forgone because no live net was cull-eligible.
    pub deferred_clocks: usize,
}

/// Everything that defines a step-race run's reproducible configuration —
/// the field-by-field input to [`RunHeader::from_race_options`].
#[derive(Debug)]
pub struct RunConfig {
    /// Timestamped run id (also the run dir name).
    pub run_id: String,
    /// The dataset directory a TABULAR run was launched from — recorded so a resume
    /// can find its data with no second argument. `None` for RL runs.
    pub data_dir: Option<String>,
    /// Mode discriminator (`"tabular"` | `"rl"`) — see [`RunHeader::engine_mode`].
    pub engine_mode: Option<String>,
    /// Deterministic seed for the whole run.
    pub run_seed: u64,
    /// Ranking fitness label.
    pub fitness_label: FitnessLabel,
    /// Ranking direction (maximize/minimize).
    pub fitness_direction: Direction,
    /// Input feature dimension.
    pub input_dim: usize,
    /// Output dimension.
    pub output_dim: usize,
    /// The topology template options.
    pub topology_options: TopologyOptions,
    /// Hidden-dim pool the run sampled
    pub hidden_dim_pool: std::ops::RangeInclusive<usize>,
    /// Hidden-dim stride.
    pub hidden_dim_stride: usize,
    /// Combine-op pool.
    pub combine_op_pool: Vec<String>,
    /// Activation pool.
    pub activation_pool: Vec<String>,
    /// Standardize-op pool.
    pub standardize_op_pool: Vec<String>,
    /// Informative (non-ranking) metrics.
    pub informative_metrics: Vec<Metric>,
    /// Step budget as configured (`None` = no limit).
    pub max_steps: Option<usize>,
    /// Train/eval split ratio.
    pub train_eval_split_ratio: Option<f32>,
    /// See [`RunHeader::explicit_test_rows`].
    pub explicit_test_rows: Option<usize>,
    /// See [`RunHeader::eval_split`].
    pub eval_split: Option<String>,
    /// See [`RunHeader::exam_rows`].
    pub exam_rows: Option<usize>,
    /// Cumulative culls at the last stop.
    pub culls: usize,
    /// Accumulated wall-clock seconds at the last stop.
    pub run_elapsed_secs: u64,
    /// Children born per clock (persisted counter).
    pub children_born_at_clock: std::collections::HashMap<usize, usize>,
    /// The run's complete configuration (see [`ConfigSnapshot`]).
    pub config: ConfigSnapshot,
    /// The training scheme's self-description (see `Trainer::describe`).
    pub trainer: Option<serde_json::Value>,
}

impl RunHeader {
    /// Build the header from the run's launch config.
    pub fn from_race_options(cfg: RunConfig) -> Self {
        let RunConfig {
            run_id,
            data_dir,
            engine_mode,
            run_seed,
            fitness_label,
            fitness_direction,
            input_dim,
            output_dim,
            topology_options,
            hidden_dim_pool,
            hidden_dim_stride,
            combine_op_pool,
            activation_pool,
            standardize_op_pool,
            informative_metrics,
            max_steps,
            train_eval_split_ratio,
            explicit_test_rows,
            eval_split,
            exam_rows,
            culls,
            run_elapsed_secs,
            children_born_at_clock,
            config,
            trainer,
        } = cfg;
        RunHeader {
            run_id,
            data_dir,
            engine_mode,
            run_seed,
            fitness_label,
            fitness_direction,
            input_dim,
            output_dim,
            topology_options,
            hidden_dim_pool: format!("{}..={}", hidden_dim_pool.start(), hidden_dim_pool.end()),
            hidden_dim_stride,
            combine_op_pool,
            activation_pool,
            standardize_op_pool,
            informative_metrics: informative_metrics
                .into_iter()
                .map(|m| m.label().to_string())
                .collect(),
            max_steps,
            started_at: None,
            train_eval_split_ratio,
            // Stamped by `CoreEngine::from_spec` right after construction:
            // constructor has no view of the cadence, the engine does.
            eval_era_every: None,
            explicit_test_rows,
            eval_split,
            exam_rows,
            culls,
            run_elapsed_secs,
            children_born_at_clock,
            config,
            trainer,
            // A post-construction fact: the seed source is stamped in right after
            // population is resolved.
            run_topology_source: None,
            accounting: None,
        }
    }

    /// Like `from_race_options`, but also stamps `started_at`.
    pub fn from_race_options_at(cfg: RunConfig, started_at: String) -> Self {
        let mut out = Self::from_race_options(cfg);
        out.started_at = Some(started_at);
        out
    }

    /// Serialize to pretty JSON for writing `engine.json`.
    pub fn to_json(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(self)
            .map_err(|e| EngineError::Json(format!("engine.json serialize: {e}")))?)
    }

    /// Load a previously written `engine.json`.
    pub fn from_json(raw: &str) -> Result<Self> {
        let v: serde_json::Value = serde_json::from_str(raw)
            .map_err(|e| EngineError::Json(format!("engine.json parse: {e}")))?;
        let fitness_direction = v
            .get("fitness_direction")
            .and_then(|f| f.as_str())
            .and_then(|s| match s {
                "Minimize" => Some(Direction::Minimize),
                "Maximize" => Some(Direction::Maximize),
                _ => None,
            })
            .unwrap_or(Direction::Maximize);
        let fitness_label = serde_json::from_value(
            v.get("fitness_label")
                .cloned()
                .unwrap_or_else(|| serde_json::Value::String("loss".into())),
        )
        .unwrap_or(FitnessLabel("loss".into()));
        let input_dim = v.get("input_dim").and_then(|f| f.as_u64()).unwrap_or(0) as usize;
        let output_dim = v.get("output_dim").and_then(|f| f.as_u64()).unwrap_or(0) as usize;
        let topology_options = v
            .get("topology_options")
            .map(|t| serde_json::from_value(t.clone()).unwrap_or_default())
            .unwrap_or_default();
        let hidden_dim_pool = v
            .get("hidden_dim_pool")
            .and_then(|f| f.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| "4..=8".into());
        let hidden_dim_stride: usize = v
            .get("hidden_dim_stride")
            .and_then(|f| f.as_u64())
            .map(|n| n as usize)
            .unwrap_or(1);
        let combine_op_pool: Vec<String> = serde_json::from_value(
            v.get("combine_op_pool")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
        )
        .unwrap_or_default();
        let activation_pool: Vec<String> = serde_json::from_value(
            v.get("activation_pool")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
        )
        .unwrap_or_default();
        let standardize_op_pool: Vec<String> = serde_json::from_value(
            v.get("standardize_op_pool")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
        )
        .unwrap_or_default();
        let informative_metrics: Vec<String> = serde_json::from_value(
            v.get("informative_metrics")
                .cloned()
                .unwrap_or(serde_json::Value::Null),
        )
        .unwrap_or_default();
        let max_steps = v
            .get("max_steps")
            .and_then(|f| f.as_u64())
            .map(|n| n as usize);
        let started_at = v
            .get("started_at")
            .and_then(|f| f.as_str())
            .map(|s| s.to_string());
        let train_eval_split_ratio = v
            .get("train_eval_split_ratio")
            .and_then(|f| f.as_f64())
            .map(|n| n as f32);
        // Absent on every header written before the VAL role existed: those runs
        // can only have ranked on `test/`, and the resume guard reads
        let eval_split = v
            .get("eval_split")
            .and_then(|f| f.as_str())
            .map(|s| s.to_string());
        let explicit_test_rows = v
            .get("explicit_test_rows")
            .and_then(|f| f.as_u64())
            .map(|n| n as usize);
        // Absent on every header written before the exam existed: no exam supplied.
        let exam_rows = v
            .get("exam_rows")
            .and_then(|f| f.as_u64())
            .map(|n| n as usize);
        // Counter persistence (written at stop; legacy files read as fresh).
        let culls = v.get("culls").and_then(|f| f.as_u64()).unwrap_or(0) as usize;
        let run_elapsed_secs = v
            .get("run_elapsed_secs")
            .and_then(|f| f.as_u64())
            .unwrap_or(0);
        let children_born_at_clock: std::collections::HashMap<usize, usize> = v
            .get("children_born_at_clock")
            .and_then(|c| c.as_object())
            .map(|m| {
                m.iter()
                    .filter_map(|(k, val)| {
                        let clock: usize = k.parse().ok()?;
                        let n = val.as_u64()? as usize;
                        Some((clock, n))
                    })
                    .collect()
            })
            .unwrap_or_default();
        let config: ConfigSnapshot = v
            .get("config")
            .cloned()
            .and_then(|c| serde_json::from_value(c).ok())
            .unwrap_or_default();
        // Trainer self-description (see `Trainer::describe`). Absent on legacy
        // files and on trainers that don't implement the hook.
        let trainer = v.get("trainer").cloned();
        let run_topology_source: Option<SeedSourceRecord> = v
            .get("run_topology_source")
            .cloned()
            .and_then(|s| serde_json::from_value(s).ok());
        // Migration: legacy headers have no root `engine_mode` — derive
        // `config.mode`. New headers carry it so a reader picks the engine first.
        let engine_mode = v
            .get("engine_mode")
            .and_then(|m| m.as_str())
            .map(|s| s.to_string())
            .or_else(|| {
                v.get("config")
                    .and_then(|c| c.get("mode"))
                    .and_then(|m| m.as_str())
                    .map(|s| s.to_string())
            });
        Ok(RunHeader {
            run_id: v
                .get("run_id")
                .and_then(|f| f.as_str())
                .unwrap_or("unknown")
                .to_string(),
            data_dir: v
                .get("data_dir")
                .and_then(|f| f.as_str())
                .map(|s| s.to_string()),
            engine_mode,
            run_seed: v.get("run_seed").and_then(|f| f.as_u64()).unwrap_or(0),
            fitness_label,
            fitness_direction,
            input_dim,
            output_dim,
            topology_options,
            hidden_dim_pool,
            hidden_dim_stride,
            combine_op_pool,
            activation_pool,
            standardize_op_pool,
            informative_metrics,
            max_steps,
            started_at,
            train_eval_split_ratio,
            eval_era_every: v
                .get("eval_era_every")
                .and_then(|f| f.as_u64())
                .map(|n| n as usize),
            explicit_test_rows,
            eval_split,
            exam_rows,
            culls,
            run_elapsed_secs,
            children_born_at_clock,
            config,
            trainer,
            run_topology_source,
            accounting: v
                .get("accounting")
                .cloned()
                .and_then(|x| serde_json::from_value(x).ok()),
        })
    }
}

/// Serde default: a net with no `alive` field is alive.
fn default_alive() -> bool {
    true
}

/// Serde default: `true`.
fn default_mutation_cull_policy() -> String {
    "worst".to_string()
}

fn default_true() -> bool {
    true
}

/// Serde default for [`ConfigSnapshot::train_merit_p_max`]: no ceiling, which is what
/// every header written before the knob meant.
fn default_p_max() -> f32 {
    1.0
}

// ── Per-net state (nets/<hash>.json) ──────────────────────────────────────

/// The last-known state of one live net, written to `nets/<hash>.json` and overwritten each
/// surviving step. The resume anchor: rebuild from the blueprint + seed, then replay.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NetState {
    /// Canonical xxh3 hash of this individual's topology (16 hex chars).
    pub hash: String,
    /// The topology blueprint, serialized (self-describing: `Network::build` reads
    /// seed and dropout from here).
    pub topology: String,
    /// Weight-init seed, stored redundantly so a reader needn't re-parse the topology.
    pub net_seed: usize,
    /// Clocks this net actually TRAINED through (real optimizer updates).
    pub step: usize,
    /// Whether this net is currently alive in the active population. Culled nets
    /// are written as final tombstones to disk with `is_alive: false`.
    #[serde(default = "default_alive")]
    pub is_alive: bool,
    /// Step this net was culled (`None` while alive).
    #[serde(default)]
    pub culled_at_step: Option<usize>,
    /// Why it left (`"crossover-lowest-fitness"` | `"crossover-random"` | `"crossover-highest-ticket-chance"` |
    /// `"immigrant-slot"` — the crossover arm names the cull policy that chose it).
    #[serde(default)]
    pub cull_reason: Option<String>,
    /// Its window fitness MEAN at culling (or at stop for a live net — same three legs, same row
    /// the run's history): the readable level, NOT the risk-adjusted score that ranked
    #[serde(default, alias = "final_smoothed_fitness")]
    pub final_fitness_mean: Option<f32>,
    /// Spread of that window (population std of the step readings). With the mean it tells
    /// "always that good" from "one lucky step" at a glance; `None` on legacy tombstones.
    #[serde(default)]
    pub final_fitness_std: Option<f32>,
    /// The RANKING score (the window centre, plus any selection terms) the net was actually ranked by at the moment
    /// culling.
    #[serde(default)]
    pub final_risk_score: Option<f32>,
    /// Step readings behind the three values above. `0` on legacy tombstones.
    #[serde(default)]
    pub final_fitness_samples: usize,
    /// When this individual entered the live population. For lifetime tracking
    /// and the robustness-equivalent (appearances / span / final score).
    pub entered_at_step: usize,
    /// Optional lineage record: which parents/mutation produced this individual.
    pub created_from: Option<String>,
    /// The clock this net's LINEAGE entered the run: its own birth for a founder, its oldest
    /// ancestor's for a child.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lineage_born: Option<usize>,
    /// Last-seen metrics snapshot (loss + fitness + informative metrics) — enough
    /// resume/time-travel read. Empty until the first persisted step.
    pub last_metrics: Option<NetMetrics>,
    /// Trainer-owned bookkeeping for THIS net (R9), opaque to the engine: exactly what
    /// `TabularStep::state()` returned at the checkpoint, handed back verbatim to `restore`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trainer_state: Option<serde_json::Value>,
    /// Inclusive clock ranges this net executed as FROZEN (act-and-measure). Replay-
    /// relevant: resume re-runs them through a no-op optimizer. Run-length, disjoint.
    #[serde(default)]
    pub frozen_spans: Vec<(usize, usize)>,
    /// Inclusive clock ranges this net spent IDLE: the training lottery gave it no train-eval
    /// ticket, so no train batch, no eval batch, no metric row and no weight update happened.
    #[serde(default)]
    pub idle_spans: Vec<(usize, usize)>,
    /// Rich per-individual metadata (params, dims, regime, run context). Missing
    /// legacy JSONs; backfilled on first rewrite.
    #[serde(default)]
    pub meta: NetMeta,
    /// When this net's weights were last updated with a real optimizer. Freeze-log
    /// never written to disk; rebuilt from `last_metrics` on resume.
    #[serde(skip)]
    pub last_update_step: usize,
    /// LEGACY: clocks an older lottery ACTED but did not update (they sit in `frozen_spans`,
    /// because that era re-ran them through a no-op optimizer).
    #[serde(default)]
    pub budget_skips: usize,
    /// Clocks whose update was followed by a RECOVERY STREAK: `(clock, extra real updates)` in clock order.
    #[serde(default)]
    pub recovery_ledger: Vec<(usize, usize)>,
}

/// Extend `spans` with `step`, merging into the previous span when contiguous.
/// Shared by the frozen and idle ledgers so both stay run-length and disjoint.
fn push_span(spans: &mut Vec<(usize, usize)>, step: usize) {
    match spans.last_mut() {
        Some((_, end)) if *end + 1 == step => *end = step,
        _ => spans.push((step, step)),
    }
}

/// Total clocks covered by run-length `spans`.
fn span_len(spans: &[(usize, usize)]) -> usize {
    spans.iter().map(|&(s, e)| e.saturating_sub(s) + 1).sum()
}

/// Rich metadata for one individual (embedded in `nets/<hash>.json` under `meta`) — enough
/// to understand the net and its training conditions without touching code.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct NetMeta {
    /// Trainable parameter count (elements) of the built network.
    #[serde(default)]
    pub params: Option<i64>,
    /// Number of parameter tensors.
    #[serde(default)]
    pub param_tensors: Option<usize>,
    /// Dataset dims the run was launched
    #[serde(default)]
    pub input_dim: Option<usize>,
    #[serde(default)]
    /// Output dimension (`None` in modes without a shared stream).
    pub output_dim: Option<usize>,
    /// Shared training regime. `None` in modes with no shared stream (RL) — LR, grad clip
    /// and volume are trainer-owned (`engine.json` → `"trainer"`).
    #[serde(default)]
    pub batch_size: Option<usize>,
    /// Dropout probability stamped into the topology (also lives
    /// topology JSON; duplicated here for quick scanning).
    #[serde(default)]
    pub dropout_prob: Option<f32>,
    /// Ranking fitness label. No `loss_label` beside it: the loss/update scheme
    /// trainer-owned, so `engine.json` → `"trainer"` is the only honest record.
    #[serde(default)]
    pub fitness_label: Option<String>,
    /// What ranking direction this run uses ("minimize"/"maximize").
    #[serde(default)]
    pub direction: Option<String>,
    /// The step this individual was born into the run (== entered_at_step;
    /// duplicated so the meta block is self-contained).
    #[serde(default)]
    pub born_at_step: Option<usize>,
    /// Population size + run seed context (inherited from the header).
    #[serde(default)]
    pub pop_size: Option<usize>,
    #[serde(default)]
    /// Run seed recorded for this net's regime (`None` if unknown).
    pub run_seed: Option<u64>,
}

/// One snapshot of metrics for a single net, at a single step.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct NetMetrics {
    /// Step this metric snapshot was recorded
    pub step: usize,
    /// Training loss for this step's train batch.
    pub train_loss: f32,
    /// Held-out loss for this step's eval batch (eval mode).
    pub eval_loss: Option<f32>,
    /// Ranking fitness for this step's eval batch (the signal the run evolves
    pub fitness: f32,
    /// Informative-only metric values, in the same order the run configured them.
    pub informative: Vec<f32>,
    /// True when this step was ACT-ONLY: the net ran and was measured on a no-op optimizer.
    #[serde(default)]
    pub frozen: bool,
}

impl NetState {
    /// The clock this net's LINEAGE entered the run: its own birth, or its oldest ancestor's,
    /// whichever is earlier.
    pub fn lineage_birth(&self) -> usize {
        self.lineage_born
            .map_or(self.entered_at_step, |b| b.min(self.entered_at_step))
    }

    /// Stamp the `meta` block from the materialized network + run context — once per net
    /// right after its `Network` is built, never per step.
    pub fn stamp_meta(
        &mut self,
        net: &crate::graph::network::Network,
        run: &crate::engine::config::RunMetaCtx,
    ) {
        use flodl::Module;
        let params = net.parameters();
        self.meta.param_tensors = Some(params.len());
        self.meta.params = Some(params.iter().map(|p| p.variable.numel()).sum());
        self.meta.input_dim = Some(run.input_dim);
        self.meta.output_dim = Some(run.output_dim);
        self.meta.batch_size = run.batch_size;
        // LR, grad clip and the loss scheme are trainer-owned, so the engine records none
        // of them here; the trainer's `describe()` block is the authoritative record.
        self.meta.fitness_label = Some(run.fitness_label.clone());
        self.meta.direction = Some(run.direction.clone());
        self.meta.born_at_step = Some(self.entered_at_step);
        self.meta.pop_size = Some(run.pop_size);
        self.meta.run_seed = Some(run.run_seed);
        // Dropout lives in the topology too — duplicate for quick scanning.
        self.meta.dropout_prob = Some(run.dropout_prob);
    }

    /// Build a new live individual's state from its topology and entry step.
    pub fn new(topo: &Topology, step: usize, created_from: Option<String>) -> Result<Self> {
        let topo_json = topo
            .to_json()
            .map_err(|e| EngineError::Json(format!("net state topology json: {e}")))?;
        let net_seed = topo.options.topology_seed;
        Ok(NetState {
            hash: topo_hash(&topo_json),
            topology: topo_json,
            net_seed,
            step,
            is_alive: true,
            culled_at_step: None,
            cull_reason: None,
            final_fitness_mean: None,
            final_fitness_std: None,
            final_risk_score: None,
            final_fitness_samples: 0,
            entered_at_step: step,
            created_from,
            lineage_born: None,
            last_metrics: None,
            trainer_state: None,
            frozen_spans: Vec::new(),
            idle_spans: Vec::new(),
            meta: NetMeta::default(),
            last_update_step: step,
            budget_skips: 0,
            recovery_ledger: Vec::new(),
        })
    }

    /// Record clock `step` as an act-and-measure (frozen) step, extending the last span
    /// when contiguous. Does NOT advance `last_update_step`.
    pub fn record_frozen_step(&mut self, step: usize) {
        push_span(&mut self.frozen_spans, step);
    }

    /// Record clock `step` as an IDLE clock (the lottery gave no train-eval ticket: no train, no
    /// eval, no metrics), extending the last span when contiguous.
    pub fn record_idle_step(&mut self, step: usize) {
        push_span(&mut self.idle_spans, step);
    }

    /// Record the `extras` extra updates ONE clock's recovery streak took, in clock order.
    pub fn record_recovery(&mut self, step: usize, extras: usize) {
        if extras == 0 {
            return;
        }
        match self.recovery_ledger.last_mut() {
            Some((last, n)) if *last == step => *n = (*n).max(extras),
            _ => self.recovery_ledger.push((step, extras)),
        }
    }

    /// Extra real updates this net took inside streaks — the part of `U` the clock ledger cannot
    /// hold. One implementation for the replay ledger and the `U` column.
    pub fn recovery_retries(&self) -> usize {
        self.recovery_ledger.iter().map(|&(_, n)| n).sum()
    }

    /// Clocks this net spent ACTING without updating (a lottery denied the update while `train_merit_learn_only` was on): the length of `frozen_spans`.
    pub fn frozen_clocks(&self) -> usize {
        span_len(&self.frozen_spans)
    }

    /// Clocks the lottery left this net idle (no train, no eval): the length
    /// `idle_spans`.
    pub fn idle_clocks(&self) -> usize {
        span_len(&self.idle_spans)
    }

    /// Clocks this net actually ran the trainer and was scored: its real updates plus its
    /// act-only passes.
    pub fn measured_clocks(&self) -> usize {
        self.step + self.frozen_clocks()
    }

    /// This net's record as it stood at clock `target`: the frozen/idle ledgers are clamped
    /// window, `step` is recomputed for it, and `last_metrics` is dropped when the file has moved
    pub fn truncated_at(mut self, target: usize) -> Self {
        let start = if self.entered_at_step == 0 {
            0
        } else {
            self.entered_at_step + 1
        };
        self.frozen_spans = clamp_spans(&self.frozen_spans, target);
        self.idle_spans = clamp_spans(&self.idle_spans, target);
        self.recovery_ledger.retain(|&(clock, _)| clock <= target);
        let span = (target + 1).saturating_sub(start);
        // The streak's extras ride ON TOP of one update per clock: without them a truncated record
        // would undercount `U` by exactly the retries taken.
        self.step = span
            .saturating_sub(span_len(&self.frozen_spans))
            .saturating_sub(span_len(&self.idle_spans))
            + self.recovery_retries();
        if self.last_metrics.as_ref().is_some_and(|m| m.step > target) {
            self.last_metrics = None;
        }
        self
    }

    /// Whether `step` lies inside a recorded frozen span.
    pub fn is_frozen_step(&self, step: usize) -> bool {
        self.frozen_spans
            .iter()
            .any(|&(s, e)| step >= s && step <= e)
    }

    /// Serialize to pretty JSON for `nets/<hash>.json`, backfilling `meta` on legacy
    /// records with a throwaway network build (cheap, once per write flight).
    pub fn to_json(&self) -> Result<String> {
        let mut to_write = self.clone();
        if to_write.meta.params.is_none() {
            let topo = crate::graph::topology::Topology::from_json(&to_write.topology)
                .map_err(|e| EngineError::Json(format!("net state meta backfill: {e}")))?;
            let net = crate::graph::network::Network::build(&topo, crate::Device::CPU)
                .map_err(|e| EngineError::Json(format!("net state meta backfill build: {e}")))?;
            to_write.stamp_meta(&net, &crate::engine::config::RunMetaCtx::default());
        }
        Ok(serde_json::to_string_pretty(&to_write)
            .map_err(|e| EngineError::Json(format!("net state json: {e}")))?)
    }

    /// Load a previously written `nets/<hash>.json`.
    pub fn from_json(raw: &str) -> Result<Self> {
        Ok(serde_json::from_str(raw)
            .map_err(|e| EngineError::Json(format!("net state parse: {e}")))?)
    }

    /// Update the last-metrics snapshot.
    pub fn record_metrics(&mut self, metrics: NetMetrics) {
        self.last_metrics = Some(metrics);
    }

    /// Advance the local step clock and record it as the last weight-update step —
    /// LIVE-path hook (a frozen step uses the separate freeze-only path).
    pub fn advance_step(&mut self) {
        self.step += 1;
        self.last_update_step = self.step;
    }

    /// Recover the topology from the embedded JSON.
    pub fn topology(&self) -> Result<Topology> {
        Ok(Topology::from_json(&self.topology)
            .map_err(|e| EngineError::Json(format!("net state topology parse: {e}")))?)
    }
}

// ── Runtime population state (in memory) ──────────────────────────────────

/// The in-memory view of the live population the scheduler reads/writes: a hash map
/// `NetState` plus a per-topology lifetime accumulator (the robustness-equivalent).
pub struct RaceState {
    /// Live nets, indexed by canonical topology hash.
    nets: HashMap<String, NetState>,
    /// Per-topology lifetime/score accumulator (robustness-equivalent).
    topology_lifetime: HashMap<String, TopologyLifetime>,
}

/// Per-topology lifetime tracking — entries, step span, and final recorded fitness.
#[derive(Clone, Debug)]
pub struct TopologyLifetime {
    /// Times this topology entered the live population.
    appearances: usize,
    /// First step this topology was live
    first_step: usize,
    /// Last step this topology was live at (updated as it survives).
    last_step: usize,
    /// Last recorded fitness for this topology (the final one seen in the run).
    last_fitness: Option<f32>,
}

impl TopologyLifetime {
    /// New accumulator seeded from the first entry.
    pub fn new(first_step: usize, fitness: Option<f32>) -> Self {
        TopologyLifetime {
            appearances: 1,
            first_step,
            last_step: first_step,
            last_fitness: fitness,
        }
    }

    /// Record one entry at `step` with `fitness`.
    pub fn record_entry(&mut self, step: usize, fitness: Option<f32>) {
        self.appearances = self.appearances.saturating_add(1);
        self.last_step = step;
        self.last_fitness = fitness;
    }

    /// Advance the liveness window: `last_step` always moves forward;
    /// fitness only overwrites when a fresh finite value is given.
    pub fn record_progress(&mut self, step: usize, fitness: Option<f32>) {
        self.last_step = self.last_step.max(step);
        if let Some(f) = fitness {
            self.last_fitness = Some(f);
        }
    }

    /// How many times this topology entered the population.
    pub fn appearances(&self) -> usize {
        self.appearances
    }

    /// First step it was seen.
    pub fn first_step(&self) -> usize {
        self.first_step
    }

    /// Last step it was seen.
    pub fn last_step(&self) -> usize {
        self.last_step
    }

    /// Steps covered from first to last.
    pub fn span(&self) -> usize {
        self.last_step.saturating_sub(self.first_step)
    }

    /// Final recorded fitness.
    pub fn last_fitness(&self) -> Option<f32> {
        self.last_fitness
    }
}

impl Default for RaceState {
    fn default() -> Self {
        Self::new()
    }
}

impl RaceState {
    /// New empty population state.
    pub fn new() -> Self {
        RaceState {
            nets: HashMap::new(),
            topology_lifetime: HashMap::new(),
        }
    }

    /// Register a newly inserted net (after initial insertion).
    pub fn insert(&mut self, state: NetState, initial_fitness: Option<f32>) {
        let key = state.hash.clone();
        if let Some(entry) = self.topology_lifetime.get_mut(&key) {
            entry.record_entry(state.entered_at_step, initial_fitness);
        } else {
            self.topology_lifetime.insert(
                key.clone(),
                TopologyLifetime::new(state.entered_at_step, initial_fitness),
            );
        }
        self.nets.insert(key, state);
    }

    /// Record that a live net advanced one step with the given metrics.
    pub fn record_step(&mut self, hash: &str, metrics: NetMetrics) -> Result<()> {
        let state = self.nets.get_mut(hash).ok_or_else(|| {
            EngineError::InvalidOptions(format!("race state: net {hash} not live"))
        })?;
        state.record_metrics(metrics.clone());
        state.advance_step();
        let fitness = metrics.fitness;
        let fitness = if fitness.is_finite() {
            Some(fitness)
        } else {
            None
        };
        let entry = self
            .topology_lifetime
            .entry(hash.to_string())
            .or_insert_with(|| TopologyLifetime::new(state.entered_at_step, fitness));
        entry.record_progress(metrics.step, fitness);
        Ok(())
    }

    /// Record a clock's recovery retries on `hash` — the net's own ledger, not a run counter: a
    /// time-travelled record clamps it and `U` is counted from it.
    pub fn record_recovery(&mut self, hash: &str, step: usize, extras: usize) -> Result<()> {
        let state = self.nets.get_mut(hash).ok_or_else(|| {
            EngineError::InvalidOptions(format!("race state: net {hash} not live"))
        })?;
        state.record_recovery(step, extras);
        Ok(())
    }

    /// Record an ACT-AND-MEASURE (frozen) step: metrics, lifetime progress and the frozen
    /// span — but WITHOUT advancing the clock. Counterpart to [`Self::record_step`].
    pub fn record_frozen_act(&mut self, hash: &str, metrics: NetMetrics) -> Result<()> {
        let state = self.nets.get_mut(hash).ok_or_else(|| {
            EngineError::InvalidOptions(format!("race state: net {hash} not live"))
        })?;
        state.record_metrics(metrics.clone());
        // The span is how replay_step re-runs this clock through
        // no-op optimizer on resume.
        state.record_frozen_step(metrics.step);
        let fitness = metrics.fitness;
        let fitness = if fitness.is_finite() {
            Some(fitness)
        } else {
            None
        };
        let entry = self
            .topology_lifetime
            .entry(hash.to_string())
            .or_insert_with(|| TopologyLifetime::new(state.entered_at_step, fitness));
        entry.record_progress(metrics.step, fitness);
        Ok(())
    }

    /// Immutable access to a live net by hash.
    pub fn net(&self, hash: &str) -> Option<&NetState> {
        self.nets.get(hash)
    }

    /// Mutable access to a live net by hash.
    pub fn net_mut(&mut self, hash: &str) -> Option<&mut NetState> {
        self.nets.get_mut(hash)
    }

    /// Hashes of every live (non-tombstoned) net.
    pub fn live_hashes(&self) -> Vec<String> {
        let mut hashes: Vec<String> = self.nets.keys().cloned().collect();
        hashes.sort();
        hashes
    }

    /// Number of live nets.
    pub fn live_count(&self) -> usize {
        self.nets.len()
    }

    /// Mutable access to every live net keyed by hash — for the commutative counter tick,
    /// so iteration order doesn't matter.
    pub fn live_mut(&mut self) -> impl Iterator<Item = (&String, &mut NetState)> {
        self.nets.iter_mut()
    }

    /// Remove a net from the live set. The state is returned so the caller can
    /// decide whether to tombstone it (off by default today) or drop
    pub fn remove(&mut self, hash: &str) -> Option<NetState> {
        let state = self.nets.remove(hash);
        if let Some(state) = &state {
            self.topology_lifetime.remove(&state.hash);
        }
        state
    }

    /// Iterate over every topology lifetime entry.
    pub fn lifetimes(&self) -> Vec<(&String, &TopologyLifetime)> {
        let mut out: Vec<_> = self.topology_lifetime.iter().collect();
        out.sort_by_key(|(a, _)| *a);
        out
    }

    /// Clear the entire state (used by tests / fresh-run init).
    pub fn clear(&mut self) {
        self.nets.clear();
        self.topology_lifetime.clear();
    }
}

// ── File I/O ───────────────────────────────────────────────────────────────

/// Write the run header to `engine.json` in `dir`.
pub fn write_engine_json(dir: &Path, header: &RunHeader) -> Result<()> {
    std::fs::create_dir_all(dir).map_err(|source| EngineError::Io {
        path: dir.display().to_string(),
        source,
    })?;
    let path = dir.join("engine.json");
    let json = header.to_json()?;
    // Atomic: `engine.json` is what a resume reads first, so a kill mid-write
    // must leave the previous header, never half of the new one.
    write_atomic(&path, json.as_bytes(), true)
}

// ── Frontier manifest (`ckpt.json`) ────────────────────────────────────────

/// Schema of [`FrontierManifest`].
pub const FRONTIER_MANIFEST_SCHEMA: u32 = 2;

/// Keep the parts of each span at or before `target` (a span that crosses
/// cut short; one that starts after it is dropped).
fn clamp_spans(spans: &[(usize, usize)], target: usize) -> Vec<(usize, usize)> {
    spans
        .iter()
        .filter(|(s, _)| *s <= target)
        .map(|(s, e)| (*s, (*e).min(target)))
        .collect()
}

/// One net's entry in the frontier manifest: its identity and the clock it had last MEASURED
/// tick.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontierNet {
    /// Full topology hash — the file name in `nets/`.
    pub hash: String,
    /// Clock this net was replayed to at the tick (`last_metrics.step`).
    pub step: usize,
}

/// The frontier as a POINT-IN-TIME SET: which nets were live when the durability tick ran, and how
/// far each had measured.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FrontierManifest {
    /// [`FRONTIER_MANIFEST_SCHEMA`].
    pub schema: u32,
    /// The clock the NEXT step will run (completed clocks + 1) — the number
    /// `CoreEngine::step_clock` must answer after a resume, independent of any net's own lag
    pub next_clock: usize,
    /// The run's seed at the tick; a resume refuses a mismatch.
    pub run_seed: u64,
    /// The live set, sorted by hash so the file's bytes are deterministic.
    pub nets: Vec<FrontierNet>,
}

/// The temporary sibling a [`write_atomic`] rename goes through.
fn tmp_sibling(path: &Path) -> std::path::PathBuf {
    let mut name = path
        .file_name()
        .map(|n| n.to_os_string())
        .unwrap_or_default();
    name.push(".tmp");
    path.with_file_name(name)
}

/// Write `bytes` to `path` via a temporary sibling + rename, so a process killed mid-write leaves
/// the OLD file intact instead of a truncated one.
pub(crate) fn write_atomic(path: &Path, bytes: &[u8], sync: bool) -> Result<()> {
    use std::io::Write;
    let tmp = tmp_sibling(path);
    let io = |e: std::io::Error, p: &Path| EngineError::Io {
        path: p.display().to_string(),
        source: e,
    };
    {
        let mut file = std::fs::File::create(&tmp).map_err(|e| io(e, &tmp))?;
        file.write_all(bytes).map_err(|e| io(e, &tmp))?;
        if sync {
            file.sync_all().map_err(|e| io(e, &tmp))?;
        }
    }
    std::fs::rename(&tmp, path).map_err(|e| io(e, path))?;
    Ok(())
}

/// Write the frontier manifest for this tick (`<run_dir>/ckpt.json`).
pub fn write_frontier_manifest(dir: &Path, manifest: &FrontierManifest) -> Result<()> {
    let json = serde_json::to_string_pretty(manifest)
        .map_err(|e| EngineError::Json(format!("ckpt.json serialize: {e}")))?;
    write_atomic(&dir.join("ckpt.json"), json.as_bytes(), true)
}

/// Read `<run_dir>/ckpt.json`.
pub fn load_frontier_manifest(dir: &Path) -> Result<Option<FrontierManifest>> {
    let path = dir.join("ckpt.json");
    let raw = match std::fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source) => {
            return Err(EngineError::Io {
                path: path.display().to_string(),
                source,
            }
            .into());
        }
    };
    let manifest: FrontierManifest = serde_json::from_str(&raw)
        .map_err(|e| EngineError::Json(format!("ckpt.json parse: {e}")))?;
    if manifest.schema != FRONTIER_MANIFEST_SCHEMA {
        let why = if manifest.schema == 1 {
            "schema 1 recorded net STATES only, so resuming it would need the retired \
             replay path — finish that run with the build that started it"
        } else {
            "re-run the experiment, or resume it with the build that wrote it"
        };
        return Err(EngineError::InvalidOptions(format!(
            "ckpt.json reports schema {} but this build resumes schema {} only — {why}",
            manifest.schema, FRONTIER_MANIFEST_SCHEMA
        ))
        .into());
    }
    if manifest.nets.is_empty() {
        return Err(EngineError::InvalidOptions(
            "ckpt.json lists no nets — the frontier snapshot is empty, so there is nothing \
             to resume; the run dir is corrupt"
                .to_string(),
        )
        .into());
    }
    Ok(Some(manifest))
}

/// Drop the rows of `<run_dir>/<file>` that belong to clock `next_clock` or later, returning how
/// many went.
pub fn truncate_csv_to_clock(dir: &Path, file: &str, next_clock: usize) -> Result<usize> {
    let path = dir.join(file);
    let Ok(raw) = std::fs::read_to_string(&path) else {
        return Ok(0);
    };
    let mut kept = String::with_capacity(raw.len());
    let mut dropped = 0usize;
    for (i, line) in raw.lines().enumerate() {
        if i == 0 {
            kept.push_str(line);
            kept.push('\n');
            continue;
        }
        let step = line
            .split(',')
            .next()
            .and_then(|s| s.trim().parse::<usize>().ok());
        match step {
            Some(s) if s >= next_clock => dropped += 1,
            _ => {
                kept.push_str(line);
                kept.push('\n');
            }
        }
    }
    if dropped > 0 {
        write_atomic(&path, kept.as_bytes(), false)?;
    }
    Ok(dropped)
}

/// Load the run header from `engine.json` in `dir`.
pub fn load_engine_json(dir: &Path) -> Result<RunHeader> {
    let path = dir.join("engine.json");
    let raw = std::fs::read_to_string(&path).map_err(|source| EngineError::Io {
        path: path.display().to_string(),
        source,
    })?;
    RunHeader::from_json(&raw)
}

/// Ensure the `nets/` directory exists under `dir`.
pub fn ensure_nets_dir(dir: &Path) -> Result<()> {
    std::fs::create_dir_all(dir.join("nets")).map_err(|source| EngineError::Io {
        path: dir.display().to_string(),
        source,
    })?;
    Ok(())
}

/// Write (overwrite) one net's state to `nets/<hash>.json`.
pub fn write_net_state(dir: &Path, state: &NetState) -> Result<()> {
    ensure_nets_dir(dir)?;
    let path = dir.join("nets").join(format!("{}.json", state.hash));
    let json = state.to_json()?;
    write_atomic(&path, json.as_bytes(), false)
}

/// Load one net's state from `nets/<hash>.json`.
pub fn load_net_state(dir: &Path, hash: &str) -> Result<NetState> {
    let path = dir.join("nets").join(format!("{}.json", hash));
    let raw = std::fs::read_to_string(&path).map_err(|source| EngineError::Io {
        path: path.display().to_string(),
        source,
    })?;
    NetState::from_json(&raw)
}

/// Remove one net's state file. Returns whether a file was removed.
pub fn remove_net_state(dir: &Path, hash: &str) -> Result<bool> {
    let path = dir.join("nets").join(format!("{}.json", hash));
    if path.exists() {
        std::fs::remove_file(&path).map_err(|source| EngineError::Io {
            path: path.display().to_string(),
            source,
        })?;
        Ok(true)
    } else {
        Ok(false)
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::topology::TopologyOptions;
    use crate::utils::fitness::{Direction, FitnessLabel};
    use std::path::PathBuf;

    fn fresh_dir() -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "gras_race_state_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        dir
    }

    /// The manifest is the frontier as a SET: it must round-trip, and a schema bump
    /// must be REFUSED by name rather than half-read.
    #[test]
    fn frontier_manifest_round_trips_and_refuses_a_newer_schema() {
        let dir = fresh_dir();
        std::fs::create_dir_all(&dir).unwrap();
        assert!(
            load_frontier_manifest(&dir).unwrap().is_none(),
            "no file = no manifest (a legacy dir resumes the old way)"
        );
        let manifest = FrontierManifest {
            schema: FRONTIER_MANIFEST_SCHEMA,
            next_clock: 41,
            run_seed: 7,
            nets: vec![
                FrontierNet {
                    hash: "aa".to_string(),
                    step: 40,
                },
                FrontierNet {
                    hash: "bb".to_string(),
                    step: 39,
                },
            ],
        };
        write_frontier_manifest(&dir, &manifest).unwrap();
        assert_eq!(load_frontier_manifest(&dir).unwrap(), Some(manifest));
        // A rejected write leaves no `ckpt.json.tmp` behind either.
        assert!(
            !dir.join("ckpt.json.tmp").exists(),
            "tmp file must be renamed away"
        );

        let mut newer =
            serde_json::to_value(load_frontier_manifest(&dir).unwrap().unwrap()).unwrap();
        newer["schema"] = serde_json::json!(FRONTIER_MANIFEST_SCHEMA + 1);
        std::fs::write(dir.join("ckpt.json"), newer.to_string()).unwrap();
        let err = load_frontier_manifest(&dir).unwrap_err().to_string();
        assert!(err.contains("schema"), "{err}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Rewinding keeps the header and every row before the clock; it drops the rows
    /// per-step flush wrote past the last checkpoint (the measured duplicate source).
    #[test]
    fn truncate_csv_to_clock_keeps_the_prefix_only() {
        let dir = fresh_dir();
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("history.csv"),
            "step,hash,fitness\n0,a,1\n1,a,2\n2,a,3\n7,b,4\n",
        )
        .unwrap();
        let dropped = truncate_csv_to_clock(&dir, "history.csv", 3).unwrap();
        assert_eq!(
            dropped, 1,
            "only clock 7 is at or past the frontier clock 3"
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("history.csv")).unwrap(),
            "step,hash,fitness\n0,a,1\n1,a,2\n2,a,3\n"
        );
        // A second call is a no-op — the file is already a prefix.
        assert_eq!(truncate_csv_to_clock(&dir, "history.csv", 3).unwrap(), 0);
        // A missing file is not an error (csv_export can be off).
        assert_eq!(truncate_csv_to_clock(&dir, "attempts.csv", 3).unwrap(), 0);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A record that has moved past the frontier is rewound consistently: spans clamped, `step` recomputed for the window, the too-late reading dropped — so the ledger identity…
    #[test]
    fn net_state_truncates_to_an_earlier_frontier() {
        // Built through the real reader, so the fixture cannot drift from the schema.
        let state = NetState::from_json(
            r#"{"hash":"aa","topology":"{}","net_seed":1,"step":10,
                 "entered_at_step":0,"is_alive":true,
                 "frozen_spans":[[8,12]],"idle_spans":[[14,15]],
                 "last_metrics":{"step":15,"train_loss":1.0,"fitness":1.0,"informative":[]}}"#,
        )
        .unwrap();
        assert_eq!(
            state.measured_clocks(),
            15,
            "10 trained + 5 crown act clocks"
        );
        let t = state.truncated_at(9);
        assert_eq!(t.frozen_spans, vec![(8, 9)]);
        assert!(t.idle_spans.is_empty());
        // Window 0..=9 is 10 clocks: 8 trained + 2 frozen.
        assert_eq!(
            t.step, 8,
            "step must cover the window minus the clamped ledgers"
        );
        assert_eq!(t.measured_clocks() + t.idle_clocks(), 10);
        assert!(
            t.last_metrics.is_none(),
            "the reading is from a later clock"
        );
    }

    fn baseline_header(run_id: &str) -> RunHeader {
        RunHeader::from_race_options(RunConfig {
            data_dir: None,
            explicit_test_rows: None,
            eval_split: None,
            exam_rows: None,
            run_id: run_id.to_string(),
            engine_mode: Some("tabular".into()),
            run_seed: 42,
            fitness_label: FitnessLabel("f1".to_string()),
            fitness_direction: Direction::Maximize,
            input_dim: 784,
            output_dim: 10,
            topology_options: TopologyOptions::default(),
            hidden_dim_pool: 4..=8,
            hidden_dim_stride: 1,
            combine_op_pool: vec!["Mean".into(), "Min".into()],
            activation_pool: vec!["ReLU".into(), "SELU".into()],
            standardize_op_pool: vec!["Identity".into()],
            informative_metrics: vec![Metric::custom("dummy", |_p, _y| Ok(0.0))],
            max_steps: Some(10_000),
            train_eval_split_ratio: Some(0.2),
            culls: 0,
            run_elapsed_secs: 0,
            children_born_at_clock: std::collections::HashMap::new(),
            config: ConfigSnapshot::default(),
            trainer: None,
        })
    }

    /// Both cull channels reach `engine.json` under their OWN key, with the stable snake_case spelling (not `Debug` casing): a header is a record a reader parses, and a…
    #[test]
    fn config_snapshot_records_both_cull_policies_in_snake_case() {
        use crate::engine::config::{CrossCullPolicy, MutationCullPolicy, RaceConfig};
        let mut cfg = RaceConfig::defaults();
        cfg.crossover_cull_policy = CrossCullPolicy::Random;
        cfg.mutation_cull_policy = MutationCullPolicy::LowestFitnessMostUpdates;
        let snap = ConfigSnapshot::from_config(&cfg, None, None);
        assert_eq!(snap.crossover_cull_policy, "random");
        assert_eq!(snap.mutation_cull_policy, "lowest_fitness_most_updates");
        // …and the default run records the policy it actually culls with —
        // `lowest_fitness_most_updates`, the `#[default]` on BOTH channels and the defaults() value.
        let dflt = ConfigSnapshot::from_config(&RaceConfig::defaults(), None, None);
        assert_eq!(dflt.mutation_cull_policy, "lowest_fitness_most_updates");
        assert_eq!(dflt.crossover_cull_policy, "lowest_fitness_most_updates");
    }

    /// The tombstone's mean was renamed (`final_smoothed_fitness` → `final_fitness_mean`); every file written before the rename must still load, or the seeding path silently…
    #[test]
    fn a_legacy_tombstone_key_still_loads_as_the_mean() {
        let legacy = serde_json::json!({
            "hash": "h",
            "net_seed": 1,
            "topology": "{}",
            "step": 0,
            "entered_at_step": 0,
            "is_alive": false,
            "final_smoothed_fitness": 1.5,
        });
        let state: NetState = serde_json::from_value(legacy).expect("legacy tombstone loads");
        assert_eq!(state.final_fitness_mean, Some(1.5));
        // New files serialize under the new name only (no duplicate key).
        let raw = serde_json::to_string(&state).unwrap();
        assert!(raw.contains("\"final_fitness_mean\""), "{raw}");
        assert!(!raw.contains("final_smoothed_fitness"), "{raw}");
    }

    /// The artifact switches and the CSV flush cadence reach `engine.json` too: they never change
    /// the search, but an artifact trail without a record of what was ASKED for cannot be read
    #[test]
    fn config_snapshot_records_artifact_flags() {
        use crate::engine::config::RaceConfig;
        let mut cfg = RaceConfig::defaults();
        cfg.champion_save_topology = false;
        let snap = ConfigSnapshot::from_config(&cfg, None, None);
        assert!(!snap.champion_save_topology);

        // A pre-field header must read the defaults those runs actually ran
        let legacy: ConfigSnapshot = serde_json::from_str("{}").expect("empty snapshot loads");
        assert!(legacy.champion_save_topology);
    }

    /// A header written before the field existed must read as the policy those runs actually used
    /// (`worst`) — not as an empty string a reader would have to guess at, and not as the enum's
    #[test]
    fn a_pre_field_header_reads_the_legacy_mutation_policy() {
        let legacy: ConfigSnapshot = serde_json::from_str("{}").expect("empty snapshot loads");
        assert_eq!(legacy.mutation_cull_policy, "worst");
        // The container-level `serde(default)` must not win over the field default.
        let explicit: ConfigSnapshot = serde_json::from_str(r#"{"mutation_cull_policy":"random"}"#)
            .expect("explicit policy loads");
        assert_eq!(explicit.mutation_cull_policy, "random");
    }

    fn tiny_topology() -> Topology {
        let mut topo = crate::graph::topology::Topology::new(
            0,
            Some(crate::graph::topology::TopologyOptions {
                topology_seed: 7,
                min_hidden_num_nodes: 1,
                max_hidden_num_nodes: 1,
                min_hidden_inputs_per_node: 1,
                max_hidden_inputs_per_node: 1,
                min_hidden_outputs_per_node: 1,
                max_hidden_outputs_per_node: 1,
                input_dim: Some(2),
                output_dim: Some(2),
                dropout_prob: 0.0,
                feature_split: None,
                weight_seed: None,
            }),
        );
        topo.nodes.push(crate::graph::node::Node::new_input(0, 2));
        topo.nodes
            .push(crate::graph::node::Node::new_hidden(1, 2, 4));
        topo.nodes
            .push(crate::graph::node::Node::new_output(2, 4, 2));
        topo
    }

    #[test]
    fn engine_json_write_and_read_back_identical() {
        let dir = fresh_dir();
        let header = baseline_header("run-1");
        write_engine_json(&dir, &header).unwrap();
        let loaded = load_engine_json(&dir).unwrap();
        assert_eq!(loaded.run_id, "run-1");
        assert_eq!(loaded.run_seed, 42);
        assert_eq!(loaded.fitness_label.0, "f1");
        assert_eq!(loaded.fitness_direction, Direction::Maximize);
        assert_eq!(loaded.input_dim, 784);
        assert_eq!(loaded.output_dim, 10);
        assert_eq!(loaded.max_steps, Some(10_000));
        // Overwrite changes the header.
        let updated = baseline_header("run-2");
        write_engine_json(&dir, &updated).unwrap();
        let again = load_engine_json(&dir).unwrap();
        assert_eq!(again.run_id, "run-2");
    }

    /// Selection terms survive the header round trip.
    #[test]
    fn selection_metrics_round_trip() {
        let mut cfg = crate::engine::config::RaceConfig::defaults();
        cfg.selection_metrics = vec![crate::utils::fitness::SelectionMetric {
            label: "r2".to_string(),
            weight: -0.25,
        }];
        let snapshot = ConfigSnapshot::from_config(&cfg, None, None);
        let back: ConfigSnapshot =
            serde_json::from_str(&serde_json::to_string(&snapshot).unwrap()).unwrap();
        assert_eq!(back.selection_metrics, cfg.selection_metrics);
    }

    /// The parent draw is recorded as its label; a pre-knob `engine.json` (no key at all) loads as `""`, which the resume guard reads as roulette — the draw those runs actually…
    #[test]
    fn config_snapshot_records_the_crossover_selection() {
        use crate::evolution::selection::SelectionMethod;
        let snapshot =
            ConfigSnapshot::from_config(&crate::engine::config::RaceConfig::defaults(), None, None);
        assert_eq!(snapshot.crossover_selection, "tournament(size=2)");
        // Round-trips at a non-default method…
        let mut cfg = crate::engine::config::RaceConfig::defaults();
        cfg.crossover_selection = SelectionMethod::Tournament { tournament_size: 4 };
        let json = serde_json::to_string(&ConfigSnapshot::from_config(&cfg, None, None)).unwrap();
        assert!(
            json.contains("tournament(size=4)"),
            "the header must name the draw: {json}"
        );
        // …and a pre-knob header (key removed) loads as empty, not as a made-up method.
        let mut legacy: serde_json::Value = serde_json::from_str(&json).unwrap();
        legacy
            .as_object_mut()
            .unwrap()
            .remove("crossover_selection");
        let loaded: ConfigSnapshot = serde_json::from_value(legacy).unwrap();
        assert_eq!(loaded.crossover_selection, "");
    }

    /// The feature-split POLICY is recorded (the masks themselves are genome live in each net's blueprint): the header must say how the run drew them, and a pre-knob…
    #[test]
    fn config_snapshot_records_the_feature_split_policy() {
        use crate::graph::topology::FeatureSplitPolicy;
        let mut cfg = crate::engine::config::RaceConfig::defaults();
        cfg.feature_split_pool = Vec::new();
        let all = ConfigSnapshot::from_config(&cfg, None, None);
        assert_eq!(
            all.feature_split, None,
            "an all-three pool is not one policy"
        );
        assert_eq!(
            all.feature_split_pool,
            vec!["none", "split_random", "split_exclusive"],
            "the record names the resolved pool, in draw order"
        );
        for (policy, wire) in [
            (FeatureSplitPolicy::Exclusive, "split_exclusive"),
            (FeatureSplitPolicy::Random, "split_random"),
        ] {
            cfg.feature_split_pool = vec![policy.to_string()];
            let snap = ConfigSnapshot::from_config(&cfg, None, None);
            assert_eq!(snap.feature_split.as_deref(), Some(wire));
            // Round-trips…
            let json = serde_json::to_string(&snap).unwrap();
            let back: ConfigSnapshot = serde_json::from_str(&json).unwrap();
            assert_eq!(back.feature_split, snap.feature_split);
            // …and a header written before the key existed loads as no split.
            let mut legacy: serde_json::Value = serde_json::from_str(&json).unwrap();
            legacy.as_object_mut().unwrap().remove("feature_split");
            let loaded: ConfigSnapshot = serde_json::from_value(legacy).unwrap();
            assert_eq!(
                loaded.feature_split, None,
                "a legacy header predates the split"
            );
        }
    }

    #[test]
    fn net_state_round_trip_keeps_hash_and_seed_and_step() {
        let dir = fresh_dir();
        let topo = tiny_topology();
        let mut state = NetState::new(&topo, 0, Some("parent-a x parent-b".into())).unwrap();
        state.record_metrics(NetMetrics {
            step: 5,
            train_loss: 1.25,
            eval_loss: Some(1.40),
            fitness: 0.61,
            informative: vec![0.4, 0.6],
            frozen: false,
        });
        write_net_state(&dir, &state).unwrap();
        let loaded = load_net_state(&dir, &state.hash).unwrap();
        assert_eq!(loaded.hash, state.hash);
        assert_eq!(loaded.net_seed, 7);
        assert_eq!(loaded.step, 0);
        assert_eq!(loaded.entered_at_step, 0);
        assert_eq!(loaded.created_from.as_deref(), Some("parent-a x parent-b"));
        let m = loaded.last_metrics.as_ref().unwrap();
        assert_eq!(m.step, 5);
        assert_eq!(m.train_loss, 1.25);
        assert_eq!(m.eval_loss, Some(1.40));
        assert_eq!(m.fitness, 0.61);
        assert_eq!(m.informative, vec![0.4, 0.6]);
        // Topology round-trips exactly (topo_hash is canonical — same JSON ⇒ same hash).
        assert_eq!(loaded.hash, topo_hash(&loaded.topology));
        let rebuilt = loaded.topology().unwrap();
        let rebuilt_json = rebuilt.to_json().unwrap();
        assert_eq!(rebuilt_json, loaded.topology);
    }

    /// Schema separation: run-level facts in the header's `config`, per-net facts
    /// `nets/<hash>.json` — neither invents a value for a mode that has none.
    #[test]
    fn schema_records_mode_appropriate_geometry_and_no_trainer_owned_fields() {
        // RL header: no stream, so geometry is genuinely absent (`null`),
        // the step budget sits beside the fitness target in `config`.
        let rl_cfg = crate::engine::RaceConfig {
            mode: crate::engine::config::RunMode::Rl,
            max_steps: Some(25),
            ..Default::default()
        };
        let rl = ConfigSnapshot::from_config(&rl_cfg, None, None);
        assert_eq!(rl.batch_size, None);
        assert_eq!(rl.eval_batch_size, None);
        assert_eq!(
            rl.max_steps,
            Some(25),
            "step budget recorded with the stop criteria"
        );

        // Tabular header: the stream shape the run actually used is recorded.
        let tab =
            ConfigSnapshot::from_config(&crate::engine::RaceConfig::default(), Some(16), Some(128));
        assert_eq!(tab.batch_size, Some(16));
        assert_eq!(tab.eval_batch_size, Some(128));

        // In the written header, absent means absent — not a 16 default.
        let dir = fresh_dir();
        let mut header = baseline_header("rl-run");
        header.config = rl;
        write_engine_json(&dir, &header).unwrap();
        let v: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(dir.join("engine.json")).unwrap())
                .unwrap();
        assert_eq!(v["config"]["batch_size"], serde_json::Value::Null);
        assert_eq!(v["config"]["max_steps"], serde_json::json!(25));

        // Per-net meta follows the same rule, and carries no trainer-owned knob.
        let topo = tiny_topology();
        let net = crate::graph::network::Network::build(&topo, crate::Device::CPU).unwrap();
        let mut state = NetState::new(&topo, 0, None).unwrap();
        state.stamp_meta(&net, &crate::engine::config::RunMetaCtx::default());
        assert_eq!(state.meta.batch_size, None);
        let net_json: serde_json::Value = serde_json::from_str(&state.to_json().unwrap()).unwrap();
        for absent in ["loss_label", "learning_rate", "grad_clip"] {
            assert!(
                net_json["meta"].get(absent).is_none(),
                "`{absent}` is trainer-owned (engine.json → trainer), not per-net schema"
            );
        }
    }

    #[test]
    fn overwrite_replaces_previous_step() {
        let dir = fresh_dir();
        let topo = tiny_topology();
        let mut state = NetState::new(&topo, 0, None).unwrap();
        state.record_metrics(NetMetrics {
            step: 0,
            train_loss: 2.0,
            eval_loss: Some(2.1),
            fitness: 0.1,
            informative: vec![],
            frozen: false,
        });
        write_net_state(&dir, &state).unwrap();

        state.advance_step();
        state.record_metrics(NetMetrics {
            step: 1,
            train_loss: 1.5,
            eval_loss: Some(1.6),
            fitness: 0.2,
            informative: vec![],
            frozen: false,
        });
        write_net_state(&dir, &state).unwrap();

        let loaded = load_net_state(&dir, &state.hash).unwrap();
        assert_eq!(loaded.step, 1);
        assert_eq!(loaded.last_metrics.as_ref().unwrap().fitness, 0.2);
    }

    #[test]
    fn race_state_insert_and_remove() {
        let mut st = RaceState::new();
        let topo = tiny_topology();
        let state = NetState::new(&topo, 0, None).unwrap();
        st.insert(state, Some(0.3));

        assert_eq!(st.live_count(), 1);
        let hashes = st.live_hashes();
        assert_eq!(hashes.len(), 1);
        assert_eq!(hashes[0].len(), 16);

        let removed = st.remove(&hashes[0]);
        assert!(removed.is_some());
        assert_eq!(st.live_count(), 0);
    }

    #[test]
    fn race_state_lifetime_tracks_appearances_and_span() {
        let mut st = RaceState::new();
        let topo = tiny_topology();
        // Insert a net at step 10 with an initial fitness — the lifetime
        // accumulator seeds from that entry call.
        let state = NetState::new(&topo, 10, None).unwrap();
        st.insert(state, Some(0.3));

        let h = st.live_hashes()[0].clone();
        // Each record_step advances the net's own step counter, and seeds
        // updates the per-topology lifetime from the metrics' step and fitness.
        st.record_step(
            &h,
            NetMetrics {
                step: 10,
                train_loss: 0.0,
                eval_loss: None,
                fitness: 0.4,
                informative: vec![],
                frozen: false,
            },
        )
        .unwrap();
        st.record_step(
            &h,
            NetMetrics {
                step: 11,
                train_loss: 0.0,
                eval_loss: None,
                fitness: 0.5,
                informative: vec![],
                frozen: false,
            },
        )
        .unwrap();

        let (_, life) = st.lifetimes().into_iter().next().unwrap();
        assert_eq!(life.appearances(), 1);
        assert_eq!(life.first_step(), 10);
        assert_eq!(life.last_step(), 11);
        assert_eq!(life.span(), 1);
        assert_eq!(life.last_fitness(), Some(0.5));
        assert_eq!(st.live_count(), 1);
    }

    #[test]
    fn removed_net_file_is_gone() {
        let dir = fresh_dir();
        let topo = tiny_topology();
        let state = NetState::new(&topo, 0, None).unwrap();
        write_net_state(&dir, &state).unwrap();
        assert!(
            dir.join("nets")
                .join(format!("{}.json", state.hash))
                .exists()
        );
        remove_net_state(&dir, &state.hash).unwrap();
        assert!(
            !dir.join("nets")
                .join(format!("{}.json", state.hash))
                .exists()
        );
    }

    #[test]
    fn load_nonexistent_net_errors() {
        let dir = fresh_dir();
        let err = load_net_state(&dir, "deadbeef").unwrap_err();
        assert!(err.to_string().contains("cannot access"));
    }
}