cortex-hybrid 0.2.0

Backend-neutral ANN stage layer and deterministic Vec reference backend for hybrid ANN/SNN systems.
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use super::*;
use crate::error::HybridError;
use crate::moe::MoeRouter;
use crate::types::EMBEDDING_DIM;

#[cfg(feature = "axon-encoder")]
use axon_encoder::Encoder;

/// Deterministic in-tree backend for contract tests. Spikes every channel
/// whose stimulus exceeds `threshold`; tracks step count to prove state
/// advances and reset works. Not neuron dynamics — the test boundary.
struct MockBackend {
    channels: usize,
    threshold: f32,
    steps: usize,
    frozen_steps: usize,
}

impl MockBackend {
    fn new(channels: usize, threshold: f32) -> Self {
        Self {
            channels,
            threshold,
            steps: 0,
            frozen_steps: 0,
        }
    }
}

impl SnnBackend for MockBackend {
    fn channels(&self) -> usize {
        self.channels
    }

    fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        assert_eq!(stimulus.len(), self.channels);
        self.steps += 1;
        Ok(SnnStepOutput {
            spikes: stimulus
                .iter()
                .enumerate()
                .filter(|(_, v)| **v > self.threshold)
                .map(|(idx, _)| idx)
                .collect(),
        })
    }

    fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        assert_eq!(stimulus.len(), self.channels);
        self.frozen_steps += 1;
        Ok(SnnStepOutput { spikes: Vec::new() })
    }

    fn reset(&mut self) {
        self.steps = 0;
        self.frozen_steps = 0;
    }

    fn capabilities(&self) -> SnnCapabilities {
        SnnCapabilities {
            backend_name: "mock",
            frozen_evaluation: true,
            plasticity: true,
            caller_rng: false,
            neuromodulation: false,
        }
    }
}

fn spiking_router(backend: MockBackend) -> SpikingMoeRouter<MockBackend> {
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    SpikingMoeRouter::new(router, backend, RateEncoder::default(), SpikeCountDecoder).unwrap()
}

#[test]
fn rate_encoder_tiles_signal_across_channels() {
    let mut enc = RateEncoder { gain: 2.0 };
    assert_eq!(
        enc.encode(&[0.5, -1.0], 5).unwrap(),
        vec![1.0, -2.0, 1.0, -2.0, 1.0]
    );
    assert_eq!(enc.encode(&[], 3).unwrap(), vec![0.0; 3]);
}

#[test]
fn spike_count_decoder_counts_per_channel() {
    let out = SnnStepOutput {
        spikes: vec![0, 2, 9],
    };
    assert_eq!(
        SpikeCountDecoder.decode(&out, 4).unwrap(),
        vec![1.0, 0.0, 1.0, 0.0]
    );
}

#[test]
fn oversized_channel_counts_are_invalid_config_not_panics() {
    // Every `channels`-sized allocation on the SNN boundary is bounded by
    // MAX_SNN_CHANNELS; beyond it the answer is a typed error, not a
    // capacity-overflow panic or an allocator abort.
    let mut enc = RateEncoder::default();
    for channels in [MAX_SNN_CHANNELS + 1, usize::MAX] {
        assert!(matches!(
            enc.encode(&[1.0], channels),
            Err(HybridError::InvalidConfig(_))
        ));
    }

    let out = SnnStepOutput { spikes: vec![0] };
    assert!(matches!(
        SpikeCountDecoder.decode(&out, MAX_SNN_CHANNELS + 1),
        Err(HybridError::InvalidConfig(_))
    ));

    let router = MoeRouter::load_with_mode("", 8, 1, crate::moe::RoutingMode::DenseSim).unwrap();
    assert!(matches!(
        SpikingMoeRouter::new(
            router,
            MockBackend::new(usize::MAX, 0.0),
            RateEncoder::default(),
            SpikeCountDecoder,
        ),
        Err(HybridError::InvalidConfig(_))
    ));
}

/// Backend whose reported width jumps to `usize::MAX` on the
/// `huge_from_call`-th `channels()` invocation, modelling a backend that
/// grows between the router's construction, pre-step and post-step reads.
struct GrowingBackend {
    inner: MockBackend,
    calls: std::cell::Cell<usize>,
    huge_from_call: usize,
}

impl SnnBackend for GrowingBackend {
    fn channels(&self) -> usize {
        let n = self.calls.get();
        self.calls.set(n + 1);
        if n >= self.huge_from_call {
            usize::MAX
        } else {
            self.inner.channels()
        }
    }

    fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        self.inner.step(stimulus)
    }

    fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        self.inner.step_frozen(stimulus)
    }

    fn reset(&mut self) {
        self.inner.reset();
    }

    fn capabilities(&self) -> SnnCapabilities {
        self.inner.capabilities()
    }
}

/// Encoder that ignores the channel width and returns a fixed small
/// stimulus, so the test can distinguish the router's own width guard from
/// the cap inside `RateEncoder`.
struct LenientEncoder;

impl SnnEncoder for LenientEncoder {
    fn encode(&mut self, _ann_signal: &[f32], _channels: usize) -> Result<Vec<f32>> {
        Ok(vec![0.0; 4])
    }
}

#[test]
fn backend_channel_growth_is_rejected_before_and_after_the_tick() {
    let router = || MoeRouter::load_with_mode("", 8, 1, crate::moe::RoutingMode::DenseSim).unwrap();
    let growing = |huge_from_call| GrowingBackend {
        inner: MockBackend::new(8, 0.0),
        calls: std::cell::Cell::new(0),
        huge_from_call,
    };

    // channels() call order per forward: new() reads it twice (cap check,
    // then the expert-count check), then pre-step, then post-step — so
    // call indices 0-1 are construction, 2 is pre-step, 3 is post-step.
    // Growth visible at the pre-step read: the tick never runs. The lenient
    // encoder does not cap channels itself, so an `InvalidConfig` here can
    // only come from the router's width guard — without it the encoder
    // would run and the fixed stimulus would fail as `SnnStimulusLength`.
    let mut model =
        SpikingMoeRouter::new(router(), growing(2), LenientEncoder, SpikeCountDecoder).unwrap();
    assert!(matches!(
        model.forward(&[1.0; EMBEDDING_DIM]),
        Err(HybridError::InvalidConfig(_))
    ));
    assert_eq!(model.backend().inner.steps, 0);

    // Growth only visible after the step: the tick is consumed, then the
    // post-step width check rejects before spike validation allocates.
    let mut model = SpikingMoeRouter::new(
        router(),
        growing(3),
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap();
    assert!(matches!(
        model.forward(&[1.0; EMBEDDING_DIM]),
        Err(HybridError::InvalidConfig(_))
    ));
    assert_eq!(model.backend().inner.steps, 1);
}

#[test]
fn spiking_forward_routes_and_steps_backend() {
    let backend = MockBackend::new(8, 0.0);
    let mut model = spiking_router(backend);
    let mut embedding = vec![0.0f32; EMBEDDING_DIM];
    let chunk = (EMBEDDING_DIM / 8).max(1);
    embedding[3 * chunk] = 1.0e6;
    let out = model.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts[0], 3);
    assert_eq!(model.backend().steps, 1);
}

/// ±Inf gate scores are rejected before the encoder or backend runs.
#[test]
fn spiking_forward_rejects_infinite_gate_before_backend_step() {
    for bad in [f32::INFINITY, f32::NEG_INFINITY] {
        let mut model = spiking_router(MockBackend::new(8, 0.0));
        let mut embedding = vec![0.0f32; EMBEDDING_DIM];
        let chunk = (EMBEDDING_DIM / 8).max(1);
        embedding[3 * chunk] = bad;
        match model.forward(&embedding).unwrap_err() {
            HybridError::SnnInvalidStimulus { channel: 3, value } => assert_eq!(value, bad),
            other => panic!("expected SnnInvalidStimulus, got {other:?}"),
        }
        assert!(matches!(
            model.forward_frozen(&embedding),
            Err(HybridError::SnnInvalidStimulus { .. })
        ));
        assert_eq!(model.backend().steps, 0);
        assert_eq!(model.backend().frozen_steps, 0);
    }
}

/// A finite gate can still overflow to ±Inf in the encoder (`gain` scaling).
#[test]
fn overflowing_encoder_stimulus_is_rejected_before_backend_step() {
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        MockBackend::new(8, 0.0),
        RateEncoder { gain: f32::MAX },
        SpikeCountDecoder,
    )
    .unwrap();
    let err = model.forward(&[f32::MAX; EMBEDDING_DIM]).unwrap_err();
    assert!(
        matches!(err, HybridError::SnnInvalidStimulus { .. }),
        "got {err:?}"
    );
    assert_eq!(model.backend().steps, 0);
}

/// A finite gate can still overflow to ±Inf in the encoder (`gain` scaling),
/// and that is a separate rejection from the infinite *gate* case above: the
/// gate scores stay finite, the encoder output does not.
#[test]
fn infinite_encoder_stimulus_is_rejected_before_backend_step() {
    for bad in [f32::INFINITY, f32::NEG_INFINITY] {
        let router =
            MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
        let mut model = SpikingMoeRouter::new(
            router,
            MockBackend::new(8, 0.0),
            RateEncoder { gain: bad },
            SpikeCountDecoder,
        )
        .unwrap();
        // The gate scores are finite here (a sum of 1.0s), so only the
        // encoder output is infinite.
        let err = model.forward(&[1.0; EMBEDDING_DIM]).unwrap_err();
        assert!(
            matches!(err, HybridError::SnnInvalidStimulus { .. }),
            "got {err:?}"
        );
        assert_eq!(model.backend().steps, 0);
    }
}

/// Encoder that ignores the requested width and returns `len` zeros.
struct FixedLengthEncoder(usize);

impl SnnEncoder for FixedLengthEncoder {
    fn encode(&mut self, _ann_signal: &[f32], _channels: usize) -> Result<Vec<f32>> {
        Ok(vec![0.0; self.0])
    }
}

/// A stimulus of the wrong width breaks the `SnnEncoder` contract. It is
/// rejected with its own variant before the backend ticks, instead of being
/// handed to a backend that may index it by channel.
#[test]
fn wrong_length_encoder_stimulus_is_rejected_before_backend_step() {
    let embedding = vec![0.0f32; EMBEDDING_DIM];
    for got in [0usize, 7, 9] {
        let router =
            MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
        let mut model = SpikingMoeRouter::new(
            router,
            MockBackend::new(8, 0.0),
            FixedLengthEncoder(got),
            SpikeCountDecoder,
        )
        .unwrap();
        for frozen in [false, true] {
            let err = if frozen {
                model.forward_frozen(&embedding).unwrap_err()
            } else {
                model.forward(&embedding).unwrap_err()
            };
            assert!(
                matches!(err, CortexError::SnnStimulusLength { expected: 8, got: g } if g == got),
                "got {err:?}"
            );
        }
        assert_eq!(model.backend().steps, 0);
        assert_eq!(model.backend().frozen_steps, 0);
    }
    assert_eq!(
        CortexError::SnnStimulusLength {
            expected: 8,
            got: 7
        }
        .to_string(),
        "SNN encoder returned 7 stimulus values for 8 channels"
    );
}

/// Issue #89: `SpikingMoeRouter` shares `MoeRouter::gate_scores`, so a
/// checkpoint gate written in GGUF `ne` order must route the same way through
/// the spiking path. Expert 5's row is all ones; input `e_0` selects expert 5.
#[test]
fn spiking_forward_selects_expert_by_gguf_ne_order_row() {
    use crate::moe::test_fixtures::{build_real_size_checkpoint, write_temp_file};

    let experts = 64usize;
    let mut gate = vec![0.0f32; EMBEDDING_DIM * experts];
    gate[5 * EMBEDDING_DIM..6 * EMBEDDING_DIM].fill(1.0);
    let gate_bytes: Vec<u8> = gate.iter().flat_map(|value| value.to_le_bytes()).collect();
    let path = write_temp_file(&build_real_size_checkpoint(gate_bytes), "spiking-row-order");

    let router = MoeRouter::load_with_mode(
        path.to_str().unwrap(),
        8,
        1,
        crate::moe::RoutingMode::DenseSim,
    )
    .unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        MockBackend::new(8, 0.5),
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap();
    let mut embedding = vec![0.0f32; EMBEDDING_DIM];
    embedding[0] = 1.0;
    let out = model.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts, vec![5]);

    let _ = std::fs::remove_file(path);
}

#[test]
fn spiking_forward_rejects_nan_before_backend_step() {
    let backend = MockBackend::new(8, 0.0);
    let mut model = spiking_router(backend);
    let mut embedding = vec![0.0f32; EMBEDDING_DIM];
    let chunk = (EMBEDDING_DIM / 8).max(1);
    embedding[3 * chunk] = f32::NAN;
    assert!(matches!(
        model.forward(&embedding).unwrap_err(),
        HybridError::NanRoutingScore { expert_id: 3 }
    ));
    // Fail-closed: no tick consumed.
    assert_eq!(model.backend().steps, 0);
}

#[test]
fn constructor_rejects_fewer_channels_than_experts() {
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    assert!(matches!(
        SpikingMoeRouter::new(
            router,
            MockBackend::new(4, 0.0),
            RateEncoder::default(),
            SpikeCountDecoder
        ),
        Err(HybridError::SnnChannelMismatch {
            experts: 8,
            channels: 4
        })
    ));
}

#[test]
fn forward_rechecks_channel_width_every_tick() {
    // `new` enforces channels >= experts, but the backend is reachable through
    // `backend_mut` and user backends need not be constant-width. A width that
    // drops below the expert count must be a typed error on the next forward,
    // not an index panic on `decoded[expert_id]`, and must not consume a tick.
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        MockBackend::new(8, 0.0),
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap();
    let embedding = vec![0.1f32; EMBEDDING_DIM];
    model.forward(&embedding).unwrap();
    assert_eq!(model.backend().steps, 1);

    model.backend_mut().channels = 4;
    for frozen in [false, true] {
        let err = if frozen {
            model.forward_frozen(&embedding).unwrap_err()
        } else {
            model.forward(&embedding).unwrap_err()
        };
        assert!(
            matches!(
                err,
                HybridError::SnnChannelMismatch {
                    experts: 8,
                    channels: 4
                }
            ),
            "{err}"
        );
    }
    assert_eq!(model.backend().steps, 1);
    assert_eq!(model.backend().frozen_steps, 0);

    // Restoring the width makes the router usable again without a reset.
    model.backend_mut().channels = 8;
    model.forward(&embedding).unwrap();
    assert_eq!(model.backend().steps, 2);
}

#[test]
fn forward_rejects_width_that_shrinks_during_the_step() {
    // A backend whose width changes *inside* `step` passes the pre-tick
    // check; the post-step re-read must still reject it with a typed error
    // instead of indexing a readout shorter than the expert count.
    struct Shrinking {
        channels: usize,
        shrink_to: usize,
        steps: usize,
    }
    impl SnnBackend for Shrinking {
        fn channels(&self) -> usize {
            self.channels
        }
        fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
            assert_eq!(stimulus.len(), self.channels);
            self.steps += 1;
            self.channels = self.shrink_to;
            Ok(SnnStepOutput { spikes: Vec::new() })
        }
        fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
            self.step(stimulus)
        }
        fn reset(&mut self) {}
        fn capabilities(&self) -> SnnCapabilities {
            SnnCapabilities {
                backend_name: "shrinking",
                frozen_evaluation: true,
                plasticity: false,
                caller_rng: false,
                neuromodulation: false,
            }
        }
    }

    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        Shrinking {
            channels: 8,
            shrink_to: 4,
            steps: 0,
        },
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap();
    let err = model.forward(&vec![0.1f32; EMBEDDING_DIM]).unwrap_err();
    assert!(
        matches!(
            err,
            HybridError::SnnChannelMismatch {
                experts: 8,
                channels: 4
            }
        ),
        "{err}"
    );
    // The tick was consumed (documented); the next call fails pre-tick.
    assert_eq!(model.backend().steps, 1);
    let err = model.forward(&vec![0.1f32; EMBEDDING_DIM]).unwrap_err();
    assert!(matches!(err, HybridError::SnnChannelMismatch { .. }));
    assert_eq!(model.backend().steps, 1);
}

#[test]
fn nan_stimulus_rejected_before_backend_step() {
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        MockBackend::new(8, 0.0),
        RateEncoder { gain: f32::NAN },
        SpikeCountDecoder,
    )
    .unwrap();
    assert!(matches!(
        model.forward(&[1.0; EMBEDDING_DIM]).unwrap_err(),
        HybridError::SnnNan { .. }
    ));
    // Fail-closed: no tick consumed.
    assert_eq!(model.backend().steps, 0);
}

#[test]
fn forward_frozen_uses_frozen_path_and_reset_clears_state() {
    let backend = MockBackend::new(8, 0.0);
    let mut model = spiking_router(backend);
    let _ = model.forward(&[1.0; EMBEDDING_DIM]).unwrap();
    let _ = model.forward_frozen(&[1.0; EMBEDDING_DIM]).unwrap();
    assert_eq!(model.backend().steps, 1);
    assert_eq!(model.backend().frozen_steps, 1);
    assert!(model.capabilities().frozen_evaluation);
    model.reset();
    assert_eq!(model.backend().steps, 0);
    assert_eq!(model.backend().frozen_steps, 0);
}

#[test]
fn spiking_forward_rejects_wrong_embedding_length() {
    let backend = MockBackend::new(8, 0.0);
    let mut model = spiking_router(backend);
    assert!(matches!(
        model.forward(&[0.0; 8]).unwrap_err(),
        HybridError::InputLengthMismatch { .. }
    ));
}

/// Backend that replays a fixed spike list every tick, so tests can script
/// exactly which channels fire (including out-of-range and duplicate indices
/// a misbehaving backend might emit). Not neuron dynamics — the test boundary.
struct ScriptedBackend {
    channels: usize,
    spikes: Vec<usize>,
}

impl SnnBackend for ScriptedBackend {
    fn channels(&self) -> usize {
        self.channels
    }

    fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        assert_eq!(stimulus.len(), self.channels);
        Ok(SnnStepOutput {
            spikes: self.spikes.clone(),
        })
    }

    fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        self.step(stimulus)
    }

    fn reset(&mut self) {}

    fn capabilities(&self) -> SnnCapabilities {
        SnnCapabilities {
            backend_name: "scripted",
            frozen_evaluation: false,
            plasticity: false,
            caller_rng: false,
            neuromodulation: false,
        }
    }
}

/// Decoder that multiplies each spike count by a large factor, standing in
/// for multi-count readouts (burst counts, rate estimates) whose magnitude
/// is unbounded from the router's point of view.
struct ScaledCountDecoder(f32);

impl SnnDecoder for ScaledCountDecoder {
    fn decode(&self, output: &SnnStepOutput, channels: usize) -> Result<Vec<f32>> {
        Ok(SpikeCountDecoder
            .decode(output, channels)?
            .into_iter()
            .map(|count| count * self.0)
            .collect())
    }
}

/// Decoder that emits a fixed readout regardless of spikes, used to feed the
/// router readouts (negative, non-finite) a well-behaved decoder never would.
struct FixedReadoutDecoder(Vec<f32>);

impl SnnDecoder for FixedReadoutDecoder {
    fn decode(&self, _output: &SnnStepOutput, _channels: usize) -> Result<Vec<f32>> {
        Ok(self.0.clone())
    }
}

/// Embedding whose stub (`DenseSim`) gate scores equal `logits` exactly:
/// expert *e*'s gate is the sum of embedding chunk *e*, so one non-zero
/// element per chunk pins the logit.
fn embedding_with_gate_logits(logits: &[f32]) -> Vec<f32> {
    assert!(!logits.is_empty(), "need at least one gate logit");
    let chunk = (EMBEDDING_DIM / logits.len()).max(1);
    let mut embedding = vec![0.0f32; EMBEDDING_DIM];
    for (expert, &logit) in logits.iter().enumerate() {
        embedding[expert * chunk] = logit;
    }
    embedding
}

/// Issue #93 repro: eight experts with strictly negative gate logits.
const NEGATIVE_LOGITS: [f32; 8] = [-1.0, -1.25, -1.5, -1.75, -2.0, -2.25, -2.5, -2.75];

fn scripted_router<D: SnnDecoder>(
    spikes: Vec<usize>,
    decoder: D,
) -> SpikingMoeRouter<ScriptedBackend, RateEncoder, D> {
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    SpikingMoeRouter::new(
        router,
        ScriptedBackend {
            channels: 8,
            spikes,
        },
        RateEncoder::default(),
        decoder,
    )
    .unwrap()
}

/// Issue #93 (1): a spike must never demote its expert. With the old
/// `gate * (1 + spikes)` boost, spiking channel 0 on negative logits evicted
/// expert 0 (`[0, 1]` → `[1, 2]`).
#[test]
fn spike_boost_promotes_spiked_expert_with_negative_gate_logits() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);

    // Silent backend: ranking is the dense ranking.
    let mut silent = scripted_router(Vec::new(), SpikeCountDecoder);
    assert_eq!(
        silent.forward(&embedding).unwrap().selected_experts,
        vec![0, 1]
    );

    // Spiking the already-top expert keeps it on top.
    let mut spike_top = scripted_router(vec![0], SpikeCountDecoder);
    assert_eq!(
        spike_top.forward(&embedding).unwrap().selected_experts,
        vec![0, 1]
    );

    // Spiking a lower-ranked expert promotes it: -1.5 + 1.0 beats -1.0.
    let mut spike_mid = scripted_router(vec![2], SpikeCountDecoder);
    assert_eq!(
        spike_mid.forward(&embedding).unwrap().selected_experts,
        vec![2, 0]
    );
}

/// Issue #93 (1): the boost is monotone in the spike count for either logit
/// sign — more spikes never lower an expert's rank.
#[test]
fn spike_boost_is_monotone_in_spike_count_regardless_of_logit_sign() {
    // Same spread shifted into positive territory (2.75 … 1.0) keeps expert 7 weakest.
    for logits in [NEGATIVE_LOGITS, NEGATIVE_LOGITS.map(|v| v + 3.75)] {
        let embedding = embedding_with_gate_logits(&logits);
        let mut previous_rank = usize::MAX;
        // Expert 7 holds the lowest logit of each set; raise its readout from
        // 0 to 4 "spikes" via a scaled decoder and watch its rank only improve.
        for count in 0..5 {
            let mut model = scripted_router(vec![7], ScaledCountDecoder(count as f32));
            let out = model.forward(&embedding).unwrap();
            let rank = out
                .selected_experts
                .iter()
                .position(|&e| e == 7)
                .unwrap_or(out.selected_experts.len());
            assert!(
                rank <= previous_rank,
                "count {count}: rank {rank} > {previous_rank}"
            );
            previous_rank = rank;
        }
        // Four spikes lift the weakest expert (-2.75 or 1.0) to the top.
        assert_eq!(previous_rank, 0, "logits {logits:?}");
    }
}

/// Issue #93 (1): `with_spike_boost` scales the additive boost and rejects
/// values that would break monotonicity.
#[test]
fn spike_boost_gain_is_configurable_and_validated() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    // beta = 0.1: -1.5 + 0.1 does not beat -1.25, so spiking expert 2 changes nothing.
    let mut weak = SpikingMoeRouter::new(
        router,
        ScriptedBackend {
            channels: 8,
            spikes: vec![2],
        },
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap()
    .with_spike_boost(0.1)
    .unwrap();
    assert_eq!(weak.spike_boost(), 0.1);
    assert_eq!(
        weak.forward(&embedding).unwrap().selected_experts,
        vec![0, 1]
    );

    for bad in [-1.0, f32::NAN, f32::INFINITY] {
        let model = scripted_router(Vec::new(), SpikeCountDecoder);
        assert!(matches!(
            model.with_spike_boost(bad),
            Err(CortexError::InvalidConfig(_))
        ));
    }
}

/// Issue #93 (2): `hidden` is scaled by selected softmax mass weighted by
/// normalised spike activity, so its gain stays in `[0, 1]` even when the
/// decoder reports huge counts, and a silent tick falls back to the dense
/// selected mass instead of zeroing the hidden state.
#[test]
fn hidden_scale_is_bounded_and_silent_tick_keeps_dense_mass() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);

    // Silent backend: same scale as `MoeRouter::forward` (sum of selected softmax weights).
    let mut silent = scripted_router(Vec::new(), SpikeCountDecoder);
    let out = silent.forward(&embedding).unwrap();
    let dense_mass: f32 = out
        .selected_experts
        .iter()
        .map(|&e| out.expert_weights[e])
        .sum();
    assert!(dense_mass > 0.0 && dense_mass <= 1.0);
    assert_eq!(out.hidden[0], embedding[0] * dense_mass);
    assert!(
        out.hidden
            .iter()
            .zip(&embedding)
            .all(|(h, e)| *h == e * dense_mass)
    );

    // Huge multi-count readout on both selected experts: gain is still ≤ 1.
    let mut loud = scripted_router(vec![0, 1], ScaledCountDecoder(1e6));
    let out = loud.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts, vec![0, 1]);
    let mass: f32 = out
        .selected_experts
        .iter()
        .map(|&e| out.expert_weights[e])
        .sum();
    assert_eq!(out.hidden[0], embedding[0] * mass);
    assert!(out.hidden.iter().all(|h| h.is_finite() && h.abs() <= 2.75));

    // One selected expert spiking, the other silent: only the spiking expert's
    // softmax weight contributes.
    let mut partial = scripted_router(vec![0], SpikeCountDecoder);
    let out = partial.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts, vec![0, 1]);
    assert_eq!(out.hidden[0], embedding[0] * out.expert_weights[0]);
}

/// Issue #93 (3): backend spike indices outside `0..channels` are rejected
/// before decoding instead of being silently dropped by the decoder.
#[test]
fn forward_rejects_backend_spike_outside_channel_space() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);
    let mut model = scripted_router(vec![0, 9], SpikeCountDecoder);
    assert!(matches!(
        model.forward(&embedding).unwrap_err(),
        CortexError::SnnSpikeOutOfRange {
            channel: 9,
            channels: 8
        }
    ));
}

/// Issue #93 (3): a channel reported twice in one tick violates the
/// `SnnStepOutput` contract and is rejected instead of double-counted.
#[test]
fn forward_rejects_duplicate_backend_spikes() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);
    let mut model = scripted_router(vec![3, 1, 3], SpikeCountDecoder);
    assert!(matches!(
        model.forward_frozen(&embedding).unwrap_err(),
        CortexError::SnnDuplicateSpike { channel: 3 }
    ));
}

/// Issue #93 (3): decoder readouts must be finite and non-negative — the
/// boost and the hidden-state normalisation both assume activity ≥ 0.
#[test]
fn forward_rejects_negative_or_non_finite_decoder_readout() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);
    for (bad, channel) in [(-1.0, 2usize), (f32::INFINITY, 5), (f32::NEG_INFINITY, 0)] {
        let mut readout = vec![0.0f32; 8];
        readout[channel] = bad;
        let mut model = scripted_router(Vec::new(), FixedReadoutDecoder(readout));
        match model.forward(&embedding).unwrap_err() {
            CortexError::SnnInvalidReadout {
                channel: got,
                value,
            } => {
                assert_eq!(got, channel);
                assert_eq!(value, bad);
            }
            other => panic!("expected SnnInvalidReadout, got {other:?}"),
        }
    }
    // NaN keeps its dedicated variant.
    let mut nan = scripted_router(Vec::new(), FixedReadoutDecoder(vec![f32::NAN; 8]));
    assert!(matches!(
        nan.forward(&embedding).unwrap_err(),
        CortexError::SnnNan {
            stage: "decoder readout"
        }
    ));
}

/// A decoder readout of the wrong length is a structural violation, not a
/// NaN: it gets its own variant carrying the expected and actual lengths.
#[test]
fn forward_rejects_wrong_length_decoder_readout() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);
    for got in [0usize, 7, 9] {
        let mut model = scripted_router(Vec::new(), FixedReadoutDecoder(vec![0.0; got]));
        assert!(matches!(
            model.forward(&embedding).unwrap_err(),
            CortexError::SnnReadoutLength {
                expected: 8,
                got: g
            } if g == got
        ));
    }
}

/// `spike_boost * activity` saturates instead of overflowing: a finite gate
/// stays finite and a `-Inf` gate stays `-Inf` rather than becoming NaN
/// after the backend tick has been consumed.
#[test]
fn spike_boost_saturates_instead_of_overflowing() {
    // Expert 0 gated at f32::MIN (±Inf gates are rejected, see
    // `spiking_forward_rejects_infinite_gate_before_backend_step`), expert 1
    // at 0.0; both spike with activity 1e30.
    let mut logits = [0.0f32; 8];
    logits[0] = f32::MIN;
    let embedding = embedding_with_gate_logits(&logits);
    let mut model = scripted_router(vec![0, 1], ScaledCountDecoder(1e30))
        .with_spike_boost(1e30)
        .unwrap();
    let out = model.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts[0], 1);
    // f32::MIN + a saturated f32::MAX bonus is exactly 0.0: finite, not NaN.
    assert!(out.expert_weights.iter().all(|w| w.is_finite()));
    assert!(out.hidden.iter().all(|h| !h.is_nan()));
}

/// A gate already at `f32::MAX` plus a large bonus must saturate rather
/// than overflow to `+Inf`: the score stays finite and the expert wins.
/// Expert 1 sits at `f32::MAX` without spiking, so if the spiked expert 0
/// overflowed to `+Inf` the softmax would hand it all the mass; saturation
/// leaves both at `f32::MAX` and they share it.
#[test]
fn finite_gate_plus_large_bonus_saturates_to_finite_score() {
    let mut logits = [0.0f32; 8];
    logits[0] = f32::MAX;
    logits[1] = f32::MAX;
    let embedding = embedding_with_gate_logits(&logits);
    // Expert 0 spikes with activity 1e30 under a 1e30 boost.
    let mut model = scripted_router(vec![0], ScaledCountDecoder(1e30))
        .with_spike_boost(1e30)
        .unwrap();
    let scores = model.router().gate_scores(&embedding).unwrap();
    assert!(scores[0].is_finite(), "gate must be finite: {}", scores[0]);
    let out = model.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts, vec![0, 1]);
    assert!(out.expert_weights.iter().all(|w| w.is_finite()));
    assert_eq!(
        out.expert_weights[0], out.expert_weights[1],
        "both scores saturate at f32::MAX, so neither may absorb the mass"
    );
    assert!(out.expert_weights[0] > 0.0);
    assert!(out.hidden.iter().all(|h| h.is_finite()));
}

/// Spikes only on unselected experts must not zero the hidden state: the
/// gain falls back to the dense selected mass exactly as on a silent tick.
#[test]
fn hidden_keeps_dense_mass_when_only_unselected_experts_spike() {
    let embedding = embedding_with_gate_logits(&NEGATIVE_LOGITS);
    // Expert 7 spikes but -2.75 + 1.0 still loses to -1.0 / -1.25.
    let mut model = scripted_router(vec![7], SpikeCountDecoder);
    let out = model.forward(&embedding).unwrap();
    assert_eq!(out.selected_experts, vec![0, 1]);
    let dense_mass: f32 = out
        .selected_experts
        .iter()
        .map(|&e| out.expert_weights[e])
        .sum();
    assert!(dense_mass > 0.0);
    assert!(
        out.hidden
            .iter()
            .zip(&embedding)
            .all(|(h, e)| *h == e * dense_mass)
    );
}

#[cfg(feature = "axon-encoder")]
#[test]
fn axon_encoder_adapter_counts_spikes_per_channel() {
    let enc = axon_encoder::prelude::RateEncoder::try_new(0.0, 100.0, (0.0, 1.0), 0.1).unwrap();
    let mut adapter = AxonEncoder::new(enc);
    // 100 Hz * 0.1 s = 10 spikes on channel 0 for input 1.0; input 0.0 stays silent.
    let stimulus = adapter.encode(&[1.0, 0.0], 8).unwrap();
    assert_eq!(stimulus[0], 10.0);
    assert!(stimulus[1..].iter().all(|&v| v == 0.0));
}

#[cfg(feature = "axon-encoder")]
#[test]
fn axon_encoder_rejects_spikes_outside_channel_space() {
    let enc = axon_encoder::prelude::RateEncoder::try_new(0.0, 100.0, (0.0, 1.0), 0.1).unwrap();
    let mut adapter = AxonEncoder::new(enc);
    // 8 input channels of spikes cannot be represented in a 4-channel stimulus.
    assert!(matches!(
        adapter.encode(&[1.0; 8], 4),
        Err(HybridError::SnnSpikeOutOfRange {
            channel: 4,
            channels: 4
        })
    ));
}

#[cfg(feature = "axon-encoder")]
#[test]
fn axon_encoder_streams_phase_across_calls() {
    // 5 Hz * 0.1 s = 0.5 expected spikes per step: the first call accumulates
    // phase and emits nothing; the second emits the deferred spike — encoder
    // state advances per call (documented streaming contract, not atomic).
    let enc = axon_encoder::prelude::RateEncoder::try_new(5.0, 5.0, (0.0, 1.0), 0.1).unwrap();
    let mut adapter = AxonEncoder::new(enc);
    assert_eq!(adapter.encode(&[1.0], 1).unwrap()[0], 0.0);
    assert_eq!(adapter.encode(&[1.0], 1).unwrap()[0], 1.0);
    SnnEncoder::reset(&mut adapter);
    // Clean epoch: accumulated phase is gone, next call accumulates again.
    assert_eq!(adapter.encode(&[1.0], 1).unwrap()[0], 0.0);
}

#[cfg(feature = "axon-encoder")]
#[test]
fn population_encoder_keeps_one_population_per_input_inside_u16_ids() {
    // Endpoint preferences fire with probability 1, on channels
    // `input_index * num_neurons + neuron` (0 and 3). axon-encoder 0.5 would
    // have encoded only the first input.
    let enc = axon_encoder::prelude::PopulationEncoder::try_new(2, (0.0, 100.0), f32::MIN_POSITIVE)
        .unwrap();
    let mut adapter = AxonEncoder::new(enc);
    let stimulus = adapter.encode(&[0.0, 100.0], 4).unwrap();
    assert_eq!(stimulus, vec![1.0, 0.0, 0.0, 1.0]);
}

#[cfg(feature = "axon-encoder")]
#[test]
fn population_encoder_width_over_u16_is_an_error_not_a_panic() {
    // 8 × 8,193 = 65,544 > 65,536. `try_new` allows 8,193 neurons; 0.6
    // `encode_step` asserts on the product with the gate-score slice.
    let enc = axon_encoder::prelude::PopulationEncoder::try_new(8_193, (0.0, 1.0), 0.2).unwrap();
    let mut bare = enc.clone();
    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        bare.encode_step(&[0.0; 8]);
    }));
    assert!(
        panicked.is_err(),
        "axon-encoder 0.6 PopulationEncoder::encode_step panics above the u16 id space"
    );

    let mut adapter = AxonEncoder::new(enc);
    match adapter.encode(&[0.0; 8], 8) {
        Err(HybridError::InvalidConfig(message)) => {
            assert!(message.contains("65544"));
            assert!(message.contains("65536"));
        }
        other => panic!("expected InvalidConfig, got {other:?}"),
    }

    // Same guard when `new` is called through a generic wrapper: the check
    // reads the concrete encoder at encode time.
    fn wrap<E: axon_encoder::Encoder + 'static>(encoder: E) -> AxonEncoder<E> {
        AxonEncoder::new(encoder)
    }
    let enc = axon_encoder::prelude::PopulationEncoder::try_new(8_193, (0.0, 1.0), 0.2).unwrap();
    assert!(matches!(
        wrap(enc).encode(&[0.0; 8], 8),
        Err(HybridError::InvalidConfig(_))
    ));
}

/// axon-encoder 0.6 `expect`s on a `u16` channel index in these two encoders.
#[cfg(feature = "axon-encoder")]
#[test]
fn derivative_and_embedding_rate_encoders_over_u16_inputs_are_errors_not_panics() {
    let derivative = axon_encoder::prelude::DerivativeEncoder::try_new(vec![0.0; 65_536]).unwrap();
    let mut adapter = AxonEncoder::new(derivative);
    let mut jump = vec![0.0f32; 70_000];
    jump[66_000] = 1.0e6;
    assert!(matches!(
        adapter.encode(&jump, 8),
        Err(HybridError::InvalidConfig(_))
    ));

    let embedding = axon_encoder::prelude::EmbeddingRateEncoder::try_new(
        65_536,
        axon_encoder::prelude::EmbeddingEncoderConfig { v_th: 0.1 },
    )
    .expect("construct EmbeddingRateEncoder");
    let mut adapter = AxonEncoder::new(embedding);
    assert!(matches!(
        adapter.encode(&vec![1.0f32; 70_000], 8),
        Err(HybridError::InvalidConfig(_))
    ));
}

/// Newtype wrapper that hides the concrete `PopulationEncoder` from the
/// `AxonEncoder` downcast — the bypass the declared-width API exists for.
#[cfg(feature = "axon-encoder")]
struct WrappedPopulationEncoder(axon_encoder::prelude::PopulationEncoder);

#[cfg(feature = "axon-encoder")]
impl Encoder for WrappedPopulationEncoder {
    fn encode(&mut self, input: &[f32]) -> axon_encoder::types::EncodedOutput {
        self.0.encode(input)
    }

    fn encode_step(&mut self, input: &[f32]) -> axon_encoder::types::EncodedOutput {
        self.0.encode_step(input)
    }

    fn reset(&mut self) {
        self.0.reset();
    }
}

#[cfg(feature = "axon-encoder")]
#[test]
fn wrapped_population_encoder_needs_declared_neurons() {
    let population =
        || axon_encoder::prelude::PopulationEncoder::try_new(8_193, (0.0, 1.0), 0.2).unwrap();

    // Undeclared: the downcast cannot see through the newtype, so the width
    // check is skipped and axon-encoder panics inside `encode_step` — pinned
    // with catch_unwind like the bare-encoder test above.
    let mut hidden = AxonEncoder::new(WrappedPopulationEncoder(population()));
    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = hidden.encode(&[0.0; 8], 8);
    }));
    assert!(
        panicked.is_err(),
        "an undeclared wrapped PopulationEncoder still panics inside axon-encoder"
    );

    // Declared: the same width is rejected with a typed error instead.
    let mut declared =
        AxonEncoder::new(WrappedPopulationEncoder(population())).with_population_neurons(8_193);
    assert!(matches!(
        declared.encode(&[0.0; 8], 8),
        Err(HybridError::InvalidConfig(_))
    ));
}

#[cfg(feature = "axon-encoder")]
#[test]
fn concrete_population_width_outranks_a_stale_declaration() {
    // A live `PopulationEncoder` reports its own `num_neurons`; a declared
    // width must not mask a wider real configuration (e.g. after an
    // `encoder_mut` swap or a wrong declaration).
    let enc = axon_encoder::prelude::PopulationEncoder::try_new(8_193, (0.0, 1.0), 0.2).unwrap();
    let mut adapter = AxonEncoder::new(enc).with_population_neurons(8);
    assert!(matches!(
        adapter.encode(&[0.0; 8], 8),
        Err(HybridError::InvalidConfig(_))
    ));
}

#[cfg(feature = "axon-encoder")]
#[test]
fn population_encoder_over_u16_fails_closed_before_the_backend_steps() {
    let enc = axon_encoder::prelude::PopulationEncoder::try_new(8_193, (0.0, 1.0), 0.2).unwrap();
    let router = MoeRouter::load_with_mode("", 8, 1, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        MockBackend::new(8, 0.0),
        AxonEncoder::new(enc),
        SpikeCountDecoder,
    )
    .unwrap();
    assert!(matches!(
        model.forward(&[1.0; EMBEDDING_DIM]),
        Err(HybridError::InvalidConfig(_))
    ));
    assert_eq!(model.backend().steps, 0);
}

#[cfg(feature = "axon-encoder")]
#[test]
fn axon_encoder_adapter_drives_spiking_router() {
    let enc = axon_encoder::prelude::RateEncoder::try_new(0.0, 100.0, (0.0, 1.0), 0.1).unwrap();
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        MockBackend::new(8, 0.0),
        AxonEncoder::new(enc),
        SpikeCountDecoder,
    )
    .unwrap();
    model.forward(&[1.0; EMBEDDING_DIM]).unwrap();
    assert_eq!(model.backend().steps, 1);
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_steps_and_reports_capabilities() {
    // One LIF neuron per channel; the Izhikevich bank is auxiliary and does
    // not count toward the output width (#91).
    let mut net = NeuromodNetwork::new(8, 1, 8).unwrap();
    assert_eq!(net.channels(), 8);
    let caps = net.capabilities();
    assert_eq!(caps.backend_name, "neuromod::SpikingNetwork");
    // neuromod 0.7 ships `step_frozen`; the thread-local RNG path is the
    // default, so replay is only advertised once a seed is installed (#92).
    assert!(caps.frozen_evaluation && caps.plasticity && caps.neuromodulation);
    assert!(!caps.caller_rng);

    let out = net.step(&[0.5; 8]).unwrap();
    assert!(out.spikes.iter().all(|&i| i < 8));
    let _ = net.step_frozen(&[0.5; 8]).unwrap();
    net.reset();
    assert_eq!(net.network().global_step, 0);

    // Length validation is failure-atomic via neuromod's preflight.
    assert!(matches!(
        net.step(&[0.5; 4]),
        Err(CortexError::InputLengthMismatch {
            expected: 8,
            got: 4
        })
    ));
    assert_eq!(net.network().global_step, 0);

    // Non-finite stimulus maps to a typed error, not `SnnBackend(String)`.
    let mut bad = [0.5f32; 8];
    bad[5] = f32::INFINITY;
    assert!(matches!(
        net.step(&bad),
        Err(CortexError::SnnInvalidStimulus { channel: 5, value }) if value == f32::INFINITY
    ));
    bad[5] = f32::NEG_INFINITY;
    assert!(matches!(
        net.step_frozen(&bad),
        Err(CortexError::SnnInvalidStimulus { channel: 5, value }) if value == f32::NEG_INFINITY
    ));
    assert_eq!(net.network().global_step, 0);

    // LIF count must equal channel count for the 1:1 output contract.
    assert!(matches!(
        NeuromodNetwork::new(4, 1, 8),
        Err(CortexError::InvalidConfig(_))
    ));
}

/// Spike counts per channel after driving `net` with `stimulus` for `steps`
/// learning-enabled ticks.
#[cfg(feature = "neuromod")]
fn neuromod_spike_counts(net: &mut NeuromodNetwork, stimulus: &[f32], steps: usize) -> Vec<usize> {
    let mut counts = vec![0usize; net.channels()];
    for _ in 0..steps {
        for idx in net.step(stimulus).unwrap().spikes {
            counts[idx] += 1;
        }
    }
    counts
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_rejects_izhikevich_neurons_as_output_channels() {
    // neuromod's `step` returns LIF indices only, so an Izhikevich neuron
    // counted toward `num_channels` is a channel that can never spike (#91).
    for (lif, izh) in [(7, 1), (0, 8), (4, 4)] {
        let err = NeuromodNetwork::new(lif, izh, 8).err().expect("rejected");
        assert!(
            matches!(err, CortexError::InvalidConfig(_)),
            "{lif}/{izh}: {err}"
        );
        assert!(err.to_string().contains("Izhikevich"), "{err}");
    }
    // Izhikevich neurons are allowed as an auxiliary bank on top of the
    // one-LIF-per-channel requirement.
    assert!(NeuromodNetwork::new(8, 3, 8).is_ok());
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_new_wires_every_channel_to_a_spiking_neuron() {
    // `SpikingNetwork::with_dimensions` zero-initialises LIF weights and the
    // L1 renormalization keeps a blank neuron blank, so a backend built that
    // way never spikes (#91). `new` must seed weights so every channel can.
    let mut net = NeuromodNetwork::new(8, 0, 8)
        .unwrap()
        .with_seed(0x5EED_0001);
    let counts = neuromod_spike_counts(&mut net, &[1.0; 8], 200);
    assert!(
        counts.iter().all(|&c| c > 0),
        "every channel must spike under strong stimulus: {counts:?}"
    );

    // Identity wiring: driving channel `i` alone spikes neuron `i` alone, so
    // `SpikingMoeRouter`'s expert-to-channel mapping holds.
    for ch in 0..8 {
        let mut net = NeuromodNetwork::new(8, 0, 8)
            .unwrap()
            .with_seed(0x5EED_0002);
        let mut stimulus = [0.0; 8];
        stimulus[ch] = 1.0;
        let counts = neuromod_spike_counts(&mut net, &stimulus, 50);
        assert!(counts[ch] > 0, "channel {ch} silent: {counts:?}");
        assert!(
            counts.iter().enumerate().all(|(i, &c)| i == ch || c == 0),
            "channel {ch} leaked: {counts:?}"
        );
    }
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_rejects_blank_lif_neurons() {
    // A restored or hand-built network with an all-zero LIF neuron carries a
    // channel that provably cannot spike; fail at construction, not after
    // thousands of silent ticks (#91).
    let blank = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    let err = NeuromodNetwork::from_network(blank)
        .err()
        .expect("rejected");
    assert!(matches!(err, CortexError::InvalidConfig(_)), "{err}");
    assert!(err.to_string().contains("network_mut"), "{err}");

    let mut one_blank = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in one_blank.neurons.iter_mut().enumerate() {
        if i != 3 {
            neuron.weights[i] = 1.0;
        }
    }
    let err = NeuromodNetwork::from_network(one_blank)
        .err()
        .expect("rejected");
    assert!(err.to_string().contains("neuron 3"), "{err}");

    // Only `weights[..num_channels]` is ever integrated, so a neuron whose
    // sole non-zero weight sits past the channel range is just as silent.
    let mut out_of_range = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in out_of_range.neurons.iter_mut().enumerate() {
        if i == 3 {
            neuron.weights.push(1.0);
        } else {
            neuron.weights[i] = 1.0;
        }
    }
    let err = NeuromodNetwork::from_network(out_of_range)
        .err()
        .expect("rejected");
    assert!(err.to_string().contains("neuron 3"), "{err}");

    // neuromod integrates `|stimulus|`, so a negative-only neuron receives
    // non-positive current and never reaches threshold either.
    let mut negative = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in negative.neurons.iter_mut().enumerate() {
        neuron.weights[i] = if i == 3 { -1.0 } else { 1.0 };
    }
    let err = NeuromodNetwork::from_network(negative)
        .err()
        .expect("rejected");
    assert!(err.to_string().contains("neuron 3"), "{err}");

    // A non-finite in-range weight poisons the membrane; a short weight vector
    // leaves channels the engine silently skips. Both are rejected by name.
    let mut nan = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in nan.neurons.iter_mut().enumerate() {
        neuron.weights[i] = 1.0;
    }
    nan.neurons[3].weights[5] = f32::NAN;
    let err = NeuromodNetwork::from_network(nan).err().expect("rejected");
    assert!(err.to_string().contains("neuron 3"), "{err}");

    // The engine skips channels past a short weight vector, so a sparse
    // checkpoint is accepted when one present weight can drive the neuron...
    let mut short = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in short.neurons.iter_mut().enumerate() {
        neuron.weights[i] = 1.0;
    }
    short.neurons[3].weights.truncate(4);
    let mut short = NeuromodNetwork::from_network(short)
        .expect("sparse but drivable")
        .with_seed(0x5EED_0003);
    let mut one_hot = [0.0; 8];
    one_hot[3] = 1.0;
    assert!(neuromod_spike_counts(&mut short, &one_hot, 50)[3] > 0);

    // ...and rejected when none of the present weights is positive.
    let mut short_blank = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in short_blank.neurons.iter_mut().enumerate() {
        neuron.weights[i] = 1.0;
    }
    short_blank.neurons[3].weights = vec![0.0; 2];
    let err = NeuromodNetwork::from_network(short_blank)
        .err()
        .expect("rejected");
    assert!(err.to_string().contains("neuron 3"), "{err}");
    let mut empty = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for (i, neuron) in empty.neurons.iter_mut().enumerate() {
        neuron.weights[i] = 1.0;
    }
    empty.neurons[3].weights.clear();
    let err = NeuromodNetwork::from_network(empty)
        .err()
        .expect("rejected");
    assert!(err.to_string().contains("neuron 3"), "{err}");

    // A fully wired network round-trips through `from_network`.
    let wired = NeuromodNetwork::new(8, 0, 8).unwrap();
    let json = serde_json::to_string(wired.network()).unwrap();
    let restored: neuromod::SpikingNetwork = serde_json::from_str(&json).unwrap();
    assert!(NeuromodNetwork::from_network(restored).is_ok());
}

/// Learning state of every LIF neuron (weights, eligibility traces, threshold
/// and decay parameters) plus the stored modulators and R-STDP config — what
/// `step_frozen` must leave bit-for-bit intact. Runtime state (membranes,
/// spike timestamps, `global_step`) is allowed to advance and is excluded.
#[cfg(feature = "neuromod")]
fn neuromod_learning_state(net: &NeuromodNetwork) -> String {
    let network = net.network();
    let lif: Vec<_> = network
        .neurons
        .iter()
        .map(|n| {
            (
                n.weights.clone(),
                n.eligibility.clone(),
                n.threshold.to_bits(),
                n.base_threshold.to_bits(),
                n.decay_rate.to_bits(),
            )
        })
        .collect();
    serde_json::to_string(&(lif, network.modulators, network.stdp_config)).unwrap()
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_step_frozen_preserves_learning_state() {
    // Before neuromod 0.7 the adapter delegated `step_frozen` to `step`, so a
    // held-out `forward_frozen` kept advancing eligibility traces (#92).
    let mut net = NeuromodNetwork::new(8, 0, 8).unwrap().with_seed(7);
    // Warm up so traces are non-trivial, then snapshot.
    for _ in 0..5 {
        net.step(&[1.0; 8]).unwrap();
    }
    let before = neuromod_learning_state(&net);
    let step_before = net.network().global_step;

    let out = net.step_frozen(&[1.0; 8]).unwrap();
    assert!(!out.spikes.is_empty(), "frozen path still produces spikes");
    assert_eq!(
        net.network().global_step,
        step_before + 1,
        "runtime state advances"
    );
    assert_eq!(
        neuromod_learning_state(&net),
        before,
        "frozen step mutated learning state"
    );

    // Control: a learning-enabled step with the same input does move traces.
    net.step(&[1.0; 8]).unwrap();
    assert_ne!(neuromod_learning_state(&net), before);
}

/// `SpikingNetwork` is not `Clone`; its serde checkpoint is the supported copy.
#[cfg(feature = "neuromod")]
fn neuromod_clone(net: &NeuromodNetwork) -> NeuromodNetwork {
    let json = serde_json::to_string(net.network()).unwrap();
    let mut copy = NeuromodNetwork::from_network(serde_json::from_str(&json).unwrap()).unwrap();
    copy.modulators = net.modulators;
    copy.set_seed(net.seed());
    copy
}

#[cfg(feature = "neuromod")]
fn neuromod_weights(net: &NeuromodNetwork) -> Vec<Vec<f32>> {
    net.network()
        .neurons
        .iter()
        .map(|n| n.weights.clone())
        .collect()
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_seeded_rng_replays_bit_for_bit() {
    // Bernoulli input encoding draws from the thread-local RNG unless the
    // adapter routes a caller seed through `step_with_rng` (#92).
    fn run(net: &mut NeuromodNetwork, frozen_only: bool) -> (Vec<Vec<usize>>, Vec<i64>, String) {
        let mut spikes = Vec::new();
        for i in 0..40 {
            let stimulus = if i % 2 == 0 { [0.5; 8] } else { [0.3; 8] };
            spikes.push(if frozen_only || i % 5 == 0 {
                net.step_frozen(&stimulus).unwrap().spikes
            } else {
                net.step(&stimulus).unwrap().spikes
            });
        }
        (
            spikes,
            net.network().input_spike_times.clone(),
            serde_json::to_string(net.network()).unwrap(),
        )
    }

    let mut a = NeuromodNetwork::new(8, 0, 8)
        .unwrap()
        .with_seed(0xC0FF_EE01);
    let mut b = NeuromodNetwork::new(8, 0, 8)
        .unwrap()
        .with_seed(0xC0FF_EE01);
    assert!(a.capabilities().caller_rng);
    assert_eq!(a.seed(), Some(0xC0FF_EE01));
    let first = run(&mut a, false);
    assert_eq!(
        first,
        run(&mut b, false),
        "same seed, same inputs, different trajectory"
    );

    // Dropping the seed falls back to the thread-local RNG and says so.
    a.set_seed(None);
    assert!(!a.capabilities().caller_rng);
    assert_eq!(a.seed(), None);
    a.step(&[0.5; 8]).unwrap();

    // The seed can also be installed on a wrapped checkpoint after the fact.
    let mut c = NeuromodNetwork::new(8, 0, 8).unwrap();
    assert!(!c.capabilities().caller_rng);
    c.set_seed(Some(0xC0FF_EE01));
    assert!(c.capabilities().caller_rng);
    assert_eq!(run(&mut c, false), first);

    // `reset` rewinds the RNG to the seed. neuromod's `reset` keeps learned
    // weights, so a post-reset epoch replays the previous one only when the
    // learned state at both resets is the same: a frozen-only epoch...
    let mut frozen = NeuromodNetwork::new(8, 0, 8)
        .unwrap()
        .with_seed(0xC0FF_EE01);
    let frozen_first = run(&mut frozen, true);
    frozen.reset();
    assert_eq!(
        run(&mut frozen, true),
        frozen_first,
        "frozen-only epoch did not replay after reset"
    );

    // ...or a clone taken at the previous reset, even with learning on and
    // dopamine converting traces into weight changes.
    let mut learner = NeuromodNetwork::new(8, 0, 8)
        .unwrap()
        .with_seed(0xC0FF_EE01);
    learner.modulators.dopamine = 0.9;
    for (i, neuron) in learner.network_mut().neurons.iter_mut().enumerate() {
        // Off-diagonal room for STDP to move weight within the L1 budget.
        neuron.weights[i] = 1.0;
        neuron.weights[(i + 1) % 8] = 1.0;
    }
    let weights_at_reset = neuromod_weights(&learner);
    let mut twin = neuromod_clone(&learner);
    let learned = run(&mut learner, false);
    assert_ne!(
        neuromod_weights(&learner),
        weights_at_reset,
        "learning epoch must change weights for this case to mean anything"
    );
    twin.reset();
    assert_eq!(
        run(&mut twin, false),
        learned,
        "clone-at-reset replay diverged"
    );

    // The documented limit: once weights have moved, reset alone does not
    // rewind them, so the same stream from the learned state diverges.
    learner.reset();
    assert_eq!(neuromod_weights(&learner), neuromod_weights(&twin));
    assert_ne!(
        run(&mut learner, false),
        learned,
        "reset is not expected to rewind learned weights"
    );
}

/// Backend wrapper that counts spikes per channel while delegating to a real
/// backend, so tests can observe the spikes the router's own `forward` /
/// `forward_frozen` path draws instead of inferring them from `hidden`.
#[cfg(feature = "neuromod")]
struct RecordingBackend {
    inner: NeuromodNetwork,
    counts: Vec<usize>,
}

#[cfg(feature = "neuromod")]
impl SnnBackend for RecordingBackend {
    fn channels(&self) -> usize {
        self.inner.channels()
    }
    fn step(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        let out = self.inner.step(stimulus)?;
        for &idx in &out.spikes {
            self.counts[idx] += 1;
        }
        Ok(out)
    }
    fn step_frozen(&mut self, stimulus: &[f32]) -> Result<SnnStepOutput> {
        let out = self.inner.step_frozen(stimulus)?;
        for &idx in &out.spikes {
            self.counts[idx] += 1;
        }
        Ok(out)
    }
    fn reset(&mut self) {
        self.inner.reset();
        self.counts.fill(0);
    }
    fn capabilities(&self) -> SnnCapabilities {
        self.inner.capabilities()
    }
}

#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_drives_spiking_router_on_every_expert() {
    // End to end: a backend that never spikes leaves `SpikingMoeRouter` with
    // no spike signal at all, so routing degrades to the bare ANN gate (#91).
    // Since #93 the hidden gain is bounded and a silent tick falls back to the
    // dense selected mass, so `hidden` can no longer tell "every channel
    // fired" from "nothing fired". Record the spikes the router's own
    // `forward` path draws from the backend instead.
    let router = MoeRouter::load_with_mode("", 8, 8, crate::moe::RoutingMode::DenseSim).unwrap();
    let backend = RecordingBackend {
        inner: NeuromodNetwork::new(8, 0, 8)
            .unwrap()
            .with_seed(0x5EED_0004),
        counts: vec![0; 8],
    };
    let mut model =
        SpikingMoeRouter::new(router, backend, RateEncoder::default(), SpikeCountDecoder).unwrap();
    // A uniform gate with `top_k == num_experts` stimulates all eight expert
    // channels, so each one must fire at least once through `forward`.
    for _ in 0..200 {
        let out = model.forward(&[1.0; EMBEDDING_DIM]).unwrap();
        assert!(out.hidden.iter().all(|v| v.is_finite()));
    }
    let counts = &model.backend().counts;
    assert!(
        counts.iter().all(|&c| c > 0),
        "not every expert channel spiked: {counts:?}"
    );
}

/// RM-2364: a `NeuromodNetwork`-backed router rejects an overflowing gate with
/// a typed error before any tick, instead of `SnnBackend(String)` afterwards.
#[cfg(feature = "neuromod")]
#[test]
fn neuromod_router_rejects_overflowing_gate_pre_tick_with_typed_error() {
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut model = SpikingMoeRouter::new(
        router,
        NeuromodNetwork::new(8, 1, 8).unwrap(),
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap();
    let err = model.forward(&[f32::MAX; EMBEDDING_DIM]).unwrap_err();
    assert!(
        matches!(err, HybridError::SnnInvalidStimulus { .. }),
        "got {err:?}"
    );
    assert_eq!(model.backend().network().global_step, 0);
}

/// Control for the per-channel tests: a raw `SpikingNetwork::with_dimensions`
/// keeps every LIF weight at 0.0, integrates `|stimulus| * weight`, and its
/// L1 renormalization skips blank neurons — so under strong stimulus it can
/// never spike. Without this the "every channel fires" assertions above would
/// prove nothing about `new`'s identity wiring (#91).
#[cfg(feature = "neuromod")]
#[test]
fn neuromod_zero_init_base_network_stays_silent_under_strong_stimulus() {
    let mut raw = neuromod::SpikingNetwork::with_dimensions(8, 0, 8);
    for _ in 0..200 {
        let out = raw
            .step(&[1.0; 8], &neuromod::NeuroModulators::default())
            .unwrap();
        assert!(
            out.is_empty(),
            "zero-initialised weights must never spike, got {out:?}"
        );
    }

    // Same shape through the adapter's seeded identity wiring: every channel
    // fires under a fixed seed.
    let mut net = NeuromodNetwork::new(8, 0, 8)
        .unwrap()
        .with_seed(0x5EED_0005);
    let counts = neuromod_spike_counts(&mut net, &[1.0; 8], 200);
    assert!(
        counts.iter().all(|&c| c > 0),
        "wired channels must all spike: {counts:?}"
    );
}

/// The Izhikevich bank is auxiliary — its units are driven from mean LIF
/// membrane potential plus dopamine and do not report through `step`'s spike
/// list — but the drive must actually reach them. Under saturating dopamine
/// (`iz_drive` clamps at 15) every regular-spiking unit fires; a fired unit
/// is observable through `last_spike_time` leaving its -1 sentinel and its
/// recovery variable moving off `b * c`.
#[cfg(feature = "neuromod")]
#[test]
fn neuromod_adapter_izhikevich_bank_spikes_under_modulator_drive() {
    let mut net = NeuromodNetwork::new(8, 3, 8)
        .unwrap()
        .with_seed(0x5EED_0006);
    net.modulators.dopamine = 3.0;
    for _ in 0..200 {
        net.step(&[1.0; 8]).unwrap();
    }
    for (idx, iz) in net.network().iz_neurons.iter().enumerate() {
        assert!(
            iz.last_spike_time >= 0,
            "Izhikevich neuron {idx} never fired under saturating drive"
        );
        assert_ne!(
            iz.u,
            iz.b * iz.c,
            "Izhikevich neuron {idx} still sits at resting recovery"
        );
    }
}

/// Fixed-seed ANN → SNN → ANN smoke test: a fixed embedding produces gate
/// scores (ANN), the encoder maps them to stimuli, the seeded neuromod
/// backend spikes (SNN), and the decoded readout feeds the boosted softmax
/// and scaled hidden state (ANN). Two identically seeded models must replay
/// the whole output trajectory bit-for-bit, and the SNN leg must actually
/// have spiked.
#[cfg(feature = "neuromod")]
#[test]
fn ann_snn_ann_round_trip_replays_bit_for_bit_under_fixed_seed() {
    fn run() -> (Vec<crate::moe::MoeOutput>, Vec<usize>) {
        let router =
            MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
        let backend = RecordingBackend {
            inner: NeuromodNetwork::new(8, 0, 8)
                .unwrap()
                .with_seed(0xA55E_ED01),
            counts: vec![0; 8],
        };
        let mut model =
            SpikingMoeRouter::new(router, backend, RateEncoder::default(), SpikeCountDecoder)
                .unwrap();
        // Mixed-sign logits so spiking experts can visibly reorder the top-2.
        let embedding = embedding_with_gate_logits(&[2.0, -0.5, 0.25, 1.5, -1.0, 0.75, 0.0, -2.0]);
        let mut outputs = Vec::new();
        for _ in 0..30 {
            outputs.push(model.forward(&embedding).unwrap());
        }
        (outputs, model.backend().counts.clone())
    }

    let (first, counts) = run();
    let (second, replay_counts) = run();
    assert_eq!(counts, replay_counts);
    assert!(
        counts.iter().sum::<usize>() > 0,
        "the SNN leg never spiked: {counts:?}"
    );

    // Silent control: spikes produced is not spikes influential. A backend
    // that never reports a spike must produce a different trajectory, or the
    // decoded readout is not reaching `MoeOutput`.
    let router = MoeRouter::load_with_mode("", 8, 2, crate::moe::RoutingMode::DenseSim).unwrap();
    let mut silent = SpikingMoeRouter::new(
        router,
        ScriptedBackend {
            channels: 8,
            spikes: Vec::new(),
        },
        RateEncoder::default(),
        SpikeCountDecoder,
    )
    .unwrap();
    let embedding = embedding_with_gate_logits(&[2.0, -0.5, 0.25, 1.5, -1.0, 0.75, 0.0, -2.0]);
    let differing_ticks = first
        .iter()
        .zip((0..30).map(|_| silent.forward(&embedding).unwrap()))
        .filter(|(spiked, quiet)| {
            spiked.selected_experts != quiet.selected_experts
                || spiked.expert_weights != quiet.expert_weights
                || spiked.hidden != quiet.hidden
        })
        .count();
    assert!(
        differing_ticks > 0,
        "spikes never influenced the output; the decoded readout is not reaching MoeOutput"
    );

    assert_eq!(first.len(), second.len());
    for (tick, (a, b)) in first.iter().zip(&second).enumerate() {
        assert_eq!(a.selected_experts, b.selected_experts, "tick {tick}");
        assert_eq!(a.expert_weights, b.expert_weights, "tick {tick}");
        assert_eq!(a.hidden, b.hidden, "tick {tick}");
        assert_eq!(a.hidden.len(), EMBEDDING_DIM, "tick {tick}");
        assert!(
            a.hidden.iter().all(|v| v.is_finite()),
            "tick {tick}: non-finite hidden egress"
        );
    }
}