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
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
//! The graph blueprint — pure topology data, no tensors.

use fastrand::Rng;
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

use crate::utils::error::TopologyError;

use crate::graph::node::{Activation, Node, NodeKind};

pub use crate::graph::node::CombineOp;

// ── KindCounts — node-role histogram ──────────────────────────────────────

/// Node counts by kind — the return type of [`Topology::kind_counts`]:
/// no more guessing the order of a bare `(usize, usize, usize)` tuple.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct KindCounts {
    /// Input-node count.
    pub input: usize,
    /// Hidden-node count.
    pub hidden: usize,
    /// Output-node count.
    pub output: usize,
}

/// Knobs for building a graph: dims, RNG seed, combine op, ranges. Serialized
/// every topology, so a saved graph is self-describing for `Network::build`.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
// ── TopologyOptions — the blueprint template ──────────────────────────────

/// Knobs for building a graph (see the module docs).
pub struct TopologyOptions {
    /// RNG seed — same seed => same random graph.
    pub topology_seed: usize,
    /// Seed the network's INITIAL WEIGHTS are drawn from, when it must differ from `topology_seed`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub weight_seed: Option<usize>,
    /// Min hidden nodes per individual (sampled by engine).
    pub min_hidden_num_nodes: usize,
    /// Max hidden nodes per individual (sampled by engine).
    pub max_hidden_num_nodes: usize,
    /// Each random hidden node gets at least this many inputs.
    pub min_hidden_inputs_per_node: usize,
    /// Each random hidden node gets at most this many inputs.
    pub max_hidden_inputs_per_node: usize,
    /// Each random hidden node gets at least this many outputs.
    pub min_hidden_outputs_per_node: usize,
    /// Each random hidden node gets at most this many outputs.
    pub max_hidden_outputs_per_node: usize,
    /// Feature dimension of the network input tensor. `None` = infer
    /// dataset at run start (the engine fills it in and validates
    pub input_dim: Option<usize>,
    /// Output dimension of the network (set on the Output node's layer).
    /// `None` = infer from the dataset at run start.
    pub output_dim: Option<usize>,
    /// Dropout probability the engine used when building this topology's network —
    /// part of the blueprint so replays don't diverge; defaults to 0.0.
    #[serde(default)]
    pub dropout_prob: f32,
    /// Feature-split policy this blueprint's Input ports were drawn under — part of the topology,
    /// not the run, so a newborn's policy travels with its blueprint and a population can hold
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feature_split: Option<FeatureSplitPolicy>,
}

// `dropout_prob: f32` isn't `Eq`/`Hash`, so these are manual: every other field compares normally,
// dropout by bit pattern.
impl PartialEq for TopologyOptions {
    fn eq(&self, other: &Self) -> bool {
        self.topology_seed == other.topology_seed
            && self.min_hidden_num_nodes == other.min_hidden_num_nodes
            && self.max_hidden_num_nodes == other.max_hidden_num_nodes
            && self.min_hidden_inputs_per_node == other.min_hidden_inputs_per_node
            && self.max_hidden_inputs_per_node == other.max_hidden_inputs_per_node
            && self.min_hidden_outputs_per_node == other.min_hidden_outputs_per_node
            && self.max_hidden_outputs_per_node == other.max_hidden_outputs_per_node
            && self.input_dim == other.input_dim
            && self.output_dim == other.output_dim
            && self.dropout_prob.to_bits() == other.dropout_prob.to_bits()
            && self.feature_split == other.feature_split
    }
}

impl Eq for TopologyOptions {}

impl std::hash::Hash for TopologyOptions {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.topology_seed.hash(state);
        self.min_hidden_num_nodes.hash(state);
        self.max_hidden_num_nodes.hash(state);
        self.min_hidden_inputs_per_node.hash(state);
        self.max_hidden_inputs_per_node.hash(state);
        self.min_hidden_outputs_per_node.hash(state);
        self.max_hidden_outputs_per_node.hash(state);
        self.input_dim.hash(state);
        self.output_dim.hash(state);
        self.dropout_prob.to_bits().hash(state);
        self.feature_split.hash(state);
    }
}

/// How a topology draws the Input node's per-port feature masks — the feature split.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FeatureSplitPolicy {
    /// **Exclusive** — every feature lands in exactly one port (a true partition): drawn as "each
    /// feature picks one random port".
    Exclusive,
    /// **Random** — every port flips an independent `p = 0.5` coin per feature.
    /// A feature can land in several ports, and some features may go unused.
    Random,
    /// **Inherited** — the rows were RECOMBINED from two parents, so they are neither a fresh
    /// partition (`Exclusive`) nor a fresh coin flip (`Random`): a per-port mix of two partitions
    Inherited,
}

impl FeatureSplitPolicy {
    /// Whether a run's pool may DRAW this policy for a newborn. `Inherited` describes
    /// provenance, so it can only arrive through crossover.
    pub fn is_drawable(self) -> bool {
        !matches!(self, FeatureSplitPolicy::Inherited)
    }
}

/// Whether `rows` PARTITION the input: every feature belongs to exactly one port.
fn split_rows_are_partition(rows: &[Vec<u8>], input_dim: usize) -> bool {
    (0..input_dim).all(|feat| {
        rows.iter()
            .filter(|row| row.get(feat).copied().unwrap_or(0) != 0)
            .count()
            == 1
    })
}

impl Default for TopologyOptions {
    fn default() -> Self {
        TopologyOptions {
            topology_seed: 55,
            min_hidden_num_nodes: 2,
            // The cartpole reference's caps, promoted to the engine defaults: the mins stay at 2
            // bare chain still exists) and the maxes allow a genuinely wide net, which is what
            max_hidden_num_nodes: 15,
            min_hidden_inputs_per_node: 2,
            max_hidden_inputs_per_node: 15,
            min_hidden_outputs_per_node: 2,
            max_hidden_outputs_per_node: 15,
            input_dim: None,
            output_dim: None,
            // `0.25` — the cartpole reference's dropout, promoted to the engine default.
            dropout_prob: 0.25,
            feature_split: None,
            weight_seed: None,
        }
    }
}

// ── Port & Connection — wiring primitives ─────────────────────────────────

/// A port is a "socket" on a node: a destination (input port) or a source (output
/// port). **All of a node's output ports emit the same tensor** — index is bookkeeping.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Port {
    pub node: usize,  //  which node
    pub index: usize, //  which socket on that node
}

/// A directed wire from one node's output port to another node's input port, e.g.
/// `n1_o0 -> n2_i0`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Connection {
    /// Wire source (output port).
    pub from: Port,
    /// Wire destination (input port).
    pub to: Port,
}

impl Connection {
    /// Source port label, e.g. `"n0_o0"`.
    pub fn from_label(&self) -> String {
        format!("n{}_o{}", self.from.node, self.from.index)
    }

    /// Destination port label, e.g. `"n1_i0"`.
    pub fn to_label(&self) -> String {
        format!("n{}_i{}", self.to.node, self.to.index)
    }
}

// ── graph diagnostics ─────────────────────────────────────────────────
// Free functions live in `crate::utils::graph_utils`; methods delegate to them.

/// What one crossover operator actually exchanged — the operator's own answer, carried so the birth
/// can say how much of the child came from the other parent.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CxReport {
    /// Genes taken from the other parent.
    pub swaps: usize,
    /// Genes the operator compared (the denominator of `3/6`).
    pub pairs: usize,
    /// PROVENANCE, one slot per HIDDEN node in child order: `Some(i)` = this gene came from node
    /// `i` of the other parent, `None` = it stayed with the kept parent.
    pub moved: Vec<Option<usize>>,
    /// The MIRROR of [`Self::moved`] for the reciprocal child (`b` after the cut): `Some(i)` =
    /// slot came from node `i` of `a`, `None` = it stayed with `b`.
    pub moved_b: Vec<Option<usize>>,
}

impl CxReport {
    /// `3/6` — the spelling the log line, the origin cell and the lineage string use.
    pub fn label(&self) -> String {
        format!("{}/{}", self.swaps, self.pairs)
    }
}

/// The blueprint of a gras network: pure data, no tensors — **who exists**
/// (`nodes`) and **who feeds whom** (`connections`). Inert until validated/built.
#[derive(Clone, Debug, PartialEq)]
// ── Topology — the graph blueprint ───────────────────────────────────────

/// The blueprint of a gras network: pure data, no tensors.
pub struct Topology {
    /// Instance id (used to name `Network`s uniquely).
    pub id: usize,
    /// Nodes, ids contiguous `0..n`.
    pub nodes: Vec<Node>,
    /// Dims, RNG seed, combine op.
    pub options: TopologyOptions,
    pub(crate) graph_inputs: Vec<String>,
    pub(crate) graph_outputs: Vec<String>,
    /// Wires from output ports to input ports.
    pub connections: Vec<Connection>,
    pub(crate) rng: Rng,
}

impl Topology {
    // ── Creation ─────────────────────────────────────────────────────────────

    /// Create an empty graph; `None` uses the default options. Add nodes
    /// [`Node`] constructors + `graph.nodes.push(...)`.
    pub fn new(id: usize, options: Option<TopologyOptions>) -> Topology {
        // Create a new graph with the given id and options, or default options if None
        let opts = options.unwrap_or_default();
        Topology {
            id,
            nodes: Vec::new(),
            options: opts,
            graph_inputs: Vec::new(),
            graph_outputs: Vec::new(),
            connections: Vec::new(),
            rng: Rng::with_seed(opts.topology_seed as u64),
        }
    }

    /// Append one random hidden node whose port counts come from the options ranges;
    /// its id is the current node count, so ids stay contiguous.
    pub fn create_random_hidden_node(&mut self) {
        // Random input/output counts within the options ranges:
        // inputs ∈ [min,max]_hidden_inputs_per_node; outputs likewise.
        let num_inputs = self.rng.usize(
            self.options.min_hidden_inputs_per_node..=self.options.max_hidden_inputs_per_node,
        );
        let num_outputs = self.rng.usize(
            self.options.min_hidden_outputs_per_node..=self.options.max_hidden_outputs_per_node,
        );
        // Node id = current node count, so ids stay contiguous: 0, 1, 2, ...
        let node = Node::new_hidden(self.nodes.len(), num_inputs, num_outputs);
        self.nodes.push(node);
    }

    /// Append `num_nodes` random hidden nodes (see
    /// [`Topology::create_random_hidden_node`]).
    pub fn create_random_hidden_nodes(&mut self, num_nodes: usize) {
        // Create multiple random hidden nodes
        for _ in 0..num_nodes {
            self.create_random_hidden_node();
        }
    }

    /// Assign per-output-port activations to every hidden node from `pool`: port 0
    /// mirrors the node-level activation, ports 1..n draw from the seeded RNG.
    pub fn assign_port_activations(&mut self, pool: &[Activation]) {
        if pool.is_empty() {
            return;
        }
        for node in &mut self.nodes {
            if node.kind == NodeKind::Input || node.num_outputs <= 1 {
                continue;
            }
            // FILL-ONLY: a port's activation is genome, and `finalize` carries it through the port
            // remap — so only ports that still have none (a fresh net, or a port the rebuild ADDED)
            let mut ports: Vec<Option<Activation>> = node
                .port_activations
                .take()
                .unwrap_or_default()
                .into_iter()
                .map(Some)
                .collect();
            ports.truncate(node.num_outputs);
            ports.resize(node.num_outputs, None);
            for slot in ports.iter_mut().skip(1) {
                if slot.is_none() {
                    *slot = Some(pool[self.rng.usize(0..pool.len())]);
                }
            }
            // Port 0 mirrors the node-level activation by construction:
            // node gene, not a per-port one.
            ports[0] = Some(node.activation);
            node.port_activations = Some(
                ports
                    .into_iter()
                    .map(|p| p.unwrap_or(node.activation))
                    .collect(),
            );
        }
    }

    /// Assign per-output-port feature masks to the Input node from `policy` — the feature split.
    pub fn assign_feature_masks(&mut self, policy: FeatureSplitPolicy) {
        let input_dim = self.options.input_dim.unwrap_or(1);
        let Some(input) = self.nodes.iter().position(|n| n.kind == NodeKind::Input) else {
            return;
        };
        let n_ports = self.nodes[input].num_outputs.max(1);
        if input_dim == 0 {
            return;
        }
        let mut masks = vec![vec![0u8; input_dim]; n_ports];
        match policy {
            // Provenance, not a draw rule: the only way to get these rows is to inherit
            // them, so drawing is a no-op rather than a guess at what they ''should'' be.
            FeatureSplitPolicy::Inherited => return,
            FeatureSplitPolicy::Exclusive => {
                // Each feature picks one random port: by construction every feature is placed
                // exactly once and none is shared.
                let owners: Vec<usize> =
                    (0..input_dim).map(|_| self.rng.usize(0..n_ports)).collect();
                for (feat, &port) in owners.iter().enumerate() {
                    masks[port][feat] = 1;
                }
            }
            FeatureSplitPolicy::Random => {
                // Independent coin flip per (port, feature): overlaps allowed, and some
                // features may go unused.
                for mask in masks.iter_mut() {
                    for slot in mask.iter_mut() {
                        *slot = u8::from(self.rng.f32() < 0.5);
                    }
                }
            }
        }
        self.nodes[input].feature_masks = Some(masks);
        self.options.feature_split = Some(policy);
    }

    /// The Input node's per-port feature masks, cloned (`None` when this topology carries no
    /// split).
    pub fn input_feature_masks(&self) -> Option<Vec<Vec<u8>>> {
        self.nodes
            .iter()
            .find(|n| n.kind == NodeKind::Input)
            .and_then(|n| n.feature_masks.clone())
    }

    /// Install INHERITED masks on the Input node — the crossover path's counterpart
    /// [`Self::assign_feature_masks`].
    pub fn install_input_feature_masks(
        &mut self,
        rows: &[Vec<u8>],
        policy: Option<FeatureSplitPolicy>,
    ) {
        let input_dim = self.options.input_dim.unwrap_or(1);
        let Some(input) = self.nodes.iter().position(|n| n.kind == NodeKind::Input) else {
            return;
        };
        if input_dim == 0 {
            return;
        }
        // Nothing inherited at all: keep the net UNSHARED (no rows, no masks) rather
        // materializing cover-all rows, which cost a real elementwise multiply at every forward
        if rows.is_empty() {
            self.nodes[input].feature_masks = None;
            self.options.feature_split = policy;
            return;
        }
        let n_ports = self.nodes[input].num_outputs.max(1);
        let masks: Vec<Vec<u8>> = (0..n_ports)
            .map(|i| {
                rows.get(i)
                    // No inherited row for this port: every feature reaches
                    .cloned()
                    .unwrap_or_else(|| vec![1u8; input_dim])
            })
            .collect();
        // PADDING BREAKS AN `Exclusive` CLAIM.
        let partition = split_rows_are_partition(&masks, input_dim);
        self.nodes[input].feature_masks = Some(masks);
        self.options.feature_split = Some(match policy.unwrap_or(FeatureSplitPolicy::Inherited) {
            FeatureSplitPolicy::Exclusive if !partition => FeatureSplitPolicy::Inherited,
            kept => kept,
        });
    }

    /// Reconcile a LOADED blueprint with the rule "rows present ⇒ policy present": a record written
    /// before `Inherited` existed (or by the crossover bug it fixes) can carry masks under
    pub fn reconcile_split_policy(&mut self) {
        if self.options.feature_split.is_none()
            && self
                .nodes
                .iter()
                .any(|n| n.kind == NodeKind::Input && n.feature_masks.is_some())
        {
            self.options.feature_split = Some(FeatureSplitPolicy::Inherited);
            return;
        }
        // And the other direction: a record can STATE `Exclusive` while carrying rows
        // a partition (a port the rebuild added, or one an older build padded).
        if self.options.feature_split == Some(FeatureSplitPolicy::Exclusive) {
            let input_dim = self.options.input_dim.unwrap_or(1);
            if let Some(masks) = self.input_feature_masks() {
                if !split_rows_are_partition(&masks, input_dim) {
                    self.options.feature_split = Some(FeatureSplitPolicy::Inherited);
                }
            }
        }
    }

    /// Assign every hidden node a random activation from `pool` (Input/Output stay
    /// `Identity`). Refresh the port labels (`n1_i0`, `n2_o3`, …) for printing.
    pub fn renumber_ids(&mut self) {
        for (i, node) in self.nodes.iter_mut().enumerate() {
            node.id = i;
        }
    }

    ///   num_inputs  labels to graph_inputs  -> "n{i}_i0", "n{i}_i1", ...
    ///   num_outputs labels to graph_outputs -> "n{i}_o0", "n{i}_o1", ...
    pub fn refresh_labels(&mut self) {
        self.graph_inputs.clear();
        self.graph_outputs.clear();

        for node in &self.nodes {
            for i in 0..node.num_inputs {
                self.graph_inputs.push(format!("n{}_i{}", node.id, i));
            }
            for i in 0..node.num_outputs {
                self.graph_outputs.push(format!("n{}_o{}", node.id, i));
            }
        }
    }

    /// Finalize the graph: scaffold the skeleton, wire every port, and auto-de-orphan
    /// dangling outputs — one call turns a pile of nodes into a complete graph.
    pub fn finalize(&mut self) {
        self.connections.clear();

        // Step 1: build_skeleton — ensure Input + Output nodes exist
        self.ensure_scaffold();

        // Step 2: fill_dims — resolve per-node hidden_dim (None -> graph default)
        self.resolve_dims();

        // Step 3: mark_ports — refresh port labels for display
        self.refresh_labels();

        // Step 4: connect — wire input ports to unused output ports from earlier nodes
        self.wire_ports();

        // Step 5: filter_input — set input node output count = number of hidden nodes
        self.set_input_fanout();

        // Step 6: connect_orphans — wire orphaned inputs to the input node (cycle ports)
        self.rewire_orphaned_inputs();

        // Step 6b: clean_wiring — one Input wire per target (the Input node fans out)
        self.dedup_input_connections();

        // Step 7: rescue_outputs — wire orphaned outputs into a free input port, or grow
        // one. Inline de-dup: a rescue never repeats a source→target pair.
        self.rewire_orphaned_outputs();

        // Step 8: trim_ports — drop ports nothing uses and renumber the rest
        self.trim_orphaned_ports();

        // Step 9: verify — validate the final wiring
        if let Err(e) = self.validate() {
            panic!("finalize validation failed: {e}\n{self:?}");
        }
    }

    /// Step 2: Resolve per-node hidden_dim -- None becomes graph default.
    fn resolve_dims(&mut self) {
        let eff = self.effective_hidden_dim();
        for node in &mut self.nodes {
            if node.hidden_dim.is_none() {
                node.hidden_dim = Some(match node.kind {
                    NodeKind::Output => self.options.output_dim.unwrap_or(1),
                    _ => eff,
                });
            }
        }
    }

    /// Step 4: Wire input ports to unused output ports from earlier nodes.
    fn wire_ports(&mut self) {
        let mut input_ports: Vec<Port> = Vec::new();
        let mut output_ports: Vec<Port> = Vec::new();
        for node in &self.nodes {
            for i in 0..node.num_inputs {
                input_ports.push(Port {
                    node: node.id,
                    index: i,
                });
            }
            for i in 0..node.num_outputs {
                output_ports.push(Port {
                    node: node.id,
                    index: i,
                });
            }
        }
        self.rng.shuffle(&mut input_ports);
        self.rng.shuffle(&mut output_ports);

        let mut used = vec![false; output_ports.len()];
        for target in input_ports {
            // Track which source nodes already feed this target (avoid redundancy).
            let already_used: Vec<usize> = self
                .connections
                .iter()
                .filter(|c| c.to.node == target.node)
                .map(|c| c.from.node)
                .collect();
            let source = output_ports
                .iter()
                .enumerate()
                .find(|(i, p)| !used[*i] && p.node < target.node && !already_used.contains(&p.node))
                .map(|(i, p)| (i, *p));
            if let Some((i, source)) = source {
                used[i] = true;
                self.connections.push(Connection {
                    from: source,
                    to: target,
                });
            }
        }
    }

    /// Step 5: Set input node output count = number of hidden nodes (at least).
    fn set_input_fanout(&mut self) {
        let n_hidden = self
            .nodes
            .iter()
            .filter(|n| n.kind == NodeKind::Hidden)
            .count();
        let input_node = self
            .nodes
            .iter_mut()
            .find(|n| n.kind == NodeKind::Input)
            .unwrap();
        input_node.num_outputs = input_node.num_outputs.max(n_hidden).max(1);
    }

    /// Step 6: wire orphaned input ports to the input node's output ports, cycling
    /// through available ports (the combine op merges shared ones).
    fn rewire_orphaned_inputs(&mut self) {
        let input_id = self
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Input)
            .unwrap()
            .id;
        let n_ports = self
            .nodes
            .iter()
            .find(|n| n.id == input_id)
            .unwrap()
            .num_outputs;
        let mut output_idx = 0usize;
        for node in &self.nodes {
            for i in 0..node.num_inputs {
                let port = Port {
                    node: node.id,
                    index: i,
                };
                if !self.connections.iter().any(|c| c.to == port) {
                    self.connections.push(Connection {
                        from: Port {
                            node: input_id,
                            index: output_idx % n_ports,
                        },
                        to: port,
                    });
                    output_idx += 1;
                }
            }
        }
    }

    /// The Input node is the one deliberate fan-out node (its ports are the features, and each may
    /// feed several targets), so ONE target must not be fed by two Input ports: every Input port
    fn dedup_input_connections(&mut self) {
        let input_id = self
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Input)
            .map(|n| n.id);
        if let Some(id) = input_id {
            let mut seen: Vec<usize> = Vec::new();
            self.connections.retain(|c| {
                if c.from.node != id {
                    return true;
                }
                if seen.contains(&c.to.node) {
                    false
                } else {
                    seen.push(c.to.node);
                    true
                }
            });
        }
    }

    /// Human-readable connection labels, e.g. `("n0_o0", "n1_i0")` — a string view
    /// `self.connections`, handy for debugging/DSL rendering.
    pub fn connection_labels(&self) -> Vec<(String, String)> {
        self.connections
            .iter()
            .map(|c| (c.from_label(), c.to_label()))
            .collect()
    }

    /// Check the graph is executable before building: contiguous ids, forward-only
    /// wires, in-range ports, output 1:1, no orphaned inputs. `Network::build` calls
    pub fn validate(&self) -> Result<(), TopologyError> {
        // 1. Options sanity
        if self.options.input_dim == Some(0) || self.options.output_dim == Some(0) {
            return Err(TopologyError::InvalidOptions(
                "input_dim and output_dim must be > 0 or unset (None)".to_string(),
            ));
        }
        if self.options.min_hidden_inputs_per_node > self.options.max_hidden_inputs_per_node
            || self.options.min_hidden_outputs_per_node > self.options.max_hidden_outputs_per_node
        {
            return Err(TopologyError::InvalidOptions(
                "min/max inputs or outputs per node ranges are inverted".to_string(),
            ));
        }

        // 2. At least one node, with contiguous ids and sane per-node dims
        if self.nodes.is_empty() {
            return Err(TopologyError::EmptyTopology);
        }
        for (i, node) in self.nodes.iter().enumerate() {
            if node.id != i {
                return Err(TopologyError::NonContiguousNodeIds);
            }
            if node.hidden_dim == Some(0) {
                return Err(TopologyError::InvalidOptions(format!(
                    "node n{i} has hidden_dim 0"
                )));
            }
            // Per-port activations: length must match the port count, and Input nodes
            // keep their ports raw (Identity) — activating raw data is a bug.
            if let Some(ports) = &node.port_activations {
                if ports.len() != node.num_outputs {
                    return Err(TopologyError::InvalidOptions(format!(
                        "node n{i} has {} port activations but {} output ports",
                        ports.len(),
                        node.num_outputs
                    )));
                }
                if node.kind == NodeKind::Input && ports.iter().any(|a| *a != Activation::Identity)
                {
                    return Err(TopologyError::InvalidOptions(format!(
                        "node n{i} is an Input node — its ports must stay Identity"
                    )));
                }
            }
            // Feature masks (the feature split): Input nodes only, one mask per
            // output port, each `input_dim` wide and 0/1-valued.
            if let Some(masks) = &node.feature_masks {
                if node.kind != NodeKind::Input {
                    return Err(TopologyError::InvalidOptions(format!(
                        "node n{i} carries feature masks but is not an Input node"
                    )));
                }
                let d = self.options.input_dim.unwrap_or(1);
                if masks.len() != node.num_outputs {
                    return Err(TopologyError::InvalidOptions(format!(
                        "node n{i} has {} feature masks but {} output ports",
                        masks.len(),
                        node.num_outputs
                    )));
                }
                if let Some(bad) = masks.iter().position(|m| m.len() != d) {
                    return Err(TopologyError::InvalidOptions(format!(
                        "node n{i} port {bad} carries a {}-entry feature mask but input_dim is {d}",
                        masks[bad].len()
                    )));
                }
                if masks.iter().flatten().any(|b| *b > 1) {
                    return Err(TopologyError::InvalidOptions(format!(
                        "node n{i} feature masks must be 0/1"
                    )));
                }
            }
        }

        // 2b. Exactly one Output node (output_dim handles the projection;
        //     multiple Output nodes are not supported).
        let n_outputs = self
            .nodes
            .iter()
            .filter(|n| n.kind == NodeKind::Output)
            .count();
        if n_outputs > 1 {
            return Err(TopologyError::InvalidOptions(
                "multiple Output nodes are not supported (use exactly one)".to_string(),
            ));
        }

        // 3.
        let mut used_sources: Vec<Port> = Vec::new();
        let mut used_targets: Vec<Port> = Vec::new();
        for conn in &self.connections {
            if conn.from.node >= conn.to.node {
                return Err(TopologyError::BackwardConnection(conn.clone()));
            }
            if conn.from.node >= self.nodes.len() || conn.to.node >= self.nodes.len() {
                return Err(TopologyError::UnknownNode(conn.from.node));
            }
            let src = &self.nodes[conn.from.node];
            let dst = &self.nodes[conn.to.node];
            if conn.from.index >= src.num_outputs {
                return Err(TopologyError::PortOutOfBounds {
                    port: conn.from,
                    num_ports: src.num_outputs,
                });
            }
            if conn.to.index >= dst.num_inputs {
                return Err(TopologyError::PortOutOfBounds {
                    port: conn.to,
                    num_ports: dst.num_inputs,
                });
            }
            // Input node's output ports can fan out to multiple destinations.
            let is_input_node = self.nodes[conn.from.node].kind == NodeKind::Input;
            if !is_input_node && used_sources.contains(&conn.from) {
                return Err(TopologyError::DoubleUsedOutput(conn.from));
            }
            used_sources.push(conn.from);
            if used_targets.contains(&conn.to) {
                return Err(TopologyError::MultiWiredInputPort(conn.to));
            }
            used_targets.push(conn.to);
        }

        // 4. Feature-dim consistency per node: with per-node hidden_dim + port
        // projections, all source dim combinations are valid. No check needed.

        Ok(())
    }

    /// Count orphaned ports: `(orphaned_inputs, orphaned_outputs)`. An orphaned input
    /// is fed `net_input` at execution; the graph-output node's ports are excluded.
    pub fn orphan_counts(&self) -> (usize, usize) {
        node_orphan_counts(&self.nodes, &self.connections, self.nodes.len() - 1)
    }

    // ── shared helpers ──────────────────────────────────────────────────

    /// Output dim of a node: its `hidden_dim` override, or the graph default.
    fn out_dim_of(&self, node: &Node) -> usize {
        node.hidden_dim.unwrap_or(8)
    }

    /// The effective hidden dim for orphan projections: the max output dim across
    /// nodes, so orphans project straight to the widest dim (no double projection).
    fn effective_hidden_dim(&self) -> usize {
        self.nodes
            .iter()
            .map(|n| self.out_dim_of(n))
            .max()
            .unwrap_or(8)
    }

    /// Derived per-node feature dims `(in_dim, out_dim)` indexed by node id — the same
    /// derivation `Network::build` uses. Orphan/no-source nodes read `hidden_dim`.
    pub fn node_dims(&self) -> Vec<(usize, usize)> {
        let num_inputs: Vec<usize> = self.nodes.iter().map(|n| n.num_inputs).collect();
        let sources = build_node_sources(&self.connections, &num_inputs);
        self.nodes
            .iter()
            .map(|node| {
                let in_dim = if node.kind == NodeKind::Input {
                    // Input node reads raw data: in_dim = input_dim
                    self.options.input_dim.unwrap_or(1)
                } else {
                    sources[node.id]
                        .iter()
                        .flatten()
                        .map(|p| self.out_dim_of(&self.nodes[p.node]))
                        .max()
                        .unwrap_or_else(|| self.effective_hidden_dim())
                };
                (in_dim, self.out_dim_of(node))
            })
            .collect()
    }

    /// Orphaned ports of one node: `(orphaned input indices, orphaned output indices)`.
    /// The graph-output node's own ports are the answer, not orphans.
    pub fn orphan_ports(&self, node: usize) -> (Vec<usize>, Vec<usize>) {
        let mut ins = Vec::new();
        let mut outs = Vec::new();
        for i in 0..self.nodes[node].num_inputs {
            let port = Port { node, index: i };
            if !self.connections.iter().any(|c| c.to == port) {
                ins.push(i);
            }
        }
        for o in 0..self.nodes[node].num_outputs {
            let port = Port { node, index: o };
            if !self.connections.iter().any(|c| c.from == port) {
                outs.push(o);
            }
        }
        (ins, outs)
    }

    /// Every input port that carries more than one wire, with its wire count — `[]` is the healthy
    /// answer.
    pub fn input_ports_with_multiple_wires(&self) -> Vec<(Port, usize)> {
        let mut counts: Vec<(Port, usize)> = Vec::new();
        for c in &self.connections {
            match counts.iter_mut().find(|(p, _)| *p == c.to) {
                Some((_, n)) => *n += 1,
                None => counts.push((c.to, 1)),
            }
        }
        counts.retain(|(_, n)| *n > 1);
        counts
    }

    /// Give a blueprint the one-wire-per-port shape: every input port that carries several wires
    /// split into that many ports.
    pub(crate) fn unstack_input_ports(&mut self) {
        let stacked = self.input_ports_with_multiple_wires();
        if stacked.is_empty() {
            return;
        }
        let wires: usize = stacked.iter().map(|(_, n)| n).sum();
        let mut reshaped: Vec<Connection> = Vec::with_capacity(self.connections.len());
        for conn in &self.connections {
            let taken = reshaped.iter().any(|c| c.to == conn.to);
            let to = if taken {
                let node = &mut self.nodes[conn.to.node];
                let index = node.num_inputs;
                node.num_inputs += 1;
                Port {
                    node: conn.to.node,
                    index,
                }
            } else {
                conn.to
            };
            reshaped.push(Connection {
                from: conn.from,
                to,
            });
        }
        self.connections = reshaped;
        info!(
            "legacy blueprint: {} input port(s) carried {wires} wires — split into one port per wire",
            stacked.len()
        );
    }

    /// Panic unless the wiring invariant holds: every input port has exactly one
    /// wire (test helper — `validate` enforces the same rule).
    pub fn assert_one_wire_per_port(&self) {
        let multi = self.input_ports_with_multiple_wires();
        assert!(multi.is_empty(), "input ports with >1 wire: {multi:?}");
        for node in &self.nodes {
            for i in 0..node.num_inputs {
                let port = Port {
                    node: node.id,
                    index: i,
                };
                assert!(
                    self.connections.iter().any(|c| c.to == port),
                    "input port n{}_i{} has no wire",
                    node.id,
                    i
                );
            }
        }
    }

    /// Wired degrees `(in_degree, out_degree)` per node, indexed by node id
    /// — one count per *wire*.
    pub fn degrees(&self) -> Vec<(usize, usize)> {
        node_degrees(&self.nodes, &self.connections)
    }

    /// Longest path from an `Input` node per node id — a topological level. Input nodes
    /// sit at 0; others are `1 + max` over wired sources. Ascending ids are a valid order.
    pub fn depths(&self) -> Vec<usize> {
        node_depths(&self.nodes, &self.connections)
    }

    /// Estimated total learnable elements (weights + biases) without building —
    /// input projection plus every node's `in·out + out`. Matches a built `Network`.
    pub fn param_estimate(&self) -> usize {
        let dims = self.node_dims();
        let mut total = 0;
        // Node layers: in*out + out each.
        for &(in_dim, out_dim) in &dims {
            total += in_dim * out_dim + out_dim;
        }
        total
    }

    /// Node counts by kind — [`KindCounts`] (no more guessing the tuple
    /// order).
    pub fn kind_counts(&self) -> KindCounts {
        node_kind_counts(&self.nodes)
    }

    /// Activation histogram across nodes: `(activation, count)` pairs.
    pub fn activation_counts(&self) -> Vec<(Activation, usize)> {
        node_activation_counts(&self.nodes)
    }

    /// Ensure the canonical skeleton: at least one `Input` node and exactly one `Output`
    /// node. Idempotent; called as phase 1 of `finalize`. More than one Output is rejected.
    pub fn ensure_scaffold(&mut self) {
        // 1. At least one Input node (single output port; net_input feeds
        //    the rest of the graph).
        if !self.nodes.iter().any(|n| n.kind == NodeKind::Input) {
            self.nodes.insert(0, Node::new_input(0, 1));
            for node in self.nodes.iter_mut().skip(1) {
                node.id += 1;
            }
            for conn in &mut self.connections {
                conn.from.node += 1;
                conn.to.node += 1;
            }
        }

        // 2.
        let has_output = self.nodes.iter().any(|n| n.kind == NodeKind::Output);
        if !has_output {
            let mut out = Node::new_output(self.nodes.len(), 1, 1);
            out.hidden_dim = Some(self.options.output_dim.unwrap_or(1));
            self.nodes.push(out);
        }
    }

    /// Re-wire orphaned output ports into random *later* nodes — the de-orphaning rule, called
    /// the end of `finalize`.
    pub fn rewire_orphaned_outputs(&mut self) -> usize {
        // Collect the orphaned output ports (graph-output node excluded).
        // The Output node is always the last node (created by ensure_scaffold).
        let output_node = self.nodes.len() - 1;
        let mut orphans: Vec<Port> = Vec::new();
        for node in &self.nodes {
            if node.id == output_node {
                continue;
            }
            for o in 0..node.num_outputs {
                let port = Port {
                    node: node.id,
                    index: o,
                };
                if !self.connections.iter().any(|c| c.from == port) {
                    orphans.push(port);
                }
            }
        }

        let mut added = 0usize;
        for src in orphans {
            // Only wire to later nodes NOT already fed by this source.
            // Prevents duplicates at creation time — no cleanup needed.
            let targets: Vec<usize> = self
                .nodes
                .iter()
                .filter(|n| {
                    n.id > src.node
                        && n.num_inputs > 0
                        && !self
                            .connections
                            .iter()
                            .any(|c| c.from.node == src.node && c.to.node == n.id)
                })
                .map(|n| n.id)
                .collect();
            if targets.is_empty() {
                continue;
            }
            // Target choice, in order of preference: 1.
            let free: Vec<usize> = targets
                .iter()
                .copied()
                .filter(|&t| self.free_input_port(t).is_some())
                .collect();
            let target = if !free.is_empty() {
                free[self.rng.usize(0..free.len())]
            } else {
                let growable: Vec<usize> = targets
                    .iter()
                    .copied()
                    .filter(|&t| self.may_grow_inputs(t))
                    .collect();
                if growable.is_empty() {
                    continue;
                }
                growable[self.rng.usize(0..growable.len())]
            };
            let port = match self.free_input_port(target) {
                Some(i) => i,
                None => {
                    // Every socket is taken: add one.
                    let node = &mut self.nodes[target];
                    let i = node.num_inputs;
                    node.num_inputs += 1;
                    i
                }
            };
            self.connections.push(Connection {
                from: src,
                to: Port {
                    node: target,
                    index: port,
                },
            });
            added += 1;
        }
        added
    }

    /// Whether `node` may take another input port.
    fn may_grow_inputs(&self, node: usize) -> bool {
        match self.nodes[node].kind {
            NodeKind::Hidden => {
                self.nodes[node].num_inputs < self.options.max_hidden_inputs_per_node
            }
            _ => true,
        }
    }

    /// The lowest input port of `node` that nothing feeds yet.
    fn free_input_port(&self, node: usize) -> Option<usize> {
        (0..self.nodes[node].num_inputs).find(|&i| {
            !self
                .connections
                .iter()
                .any(|c| c.to == Port { node, index: i })
        })
    }

    /// Remove orphaned ports and renumber connections to close gaps.
    fn trim_orphaned_ports(&mut self) {
        let output_id = self
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Output)
            .map(|n| n.id);

        // Remap tables: for each node, old port index -> compact new index.
        let out_remap: Vec<Vec<usize>> = self
            .nodes
            .iter()
            .map(|n| {
                let mut used: Vec<bool> = vec![false; n.num_outputs];
                for c in &self.connections {
                    if c.from.node == n.id && c.from.index < used.len() {
                        used[c.from.index] = true;
                    }
                }
                let mut map = vec![0usize; n.num_outputs];
                let mut next = 0;
                for i in 0..n.num_outputs {
                    if used[i] {
                        map[i] = next;
                        next += 1;
                    } else {
                        map[i] = usize::MAX; // orphan — will be dropped
                    }
                }
                map
            })
            .collect();

        let in_remap: Vec<Vec<usize>> = self
            .nodes
            .iter()
            .map(|n| {
                let mut used: Vec<bool> = vec![false; n.num_inputs];
                for c in &self.connections {
                    if c.to.node == n.id && c.to.index < used.len() {
                        used[c.to.index] = true;
                    }
                }
                let mut map = vec![0usize; n.num_inputs];
                let mut next = 0;
                for i in 0..n.num_inputs {
                    if used[i] {
                        map[i] = next;
                        next += 1;
                    } else {
                        map[i] = usize::MAX; // empty after dedup — dropped
                    }
                }
                map
            })
            .collect();

        // Renumber connections, dropping the ones whose source or target port died.
        self.connections.retain(|c| {
            let from_map = &out_remap[c.from.node];
            let to_map = &in_remap[c.to.node];
            c.from.index < from_map.len()
                && c.to.index < to_map.len()
                && from_map[c.from.index] != usize::MAX
                && to_map[c.to.index] != usize::MAX
        });
        for c in &mut self.connections {
            c.from.index = out_remap[c.from.node][c.from.index];
            c.to.index = in_remap[c.to.node][c.to.index];
        }

        // Update port counts.
        let mask_width = self.options.input_dim.unwrap_or(1);
        for (i, node) in self.nodes.iter_mut().enumerate() {
            if Some(node.id) != output_id {
                node.num_outputs = out_remap[i]
                    .iter()
                    .filter(|&&v| v != usize::MAX)
                    .count()
                    .max(1);
                // Compact port_activations alongside the port remap — the vec must always
                // match num_outputs (`validate()` enforces it). Input ports stay Identity.
                if let Some(ports) = &mut node.port_activations {
                    let mut compacted: Vec<crate::graph::node::Activation> = out_remap[i]
                        .iter()
                        .filter(|&&v| v != usize::MAX)
                        .filter_map(|&old| ports.get(old).copied())
                        .collect();
                    compacted.resize(
                        node.num_outputs,
                        compacted
                            .last()
                            .copied()
                            .unwrap_or(crate::graph::node::Activation::Identity),
                    );
                    *ports = compacted;
                }
                // Feature masks are port-bound too: carry each row with the port it belongs
                // drop the rows of ports the rebuild removed, and leave a port the rebuild ADDED
                if let Some(masks) = &mut node.feature_masks {
                    let mut kept: Vec<Vec<u8>> = Vec::with_capacity(node.num_outputs);
                    for &old in &out_remap[i] {
                        if old == usize::MAX {
                            continue;
                        }
                        kept.push(
                            masks
                                .get(old)
                                .cloned()
                                .unwrap_or_else(|| vec![1u8; mask_width]),
                        );
                    }
                    kept.resize(node.num_outputs, vec![1u8; mask_width]);
                    *masks = kept;
                }
            }
            let connected_in = in_remap[i].iter().filter(|&&v| v != usize::MAX).count();
            if connected_in > 0 {
                node.num_inputs = connected_in;
            }
        }
        // The rebuild can ADD an Input port, and a port the rebuild added keeps every feature —
        // a partition plus a cover-all port is no longer "each feature in exactly one port".
        if self.options.feature_split == Some(FeatureSplitPolicy::Exclusive) {
            let input_dim = self.options.input_dim.unwrap_or(1);
            if let Some(masks) = self.input_feature_masks() {
                if !split_rows_are_partition(&masks, input_dim) {
                    self.options.feature_split = Some(FeatureSplitPolicy::Inherited);
                }
            }
        }
    }

    /// Serialize the whole blueprint (options, nodes, labels, connections) to JSON
    /// (see [`crate::spec::Spec`]); the RNG is not stored.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Deserialize a blueprint from JSON (see `to_json`). The RNG is re-seeded
    /// `options.topology_seed`, so loaded graphs wire identically; weights are fresh.
    pub fn from_json(s: &str) -> Result<Topology, serde_json::Error> {
        let mut topo: Topology = serde_json::from_str(s)?;
        // Every loaded net (live, tombstone, resumed or imported) passes through here:
        // the one place that can promise a reader "policy present ⇔ rows present".
        topo.reconcile_split_policy();
        Ok(topo)
    }

    // ── Crossover ──────────────────────────────────────────────────────────

    /// Find a hidden node with the same interface in both topologies
    /// (`num_inputs`/`num_outputs`); returns indices into each hidden-only list.
    fn find_matching_node(a: &Topology, b: &Topology, rng: &mut Rng) -> Option<(usize, usize)> {
        let ha: Vec<usize> = a
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, n)| n.kind == NodeKind::Hidden)
            .map(|(i, _)| i)
            .collect();
        let hb: Vec<usize> = b
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, n)| n.kind == NodeKind::Hidden)
            .map(|(i, _)| i)
            .collect();

        // Collect all matching pairs — only the structural interface matters;
        // finalize() handles wiring, so activations/combine ops may differ freely.
        let mut matches: Vec<(usize, usize)> = Vec::new();
        for (ai, &a_idx) in ha.iter().enumerate() {
            let an = &a.nodes[a_idx];
            for (bi, &b_idx) in hb.iter().enumerate() {
                let bn = &b.nodes[b_idx];
                if an.num_inputs == bn.num_inputs && an.num_outputs == bn.num_outputs {
                    matches.push((ai, bi));
                }
            }
        }

        if matches.is_empty() {
            None
        } else {
            Some(matches[rng.usize(0..matches.len())])
        }
    }

    /// Crossover: find a matching-node pivot (same port counts), swap everything
    /// that pivot onward, then finalize both. Returns true if a swap happened.
    pub fn cx_one_point(a: &mut Topology, b: &mut Topology, rng: &mut Rng) -> bool {
        Self::cx_one_point_with_report(a, b, rng).is_some()
    }

    /// [`Self::cx_one_point`] carrying the provenance the weights need: one entry per hidden node
    /// of the returned `a` — `None` when it kept its own gene, `Some(index)` naming the donor NODE
    pub fn cx_one_point_with_report(
        a: &mut Topology,
        b: &mut Topology,
        rng: &mut Rng,
    ) -> Option<CxReport> {
        let ha: Vec<usize> = a
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, n)| n.kind == NodeKind::Hidden)
            .map(|(i, _)| i)
            .collect();
        let hb: Vec<usize> = b
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, n)| n.kind == NodeKind::Hidden)
            .map(|(i, _)| i)
            .collect();

        if ha.is_empty() || hb.is_empty() {
            return None;
        }

        // Only crossover if a matching-node pivot exists — no random cuts
        if let Some((pivot_a, pivot_b)) = Self::find_matching_node(a, b, rng) {
            let swap_a = &ha[pivot_a..];
            let swap_b = &hb[pivot_b..];
            let len = swap_a.len().min(swap_b.len());
            for k in 0..len {
                let tmp = a.nodes[swap_a[k]].clone();
                a.nodes[swap_a[k]] = b.nodes[swap_b[k]].clone();
                b.nodes[swap_b[k]] = tmp;
            }
            a.renumber_ids();
            a.finalize();
            b.renumber_ids();
            b.finalize();
            let mut moved = vec![None; ha.len()];
            let mut moved_b = vec![None; hb.len()];
            for offset in 0..len {
                moved[pivot_a + offset] = Some(hb[pivot_b + offset]);
                moved_b[pivot_b + offset] = Some(ha[pivot_a + offset]);
            }
            debug!(
                "cx_one_point: pivot hidden[{}] <-> hidden[{}], swapped {} nodes",
                pivot_a, pivot_b, len
            );
            return Some(CxReport {
                swaps: len,
                pairs: ha.len(),
                moved,
                moved_b,
            });
        }
        debug!("cx_one_point: no matching node found, skipping");
        None
    }

    /// Uniform crossover: per-node independent swap, requiring equal hidden counts.
    pub fn cx_uniform(
        a: &mut Topology,
        b: &mut Topology,
        swap_prob: f32,
        rng: &mut Rng,
    ) -> Option<CxReport> {
        let ha: Vec<usize> = a
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, n)| n.kind == NodeKind::Hidden)
            .map(|(i, _)| i)
            .collect();
        let hb: Vec<usize> = b
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, n)| n.kind == NodeKind::Hidden)
            .map(|(i, _)| i)
            .collect();

        // Same-length requirement for per-node alignment
        if ha.len() != hb.len() || ha.is_empty() {
            debug!(
                "cx_uniform: hidden node count mismatch ({} vs {}), skipping",
                ha.len(),
                hb.len()
            );
            return None;
        }

        let mut swaps = 0usize;
        let mut moved = vec![None; ha.len()];
        let mut moved_b = vec![None; hb.len()];
        for (slot, (&ai, &bi)) in ha.iter().zip(hb.iter()).enumerate() {
            if rng.f32() < swap_prob {
                std::mem::swap(&mut a.nodes[ai], &mut b.nodes[bi]);
                moved[slot] = Some(bi);
                swaps += 1;
            } else {
                // No coin: the reciprocal child took THIS parent's node,
                // provenance names the donor
                moved_b[slot] = Some(ai);
            }
        }

        if swaps == 0 {
            return None;
        }
        a.renumber_ids();
        a.finalize();
        b.renumber_ids();
        b.finalize();
        debug!("cx_uniform: swapped {swaps}/{} hidden nodes", ha.len());
        Some(CxReport {
            swaps,
            pairs: ha.len(),
            moved,
            moved_b,
        })
    }
}

use crate::utils::graph_utils::{
    build_node_sources, node_activation_counts, node_degrees, node_depths, node_kind_counts,
    node_orphan_counts,
};

/// Test-only proptest strategies, shared across the crate's test modules
/// (topology's own tests and the serialization tests in [`crate::spec`]).
#[cfg(test)]
pub(crate) mod test_strategies {
    use super::*;
    use proptest::prelude::*;

    /// Valid random `TopologyOptions`: non-zero dims and non-inverted ranges —
    /// exactly what `validate()` rejects is what we never generate.
    pub(crate) fn topology_options_strategy() -> impl Strategy<Value = TopologyOptions> {
        (
            0usize..10_000, //  seed
            1usize..4,      //  min inputs per node
            1usize..4,      //  min outputs per node
            1usize..8,      // input_dim
            1usize..8,      // output_dim
        )
            .prop_map(
                |(seed, min_in, min_out, input_dim, output_dim)| TopologyOptions {
                    topology_seed: seed,
                    min_hidden_num_nodes: 2,
                    max_hidden_num_nodes: 6,
                    min_hidden_inputs_per_node: min_in,
                    max_hidden_inputs_per_node: min_in + 3,
                    min_hidden_outputs_per_node: min_out,
                    max_hidden_outputs_per_node: min_out + 3,
                    input_dim: Some(input_dim),
                    output_dim: Some(output_dim),
                    dropout_prob: 0.0,
                    feature_split: None,
                    weight_seed: None,
                },
            )
    }

    /// A random graph: input + 0..5 hidden + output, fully wired through the standard
    /// pipeline (`refresh_labels` + `finalize`, which auto-de-orphans).
    pub(crate) fn topology_strategy() -> impl Strategy<Value = Topology> {
        (topology_options_strategy(), 0usize..6).prop_map(|(opts, n_hidden)| {
            let mut graph = Topology::new(0, Some(opts));
            graph.nodes.push(Node::new_input(0, 2));
            for i in 0..n_hidden {
                let span_in = opts.max_hidden_inputs_per_node - opts.min_hidden_inputs_per_node + 1;
                let span_out =
                    opts.max_hidden_outputs_per_node - opts.min_hidden_outputs_per_node + 1;
                let ins = opts.min_hidden_inputs_per_node + (i * 7) % span_in;
                let outs = opts.min_hidden_outputs_per_node + (i * 3) % span_out;
                graph.nodes.push(Node::new_hidden(i + 1, ins, outs));
            }
            graph.nodes.push(Node::new_output(n_hidden + 1, 1, 1));
            graph.refresh_labels();
            graph.finalize();
            graph
        })
    }
}

#[cfg(test)]
mod tests {
    use super::test_strategies::*;
    use super::*;
    use crate::graph::network::Network;
    use flodl::nn::Module;
    use flodl::{DType, Device, Tensor, TensorOptions, Variable};
    use proptest::prelude::*;

    fn cpu_opts() -> TensorOptions {
        TensorOptions {
            dtype: DType::Float32,
            device: Device::CPU,
        }
    }

    fn rand_input(batch: i64, input_dim: usize) -> Variable {
        Variable::new(
            Tensor::randn(&[batch, input_dim as i64], cpu_opts()).unwrap(),
            false,
        )
    }

    // ── topology (Topology) ────────────────────────────────────────────────────

    #[test]
    fn test_new_without_options() {
        let graph = Topology::new(1, None);
        assert_eq!(graph.nodes.len(), 0);
        assert_eq!(graph.options.min_hidden_num_nodes, 2);
        assert_eq!(graph.options.max_hidden_num_nodes, 15);
    }

    #[test]
    fn test_new_with_options() {
        let opts = TopologyOptions {
            topology_seed: 123,
            min_hidden_num_nodes: 3,
            max_hidden_num_nodes: 10,
            min_hidden_inputs_per_node: 1,
            max_hidden_inputs_per_node: 5,
            min_hidden_outputs_per_node: 1,
            max_hidden_outputs_per_node: 5,
            input_dim: Some(4),
            output_dim: Some(10),
            dropout_prob: 0.0,
            feature_split: None,
            weight_seed: None,
        };
        let graph = Topology::new(1, Some(opts));
        assert_eq!(graph.nodes.len(), 0);
        assert_eq!(graph.options.min_hidden_num_nodes, 3);
        assert_eq!(graph.options.max_hidden_num_nodes, 10);
        assert_eq!(graph.options.input_dim, Some(4));
        assert_eq!(graph.options.output_dim, Some(10));
    }

    #[test]
    fn test_create_random_hidden_node() {
        let mut graph = Topology::new(1, None);
        graph.create_random_hidden_node();
        assert_eq!(graph.nodes.len(), 1);
    }

    #[test]
    fn test_assign_port_activations_deterministic() {
        // Same seed ⇒ same per-port assignment, twice.
        let build = || {
            let mut g = Topology::new(0, Some(TopologyOptions::default()));
            g.create_random_hidden_nodes(3);
            g.refresh_labels();
            g.finalize();
            g.assign_port_activations(&[Activation::ReLU, Activation::Tanh, Activation::Sin]);
            g
        };
        let a = build();
        let b = build();
        for (na, nb) in a.nodes.iter().zip(&b.nodes) {
            assert_eq!(na.port_activations, nb.port_activations);
        }
        // Ports >= 1 actually drew from the pool; port 0 mirrors the node.
        let pool = [Activation::ReLU, Activation::Tanh, Activation::Sin];
        for node in &a.nodes {
            if let Some(ports) = &node.port_activations {
                assert_eq!(ports.len(), node.num_outputs);
                assert_eq!(ports[0], node.activation);
                for p in &ports[1..] {
                    assert!(pool.contains(p), "port activation {p:?} not from pool");
                }
            }
        }
    }

    #[test]
    fn test_trim_orphaned_ports_compacts_port_activations() {
        // An orphaned output port must compact port_activations along with num_outputs,
        // or finalize's validate() rejects the length mismatch.
        let mut g = Topology::new(0, Some(TopologyOptions::default()));
        g.nodes.push(Node::new_input(0, 1));
        let mut n1 = Node::new_hidden(1, 1, 3);
        n1.activation = Activation::ReLU;
        n1.port_activations = Some(vec![
            Activation::ReLU,
            Activation::Tanh,
            Activation::Sigmoid,
        ]);
        g.nodes.push(n1);
        g.nodes.push(Node::new_output(2, 1, 1));
        // Only ports 0 and 2 are wired; port 1 is orphaned and must be trimmed.
        g.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        g.finalize();
        let n1 = &g.nodes[1];
        // Core invariant: port_activations always matches num_outputs after trim —
        // exactly what validate() enforces.
        let ports = n1.port_activations.as_ref().unwrap();
        assert_eq!(
            ports.len(),
            n1.num_outputs,
            "port_activations must be compacted with ports"
        );
        // Port 0 is wired explicitly, so it survives with its activation.
        assert!(n1.num_outputs >= 1);
        assert_eq!(ports[0], Activation::ReLU);
    }

    #[test]
    fn test_validate_rejects_port_activation_mismatch() {
        let mut g = Topology::new(0, Some(TopologyOptions::default()));
        g.nodes.push(Node::new_input(0, 1));
        let mut n1 = Node::new_hidden(1, 1, 2);
        n1.port_activations = Some(vec![Activation::ReLU]); // 1 entry, 2 ports
        g.nodes.push(n1);
        g.nodes.push(Node::new_output(2, 1, 1));
        assert!(g.validate().is_err());
        // Input node with a non-Identity port is also rejected.
        let mut g2 = Topology::new(0, Some(TopologyOptions::default()));
        let mut input = Node::new_input(0, 1);
        input.port_activations = Some(vec![Activation::ReLU]);
        g2.nodes.push(input);
        g2.nodes.push(Node::new_output(1, 1, 1));
        assert!(g2.validate().is_err());
    }

    #[test]
    fn test_refresh_labels() {
        let mut graph = Topology::new(1, None);
        graph.create_random_hidden_node();
        graph.create_random_hidden_node();
        graph.create_random_hidden_node();
        graph.refresh_labels();

        // One label per port, matching each node's declared inputs/outputs
        let total_inputs: usize = graph.nodes.iter().map(|n| n.num_inputs).sum();
        let total_outputs: usize = graph.nodes.iter().map(|n| n.num_outputs).sum();
        assert_eq!(graph.graph_inputs.len(), total_inputs);
        assert_eq!(graph.graph_outputs.len(), total_outputs);
    }

    #[test]
    fn test_refresh_labels_mints_port_labels() {
        let mut graph = Topology::new(1, None);
        // Fixed nodes: input with 2 outputs, hidden with 3 inputs / 2 outputs
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 3, 2));
        graph.refresh_labels();

        assert_eq!(graph.graph_inputs, vec!["n1_i0", "n1_i1", "n1_i2"]);
        assert_eq!(
            graph.graph_outputs,
            vec!["n0_o0", "n0_o1", "n1_o0", "n1_o1"]
        );
    }

    #[test]
    fn test_finalize() {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 3, 2));
        graph.nodes.push(Node::new_hidden(2, 2, 1));
        graph.finalize();

        // Output ports stay 1:1; input ports may hold several wires because finalize
        // auto-de-orphans (stacks extra sources into later nodes, even occupied ports).
        let mut seen_from: Vec<Port> = Vec::new();
        let input_id = graph
            .nodes
            .iter()
            .find(|n| n.kind == NodeKind::Input)
            .unwrap()
            .id;
        for conn in &graph.connections {
            assert!(
                conn.from.node < conn.to.node,
                "connection must go strictly forward: {conn}"
            );
            // Input node's output ports can fan out to multiple destinations.
            if conn.from.node != input_id {
                assert!(
                    !seen_from.contains(&conn.from),
                    "output port {} used twice",
                    conn.from_label()
                );
            }
            seen_from.push(conn.from);
        }
        // Connections can exceed output port count due to input node fan-out,
        // but non-input output ports stay 1:1.
        assert!(!graph.connections.is_empty());
        assert!(!graph.connections.is_empty());

        // String pairs match the typed connections
        assert_eq!(graph.connections.len(), graph.connection_labels().len());
    }

    // ── validation ──────────────────────────────────────────────────────────

    #[test]
    fn test_validate_ok_on_generated_graph() {
        let mut graph = Topology::new(1, None);
        graph.create_random_hidden_nodes(5);
        graph.refresh_labels();
        graph.finalize();
        assert_eq!(graph.validate(), Ok(()));
    }

    #[test]
    fn test_validate_rejects_empty_graph() {
        let graph = Topology::new(1, None);
        assert_eq!(graph.validate(), Err(TopologyError::EmptyTopology));
    }

    #[test]
    fn test_validate_rejects_non_contiguous_ids() {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(2, 1, 1)); // id 1 skipped
        assert_eq!(graph.validate(), Err(TopologyError::NonContiguousNodeIds));
    }

    #[test]
    fn test_validate_rejects_backward_connection() {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 1));
        graph.nodes.push(Node::new_hidden(1, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 0, index: 0 },
        });
        assert!(matches!(
            graph.validate(),
            Err(TopologyError::BackwardConnection(_))
        ));
    }

    #[test]
    fn test_validate_rejects_unknown_node() {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 1));
        // Forward-looking (1 < 2) but both ids are past the single node we have.
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        assert!(matches!(
            graph.validate(),
            Err(TopologyError::UnknownNode(_))
        ));
    }

    #[test]
    fn test_validate_rejects_port_out_of_bounds() {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 1));
        graph.nodes.push(Node::new_hidden(1, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 3 }, // n1 has only 1 input port
        });
        assert!(matches!(
            graph.validate(),
            Err(TopologyError::PortOutOfBounds { .. })
        ));
    }

    /// Two Input ports into one Hidden port — the shape that used to be legal.
    fn stacked_input_port_graph() -> Topology {
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 0, index: 1 },
            to: Port { node: 1, index: 0 }, // a second wire into the same port
        });
        graph
    }

    #[test]
    fn test_validate_rejects_multi_wired_input_port() {
        // A port is a socket, not a bucket: fan-in is expressed as extra ports,
        // freshly built graph may not stack two wires on one input port.
        let graph = stacked_input_port_graph();
        assert_eq!(
            graph.validate(),
            Err(TopologyError::MultiWiredInputPort(Port {
                node: 1,
                index: 0
            }))
        );
    }

    #[test]
    fn legacy_stacked_blueprint_loads_as_one_port_per_wire() {
        // A run recorded before the refactor can stack wires on one input port, and LOADING
        // only way such wiring re-enters the process (engine inheritance reads the previous run's
        let mut graph = Topology::new(
            9,
            Some(TopologyOptions {
                input_dim: Some(2),
                output_dim: Some(1),
                ..Default::default()
            }),
        );
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 1, 1)); // ONE port, two wires
        graph.nodes.push(Node::new_output(2, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 0, index: 1 },
            to: Port { node: 1, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        assert_eq!(graph.input_ports_with_multiple_wires().len(), 1);

        let loaded = Topology::from_json(&graph.to_json().unwrap()).unwrap();
        assert!(
            loaded.input_ports_with_multiple_wires().is_empty(),
            "loading must spread a stacked port over one port per wire"
        );
        assert_eq!(loaded.connections.len(), 3, "no wire may be dropped");
        assert_eq!(loaded.nodes[1].num_inputs, 2, "the stacked port became two");
        loaded.assert_one_wire_per_port();
        assert_eq!(loaded.validate(), Ok(()));
    }

    #[test]
    fn test_validate_rejects_double_used_output() {
        // Non-input nodes: output ports stay 1:1.
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 2, 1));
        graph.nodes.push(Node::new_hidden(2, 1, 1));
        graph.nodes.push(Node::new_hidden(3, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 }, // same output used twice
            to: Port { node: 3, index: 0 },
        });
        assert!(matches!(
            graph.validate(),
            Err(TopologyError::DoubleUsedOutput(_))
        ));
    }

    #[test]
    fn test_orphan_counts() {
        // n1 has 3 inputs, only i2 wired → 2 orphaned inputs. n2's output has no wire
        // → 1 orphaned output. n3 is the network output: its port is the answer, not an orphan.
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 3, 2));
        graph.nodes.push(Node::new_hidden(2, 2, 1));
        graph.nodes.push(Node::new_output(3, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 2 },
        });
        graph.connections.push(Connection {
            from: Port { node: 0, index: 1 },
            to: Port { node: 2, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 1 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 1 },
            to: Port { node: 3, index: 0 },
        });
        assert_eq!(graph.orphan_counts(), (2, 1));
    }

    // ── derived diagnostics ────────────────────────────────────────────────

    #[test]
    fn test_derived_diagnostics() {
        // n0 input (2 outs) → n1 hidden (3 in, 2 out) → n2 hidden (2 in, 1 out) → n3
        // output. Wired sparsely on purpose so orphaned ports stay orphaned.
        let mut g = Topology::new(1, None);
        g.nodes.push(Node::new_input(0, 2));
        g.nodes.push(Node::new_hidden(1, 3, 2));
        g.nodes.push(Node::new_hidden(2, 2, 1));
        g.nodes.push(Node::new_output(3, 1, 1));
        g.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        g.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        g.connections.push(Connection {
            from: Port { node: 2, index: 0 },
            to: Port { node: 3, index: 0 },
        });

        // Per-node orphaned port indices (raw — the output node's own port
        // is counted here, unlike orphan_counts which excludes
        assert_eq!(g.orphan_ports(0), (vec![], vec![1]));
        assert_eq!(g.orphan_ports(1), (vec![1, 2], vec![1]));
        assert_eq!(g.orphan_ports(2), (vec![1], vec![]));
        assert_eq!(g.orphan_ports(3), (vec![], vec![0]));

        // Wired degrees (one count per wire).
        assert_eq!(g.degrees(), vec![(0, 1), (1, 1), (1, 1), (1, 0)]);

        // Topological levels (longest path from the input).
        assert_eq!(g.depths(), vec![0, 1, 2, 3]);

        // Derived dims: input node in_dim = input_dim (1), rest = hidden_dim (8).
        assert_eq!(g.node_dims(), vec![(1, 8), (8, 8), (8, 8), (8, 8)]);

        // Counts by kind.
        assert_eq!(
            g.kind_counts(),
            KindCounts {
                input: 1,
                hidden: 2,
                output: 1
            }
        );

        // Param estimate: 4 nodes × (in*out + out).
        // n0: 1*8+8=16, n1: 8*8+8=72, n2: 8*8+8=72, n3: 8*8+8=72
        assert_eq!(g.param_estimate(), 16 + 3 * 72);

        // Activation histogram.
        assert_eq!(g.activation_counts(), vec![(Activation::Identity, 4)]);
    }

    #[test]
    fn test_node_dims_with_override() {
        // Chain with a widened middle node: n1 emits 32, so n2's in_dim re-derives
        // 32; n0 (orphan) gets effective hidden_dim = 32 so projections go straight there.
        let mut g = Topology::new(1, None);
        g.nodes.push(Node::new_input(0, 1));
        let mut wide = Node::new_hidden(1, 1, 1);
        wide.hidden_dim = Some(32);
        g.nodes.push(wide);
        g.nodes.push(Node::new_output(2, 1, 1));
        g.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        g.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        // n0: input, in_dim = input_dim (1), out_dim = template (8); n1: wired from n0
        // (out=8), out_dim = 32; n2: wired from n1 (out=32), out_dim = template (8).
        assert_eq!(g.node_dims(), vec![(1, 8), (8, 32), (32, 8)]);
    }

    #[test]
    fn test_rewire_orphaned_outputs() {
        // n2_o0 is orphaned; de-orphaning must wire it into the only later node (n3),
        // whose input port is already wired — fine, tensors are summed.
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 3, 2));
        graph.nodes.push(Node::new_hidden(2, 2, 1));
        graph.nodes.push(Node::new_output(3, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 2 },
        });
        graph.connections.push(Connection {
            from: Port { node: 0, index: 1 },
            to: Port { node: 2, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 1 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 1 },
            to: Port { node: 3, index: 0 },
        });

        assert_eq!(graph.orphan_counts(), (2, 1));
        let added = graph.rewire_orphaned_outputs();
        assert_eq!(added, 1);
        // n2_o0 now feeds n3_i0 (stacking onto n1_o1) — no more orphaned
        // outputs; n1's two orphaned inputs remain (they're fed net_input).
        assert_eq!(graph.orphan_counts(), (2, 0));
        assert_eq!(graph.validate(), Ok(()));

        let module = Network::build(&graph, Device::CPU).unwrap();
        let batch = 2i64;
        let input = rand_input(batch, graph.options.input_dim.unwrap_or(1));
        let output = module.forward(&input).unwrap();
        assert_eq!(output.shape(), &[batch, 8]);
    }

    #[test]
    fn test_rewire_orphaned_outputs_rewires_even_with_dim_mismatch() {
        // n1 widens 8 → 32 and its output is orphaned; port projections bridge any dim
        // mismatch, so the orphan is still rewired.
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 1));
        let mut wide = Node::new_hidden(1, 1, 1);
        wide.hidden_dim = Some(32);
        graph.nodes.push(wide);
        graph.nodes.push(Node::new_output(2, 1, 1));
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 1, index: 0 },
        });
        assert_eq!(graph.orphan_counts(), (1, 1));
        assert_eq!(graph.rewire_orphaned_outputs(), 1);
        // n1_o0 → n2_i0: resolves both the orphan output AND orphan input
        assert_eq!(graph.orphan_counts(), (0, 0));
    }

    #[test]
    fn test_rewire_orphaned_outputs_deterministic_per_seed() {
        // finalize auto-de-orphans; same seed ⇒ same de-orphaned
        // graph (targets drawn from graph.rng), always valid.
        let build = |seed: usize| {
            let mut graph = Topology::new(0, None);
            graph.options.topology_seed = seed;
            graph.nodes.push(Node::new_input(0, 2));
            graph.nodes.push(Node::new_hidden(1, 2, 2));
            graph.nodes.push(Node::new_hidden(2, 2, 2));
            graph.nodes.push(Node::new_output(3, 2, 1));
            graph.finalize();
            assert_eq!(graph.validate(), Ok(()));
            graph.connections.clone()
        };
        let a = build(42);
        let b = build(42);
        assert_eq!(a, b, "same seed must rewire identically");
        // Different seeds are allowed to coincide when there is only one
        // compatible target; just make sure the result is always valid.
        let _ = build(99);
    }

    #[test]
    fn test_finalize_auto_de_orphans() {
        // finalize alone must leave zero orphaned *outputs* (the graph-output node's
        // own ports are the answer) and always validate.
        let mut graph = Topology::new(0, None);
        graph.nodes.push(Node::new_input(0, 2));
        graph.nodes.push(Node::new_hidden(1, 3, 2));
        graph.nodes.push(Node::new_hidden(2, 2, 1));
        graph.nodes.push(Node::new_output(3, 1, 1));
        graph.finalize();
        assert_eq!(graph.validate(), Ok(()));
        let (_, orphaned_outputs) = graph.orphan_counts();
        assert_eq!(orphaned_outputs, 0);
    }

    #[test]
    fn test_validate_allows_inconsistent_input_dims() {
        // With per-node hidden_dim + port projections, different source
        // dims are now valid — projections bridge the mismatch.
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 2)); // out_dim = 8 (default)
        let mut wide = Node::new_hidden(1, 1, 1);
        wide.hidden_dim = Some(16);
        graph.nodes.push(wide);
        graph.nodes.push(Node::new_output(2, 2, 1)); // fed by n0 (8) and n1 (16)
        graph.connections.push(Connection {
            from: Port { node: 0, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 1 },
        });
        assert!(graph.validate().is_ok());
    }

    #[test]
    fn test_validate_allows_orphan_dim_mismatch() {
        // With per-node hidden_dim + port projections, orphan/wire dim
        // mismatches are valid — projections bridge the gap.
        let mut graph = Topology::new(1, None);
        graph.nodes.push(Node::new_input(0, 1));
        let mut wide = Node::new_hidden(1, 1, 1);
        wide.hidden_dim = Some(16);
        graph.nodes.push(wide);
        graph.nodes.push(Node::new_output(2, 2, 1));
        graph.connections.push(Connection {
            from: Port { node: 1, index: 0 },
            to: Port { node: 2, index: 0 },
        });
        assert!(graph.validate().is_ok());
    }

    // ── scaffolding (auto Input/Output) ────────────────────────────────────

    #[test]
    fn test_ensure_scaffold_adds_input_and_output() {
        // A hidden-only graph (what random generation produces) gets
        // canonical skeleton: prepend Input (single port), append Output.
        let mut graph = Topology::new(0, None);
        graph.create_random_hidden_nodes(3);
        graph.ensure_scaffold();
        assert_eq!(graph.nodes[0].kind, NodeKind::Input);
        assert_eq!(graph.nodes[0].num_outputs, 1);
        assert_eq!(graph.nodes.last().unwrap().kind, NodeKind::Output);
        // ids stay contiguous 0..n after the prepend
        for (i, n) in graph.nodes.iter().enumerate() {
            assert_eq!(n.id, i);
        }
    }

    #[test]
    fn test_ensure_scaffold_idempotent() {
        let mut graph = Topology::new(0, None);
        graph.create_random_hidden_nodes(2);
        graph.ensure_scaffold();
        let nodes = graph.nodes.clone();
        graph.ensure_scaffold();
        assert_eq!(graph.nodes, nodes);
    }

    #[test]
    fn test_finalize_scaffolds_hidden_only_graph() {
        // The pipeline alone must turn 5 random hidden nodes into a complete
        // Input → … → Output graph, still valid.
        let mut graph = Topology::new(0, None);
        graph.create_random_hidden_nodes(5);
        graph.finalize();
        let n_in = graph
            .nodes
            .iter()
            .filter(|n| n.kind == NodeKind::Input)
            .count();
        let n_out = graph
            .nodes
            .iter()
            .filter(|n| n.kind == NodeKind::Output)
            .count();
        assert_eq!(n_in, 1);
        assert_eq!(n_out, 1);
        assert_eq!(graph.validate(), Ok(()));
    }

    #[test]
    fn test_multiple_output_nodes_rejected() {
        // Multiple Output nodes are not supported — validate rejects them.
        let mut graph = Topology::new(0, None);
        graph.nodes.push(Node::new_input(0, 1));
        graph.nodes.push(Node::new_output(1, 1, 1));
        graph.nodes.push(Node::new_output(2, 1, 1)); // second output
        assert!(graph.validate().is_err(), "multiple outputs must fail");
    }

    // ── property tests (proptest) ───────────────────────────────────────────

    proptest! {
        /// Any random graph produced by the standard pipeline must validate —
        /// the invariant the whole design leans
        #[test]
        fn prop_random_graphs_always_validate(graph in topology_strategy()) {
            prop_assert!(
                graph.validate().is_ok(),
                "random graph failed validation: {:?}",
                graph.validate().err()
            );
        }

        /// finalize auto-de-orphans: no orphaned *outputs* remain
        /// (the graph-output node's own ports are the answer, not orphans).
        #[test]
        fn prop_network_auto_de_orphans_outputs(graph in topology_strategy()) {
                // After finalize, orphan counts may be nonzero when dedup removes redundant
                // same-source-to-same-target connections; the network handles orphans gracefully.
            let (_input_orphans, _output_orphans) = graph.orphan_counts();
        }

        /// The wiring invariants hold for every generated graph: strictly
        /// forward edges and 1:1 on the output side.
        #[test]
        fn prop_wiring_invariants(graph in topology_strategy()) {
            let mut seen: Vec<Port> = Vec::new();
            let input_id = graph.nodes.iter().find(|n| n.kind == NodeKind::Input).map(|n| n.id);
                // One wire per input port — the invariant that lets the runtime keep
                // single source per port instead of a list per port.
            prop_assert!(
                graph.input_ports_with_multiple_wires().is_empty(),
                "stacked input ports: {:?}",
                graph.input_ports_with_multiple_wires()
            );
            for conn in &graph.connections {
                prop_assert!(conn.from.node < conn.to.node, "backward connection: {conn}");
                // Input node's output ports can fan out.
                if Some(conn.from.node) != input_id {
                    prop_assert!(
                        !seen.contains(&conn.from),
                        "output {} used twice",
                        conn.from_label()
                    );
                }
                seen.push(conn.from);
            }
        }

        /// Every valid random graph compiles into a module whose forward pass
        /// yields exactly `[batch, hidden_dim]`.
        #[test]
        fn prop_random_graphs_build_and_forward(graph in topology_strategy()) {
            let module = Network::build(&graph, Device::CPU).unwrap();
            let input = rand_input(2, graph.options.input_dim.unwrap_or(1));
            let out = module.forward(&input).unwrap();
            prop_assert_eq!(out.shape(), &[2, graph.options.output_dim.unwrap_or(1) as i64]);
        }

            /// The blueprint's derived diagnostics match the built engine exactly: dims agree,
            /// param_estimate equals the real count, degrees balance, depth strictly increases.
        #[test]
        fn prop_diagnostics_match_built_network(graph in topology_strategy()) {
            let module = Network::build(&graph, Device::CPU).unwrap();
            let dims = graph.node_dims();
            prop_assert_eq!(&dims, &module.node_dims);
            let real_params: i64 = module
                .parameters()
                .iter()
                .map(|p| p.variable.data().numel())
                .sum();
            prop_assert_eq!(graph.param_estimate() as i64, real_params);

            let degrees = graph.degrees();
            let in_sum: usize = degrees.iter().map(|d| d.0).sum();
            let out_sum: usize = degrees.iter().map(|d| d.1).sum();
            prop_assert_eq!(in_sum, graph.connections.len());
            prop_assert_eq!(out_sum, graph.connections.len());

            let depths = graph.depths();
            for c in &graph.connections {
                prop_assert!(
                    depths[c.to.node] > depths[c.from.node],
                    "wire {c} must strictly increase depth: {:?}",
                    depths
                );
            }
        }

            /// The standard pipeline scaffolds any graph into the canonical skeleton
            /// (≥ 1 Input, exactly 1 Output, still valid) — even hidden-only/empty graphs.
        #[test]
        fn prop_finalize_scaffolds_skeleton(
            opts in topology_options_strategy(),
            n_hidden in 0usize..6,
        ) {
            let mut graph = Topology::new(0, Some(opts));
            graph.create_random_hidden_nodes(n_hidden);
            graph.finalize();
            let n_in = graph
                .nodes
                .iter()
                .filter(|n| n.kind == NodeKind::Input)
                .count();
            let n_out = graph
                .nodes
                .iter()
                .filter(|n| n.kind == NodeKind::Output)
                .count();
            prop_assert!(n_in >= 1, "scaffold must ensure an Input node");
            prop_assert_eq!(
                n_out, 1,
                "scaffold must leave exactly one Output node"
            );
            prop_assert!(graph.validate().is_ok());
        }
    }
}

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

    #[test]
    fn finalize_is_not_idempotent_so_never_run_it_on_loaded_topologies() {
        // Guardrail bug of record: loading a saved topology and calling `finalize()` threw
        // the wiring away and regenerated a DIFFERENT graph. Assert from_json preserves wiring.
        for seed in 0..25 {
            let mut original = Topology::new(seed, Some(TopologyOptions::default()));
            original.finalize();
            let json = original.to_json().unwrap();

            // 1. Round-trip is faithful — build from the parsed graph as-is.
            let parsed = Topology::from_json(&json).unwrap();
            let conns = |t: &Topology| {
                let mut v: Vec<(usize, usize, usize, usize)> = t
                    .connections
                    .iter()
                    .map(|c| (c.from.node, c.from.index, c.to.node, c.to.index))
                    .collect();
                v.sort_unstable();
                v
            };
            assert_eq!(
                conns(&original),
                conns(&parsed),
                "seed {seed}: from_json must preserve the finalized wiring"
            );

            // 2. Calling finalize() again REGENERATES — different graph.
            let mut re_finalized = parsed.clone();
            re_finalized.finalize();
            let differs = conns(&re_finalized) != conns(&parsed)
                    // A regenerated graph usually differs in wiring; even a lucky seed can leave
                    // different bridge sets. The two must never be assumed interchangeable.
                || Topology::from_json(&re_finalized.to_json().unwrap()).unwrap().connections.len()
                    != parsed.connections.len();
            if !differs {
                // Rare: finalize reproduced the same wiring for this seed.
                // Not a failure — just not evidence. Skip.
                continue;
            }
            assert!(
                differs,
                "seed {seed}: finalize() regenerated the wiring (as documented)"
            );
        }
    }

    #[test]
    fn finalize_wires_every_input_port_exactly_once() {
        // The wiring model: a port is a socket, not a bucket.
        for seed in 0..40 {
            let opts = TopologyOptions {
                topology_seed: seed,
                input_dim: Some(4),
                output_dim: Some(1),
                ..Default::default()
            };
            let mut a = Topology::new(seed, Some(opts));
            a.create_random_hidden_nodes(4);
            a.finalize();
            a.assert_one_wire_per_port();
            // The Input node is the one fan-out node, but it may not feed one target twice:
            // Input port is Identity, so the second wire would be the same signal twice, straight
            let input_id = a
                .nodes
                .iter()
                .find(|n| n.kind == NodeKind::Input)
                .unwrap()
                .id;
            for target in &a.nodes {
                let from_input = a
                    .connections
                    .iter()
                    .filter(|c| c.from.node == input_id && c.to.node == target.id)
                    .count();
                assert!(from_input <= 1, "n{} fed {from_input}× by Input", target.id);
            }

            let mut b = Topology::new(seed + 1000, Some(opts));
            b.create_random_hidden_nodes(4);
            b.finalize();
            b.assert_one_wire_per_port();

            let mut rng = Rng::with_seed(seed as u64);
            if Topology::cx_one_point(&mut a, &mut b, &mut rng) {
                a.assert_one_wire_per_port();
                b.assert_one_wire_per_port();
            }
        }
    }

    /// The uniform operator REPORTS what it exchanged: every coin at 1.0 flips every aligned gene,
    /// every coin at 0.0 flips none and is a declined pairing (no child), and the denominator
    #[test]
    fn cx_uniform_reports_the_genes_it_exchanged() {
        let opts = TopologyOptions::default();
        let pair = || {
            let mut a = Topology::new(11, Some(opts.clone()));
            a.create_random_hidden_nodes(4);
            a.finalize();
            let mut b = Topology::new(12, Some(opts.clone()));
            b.create_random_hidden_nodes(4);
            b.finalize();
            (a, b)
        };

        let (mut a, mut b) = pair();
        let all = Topology::cx_uniform(&mut a, &mut b, 1.0, &mut Rng::with_seed(5))
            .expect("every coin flips, so the operator reports");
        assert_eq!((all.swaps, all.pairs), (4, 4));
        assert_eq!(all.label(), "4/4");
        assert_eq!(
            all.moved,
            vec![Some(1), Some(2), Some(3), Some(4)],
            "every gene reports WHICH donor NODE it came from (index 1..4 = the hidden ones)"
        );
        assert_eq!(
            all.moved_b,
            vec![None; 4],
            "the reciprocal kept every gene, so its provenance is all `None`"
        );

        let (mut a, mut b) = pair();
        assert!(
            Topology::cx_uniform(&mut a, &mut b, 0.0, &mut Rng::with_seed(5)).is_none(),
            "no flips ⇒ no child ⇒ nothing to report"
        );

        // Mismatched hidden counts never pair up, so there is no denominator to print.
        let mut a = Topology::new(13, Some(opts.clone()));
        a.create_random_hidden_nodes(3);
        a.finalize();
        let mut b = Topology::new(14, Some(opts));
        b.create_random_hidden_nodes(5);
        b.finalize();
        assert!(Topology::cx_uniform(&mut a, &mut b, 1.0, &mut Rng::with_seed(5)).is_none());
    }

    /// A cut reports BOTH children: the swapped tail names the donor node on each side,
    /// so the engine can follow provenance whichever reciprocal it ends up keeping.
    #[test]
    fn cx_one_point_reports_provenance_for_both_sides() {
        let opts = TopologyOptions::default();
        let mut a = Topology::new(21, Some(opts.clone()));
        a.create_random_hidden_nodes(4);
        a.finalize();
        let mut b = Topology::new(22, Some(opts));
        b.create_random_hidden_nodes(4);
        b.finalize();

        let rep = Topology::cx_one_point_with_report(&mut a, &mut b, &mut Rng::with_seed(9))
            .expect("equal port counts always leave a pivot to cut at");
        assert_eq!(rep.pairs, 4);
        assert!(rep.swaps >= 1, "a cut that swaps nothing is declined");
        assert_eq!(rep.moved.len(), 4, "one slot per hidden node of `a`");
        assert_eq!(rep.moved_b.len(), 4, "one slot per hidden node of `b`");
        // A cut moves a CONTIGUOUS TAIL on each side; every slot before it kept its own.
        let is_tail =
            |m: &[Option<usize>]| m.iter().skip_while(|s| s.is_none()).all(|s| s.is_some());
        assert!(
            rep.moved.iter().any(|s| s.is_some()) && is_tail(&rep.moved),
            "a's moved slots are a tail: {:?}",
            rep.moved
        );
        assert!(
            rep.moved_b.iter().any(|s| s.is_some()) && is_tail(&rep.moved_b),
            "b's moved slots are a tail: {:?}",
            rep.moved_b
        );
        assert_eq!(
            rep.moved.iter().flatten().count(),
            rep.moved_b.iter().flatten().count(),
            "one swap moves one node on each side"
        );
    }

    #[test]
    fn orphan_rescue_grows_a_port_rather_than_stacking() {
        // Every candidate socket is taken, so the rescue has exactly one legal move: give
        // target another input port.
        let mut graph = Topology::new(3, Some(TopologyOptions::default()));
        graph.nodes.push(Node::new_input(0, 1));
        graph.nodes.push(Node::new_hidden(1, 1, 2));
        graph.nodes.push(Node::new_hidden(2, 1, 1));
        graph.nodes.push(Node::new_output(3, 1, 1));
        graph.connections = vec![
            Connection {
                from: Port { node: 0, index: 0 },
                to: Port { node: 1, index: 0 },
            },
            Connection {
                from: Port { node: 1, index: 0 },
                to: Port { node: 2, index: 0 },
            },
            Connection {
                from: Port { node: 2, index: 0 },
                to: Port { node: 3, index: 0 },
            },
        ];

        assert_eq!(
            graph.rewire_orphaned_outputs(),
            1,
            "n1_o1 is the only orphan"
        );

        assert!(
            graph.input_ports_with_multiple_wires().is_empty(),
            "the rescue must not stack a second wire on a taken port"
        );
        assert!(
            graph.nodes.iter().any(|n| n.num_inputs == 2),
            "the rescue must give the target a new input port"
        );
    }

    #[test]
    fn finalize_leaves_no_orphaned_input_output_ports() {
        // Regression: dedup used to run AFTER trim_orphaned_ports, stranding ports whose only wire
        // got dropped (mermaid `identity (orphan)` stubs).
        for seed in 0..40 {
            let mut g = Topology::new(seed, Some(TopologyOptions::default()));
            g.finalize();
            let in_id = g
                .nodes
                .iter()
                .find(|n| n.kind == NodeKind::Input)
                .unwrap()
                .id;
            let out_id = g
                .nodes
                .iter()
                .find(|n| n.kind == NodeKind::Output)
                .unwrap()
                .id;
            for p in 0..g.nodes[in_id].num_outputs {
                assert!(
                    g.connections
                        .iter()
                        .any(|c| c.from.node == in_id && c.from.index == p),
                    "seed {seed}: input port o{p} orphaned after finalize"
                );
            }
            for n in &g.nodes {
                for p in 0..n.num_inputs {
                    assert!(
                        g.connections
                            .iter()
                            .any(|c| c.to.node == n.id && c.to.index == p),
                        "seed {seed}: node n{} input port i{p} orphaned after finalize",
                        n.id
                    );
                }
                if n.id != out_id {
                    for p in 0..n.num_outputs {
                        assert!(
                            g.connections
                                .iter()
                                .any(|c| c.from.node == n.id && c.from.index == p),
                            "seed {seed}: node n{} output port o{p} orphaned after finalize",
                            n.id
                        );
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn finalize_respects_max_inputs_per_node() {
        // The setters bound CREATION; verify finalize never grows a node's declared input
        // count past the configured maximum (fan-in rescue only uses declared ports).
        for seed in 0..60 {
            let opts = TopologyOptions {
                min_hidden_inputs_per_node: 2,
                max_hidden_inputs_per_node: 3,
                min_hidden_outputs_per_node: 2,
                max_hidden_outputs_per_node: 3,
                ..Default::default()
            };
            let mut g = Topology::new(seed, Some(opts));
            g.create_random_hidden_nodes(5);
            g.finalize();
            for n in &g.nodes {
                if n.kind == NodeKind::Hidden {
                    assert!(
                        n.num_inputs <= 3,
                        "seed {seed}: n{} has {} inputs (max 3)",
                        n.id,
                        n.num_inputs
                    );
                }
            }
        }
    }

    #[test]
    fn exclusive_feature_masks_partition_without_sharing() {
        // Exclusive is a true partition: every feature lands in exactly one port,
        // no two branches can ever see the same feature.
        let opts = TopologyOptions {
            input_dim: Some(6),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(11, Some(opts));
        g.create_random_hidden_nodes(4);
        g.finalize();
        g.assign_feature_masks(FeatureSplitPolicy::Exclusive);

        let input = g.nodes.iter().find(|n| n.kind == NodeKind::Input).unwrap();
        let masks = input.feature_masks.as_ref().expect("masks assigned");
        assert_eq!(masks.len(), input.num_outputs, "one mask per output port");
        for feat in 0..6 {
            let owners = masks.iter().filter(|m| m[feat] == 1).count();
            assert_eq!(owners, 1, "feature {feat} must belong to exactly one port");
        }
        let placed: usize = masks
            .iter()
            .map(|m| m.iter().filter(|b| **b == 1).count())
            .sum();
        assert_eq!(placed, 6, "every feature is used exactly once");
    }

    #[test]
    fn random_feature_masks_are_per_port_and_may_overlap() {
        // Random flips an independent coin per (port, feature): no exclusivity,
        // only guarantees are the shape and that it is not degenerate.
        let opts = TopologyOptions {
            input_dim: Some(8),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(3, Some(opts));
        g.create_random_hidden_nodes(6);
        g.finalize();
        g.assign_feature_masks(FeatureSplitPolicy::Random);

        let input = g.nodes.iter().find(|n| n.kind == NodeKind::Input).unwrap();
        let masks = input.feature_masks.as_ref().expect("masks assigned");
        assert_eq!(masks.len(), input.num_outputs);
        assert!(
            masks.iter().all(|m| m.len() == 8),
            "every mask spans input_dim"
        );
        assert!(masks.iter().flatten().all(|b| *b <= 1), "masks are 0/1");
        let ones: usize = masks
            .iter()
            .map(|m| m.iter().filter(|b| **b == 1).count())
            .sum();
        assert!(
            ones > 0 && ones < masks.len() * 8,
            "random masks should be mixed, got {ones} ones"
        );
    }

    #[test]
    fn feature_masks_are_refused_off_the_input_node_and_at_the_wrong_width() {
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        // Wrong width: a mask must span exactly `input_dim`.
        let mut g = Topology::new(5, Some(opts));
        g.create_random_hidden_nodes(2);
        g.finalize();
        let idx = g
            .nodes
            .iter()
            .position(|n| n.kind == NodeKind::Input)
            .unwrap();
        let ports = g.nodes[idx].num_outputs.max(1);
        g.nodes[idx].feature_masks = Some(vec![vec![1u8, 0u8]; ports]); // 2 entries, not 4
        assert!(
            g.validate().is_err(),
            "a feature mask of the wrong width must be refused"
        );

        // Masks on a non-Input node: the split is an Input-side feature.
        let mut g2 = Topology::new(5, Some(opts));
        g2.create_random_hidden_nodes(2);
        g2.finalize();
        let hidden = g2
            .nodes
            .iter()
            .position(|n| n.kind == NodeKind::Hidden)
            .unwrap();
        g2.nodes[hidden].feature_masks = Some(vec![vec![1u8; 4]]);
        assert!(
            g2.validate().is_err(),
            "only Input nodes may carry feature masks"
        );
    }

    #[test]
    fn finalize_carries_masks_through_the_port_remap() {
        // Crossover re-finalizes both parents, and those parents already carry masks from their own
        // build.
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(13, Some(opts));
        g.create_random_hidden_nodes(3);
        g.finalize();
        g.assign_feature_masks(FeatureSplitPolicy::Exclusive);
        let before = g.input_feature_masks().expect("the split is present");

        // The rebuild itself: the rows must survive it, at the FINAL port count.
        g.finalize();
        let after = g
            .input_feature_masks()
            .expect("finalize must carry the split, not wipe it");
        let input = g.nodes.iter().find(|n| n.kind == NodeKind::Input).unwrap();
        assert_eq!(after.len(), input.num_outputs, "one row per final port");
        assert!(
            after.iter().all(|m| m.len() == 4),
            "every carried row keeps its width"
        );
        assert_eq!(after[0], before[0], "surviving ports keep their own row");
        g.validate().expect("carried masks must validate");
    }

    #[test]
    fn feature_masks_survive_the_blueprint_round_trip() {
        // The split is genome, so the masks must come back identical from the blueprint JSON —
        // file (not the weights) is also the Python side of the contract, so the field has
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(9, Some(opts));
        g.create_random_hidden_nodes(2);
        g.finalize();
        g.assign_feature_masks(FeatureSplitPolicy::Random);

        let json = g.to_json().unwrap();
        assert!(
            json.contains("feature_masks"),
            "the field must be part of the blueprint"
        );
        let back: Topology = serde_json::from_str(&json).unwrap();
        let idx = back
            .nodes
            .iter()
            .position(|n| n.kind == NodeKind::Input)
            .unwrap();
        assert_eq!(
            back.nodes[idx].feature_masks, g.nodes[idx].feature_masks,
            "masks must round-trip byte for byte"
        );

        // Old JSON predates the field: it must load as "no split".
        let legacy: Node = serde_json::from_value(serde_json::json!({
            "id": 0, "num_inputs": 0, "num_outputs": 2, "kind": "Input",
            "hidden_dim": null, "activation": "Identity",
            "port_activations": null, "combine_op": null, "standardize": null,
        }))
        .unwrap();
        assert_eq!(
            legacy.feature_masks, None,
            "serde default keeps old JSON loadable"
        );
    }

    /// The crossover path's installer: an inherited row lands on its own port, a port with no
    /// inherited row starts UNMASKED (every feature reaches it), and the result always validates
    #[test]
    fn install_feature_masks_maps_rows_and_leaves_new_ports_unmasked() {
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(23, Some(opts));
        g.create_random_hidden_nodes(3);
        g.finalize();
        fn input_of(t: &Topology) -> &crate::graph::node::Node {
            t.nodes.iter().find(|n| n.kind == NodeKind::Input).unwrap()
        }
        let ports = input_of(&g).num_outputs;
        assert!(
            ports >= 2,
            "fixture needs at least two input ports, got {ports}"
        );

        g.install_input_feature_masks(&[vec![0, 1, 1, 1]], None);
        let masks = input_of(&g)
            .feature_masks
            .clone()
            .expect("rows were installed");
        assert_eq!(masks.len(), ports, "one row per port");
        assert_eq!(masks[0], vec![0, 1, 1, 1], "the inherited row rides port 0");
        assert!(
            masks[1..].iter().all(|m| m == &vec![1u8; 4]),
            "a port with no inherited row sees every feature"
        );
        g.validate().expect("installed masks must validate");
        assert_eq!(
            g.input_feature_masks().expect("readable"),
            masks,
            "input_feature_masks must read back exactly what was installed"
        );
    }

    /// No inherited rows at all (neither parent carried a split, no policy): the input stays
    /// genuinely unmasked — no rows, no policy — rather than getting cover-all rows (which would be
    #[test]
    fn install_feature_masks_with_no_rows_leaves_the_net_unsplit() {
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(24, Some(opts));
        g.create_random_hidden_nodes(2);
        g.finalize();
        g.install_input_feature_masks(&[], None);
        assert!(
            g.input_feature_masks().is_none(),
            "no inherited rows means no masks at all"
        );
        assert_eq!(g.options.feature_split, None);
        g.validate().expect("unmasked topology must validate");
    }

    /// The LABEL follows the CONTENT, in the one place rows are installed: an inherited row set
    /// with no stated provenance is `Inherited`, never `None`.
    #[test]
    fn installing_inherited_rows_stamps_a_matching_policy() {
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let build = || {
            let mut g = Topology::new(25, Some(opts));
            g.create_random_hidden_nodes(3);
            g.finalize();
            g
        };

        // No provenance supplied → `Inherited` (the only true statement).
        let mut g = build();
        g.install_input_feature_masks(&[vec![0, 1, 0, 0]], None);
        assert_eq!(g.options.feature_split, Some(FeatureSplitPolicy::Inherited));
        assert!(g.input_feature_masks().is_some());

        // Stated provenance is kept verbatim.
        let mut g = build();
        g.install_input_feature_masks(&[vec![1, 0, 1, 0]], Some(FeatureSplitPolicy::Random));
        assert_eq!(g.options.feature_split, Some(FeatureSplitPolicy::Random));

        // A fresh draw stamps the policy it drew under, too.
        let mut g = build();
        g.assign_feature_masks(FeatureSplitPolicy::Exclusive);
        assert_eq!(g.options.feature_split, Some(FeatureSplitPolicy::Exclusive));

        // And `Inherited` is never drawable: it does not invent rows.
        let mut g = build();
        g.assign_feature_masks(FeatureSplitPolicy::Inherited);
        assert!(
            g.input_feature_masks().is_none(),
            "Inherited is provenance, not a draw rule"
        );
        assert_eq!(g.options.feature_split, None);
        assert!(!FeatureSplitPolicy::Inherited.is_drawable());
    }

    /// `Exclusive` is the one checkable claim a split makes — every feature owned EXACTLY once —
    /// a row set that fails it cannot wear the label.
    #[test]
    fn a_cover_all_port_beside_a_partition_is_not_labelled_exclusive() {
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(29, Some(opts));
        g.create_random_hidden_nodes(2);
        g.finalize();
        let input = g
            .nodes
            .iter()
            .position(|n| n.kind == NodeKind::Input)
            .unwrap();

        // 2 | 0 | 1 | 1 over 4 features: every feature in exactly one port,
        // accounting is 100% and the label stands.
        g.options.feature_split = Some(FeatureSplitPolicy::Exclusive);
        g.nodes[input].feature_masks = Some(vec![
            vec![1, 1, 0, 0],
            vec![0, 0, 0, 0],
            vec![0, 0, 1, 0],
            vec![0, 0, 0, 1],
        ]);
        g.reconcile_split_policy();
        assert_eq!(
            g.options.feature_split,
            Some(FeatureSplitPolicy::Exclusive),
            "a true partition keeps its label"
        );

        // The same rows plus one port that keeps EVERYTHING: features 0 and 1 now belong
        // to two ports, the accounting is 200%, and `exclusive` is a lie.
        g.nodes[input].feature_masks = Some(vec![
            vec![1, 1, 0, 0],
            vec![0, 0, 0, 0],
            vec![0, 0, 1, 0],
            vec![0, 0, 0, 1],
            vec![1, 1, 1, 1],
        ]);
        g.reconcile_split_policy();
        assert_eq!(
            g.options.feature_split,
            Some(FeatureSplitPolicy::Inherited),
            "a cover-all port breaks the partition, so the label follows the rows"
        );
    }

    /// Old records (and nets written by the crossover bug) load with rows under a `None` policy.
    #[test]
    fn loading_a_topology_with_rows_and_no_policy_repairs_the_label() {
        let opts = TopologyOptions {
            input_dim: Some(4),
            output_dim: Some(1),
            ..Default::default()
        };
        let mut g = Topology::new(26, Some(opts));
        g.create_random_hidden_nodes(2);
        g.finalize();
        g.assign_feature_masks(FeatureSplitPolicy::Exclusive);
        let mut json: serde_json::Value = serde_json::from_str(&g.to_json().unwrap()).unwrap();
        json["options"]
            .as_object_mut()
            .unwrap()
            .remove("feature_split"); // exactly what the old crossover path persisted
        let loaded = Topology::from_json(&json.to_string()).unwrap();
        assert_eq!(
            loaded.options.feature_split,
            Some(FeatureSplitPolicy::Inherited)
        );
        assert!(loaded.input_feature_masks().is_some());

        // An honest blueprint is left untouched.
        let again = Topology::from_json(&g.to_json().unwrap()).unwrap();
        assert_eq!(
            again.options.feature_split,
            Some(FeatureSplitPolicy::Exclusive)
        );
    }
}