vj-sim 0.3.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
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
//! Task 9 — the accessor ABI implementation (`sv_get`/`sv_set` `_scalar`/`_wide`)
//! and `SignalAccess` (ledger ST-013, ST-020, ST-021, ST-022, ST-023).
//!
//! Realizes the plan header's "what `SimHandle` points to" design decision:
//! `SimHandle.0` *is* a `Box<InstanceHandle>::into_raw`-leaked pointer for
//! this wave (`InstanceHandle::into_sim_handle`/`from_sim_handle` below).
//! `sv_get_scalar`/`sv_set_scalar` resolve `absolute_word = handle.base
//! .inline_base + layout.slots[slot.0].offset.word_offset` and read/write
//! `arena.inline[absolute_word]` directly; `sv_get_wide`/`sv_set_wide` do the
//! wide-plane analogue against `handle.base.wide_base`.
//!
//! `sv_set_scalar`/`sv_set_wide` route through `write::commit_write_at` — the
//! exact primitive `StateEngine::commit_write` also calls (see
//! `state::write`'s module doc comment for the Task 9 retrofit that makes
//! this reachable with no `&mut StateEngine` in scope) — so VC detection is
//! never bypassed by the ABI entry point and there is exactly one write path,
//! never a second, ad hoc one.
//!
//! Task 10 — accessor discipline, the reference API as real non-JIT impl,
//! single-`SimHandle` reachability (ledger ST-026, ST-027, ST-029, ST-152).
//!
//! **ST-029:** every fn in this module (`sv_get_scalar`/`sv_set_scalar`/
//! `sv_get_wide`/`sv_set_wide` above, `SignalAccess::read`/`write`/`subscribe`
//! below) is a plain Rust/`extern "C"` function, callable with nothing more
//! than an `InstanceHandle`/`StateCellId` in hand — no `ProcessFn`/
//! `CompiledKernel` invocation is required to reach any of them. This is the
//! structural property that makes them usable by `$display`/VPI/the debugger
//! once those crates exist: this crate's reference read/write API *is* the
//! actual implementation those non-JIT consumers call into, never a second,
//! parallel one only the compiled kernel path can reach.
//!
//! **ST-152:** the whole of STATE's owned state — the arena, the template
//! registry, the `cells` table, the VC-tracking state (and, once Tasks 11/16
//! land, the VC dispatch table and the undo log) — lives inside one
//! `StateEngine` (`state::instance`), reached from the ABI side exclusively
//! through the `InstanceHandle` a `SimHandle` points at (which itself, per
//! this plan's header decision, is reachable only via `SimHandle`); no
//! function in this crate accepts a second, independent "give me the arena"
//! pointer parameter. See `StateEngine`'s own doc comment (`state::instance`)
//! for the field-level half of this guarantee.

use std::ffi::c_void;

use vj_abi::{SimHandle, SlotId, WideView};

use super::instance::{InstanceHandle, StateEngine};
use super::write::{SlotLocation, commit_write_at, read_slot, resolve_mem_row, write_slot};
use super::{
    EdgeKind, FourStateValue, ListenerRole, SignalAccess, SlotClass, StateCellId, ValueChangeSink,
};

impl InstanceHandle {
    /// `Box::into_raw` leak — the handle's lifetime is the simulation run's,
    /// matching how `sim_init`/`sim_final` bracket it per ARCHITECTURE §5.
    pub fn into_sim_handle(self: Box<Self>) -> SimHandle {
        SimHandle(Box::into_raw(self) as *mut c_void)
    }

    /// # Safety
    /// `h` must be a `SimHandle` previously produced by [`Self::into_sim_handle`]
    /// on an `InstanceHandle` that has not since been passed to a reclaiming
    /// function (no such function exists this wave — every handle this crate
    /// mints lives for the simulation run's duration, per ARCHITECTURE §5, so
    /// this precondition is trivially satisfied by every caller in this
    /// wave), and no other thread is concurrently reclaiming/freeing it.
    pub unsafe fn from_sim_handle<'a>(h: SimHandle) -> &'a InstanceHandle {
        // SAFETY: forwarded to this function's own `# Safety` section above.
        unsafe { &*(h.0 as *const InstanceHandle) }
    }
}

/// Resolves `slot` against `handle`'s template-relative `StateLayout` and
/// this instance's own base, producing the already-*absolute* `SlotLocation`
/// every accessor fn below reads/writes through — the one place this
/// resolution happens, shared by every `sv_get_*`/`sv_set_*` fn (never
/// re-derived ad hoc at each call site).
pub(super) fn slot_location_for(handle: &InstanceHandle, slot: SlotId) -> SlotLocation {
    let offset = handle.layout().slots[slot.0 as usize].offset;
    let word_offset = match offset.class {
        SlotClass::Inline => handle.base.inline_base + offset.word_offset,
        SlotClass::Wide | SlotClass::Memory => handle.base.wide_base + offset.word_offset,
        // Review fix (Task 14 r2, blocking finding 2): a real elaborated
        // signal's `SlotOffset` (from `handle.layout()`) is never
        // `ForceWide` — see `SlotClass::ForceWide`'s own doc comment.
        SlotClass::ForceWide => unreachable!(
            "slot_location_for: no SlotDescriptor/SlotOffset the layout builder \
             produces is ever SlotClass::ForceWide"
        ),
    };
    SlotLocation {
        class: offset.class,
        word_offset,
        bit_width: offset.bit_width,
        elem_word_count: offset.elem_word_count,
        row_stride_words: offset.row_stride_words,
        num_rows: offset.num_rows,
    }
}

/// `slot` of `handle`: its cell, bit width, whether it is wide, and current
/// value (`force`/`release`, `state::force`).
///
/// For a windowed alias (a ref port bound to a select) the state is the
/// *target's*: its cell, width and value, plus the window's offset in it (a
/// force of the alias is a force of those bits of the target). `Err` when
/// the target is an element of a memory, which `force` does not reach.
pub(crate) fn slot_state(
    handle: SimHandle,
    slot: SlotId,
) -> Result<(StateCellId, u32, bool, FourStateValue, u32), &'static str> {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let idx = slot.0 as usize;
    let window = if idx >= this.own_slot_count() {
        this.foreign_window(idx)
    } else {
        None
    };
    if let Some(w) = &window
        && w.row.is_some()
    {
        // `real_sv_rt_force`/`release` route these to the row path first.
        return Err("force/release of a ref port bound to an element of an unpacked array");
    }
    let (handle, slot) = resolve_foreign_slot(handle, slot);
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    let cell = handle.cell_for_slot(slot.0 as usize);
    let value = super::write::read_slot(handle.arena(), loc);
    Ok((
        cell,
        loc.bit_width,
        loc.class == SlotClass::Wide,
        value,
        window.map_or(0, |w| w.lo),
    ))
}

/// The row (and the bit offset in it) of the unpacked-array element a foreign
/// `slot` of `handle` -- a ref port bound to `arr[i]` (LRM 23.3.3.2) --
/// stands for; `None` for any other slot. A `force`/`release` of such a slot
/// is one of that row ([`row_state`] follows the slot to its owner).
pub(crate) fn slot_row_alias(handle: SimHandle, slot: SlotId) -> Option<(u64, u32)> {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let idx = slot.0 as usize;
    if idx < this.own_slot_count() {
        return None;
    }
    let w = this.foreign_window(idx)?;
    w.row.map(|row| (row, w.lo))
}

/// The state a `force`/`release` of row `row` of memory `slot` needs: the
/// memory's cell, the row's word offset (its key in the force table), its
/// bit width and its value now. A foreign slot is followed to its owner.
pub(crate) fn row_state(
    handle: SimHandle,
    slot: SlotId,
    row: u64,
) -> (StateCellId, u32, u32, FourStateValue) {
    let (handle, slot) = resolve_foreign_slot(handle, slot);
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = resolve_mem_row(slot_location_for(handle, slot), row);
    let cell = handle.cell_for_slot(slot.0 as usize);
    let value = super::write::read_slot(handle.arena(), loc);
    (cell, loc.word_offset, loc.bit_width, value)
}

/// Copies `src`'s current value into `dst` of the same instance without
/// reporting a value change: the sampled value functions' hidden P/S cells
/// (`crate::sva::sampled`) are history, not signals -- no listener waits on
/// them, no waveform shows them, and their updates must not wake a process.
/// `src` may be a foreign slot (a hierarchically connected signal); `dst`
/// is always one of the instance's own cells, of the same class and width
/// as `src` by construction (`hidden_slots` clones the source's shape).
pub fn copy_slot_quiet(handle: SimHandle, src: SlotId, dst: SlotId) {
    // SAFETY: see `sv_get_scalar`.
    let dst_h = unsafe { InstanceHandle::from_sim_handle(handle) };
    let idx = src.0 as usize;
    if idx >= dst_h.own_slot_count()
        && let Some(window) = dst_h.foreign_window(idx)
    {
        let value = read_window(dst_h, idx, window);
        write_slot(dst_h.arena(), slot_location_for(dst_h, dst), &value);
        return;
    }
    let (src_handle, src) = resolve_foreign_slot(handle, src);
    let src_h = unsafe { InstanceHandle::from_sim_handle(src_handle) };
    let value = read_slot(src_h.arena(), slot_location_for(src_h, src));
    write_slot(dst_h.arena(), slot_location_for(dst_h, dst), &value);
}

/// Runs `f` on the force table of `handle`'s engine (`state::force`).
pub(crate) fn with_force_table<R>(
    handle: SimHandle,
    f: impl FnOnce(&mut super::force::ForceTable) -> R,
) -> R {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    f(&mut handle.vc().force.borrow_mut())
}

/// Narrow (`SlotClass::Inline`) scalar read (ST-020): `vj_abi::accessor`'s
/// FIXED `val` low 64 bits / `unk` high 64 bits layout, read straight out of
/// the arena's inline plane at `handle`'s own base-applied word offset.
pub extern "C" fn sv_get_scalar(handle: SimHandle, slot: SlotId) -> u128 {
    // SAFETY: see `InstanceHandle::from_sim_handle`'s own `# Safety` section
    // — this fn's only documented callers (compiled-kernel code, or this
    // crate's own tests) pass back a `SimHandle` this crate itself minted
    // via `into_sim_handle`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    handle.arena().inline()[loc.word_offset as usize]
}

/// Narrow scalar write (ST-021): writes `value` and reports whether it
/// changed by routing through [`commit_write_at`] — the same VC-detection
/// primitive `StateEngine::commit_write` uses — never a second, parallel
/// write path. The `extern "C"` signature itself returns `()` (the frozen
/// ABI type alias, `vj_abi::accessor::SvSetScalarFn`); the change report
/// lands in the same speculative VC buffer every other `commit_write_at`
/// caller's changes do, observable via `write::last_vc_record_for` in tests.
pub extern "C" fn sv_set_scalar(handle: SimHandle, slot: SlotId, value: u128) {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    let cell = handle.cell_for_slot(slot.0 as usize);
    let result = commit_write_at(
        handle.arena(),
        handle.vc(),
        loc,
        cell,
        FourStateValue::Narrow(value),
        &mut (),
    );
    handle.vc().views.note_change(cell, None, &result);
}

/// Wide (`SlotClass::Wide`) non-memory read (ST-022): a non-owning
/// [`WideView`] over `handle`'s own `aval`/`bval` plane words at `slot`'s
/// base-applied offset — `word_count` words starting at that offset in each
/// plane, per `vj_abi::accessor`'s documented shape.
pub extern "C" fn sv_get_wide(handle: SimHandle, slot: SlotId) -> WideView {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    let start = loc.word_offset as usize;
    // Review fix (Task 9 r3, blocking finding 1): seal the arena's wide
    // planes *before* handing out pointers into their live storage below.
    // The returned `WideView`'s `aval`/`bval` pointers are retained by the
    // caller past this call's return (a non-owning *view*, per `WideView`'s
    // own doc comment, deliberately aliasing the arena's own live storage,
    // not a copy) -- unlike `sv_get_scalar`/`sv_set_scalar`/`sv_set_wide`,
    // none of which ever caches a pointer across calls. Without this seal, a
    // later `StateEngine::allocate_instance` growing `wide_aval`/`wide_bval`
    // via `Arena::alloc_wide_words` (a plain growable `Vec<u64>`, not
    // individually boxed per allocation the way `TemplateRegistry` boxes
    // each `StateLayout`) could reallocate their backing buffer and dangle
    // this exact pointer pair -- a genuine use-after-free. `seal_wide_plane`
    // makes every later nonzero-word `alloc_wide_words` call panic instead
    // (see `Arena::wide_sealed`'s doc comment), which is what actually makes
    // the *reallocation* half of the SAFETY argument below true.
    handle.arena().seal_wide_plane();
    // Review fix (Task 9 r4, blocking finding): this used to read
    // `handle.arena().wide_aval_mut()[start..].as_mut_ptr()` -- forming a
    // fresh `&mut [u64]` reborrow of the *whole* wide plane on every call.
    // Under Stacked Borrows that reborrow is retagged from scratch each
    // time, which invalidates any pointer a *previous* call like this one
    // returned the instant *any* later `wide_aval_mut`/`wide_bval_mut` call
    // happens anywhere against this `Arena` -- the very next `sv_get_wide`
    // for a different instance/slot (no write required), or the next
    // wide-class `commit_write_at` write via `write::write_slot`. Confirmed
    // by an isolated Miri repro of exactly this pattern (both a later
    // unrelated wide-class write and a second, read-only-shaped
    // `sv_get_wide` call with zero intervening writes reproduce Miri's
    // "tag does not exist in the borrow stack" error against the first
    // pointer). `seal_wide_plane` above only prevents the Vec from
    // *reallocating*; it does nothing about this separate, far-more-easily
    // triggered reborrow-invalidation hazard.
    //
    // SAFETY: `start..start+elem_word_count` was reserved for this
    // instance's slot by `allocate_instance`'s bulk wide-plane allocation
    // and is not touched by any other instance's own bases (Task 7's
    // ST-067/ST-136 disjoint-base guarantee), so the pointer arithmetic
    // below stays within the plane's allocated length. `Arena::wide_aval_ptr`/
    // `wide_bval_ptr` never form a `&mut [u64]`/`&[u64]` over the plane's
    // buffer (see their own doc comments for the full argument) -- the
    // pointers they return keep the buffer's original allocation tag for
    // the Arena's whole life once sealed, so they stay valid to dereference
    // no matter how many later `wide_aval_mut`/`wide_bval_mut`-based reads
    // or writes (from `write::write_slot`, `read_slot`, `rollback::restore`,
    // or another `sv_get_wide` call) happen against this same plane
    // afterward: those all reborrow a *child* tag on top of the buffer's
    // root tag, never invalidating the root tag itself (Miri-verified; see
    // `sv_get_wide_view_stays_valid_across_a_later_sv_get_wide_and_a_later_
    // wide_class_write` below, the Miri-reachable regression test for this
    // exact fix). `seal_wide_plane` just above is what keeps the buffer's
    // *address* (not merely its tag) stable for the rest of this Arena's
    // life, which this argument also depends on.
    let aval = unsafe { handle.arena().wide_aval_ptr().add(start) };
    let bval = unsafe { handle.arena().wide_bval_ptr().add(start) };
    WideView {
        aval,
        bval,
        word_count: loc.elem_word_count,
    }
}

/// Wide non-memory write (ST-023): copies `value`'s `elem_word_count` words
/// out of the caller-supplied [`WideView`] into an owned [`FourStateValue::Wide`]
/// and routes through [`commit_write_at`] — the wide-tier sibling of
/// `sv_set_scalar`, through the identical shared primitive.
pub extern "C" fn sv_set_wide(handle: SimHandle, slot: SlotId, value: WideView) {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    let cell = handle.cell_for_slot(slot.0 as usize);
    let n = loc.elem_word_count as usize;
    // SAFETY: per the accessor-ABI contract (`vj_abi::accessor`), a
    // legitimate `SvSetWideFn` caller supplies a `WideView` whose `aval`/
    // `bval` point at (at least) `word_count` contiguous, initialized `u64`s
    // it owns for at least the duration of this call; this fn's own callers
    // (this crate's tests) uphold that by construction (`n` here comes from
    // `handle`'s own slot shape, never from `value.word_count`, so a
    // mismatched `value` would read past/short of its own buffer -- the
    // caller's obligation, not something this fn can check from a raw
    // pointer pair alone).
    let aval: Vec<u64> = unsafe { std::slice::from_raw_parts(value.aval, n) }.to_vec();
    let bval: Vec<u64> = unsafe { std::slice::from_raw_parts(value.bval, n) }.to_vec();
    let result = commit_write_at(
        handle.arena(),
        handle.vc(),
        loc,
        cell,
        FourStateValue::Wide { aval, bval },
        &mut (),
    );
    handle.vc().views.note_change(cell, None, &result);
}

/// Task 12 (ST-024, ST-025, ST-114): memory-word accessors. `slot` addresses
/// the whole `SlotClass::Memory` array the same way `sv_get_wide`/
/// `sv_set_wide` address a whole `SlotClass::Wide` signal
/// ([`slot_location_for`] is shared, unchanged); the one extra step is
/// [`resolve_mem_row`], applied to that base location with the caller's
/// *runtime* `row_index`, per state.md §3's pinned `word_offset' =
/// word_offset + row_stride_words * row_index` formula. Both fns panic
/// (never silently read/write past the array) if `row_index` is out of
/// bounds or `slot` does not resolve to a `SlotClass::Memory` location — see
/// [`resolve_mem_row`]'s own doc comment for the exact panic conditions.
///
/// This is the shape a future `sv_rt_readmemh` (RUNTIME's own, not built this
/// wave) will call once per parsed word: `sv_set_mem_word(handle, slot,
/// row_index, parsed_word_view)` in a loop, never touching `Arena` directly
/// (ST-114's literal acceptance text).
///
/// **ST-024:** the `sv_get_wide`-shaped read counterpart, through the same
/// `resolve_mem_row` step and the same live-arena-aliasing `WideView` shape
/// `sv_get_wide` returns — see that function's own doc comment for the full
/// seal/pointer-stability argument, which applies identically here (the same
/// `handle.arena().seal_wide_plane()` call, the same wide planes, just at a
/// row-resolved offset instead of the slot's own base offset).
pub extern "C" fn sv_get_mem_word(handle: SimHandle, slot: SlotId, row_index: u64) -> WideView {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    let resolved = resolve_mem_row(loc, row_index);
    let start = resolved.word_offset as usize;
    // See `sv_get_wide`'s own doc comment for why sealing before handing out
    // pointers into the live wide-plane storage is required here too.
    handle.arena().seal_wide_plane();
    // SAFETY: `start..start+elem_word_count` was reserved for this row within
    // this instance's memory slot by `allocate_instance`'s bulk wide-plane
    // allocation (the whole memory's `num_rows * row_stride_words` words are
    // disjoint from every other instance's own base, and `resolve_mem_row`
    // asserted `row_index < num_rows` above, so this row's own sub-range
    // stays within that allocation) — the identical pointer-stability
    // argument `sv_get_wide` documents applies unchanged, since both read the
    // same sealed wide planes via the same non-`&mut`-forming raw-pointer
    // accessors.
    let aval = unsafe { handle.arena().wide_aval_ptr().add(start) };
    let bval = unsafe { handle.arena().wide_bval_ptr().add(start) };
    WideView {
        aval,
        bval,
        word_count: resolved.elem_word_count,
    }
}

/// **ST-025:** the `sv_set_wide`-shaped write counterpart, through the same
/// `resolve_mem_row` step and the same `commit_write_at` primitive every
/// other write in this crate goes through — never a second, ad hoc write
/// path. `cell` is this slot's one whole-memory `StateCellId` (the same
/// `handle.cell_for_slot(slot.0)` `sv_set_wide` uses; a `SlotClass::Memory`
/// slot mints exactly one cell for the whole array, not one per row — see
/// `StateEngine::allocate_instance`'s own per-slot loop), so a VC record from
/// this fn reports "this memory changed", identifying the row via `at`/the
/// caller's own `row_index`, exactly as `sv_set_wide` already does for a
/// whole non-memory wide signal.
pub extern "C" fn sv_set_mem_word(
    handle: SimHandle,
    slot: SlotId,
    row_index: u64,
    value: WideView,
) {
    let _ = set_mem_word_reporting_change(handle, slot, row_index, value);
}

/// [`sv_set_mem_word`]'s body, returning the memory's whole-array cell and
/// whether the row's stored value actually changed -- what a
/// scheduler-aware caller (`sched::kernel_adapter::real_sv_set_mem_word`)
/// needs to wake processes sensitive to the memory.
pub fn set_mem_word_reporting_change(
    handle: SimHandle,
    slot: SlotId,
    row_index: u64,
    value: WideView,
) -> (StateCellId, bool) {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    let loc = slot_location_for(handle, slot);
    let resolved = resolve_mem_row(loc, row_index);
    let cell = handle.cell_for_slot(slot.0 as usize);
    let n = resolved.elem_word_count as usize;
    // SAFETY: per the accessor-ABI contract (`vj_abi::accessor`), a
    // legitimate `SvSetMemWordFn` caller supplies a `WideView` whose `aval`/
    // `bval` point at (at least) one row's own `elem_word_count` contiguous,
    // initialized `u64`s it owns for at least the duration of this call --
    // the same obligation `sv_set_wide` documents, `n` here likewise coming
    // from `resolved`'s own row shape, never from `value.word_count`.
    let aval: Vec<u64> = unsafe { std::slice::from_raw_parts(value.aval, n) }.to_vec();
    let bval: Vec<u64> = unsafe { std::slice::from_raw_parts(value.bval, n) }.to_vec();
    let result = commit_write_at(
        handle.arena(),
        handle.vc(),
        resolved,
        cell,
        FourStateValue::Wide { aval, bval },
        &mut (),
    );
    handle
        .vc()
        .views
        .note_change(cell, Some(row_index), &result);
    (cell, result.changed)
}

/// Task F3 (`docs/superpowers/plans/2026-09-27-wave-A2-slice-finish.md`,
/// CG-125/NL-035): resolves `slot` (the same `SlotId` `sv_get_scalar`/
/// `sv_set_scalar` already address by) to the absolute [`StateCellId`] a
/// synthetic inter-instance port-connection process needs for
/// [`crate::sched::SchedulerOps::commit_blocking_write`]/
/// [`crate::sched::StaticSensitivity`] (registering a wake on the source
/// side, writing through the canonical commit path on the destination side).
/// Every other `StateCellId` in this crate is minted directly by
/// `StateEngine::alloc_cell`/`allocate_instance`'s own per-slot loop
/// (`InstanceHandle::cell_for_slot`, `pub(crate)`); this is the one place a
/// caller *outside* this crate (`vj`'s hierarchy pipeline, which
/// holds a `SimHandle`+`SlotId` pair from its own signal-slot bookkeeping but
/// never runs `allocate_instance`'s loop itself) needs to look one back up.
/// Gives `handle`'s instance its foreign slots: slot `own + k` (where `own`
/// is the instance's own slot count, returned) names `targets[k]`, another
/// instance's own slot. A target that is itself a foreign slot is followed
/// to its owner.
pub fn set_foreign_slots(handle: SimHandle, targets: &[(SimHandle, SlotId)]) -> u32 {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let resolved = targets
        .iter()
        .map(|&(h, slot)| resolve_target(h, slot))
        .collect::<Vec<_>>();
    let views = vec![None; resolved.len()];
    this.set_foreign(resolved, views);
    this.own_slot_count() as u32
}

/// The own slot a foreign-slot target names (a target that is itself a
/// foreign slot is followed to its owner). A target that is a *windowed*
/// foreign slot cannot be followed -- the caller composes the windows first.
fn resolve_target(h: SimHandle, slot: SlotId) -> (*const InstanceHandle, usize) {
    // SAFETY: see `sv_get_scalar`.
    let target = unsafe { InstanceHandle::from_sim_handle(h) };
    let idx = slot.0 as usize;
    assert!(
        idx < target.own_slot_count() || target.foreign_window(idx).is_none(),
        "a foreign slot cannot name a windowed foreign slot; compose the windows first"
    );
    let (owner, idx) = target.resolve_slot(idx);
    (owner as *const InstanceHandle, idx)
}

/// [`set_foreign_slots`] where a target may be a window of its slot -- a ref
/// port bound to a select (IEEE 1800-2023 23.3.3.2, 13.5.2): such a foreign
/// slot is a *view* of the target (`state::alias`) with its own cell, so a
/// wait on it wakes only when the window changes.
pub fn set_foreign_slots_windowed(
    engine: &mut StateEngine,
    handle: SimHandle,
    targets: &[(SimHandle, SlotId, Option<super::AliasWindow>)],
) -> u32 {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let mut resolved = Vec::with_capacity(targets.len());
    let mut views = Vec::with_capacity(targets.len());
    for &(h, slot, window) in targets {
        let (owner, idx) = resolve_target(h, slot);
        views.push(window.map(|w| {
            // SAFETY: `owner` is a live handle (`resolve_target`).
            let root = unsafe { &*owner }.cell_for_slot(idx);
            (w, engine.alloc_view_cell(root, w))
        }));
        resolved.push((owner, idx));
    }
    this.set_foreign(resolved, views);
    this.own_slot_count() as u32
}

/// `(handle, slot)` itself for one of the instance's own slots; for a
/// foreign slot (see [`set_foreign_slots`]), the instance and slot it
/// names. Every production entry point that reads or writes a slot's
/// storage for a compiled kernel resolves through this first
/// (`real_sv_get_*`, `real_sv_set_mem_word`, force); a cell lookup needs no
/// resolving (a foreign slot's cell is in the instance's own cell table).
#[inline]
pub fn resolve_foreign_slot(handle: SimHandle, slot: SlotId) -> (SimHandle, SlotId) {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let (owner, idx) = this.resolve_slot(slot.0 as usize);
    (
        SimHandle(owner as *const InstanceHandle as *mut c_void),
        SlotId(idx as u32),
    )
}

/// `SimHandle sv_rt_slot_owner(SimHandle, SlotId)`: the instance whose storage
/// `slot` of `handle` is -- `handle` itself for one of its own slots, the
/// instance a foreign slot names otherwise (see [`set_foreign_slots`]). A
/// hierarchical call into another instance (`u1.f()`, LRM 23.6) passes this
/// as the callee's instance handle, so the callee's memories and block
/// events are `u1`'s own.
#[cfg_attr(feature = "aot-exports", unsafe(export_name = "sv_rt_slot_owner"))]
pub extern "C" fn real_sv_rt_slot_owner(handle: SimHandle, slot: SlotId) -> SimHandle {
    resolve_foreign_slot(handle, slot).0
}

/// The production binding of the `sv_get_scalar` ABI symbol:
/// [`sv_get_scalar`] after [`resolve_foreign_slot`].
#[cfg_attr(feature = "aot-exports", unsafe(export_name = "sv_get_scalar"))]
pub extern "C" fn real_sv_get_scalar(handle: SimHandle, slot: SlotId) -> u128 {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let idx = slot.0 as usize;
    if idx >= this.own_slot_count()
        && let Some(window) = this.foreign_window(idx)
    {
        return match read_window(this, idx, window) {
            FourStateValue::Narrow(v) => v,
            FourStateValue::Wide { .. } => {
                unreachable!("a scalar read of a windowed alias wider than 64 bits")
            }
        };
    }
    let (handle, slot) = resolve_foreign_slot(handle, slot);
    sv_get_scalar(handle, slot)
}

/// The production binding of `sv_get_wide` (see [`real_sv_get_scalar`]).
#[cfg_attr(feature = "aot-exports", unsafe(export_name = "sv_get_wide"))]
pub extern "C" fn real_sv_get_wide(handle: SimHandle, slot: SlotId) -> WideView {
    // SAFETY: see `sv_get_scalar`.
    let this = unsafe { InstanceHandle::from_sim_handle(handle) };
    let idx = slot.0 as usize;
    if idx >= this.own_slot_count()
        && let Some(window) = this.foreign_window(idx)
    {
        return scratch_wide(this, read_window(this, idx, window));
    }
    let (handle, slot) = resolve_foreign_slot(handle, slot);
    sv_get_wide(handle, slot)
}

/// The current value of the window foreign slot `idx` of `this` stands for.
#[cold]
#[inline(never)]
fn read_window(this: &InstanceHandle, idx: usize, window: super::AliasWindow) -> FourStateValue {
    let (owner, slot) = this.resolve_slot(idx);
    let mut loc = slot_location_for(owner, SlotId(slot as u32));
    if let Some(row) = window.row {
        loc = resolve_mem_row(loc, row);
    }
    super::alias::window_value(&read_slot(owner.arena(), loc), window)
}

fn scratch_wide(this: &InstanceHandle, value: FourStateValue) -> WideView {
    let FourStateValue::Wide { aval, bval } = value else {
        unreachable!("a wide read of a windowed alias no wider than 64 bits")
    };
    let (aval, bval, word_count) = this.scratch_wide(aval, bval);
    WideView {
        aval,
        bval,
        word_count,
    }
}

/// The production binding of `sv_get_mem_word` (see [`real_sv_get_scalar`]).
#[cfg_attr(feature = "aot-exports", unsafe(export_name = "sv_get_mem_word"))]
pub extern "C" fn real_sv_get_mem_word(
    handle: SimHandle,
    slot: SlotId,
    row_index: u64,
) -> WideView {
    let (handle, slot) = resolve_foreign_slot(handle, slot);
    sv_get_mem_word(handle, slot, row_index)
}

/// The number of slots of `handle`'s instance's own layout -- the first
/// foreign slot's number.
pub fn own_slot_count(handle: SimHandle) -> u32 {
    // SAFETY: see `sv_get_scalar`.
    unsafe { InstanceHandle::from_sim_handle(handle) }.own_slot_count() as u32
}

pub fn cell_for_slot(handle: SimHandle, slot: SlotId) -> StateCellId {
    // SAFETY: see `sv_get_scalar`.
    let handle = unsafe { InstanceHandle::from_sim_handle(handle) };
    handle.cell_for_slot(slot.0 as usize)
}

/// Task 10 (ST-026): the concrete artifact ARCHITECTURE §7 item 1's
/// "accessor-ABI as the contract with `alwaysinline` wrappers" resolves to on
/// STATE's side — a thin, `#[inline(always)]` Rust-level wrapper around the
/// `extern "C"` fn above, a pure pass-through never a second, divergent
/// implementation. CODEGEN is expected to call *these* (or emit its own
/// `alwaysinline`-attributed LLVM declaration of the `extern "C"` symbol
/// directly — either way, STATE's obligation is only that an inlinable entry
/// point exists and is documented as the one sanctioned call shape).
#[inline(always)]
pub fn sv_get_scalar_inline(handle: SimHandle, slot: SlotId) -> u128 {
    sv_get_scalar(handle, slot)
}

/// The `sv_set_scalar` twin of [`sv_get_scalar_inline`] (ST-026).
#[inline(always)]
pub fn sv_set_scalar_inline(handle: SimHandle, slot: SlotId, value: u128) {
    sv_set_scalar(handle, slot, value)
}

/// The `sv_get_wide` twin of [`sv_get_scalar_inline`] (ST-026).
#[inline(always)]
pub fn sv_get_wide_inline(handle: SimHandle, slot: SlotId) -> WideView {
    sv_get_wide(handle, slot)
}

/// The `sv_set_wide` twin of [`sv_get_scalar_inline`] (ST-026).
#[inline(always)]
pub fn sv_set_wide_inline(handle: SimHandle, slot: SlotId, value: WideView) {
    sv_set_wide(handle, slot, value)
}

/// The `sv_get_mem_word` twin of [`sv_get_scalar_inline`] (ST-026, Task 12).
#[inline(always)]
pub fn sv_get_mem_word_inline(handle: SimHandle, slot: SlotId, row_index: u64) -> WideView {
    sv_get_mem_word(handle, slot, row_index)
}

/// The `sv_set_mem_word` twin of [`sv_get_scalar_inline`] (ST-026, Task 12).
#[inline(always)]
pub fn sv_set_mem_word_inline(handle: SimHandle, slot: SlotId, row_index: u64, value: WideView) {
    sv_set_mem_word(handle, slot, row_index, value)
}

/// ST-013: fills in the Task-0 contract stub — `read`/`write` operate on the
/// *absolute*, already-instance-resolved [`StateCellId`] scheduler-side code
/// uses (distinct from the ABI's template-relative `SlotId` above), by
/// delegating to the exact same [`read_slot`]/[`commit_write_at`] primitives
/// the accessor fns use, so both paths are provably the same storage.
impl StateEngine {
    /// Writes `row` (a memory's, when `Some`) of the real cell `cell`,
    /// recording the effect on its window aliases.
    fn commit_root(
        &mut self,
        cell: StateCellId,
        row: Option<u64>,
        value: FourStateValue,
    ) -> super::write::ChangeResult {
        match row {
            None => self.commit_write(cell, value, &mut ()),
            Some(row) => {
                let loc = resolve_mem_row(self.cells[cell.0 as usize], row);
                let result = commit_write_at(&self.arena, &self.vc, loc, cell, value, &mut ());
                self.vc.views.note_change(cell, Some(row), &result);
                result
            }
        }
    }

    /// The root's own storage of `info` (its row of a memory).
    fn root_location(&self, info: &super::alias::ViewInfo) -> SlotLocation {
        let loc = self.cells[info.root.0 as usize];
        match info.window.row {
            Some(row) => resolve_mem_row(loc, row),
            None => loc,
        }
    }

    /// A write through the view cell `view`: splices into the root, commits
    /// the root, and returns whether the *window* changed.
    fn write_view(
        &mut self,
        view: StateCellId,
        info: super::alias::ViewInfo,
        value: FourStateValue,
    ) -> bool {
        let root_value = read_slot(&self.arena, self.root_location(&info));
        let spliced = super::alias::splice_window(&root_value, info.window, &value);
        self.vc.views.table().begin_write(view);
        let result = self.commit_root(info.root, info.window.row, spliced);
        self.vc.views.table().end_write();
        result.changed
            && super::write::four_state_changed(
                &super::alias::window_value(&result.old, info.window),
                &super::alias::window_value(&result.new, info.window),
            )
    }
}

impl SignalAccess for StateEngine {
    fn read(&self, cell: StateCellId) -> FourStateValue {
        if let Some(info) = self.vc.views.info(cell) {
            let root = read_slot(&self.arena, self.root_location(&info));
            return super::alias::window_value(&root, info.window);
        }
        let loc = self.cells[cell.0 as usize];
        read_slot(&self.arena, loc)
    }

    fn write(&mut self, cell: StateCellId, value: FourStateValue) -> bool {
        if let Some(info) = self.vc.views.info(cell) {
            return self.write_view(cell, info, value);
        }
        self.commit_write(cell, value, &mut ()).changed
    }

    fn read_row(&self, cell: StateCellId, row: u64) -> FourStateValue {
        let loc = resolve_mem_row(self.cells[cell.0 as usize], row);
        read_slot(&self.arena, loc)
    }

    fn write_row(&mut self, cell: StateCellId, row: u64, value: FourStateValue) -> bool {
        self.commit_root(cell, Some(row), value).changed
    }

    fn take_alias_changes(&mut self) -> Vec<super::alias::AliasChange> {
        self.vc.views.take_pending()
    }

    fn read_wide_window(
        &self,
        cell: StateCellId,
        lo_word: usize,
        words: usize,
    ) -> (Vec<u64>, Vec<u64>) {
        let loc = self.cells[cell.0 as usize];
        debug_assert_eq!(loc.class, SlotClass::Wide);
        super::huge_mirror::read_window(&self.arena, loc.word_offset as usize, lo_word, words)
    }

    fn write_wide_window(
        &mut self,
        cell: StateCellId,
        lo_word: usize,
        aval: &[u64],
        bval: &[u64],
    ) -> bool {
        let loc = self.cells[cell.0 as usize];
        // The windowed store replaces `commit_write_at` only where that does
        // nothing the window skips (see `huge_mirror`'s module doc).
        if loc.class != SlotClass::Wide
            || self.vc.force.borrow().contains(cell)
            || self.vc.records_changes()
        {
            return super::write_wide_window_whole(self, cell, lo_word, aval, bval);
        }
        let changed = super::huge_mirror::store_window(
            &self.arena,
            loc.word_offset as usize,
            loc.bit_width,
            lo_word,
            aval,
            bval,
        );
        if changed {
            self.dispatch.notify_scheduler(
                cell,
                EdgeKind::None,
                self.vc.current_time(),
                self.vc.current_region(),
            );
        }
        changed
    }

    fn subscribe(
        &mut self,
        _cell: StateCellId,
        role: ListenerRole,
        sink: Box<dyn ValueChangeSink + Send>,
    ) {
        // Task 11 (ST-035, ST-073, ST-074): fills in the placeholder left by
        // Task 9 — this is now the *one* entry point every consumer
        // (scheduler wakeup, waveform, VPI) registers into, and it forwards
        // directly to `Dispatch::register`, the fixed 3-role table
        // (`state::dispatch`), never a second ad hoc `Vec`/`HashMap`-backed
        // table.
        //
        // `_cell` stays unused this task: this wave's `Dispatch` is one
        // shared 3-role table per `StateEngine` (not per-cell), matching
        // `commit_write`'s own current fan-out shape (it does not yet route
        // per-cell either — see Task 12's GVT-gating task for where
        // per-write routing through this table is actually exercised end to
        // end). Per-cell subscription filtering, if ever needed, is future
        // scope, not part of ST-035/ST-073/ST-074's acceptance.
        self.dispatch.register(role, sink);
    }
}

// These tests build real layouts from SV source, which needs the frontend.
// The feature gate goes first: this file's own source scans find the test
// module as the test attribute immediately followed by `mod tests`.
#[cfg(feature = "frontend")]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::netlist::{SymbolKey, TemplateKey};
    use crate::state::instance::TemplateRegistry;
    use crate::state::layout::build_template_layout;
    use crate::state::value::compile_source;
    use crate::state::write::last_vc_record_for;
    use crate::state::{SlotDescriptor, SlotOffset, StateLayout};

    /// Review fix (Task 10 r1, both blocking findings): the shared boundary
    /// finder both `no_public_function_returns_a_raw_absolute_pointer_for_
    /// caller_arithmetic` (ST-027) and `state_engine_owns_every_state_owned_
    /// resource_directly_no_second_pointer` (ST-152) use to isolate a
    /// scanned file's *production* code from its trailing `mod tests` block.
    ///
    /// The original implementation (in both tests, duplicated) truncated at
    /// the FIRST literal occurrence of the substring `"#[cfg(test)]"`
    /// anywhere in the file -- including inside doc-comment prose that
    /// merely *mentions* the attribute in backticks (`write.rs`'s
    /// `last_vc_record_for` doc comment) and on real, individually
    /// `#[cfg(test)]`-gated helper items that sit well before the real test
    /// module (`write.rs`'s own `last_vc_record_for` fn; `arena.rs`'s
    /// `is_wide_plane_sealed` method, ~220 lines before its real `mod
    /// tests`). Either shape silently truncates the "production code" this
    /// function returns far too early, excluding genuine, always-compiled
    /// code from both structural scans -- a "gate that cannot fail" for any
    /// file shaped this way (verified by fault injection: a `pub fn`
    /// returning `*mut u8`/a `static mut` placed in that excluded region
    /// passed both scans green before this fix).
    ///
    /// The fix (r1): don't stop at *any* `#[cfg(test)]`, only at the one
    /// immediately (modulo whitespace) followed by `mod tests` -- the actual
    /// test-module boundary every file in this crate uses. A `#[cfg(test)]`
    /// on some other item, or the bare text of the attribute inside a doc
    /// comment, is skipped and scanning continues past it.
    ///
    /// The fix (r2, review finding "gate that cannot fail for content placed
    /// *after* `mod tests`"): r1 still `return`ed at the real boundary,
    /// which means it never scanned anything textually *after* that
    /// module's closing `}` -- nothing in the language forces `mod tests` to
    /// be the last item in a file, so genuinely-production code placed after
    /// it was silently invisible to both scans. Fixed by excising each real
    /// `#[cfg(test)] mod tests { ... }` span (located via brace-depth
    /// matching, not truncation) and concatenating everything else --
    /// before, between, and after every such block -- so scanning resumes
    /// past the excluded region for the rest of the file instead of
    /// stopping there. On every file in this crate today `mod tests` is
    /// still the last item, so the excised suffix is just trailing
    /// whitespace and this is a no-op change in practice; the fix is that
    /// it's no longer an *assumed* invariant the scan quietly depends on.
    fn production_code(src: &str) -> String {
        let marker = "#[cfg(test)]";
        let mut result = String::with_capacity(src.len());
        let mut cursor = 0usize;
        loop {
            let Some(rel_idx) = src[cursor..].find(marker) else {
                result.push_str(&src[cursor..]);
                break;
            };
            let idx = cursor + rel_idx;
            let after = &src[idx + marker.len()..];
            let after_trimmed = after.trim_start();
            if after_trimmed.starts_with("mod tests") {
                let trim_offset = after.len() - after_trimmed.len();
                let mod_tests_abs = idx + marker.len() + trim_offset;
                let after_keyword = &src[mod_tests_abs + "mod tests".len()..];
                let brace_abs = after_keyword
                    .find('{')
                    .map(|rel| mod_tests_abs + "mod tests".len() + rel);
                let close_abs = brace_abs.and_then(|b| find_matching_brace(src, b));
                match close_abs {
                    Some(close_abs) => {
                        // Keep everything up to (not including) the
                        // `#[cfg(test)]` marker, then jump past the whole
                        // module and keep scanning the remainder.
                        result.push_str(&src[cursor..idx]);
                        cursor = close_abs + 1;
                        continue;
                    }
                    None => {
                        // Malformed input (no matching brace found) --
                        // never silently include unparseable content past
                        // this point; fall back to the old truncate-here
                        // behavior for safety rather than guessing.
                        result.push_str(&src[cursor..idx]);
                        break;
                    }
                }
            }
            // Not the real boundary (either doc-comment prose mentioning the
            // attribute, or a `#[cfg(test)]`-gated item that isn't `mod
            // tests` itself) -- keep scanning past this occurrence.
            result.push_str(&src[cursor..idx + marker.len()]);
            cursor = idx + marker.len();
        }
        result
    }

    /// Depth-aware `{`/`}` matcher for [`production_code`]: given the byte
    /// index of an opening `{` in `src`, returns the byte index of its
    /// matching closing `}`, skipping braces that appear inside line/block
    /// comments, string literals and char literals (so a `"}"` or `'}'` in
    /// a test body's assertion text doesn't desynchronize the count). This
    /// is a lightweight tokenizer, not a full Rust parser -- sufficient for
    /// well-formed source files in this crate, and returns `None` (never
    /// panics or guesses) rather than silently mis-locating the boundary on
    /// anything it can't confidently classify.
    fn find_matching_brace(src: &str, open_idx: usize) -> Option<usize> {
        let bytes = src.as_bytes();
        debug_assert_eq!(bytes.get(open_idx), Some(&b'{'));
        let mut depth: i32 = 0;
        let mut i = open_idx;
        while i < bytes.len() {
            match bytes[i] {
                b'{' => {
                    depth += 1;
                    i += 1;
                }
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(i);
                    }
                    i += 1;
                }
                b'/' if bytes.get(i + 1) == Some(&b'/') => {
                    while i < bytes.len() && bytes[i] != b'\n' {
                        i += 1;
                    }
                }
                b'/' if bytes.get(i + 1) == Some(&b'*') => {
                    i += 2;
                    let mut comment_depth = 1u32;
                    while i < bytes.len() && comment_depth > 0 {
                        if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
                            comment_depth += 1;
                            i += 2;
                        } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
                            comment_depth -= 1;
                            i += 2;
                        } else {
                            i += 1;
                        }
                    }
                }
                b'"' => {
                    i += 1;
                    while i < bytes.len() && bytes[i] != b'"' {
                        if bytes[i] == b'\\' {
                            i += 1;
                        }
                        i += 1;
                    }
                    i += 1;
                }
                b'\'' => {
                    // Ambiguous between a char literal (`'x'`, `'\n'`,
                    // `'\u{7B}'`) and a lifetime tick (`'static`, `'a`).
                    // Look ahead a bounded window for a closing `'` with no
                    // intervening newline; if found, treat the whole span
                    // as a char literal and skip it (so a `'{'`/`'}'` char
                    // literal can never desync the brace count). Otherwise
                    // it's a lifetime -- just consume the tick.
                    const MAX_CHAR_LITERAL_LEN: usize = 12; // covers '\u{10FFFF}'
                    let window_end = (i + 1 + MAX_CHAR_LITERAL_LEN).min(bytes.len());
                    let mut j = i + 1;
                    let mut found_close = None;
                    while j < window_end {
                        if bytes[j] == b'\n' {
                            break;
                        }
                        if bytes[j] == b'\'' && j > i + 1 {
                            found_close = Some(j);
                            break;
                        }
                        j += 1;
                    }
                    match found_close {
                        Some(close) => i = close + 1,
                        None => i += 1,
                    }
                }
                _ => {
                    i += 1;
                }
            }
        }
        None
    }

    /// Review fix (Task 10 r1): the fault-injection cases the two blocking
    /// findings describe, run against the fixed [`production_code`] above,
    /// locking the fix in. Both cases previously passed (i.e. the injected
    /// violation went undetected) against the old first-`#[cfg(test)]`
    /// truncation; both must now be caught.
    #[test]
    fn production_code_does_not_truncate_early_at_a_pre_mod_tests_cfg_test_item() {
        // Shape 1 (write.rs): a `#[cfg(test)]`-visible peek helper, gated
        // individually, sitting before the real `mod tests` block -- plus a
        // doc comment that merely *mentions* the attribute in prose first.
        let write_shaped = concat!(
            "/// A `#[cfg(test)]`-visible peek at something.\n",
            "#[cfg(test)]\n",
            "pub fn last_vc_record_for() {}\n",
            "\n",
            "pub fn genuinely_production_and_must_stay_scanned() -> u32 { 1 }\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    // test-only code\n",
            "}\n",
        );
        let scanned = production_code(write_shaped);
        assert!(
            scanned.contains("genuinely_production_and_must_stay_scanned"),
            "a genuine production fn between an early #[cfg(test)] helper and \
             the real `mod tests` block must still be included in the scan"
        );
        assert!(
            !scanned.contains("mod tests"),
            "the real test module itself must be excluded"
        );

        // Shape 2 (arena.rs): a small `#[cfg(test)]`-gated method embedded
        // deep inside a real `impl` block, well before the real `mod tests`.
        let arena_shaped = concat!(
            "impl Arena {\n",
            "    #[cfg(test)]\n",
            "    pub(crate) fn is_wide_plane_sealed(&self) -> bool { true }\n",
            "\n",
            "    pub fn mode(&self) -> u8 { 0 }\n",
            "}\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    // test-only code\n",
            "}\n",
        );
        let scanned = production_code(arena_shaped);
        assert!(
            scanned.contains("pub fn mode"),
            "a genuine production fn after an early #[cfg(test)]-gated method \
             must still be included in the scan"
        );
        assert!(
            !scanned.contains("mod tests"),
            "the real test module itself must be excluded"
        );
    }

    /// Review fix (Task 10 r1): the same [`production_code`] boundary finder
    /// applied to the two *real* files the original findings named, proving
    /// the fix closes their exact reported blind spots (not just the
    /// synthetic shapes above). `write.rs`'s scan must reach past its early
    /// doc-comment mention of `#[cfg(test)]` (line 465-ish) and its
    /// individually-gated `last_vc_record_for` helper, and must still
    /// exclude the real `mod tests` block. `arena.rs`'s scan must reach past
    /// its early `#[cfg(test)]`-gated `is_wide_plane_sealed` method and
    /// include the genuinely-production `raw_inline_ptr`/`mode`/`ffi_view`
    /// functions that sit between it and the real `mod tests` block --
    /// exactly the ~500 lines the original first-match truncation dropped.
    #[test]
    fn production_code_reaches_the_real_mod_tests_boundary_in_write_rs_and_arena_rs() {
        let write_src = production_code(include_str!("write.rs"));
        assert!(
            write_src.contains("pub(crate) fn commit_write_at"),
            "write.rs's real mod tests boundary must not truncate before its production fns"
        );
        assert!(
            !write_src.contains("mod tests"),
            "write.rs's scan must still exclude its real test module"
        );

        let arena_src = production_code(include_str!("arena.rs"));
        for needed in [
            "pub unsafe fn raw_inline_ptr",
            "pub fn mode",
            "pub fn ffi_view",
            "pub fn wide_aval",
            "pub fn wide_bval",
        ] {
            assert!(
                arena_src.contains(needed),
                "arena.rs's scan must include the genuinely-production `{needed}`, \
                 which the original first-#[cfg(test)]-match truncation silently dropped"
            );
        }
        assert!(
            !arena_src.contains("mod tests"),
            "arena.rs's scan must still exclude its real test module"
        );
    }

    /// Review fix (Task 10 r2, both blocking findings on the boundary
    /// finder): r1's `production_code` stopped dead at the real `mod tests`
    /// boundary and never scanned anything past it -- nothing in the
    /// language forces `mod tests` to be the last item in a file, so a
    /// genuinely-production, un-gated item placed textually *after* the
    /// real `mod tests` block's closing brace was silently invisible to
    /// both structural scans. Mirrors the exact fault-injection shape the
    /// finding used (`static mut GLOBAL_LEAK: u32 = 0;` appended after a
    /// file's closing `mod tests` brace): the item must still show up in
    /// `production_code`'s output, and the brace matcher must not be
    /// confused by a `'{'`/`"}"` literal inside the excluded test body, nor
    /// stop at only the first of two `mod tests`-shaped blocks.
    #[test]
    fn production_code_resumes_scanning_after_the_real_mod_tests_closing_brace() {
        let shaped = concat!(
            "pub fn before_the_test_module() -> u32 { 1 }\n",
            "\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    #[test]\n",
            "    fn uses_brace_shaped_literals() {\n",
            "        let open = '{';\n",
            "        let close = '}';\n",
            "        let s = \"} not a real close {\";\n",
            "        assert_eq!(open, open);\n",
            "        assert_eq!(close, close);\n",
            "        let _ = s;\n",
            "    }\n",
            "}\n",
            "\n",
            "pub fn genuinely_production_placed_after_mod_tests() -> u32 { 2 }\n",
            "\n",
            "static mut GLOBAL_LEAK_AFTER_MOD_TESTS: u32 = 0;\n",
        );
        let scanned = production_code(shaped);
        assert!(
            scanned.contains("before_the_test_module"),
            "content before the real mod tests block must still be scanned"
        );
        assert!(
            !scanned.contains("uses_brace_shaped_literals"),
            "the real test module's body must still be excluded, even though it \
             contains '{{'/'}}' char literals and a \"}}...{{\" string literal that \
             could desync a naive brace counter"
        );
        assert!(
            scanned.contains("genuinely_production_placed_after_mod_tests"),
            "a genuine production fn placed AFTER the real mod tests block's \
             closing brace must still be scanned -- this is the exact gap the \
             review finding reported"
        );
        assert!(
            scanned.contains("GLOBAL_LEAK_AFTER_MOD_TESTS"),
            "a `static mut` placed after the real mod tests block must still be \
             visible to production_code's output, so the ST-152 scan built on top \
             of it can catch it"
        );

        // Two real test modules in one file: both must be excluded, and the
        // content between and after them must both survive.
        let two_modules = concat!(
            "pub fn between_none_yet() -> u32 { 0 }\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    fn first() {}\n",
            "}\n",
            "pub fn between_the_two_modules() -> u32 { 1 }\n",
            "#[cfg(test)]\n",
            "mod tests {\n",
            "    fn second() {}\n",
            "}\n",
            "pub fn after_both_modules() -> u32 { 2 }\n",
        );
        let scanned_two = production_code(two_modules);
        assert!(!scanned_two.contains("fn first"));
        assert!(!scanned_two.contains("fn second"));
        assert!(scanned_two.contains("between_the_two_modules"));
        assert!(scanned_two.contains("after_both_modules"));
    }

    /// Task 10 (ST-026): for a built instance/slot, the `#[inline(always)]`
    /// wrappers must produce results identical to the `extern "C"` fns they
    /// wrap, on both the scalar and wide tiers — proving each wrapper is a
    /// pure pass-through, never a second, divergent implementation. Fails if
    /// a wrapper re-derives its own resolution/storage path instead of
    /// simply forwarding to the existing `extern "C"` fn.
    #[test]
    fn inline_wrappers_produce_identical_results_to_the_extern_c_fns() {
        let tmpl = TemplateKey {
            definition: 10,
            params_hash: 0,
        };
        let mut engine = engine_with_template(
            "module m; logic [7:0] x; logic [127:0] w; endmodule\n",
            tmpl,
        );
        let handle = engine.allocate_instance(tmpl).expect("template registered");
        let h = handle.into_sim_handle();
        let scalar_slot = SlotId(0);
        let wide_slot = SlotId(1);

        // Scalar: write through the extern "C" fn, read back through both
        // the extern "C" fn and the inline wrapper -- they must agree.
        sv_set_scalar(h, scalar_slot, narrow_word(0x42, 0));
        assert_eq!(
            sv_get_scalar_inline(h, scalar_slot),
            sv_get_scalar(h, scalar_slot),
            "sv_get_scalar_inline must return exactly what sv_get_scalar returns"
        );

        // Scalar write path: write through the inline wrapper, read back
        // through the extern "C" fn -- both directions must agree.
        sv_set_scalar_inline(h, scalar_slot, narrow_word(0x99, 0));
        assert_eq!(sv_get_scalar(h, scalar_slot), narrow_word(0x99, 0));

        // Wide: same round trip, through both wrappers.
        let mut aval = [0x1111_1111_1111_1111u64, 0x2222_2222_2222_2222u64];
        let mut bval = [0x3333_3333_3333_3333u64, 0x4444_4444_4444_4444u64];
        let pattern = WideView {
            aval: aval.as_mut_ptr(),
            bval: bval.as_mut_ptr(),
            word_count: 2,
        };
        sv_set_wide_inline(h, wide_slot, pattern);
        let via_extern_c = sv_get_wide(h, wide_slot);
        let via_inline = sv_get_wide_inline(h, wide_slot);
        // SAFETY: both views alias the same, still-live arena storage this
        // same test's `engine`/`handle` own; `word_count` words are valid to
        // read on both planes per `sv_get_wide`'s own contract.
        unsafe {
            let extern_c_aval = std::slice::from_raw_parts(via_extern_c.aval, 2);
            let extern_c_bval = std::slice::from_raw_parts(via_extern_c.bval, 2);
            let inline_aval = std::slice::from_raw_parts(via_inline.aval, 2);
            let inline_bval = std::slice::from_raw_parts(via_inline.bval, 2);
            assert_eq!(extern_c_aval, inline_aval);
            assert_eq!(extern_c_bval, inline_bval);
        }

        // SAFETY: see the module's other tests' identical reclaim comment.
        unsafe {
            drop(Box::from_raw(h.0 as *mut InstanceHandle));
        }
    }

    /// Task 10 (ST-027): a source-text structural test proving no `pub fn` in
    /// either `accessor_impl.rs` or `write.rs` returns a raw pointer at any
    /// of this crate's actual signal-storage word widths -- the shape a
    /// raw-offset-exposing API (the superseded state.md design) would need
    /// to hand a caller a pointer it could do its own base+offset
    /// arithmetic against. Fails if a future edit reintroduces that
    /// superseded design.
    ///
    /// Review fix (Task 10 r2, both blocking findings on this test): r1 only
    /// scanned for `*mut u8`/`*const u8`, but no storage in this crate is
    /// ever addressed as `u8` -- the arena's inline plane is `Vec<u128>` and
    /// its wide planes are `Vec<u64>` (`arena.rs`'s own `raw_inline_ptr`
    /// already returns `*mut u128`, and the accepted `WideView` accessor
    /// already carries `*mut u64` fields), so a realistic reintroduction of
    /// the superseded design would use one of *those* widths and sail
    /// through undetected. Broadened to the widths this crate actually
    /// uses. `sv_get_wide`/`sv_get_wide_inline`/`sv_set_wide`/
    /// `sv_set_wide_inline` stay clean under the broadened scan because
    /// their signatures name the `WideView` struct, never a bare pointer
    /// type, in production code -- asserted explicitly below rather than
    /// just assumed.
    #[test]
    fn no_public_function_returns_a_raw_absolute_pointer_for_caller_arithmetic() {
        let forbidden = forbidden_raw_pointer_patterns();

        let accessor_impl_src = production_code(include_str!("accessor_impl.rs"));
        let write_src = production_code(include_str!("write.rs"));
        for (name, src) in [
            ("accessor_impl.rs", accessor_impl_src.as_str()),
            ("write.rs", write_src.as_str()),
        ] {
            for pattern in &forbidden {
                assert!(
                    !src.contains(pattern.as_str()),
                    "{name}'s production code must not return a raw `{pattern}` pointer \
                     from any function -- this crate's real word types are u128 (inline \
                     plane) and u64 (wide planes), not just u8"
                );
            }
        }

        // Confirm the broadened scan still doesn't false-positive on the
        // legitimate wide-plane accessors: their signatures name the
        // `WideView` struct, not a bare pointer type, so exactly the two
        // sanctioned `pub fn`s below are allowed to have `WideView` in their
        // signature and none of them may have a bare pointer return type.
        assert!(
            accessor_impl_src.contains("-> WideView"),
            "sv_get_wide/sv_get_wide_inline must still return the named WideView type"
        );
    }

    /// The forbidden raw-pointer shapes [`no_public_function_returns_a_raw_
    /// absolute_pointer_for_caller_arithmetic`] scans for -- factored out so
    /// the fault-injection test below exercises the exact same list the real
    /// scan uses, rather than a hand-copied duplicate that could silently
    /// drift out of sync with it.
    ///
    /// Built via concatenation, not as one contiguous literal per pattern,
    /// so this file's own source text never contains any forbidden
    /// substring contiguously either (this exact test function would
    /// otherwise match itself).
    fn forbidden_raw_pointer_patterns() -> Vec<String> {
        let widths = ["8", "16", "32", "64", "128"];
        widths
            .iter()
            .flat_map(|w| [["*", "mut u", w].concat(), ["*", "const u", w].concat()])
            .collect()
    }

    /// Review fix (Task 10 r2, both blocking findings on ST-027's width
    /// scan): fault injection proving the broadened scan actually catches
    /// this crate's *real* pointer shapes (`*mut u128`, `*mut u64`), not
    /// just the `*mut u8` shape the r1 scan was limited to and which has no
    /// natural occurrence anywhere in this codebase. Mirrors the exact
    /// shapes the finding named: a `raw_base_ptr`/`instance_base_words`-like
    /// signature exposing the arena's real word types for caller-side
    /// base+offset arithmetic.
    #[test]
    fn forbidden_raw_pointer_scan_catches_this_crates_real_word_widths() {
        let forbidden = forbidden_raw_pointer_patterns();

        let u128_reintroduction = concat!(
            "pub fn raw_base_ptr(handle: SimHandle) -> *mut u128 {\n",
            "    unimplemented!()\n",
            "}\n",
        );
        assert!(
            forbidden
                .iter()
                .any(|p| u128_reintroduction.contains(p.as_str())),
            "a reintroduced *mut u128 raw-offset accessor must be caught by the \
             forbidden-pattern list -- this is the arena's actual inline-plane word type"
        );

        let u64_reintroduction = concat!(
            "pub fn instance_base_words(&self) -> (*mut u128, *mut u64, *mut u64) {\n",
            "    unimplemented!()\n",
            "}\n",
        );
        assert!(
            forbidden
                .iter()
                .any(|p| u64_reintroduction.contains(p.as_str())),
            "a reintroduced *mut u64 raw-offset accessor must be caught by the \
             forbidden-pattern list -- this is the arena's actual wide-plane word type"
        );

        // The r1-era u8-only list must NOT have caught either shape (sanity
        // check that this test actually exercises new coverage, not
        // coverage the r1 scan already had).
        let u8_only: Vec<String> = vec!["*mut u8".to_string(), "*const u8".to_string()];
        assert!(
            !u8_only
                .iter()
                .any(|p| u128_reintroduction.contains(p.as_str())),
            "sanity check: the u128 shape must not contain the literal u8 substring"
        );
        assert!(
            !u8_only
                .iter()
                .any(|p| u64_reintroduction.contains(p.as_str())),
            "sanity check: the u64 shape must not contain the literal u8 substring"
        );
    }

    /// Task 10 (ST-029): `state::{StateEngine, StateCellId, FourStateValue}`
    /// alone (no `crate::process::*`, no `crate::sched::*`) must be enough to
    /// perform an `alloc_cell` + `commit_write` + `SignalAccess::read`
    /// sequence -- the import list itself is the proof this reference API
    /// needs no `ProcessFn`/`CompiledKernel` type to be reachable.
    #[test]
    fn read_and_write_are_callable_without_constructing_any_kernel_or_process_type() {
        use crate::state::write::SlotLocation;
        use crate::state::{FourStateValue, SignalAccess, StateCellId, StateEngine};

        let templates = TemplateRegistry::new();
        let mut engine = StateEngine::new(templates);
        // SAFETY: local, single-owned engine; no other live borrow of the
        // inline plane, single-threaded test.
        let word_offset = unsafe { engine.arena.alloc_inline_word() };
        let loc = SlotLocation {
            class: SlotClass::Inline,
            word_offset,
            bit_width: 8,
            elem_word_count: 1,
            row_stride_words: 0,
            num_rows: 0,
        };
        let cell: StateCellId = engine.alloc_cell(loc);

        let changed =
            engine.commit_write(cell, FourStateValue::Narrow(narrow_word(0x2A, 0)), &mut ());
        assert!(changed.changed);

        match SignalAccess::read(&engine, cell) {
            FourStateValue::Narrow(w) => assert_eq!(w, narrow_word(0x2A, 0)),
            FourStateValue::Wide { .. } => panic!("expected Narrow"),
        }
    }

    /// Task 10 (ST-152): every resource `StateEngine` owns (`arena`,
    /// `templates`, `cells`, `vc` -- `dispatch`/the undo log are added by
    /// Tasks 11/16, later than this task) is a *direct* field, reachable
    /// purely through `&engine.<field>`/`&mut engine.<field>`, never through
    /// a second, free-standing global -- and no forbidden-kind global (a
    /// mutable process-wide static, an external once-per-process-init macro,
    /// or a lazily-initialized single-cell singleton type) exists anywhere in
    /// this crate's `state` module (the concrete negative half of the proof;
    /// see this test's own body for the exact forbidden spellings it scans
    /// for, listed there rather than here so this doc comment's own prose
    /// cannot trip the very scan it describes).
    #[test]
    fn state_engine_owns_every_state_owned_resource_directly_no_second_pointer() {
        let templates = TemplateRegistry::new();
        let mut engine = StateEngine::new(templates);

        // Reach every currently-existing STATE-owned resource purely through
        // a direct field access on `&mut engine`/`&engine` -- no second,
        // free-standing global exists to reach any of them through instead.
        let _arena: &std::rc::Rc<super::super::arena::Arena> = &engine.arena;
        let _templates: &std::rc::Rc<TemplateRegistry> = &engine.templates;
        let _cells_len_before = engine.cells.len();
        let (cell, _) = {
            // SAFETY: local, single-owned engine; no other live borrow.
            let word_offset = unsafe { engine.arena.alloc_inline_word() };
            let loc = crate::state::write::SlotLocation {
                class: SlotClass::Inline,
                word_offset,
                bit_width: 1,
                elem_word_count: 1,
                row_stride_words: 0,
                num_rows: 0,
            };
            (engine.alloc_cell(loc), loc)
        };
        assert_eq!(
            engine.cells.len(),
            _cells_len_before + 1,
            "cells is a direct field"
        );
        engine.commit_write(cell, FourStateValue::Narrow(narrow_word(1, 0)), &mut ());
        engine.register_worker_thread(); // reaches `vc` purely via `&mut engine`

        // Negative half: no forbidden-kind global anywhere in this crate's
        // `state` module's *production* code. See [`forbidden_global_patterns`]
        // for the exact forbidden spellings and why each one is there.
        let forbidden = forbidden_global_patterns();
        let state_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/state");
        let entries = std::fs::read_dir(&state_dir).expect("state/ directory is readable");
        for entry in entries {
            let entry = entry.expect("directory entry is readable");
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
                continue;
            }
            let contents = std::fs::read_to_string(&path)
                .unwrap_or_else(|e| panic!("{} must be readable: {e}", path.display()));
            let scanned = production_code(&contents);
            for forbidden_pattern in &forbidden {
                assert!(
                    !scanned.contains(forbidden_pattern.as_str()),
                    "{}'s production code must not contain a free-standing global of the \
                     forbidden kind this test enforces -- every STATE-owned resource must be \
                     reachable exclusively through a direct StateEngine field",
                    path.display()
                );
            }
        }
    }

    /// The forbidden free-standing-global shapes [`state_engine_owns_every_
    /// state_owned_resource_directly_no_second_pointer`] scans for --
    /// factored out so the fault-injection test below exercises the exact
    /// same list the real scan uses, rather than a hand-copied duplicate
    /// that could silently drift out of sync with it.
    ///
    /// Review fix (Task 10 r2): r1's list (`static mut`, `lazy_static`,
    /// `OnceLock`, `OnceCell`) only catches globals that need the `mut`
    /// keyword or one of those three specific types. A free-standing,
    /// process-wide, mutably-shared global does not need any of them -- a
    /// bare `static` whose type is `Mutex<T>`/`RwLock<T>`/`AtomicPtr<T>` is
    /// an ordinary, no-`unsafe`-required way to build exactly the "second,
    /// free-standing global" pointer to STATE-owned data ST-152 forbids,
    /// using none of the four original spellings.
    ///
    /// Added: `Mutex<`/`RwLock<` (the two `Sync`-safe interior-mutability
    /// wrapper types that can hold an arbitrary `T`, including an
    /// `Rc`/`Arc`/raw pointer at STATE's owned data) and `AtomicPtr<` (the
    /// pointer-typed atomic -- deliberately narrower than a bare `Atomic`
    /// substring, which would also match this crate's existing, legitimate
    /// `instance.rs` monotonic-id counter: a plain integer atomic holds no
    /// pointer to any STATE-owned resource and is not the shape ST-152
    /// forbids, so it must not be flagged; see the fault-injection test
    /// below for the check that it stays clean).
    ///
    /// Every spelling here is built by concatenation (never as one
    /// contiguous literal, and never named in a doc/prose comment either)
    /// for the same self-matching reason r1's list already documents.
    fn forbidden_global_patterns() -> Vec<String> {
        vec![
            ["static", " mut"].concat(),
            ["lazy", "_static"].concat(),
            ["Once", "Lock"].concat(),
            ["Once", "Cell"].concat(),
            ["Mut", "ex<"].concat(),
            ["Rw", "Lock<"].concat(),
            ["Atomic", "Ptr<"].concat(),
        ]
    }

    /// Review fix (Task 10 r2): fault injection proving the broadened
    /// forbidden-global list actually catches a Mutex/RwLock/AtomicPtr-
    /// backed static -- the exact evasion shape the finding demonstrated
    /// (a `Mutex<Option<Rc<...>>>`-typed free-standing global) that passed
    /// all four r1 patterns clean. Also proves the broadened list does NOT
    /// false-positive on this crate's one existing, legitimate
    /// free-standing static (`instance.rs`'s `NEXT_ENGINE_ID: AtomicU64`
    /// monotonic-id counter), which holds no pointer to any STATE-owned
    /// resource.
    #[test]
    fn forbidden_global_scan_catches_mutex_rwlock_and_atomicptr_backed_globals() {
        let forbidden = forbidden_global_patterns();

        let mutex_leak = concat!(
            "static GLOBAL_ARENA_REGISTRY: std::sync::Mutex<Option<std::rc::Rc<u8>>> =\n",
            "    std::sync::Mutex::new(None);\n",
        );
        assert!(
            forbidden.iter().any(|p| mutex_leak.contains(p.as_str())),
            "a Mutex-backed free-standing global must be caught by the forbidden-pattern list"
        );

        let rwlock_leak = "static GLOBAL: std::sync::RwLock<u8> = std::sync::RwLock::new(0);";
        assert!(
            forbidden.iter().any(|p| rwlock_leak.contains(p.as_str())),
            "an RwLock-backed free-standing global must be caught by the forbidden-pattern list"
        );

        let atomic_ptr_leak = "static GLOBAL: std::sync::atomic::AtomicPtr<u8> = \
             std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());";
        assert!(
            forbidden
                .iter()
                .any(|p| atomic_ptr_leak.contains(p.as_str())),
            "an AtomicPtr-backed free-standing global must be caught by the forbidden-pattern list"
        );

        // None of the r1-era four patterns caught any of the above (sanity
        // check that this test actually exercises new coverage, not
        // coverage the r1 scan already had).
        let r1_patterns: Vec<String> = vec![
            ["static", " mut"].concat(),
            ["lazy", "_static"].concat(),
            ["Once", "Lock"].concat(),
            ["Once", "Cell"].concat(),
        ];
        for shape in [mutex_leak, rwlock_leak, atomic_ptr_leak] {
            assert!(
                !r1_patterns.iter().any(|p| shape.contains(p.as_str())),
                "sanity check: the r1-era pattern list must not already catch this shape"
            );
        }

        // Must NOT false-positive on this crate's real, legitimate plain
        // integer atomic counter -- it is not a pointer to STATE-owned data.
        let legitimate_counter = "static NEXT_ENGINE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);";
        assert!(
            !forbidden
                .iter()
                .any(|p| legitimate_counter.contains(p.as_str())),
            "a plain AtomicU64 counter (no pointer to any STATE-owned resource) must not be flagged"
        );
    }

    fn engine_with_template(src: &str, key: TemplateKey) -> StateEngine {
        let design = compile_source(src).expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        let layout: StateLayout = build_template_layout(&body).expect("layout builds");

        let templates = TemplateRegistry::new();
        // SAFETY: `templates` is a local, single-owned value with no other
        // live borrow and no concurrent caller.
        unsafe {
            templates.register(key, layout);
        }
        StateEngine::new(templates)
    }

    /// Review fix (Task 9 r4, blocking finding): builds a `StateEngine` with
    /// one registered template holding a single `SlotClass::Wide` slot of
    /// `elem_word_count` words, entirely by hand -- no `compile_source`/
    /// `build_template_layout` (hence no `sv_lang` C++ FFI call) anywhere in
    /// this path, unlike [`engine_with_template`] above. `sv_lang`'s FFI
    /// cannot run under Miri, so this is the route the Miri-reachable
    /// regression test below uses to build a real `sv_get_wide`-capable
    /// instance. Mirrors [`engine_with_template`]'s own registration
    /// sequence exactly, just with a hand-built [`StateLayout`] in place of
    /// one `build_template_layout` produces from real elaborated SV.
    fn engine_with_manual_wide_template(key: TemplateKey, elem_word_count: u32) -> StateEngine {
        let layout = StateLayout {
            slots: vec![SlotDescriptor {
                key: SymbolKey(0),
                offset: SlotOffset {
                    class: SlotClass::Wide,
                    word_offset: 0,
                    bit_width: elem_word_count * 64,
                    elem_word_count,
                    row_stride_words: 0,
                    num_rows: 0,
                },
                initial: None,
                net_info: None,
            }],
            inline_words: 0,
            wide_words: elem_word_count,
        };

        let templates = TemplateRegistry::new();
        // SAFETY: `templates` is a local, single-owned value with no other
        // live borrow and no concurrent caller.
        unsafe {
            templates.register(key, layout);
        }
        StateEngine::new(templates)
    }

    fn narrow_word(val: u64, unk: u64) -> u128 {
        (val as u128) | ((unk as u128) << 64)
    }

    /// Task 11 (ST-138) regression: `slot_location_for` (this module's own
    /// private resolver, exercised directly here since this test lives
    /// inside the same module) must thread a `SlotClass::Memory` slot's
    /// `row_stride_words`/`num_rows` through into the returned
    /// `SlotLocation`, not drop/zero them -- the concrete case Task 1's own
    /// hand-built-`SlotLocation` unit tests (`state::write::tests`) cannot
    /// catch, since they never go through `slot_location_for` at all. A
    /// hand-built `SlotOffset` (no `sv_lang` FFI, mirrors
    /// `engine_with_manual_wide_template`'s own reasoning) with
    /// `row_stride_words: 4, num_rows: 6` deliberately distinct from
    /// `elem_word_count: 2`, so a bug that copied `elem_word_count` into
    /// those fields instead (or left them zeroed) is caught, not silently
    /// matched.
    #[test]
    fn slot_location_for_threads_memory_row_stride_and_num_rows_through() {
        let key = TemplateKey {
            definition: 0,
            params_hash: 0,
        };
        let layout = StateLayout {
            slots: vec![SlotDescriptor {
                key: SymbolKey(0),
                offset: SlotOffset {
                    class: SlotClass::Memory,
                    word_offset: 0,
                    bit_width: 32,
                    elem_word_count: 2,
                    row_stride_words: 4,
                    num_rows: 6,
                },
                initial: None,
                net_info: None,
            }],
            inline_words: 0,
            wide_words: 2 * 6,
        };
        let templates = TemplateRegistry::new();
        // SAFETY: `templates` is a local, single-owned value with no other
        // live borrow and no concurrent caller.
        unsafe {
            templates.register(key, layout);
        }
        let mut engine = StateEngine::new(templates);
        let handle = engine.allocate_instance(key).expect("template registered");

        let resolved = slot_location_for(&handle, SlotId(0));
        assert_eq!(resolved.class, SlotClass::Memory);
        assert_eq!(resolved.elem_word_count, 2);
        assert_eq!(
            resolved.row_stride_words, 4,
            "slot_location_for must copy row_stride_words from the SlotOffset, not drop/zero it"
        );
        assert_eq!(
            resolved.num_rows, 6,
            "slot_location_for must copy num_rows from the SlotOffset, not drop/zero it"
        );
    }

    /// ST-020, ST-021: build a 1-slot template (8-bit inline var), allocate 2
    /// instances, convert each to a `SimHandle`; `sv_set_scalar` distinct
    /// patterns through each, and `sv_get_scalar` must read back exactly the
    /// pattern written through *that* handle — proving the same `SlotId`
    /// resolves to two different absolute words because the two
    /// `InstanceHandle`s carry different bases. Fails if `handle.base` is
    /// ignored (both instances would alias).
    #[test]
    fn sv_get_set_scalar_round_trips_through_a_real_instance_handle() {
        let tmpl = TemplateKey {
            definition: 0,
            params_hash: 0,
        };
        let mut engine = engine_with_template("module m; logic [7:0] x; endmodule\n", tmpl);

        let handle_a = engine.allocate_instance(tmpl).expect("template registered");
        let handle_b = engine.allocate_instance(tmpl).expect("template registered");
        let h_a = handle_a.into_sim_handle();
        let h_b = handle_b.into_sim_handle();

        let slot = SlotId(0);
        let pattern_a = narrow_word(0xAA, 0);
        let pattern_b = narrow_word(0x55, 0);
        assert_ne!(pattern_a, pattern_b);

        sv_set_scalar(h_a, slot, pattern_a);
        sv_set_scalar(h_b, slot, pattern_b);

        assert_eq!(sv_get_scalar(h_a, slot), pattern_a);
        assert_eq!(sv_get_scalar(h_b, slot), pattern_b);

        // SAFETY: reclaim the two handles this test leaked via
        // `into_sim_handle`, exactly as `from_sim_handle`'s own `# Safety`
        // section documents no wave-A caller does for a live simulation run
        // -- safe here only because this test performs no further access to
        // either handle afterward.
        unsafe {
            drop(Box::from_raw(h_a.0 as *mut InstanceHandle));
            drop(Box::from_raw(h_b.0 as *mut InstanceHandle));
        }
    }

    /// ST-021: write the same value twice via `sv_set_scalar`; the first
    /// write (different from the slot's zero-initial value) must register a
    /// change in the same VC buffer `commit_write` appends to, and the
    /// second (identical value) must not. Fails if `sv_set_scalar` wrote
    /// through a path that never touches `commit_write_at`.
    #[test]
    fn sv_set_scalar_reports_change_via_the_same_primitive_as_signal_access() {
        let tmpl = TemplateKey {
            definition: 1,
            params_hash: 0,
        };
        let mut engine = engine_with_template("module m; logic [7:0] x; endmodule\n", tmpl);
        let handle = engine.allocate_instance(tmpl).expect("template registered");
        let cell = handle.cell_for_slot(0);
        let h = handle.into_sim_handle();
        let slot = SlotId(0);

        sv_set_scalar(h, slot, narrow_word(1, 0));
        let after_first = last_vc_record_for(cell);
        assert!(
            after_first.is_some(),
            "the first write (from the zero default) must register a change"
        );

        sv_set_scalar(h, slot, narrow_word(1, 0));
        let after_second = last_vc_record_for(cell).expect("still the first write's record");
        match after_second.new {
            FourStateValue::Narrow(w) => assert_eq!(
                w,
                narrow_word(1, 0),
                "the identical second write must not append a new record"
            ),
            FourStateValue::Wide { .. } => panic!("expected Narrow"),
        }

        // SAFETY: see the previous test's identical reclaim comment.
        unsafe {
            drop(Box::from_raw(h.0 as *mut InstanceHandle));
        }
    }

    /// ST-022, ST-023: a template with one 128-bit wide member
    /// (`elem_word_count == 2`); 2 instances; `sv_set_wide` a distinct
    /// pattern per instance -- on *both* the `aval` and `bval` (unknown-bit)
    /// planes, since ST-022/ST-023's own requirement text names "the
    /// aval/bval limb planes" explicitly -- and `sv_get_wide` on the other
    /// instance must never reflect the first instance's pattern on either
    /// plane (reads its own, independently-based words) -- the wide-plane
    /// analogue of the scalar round-trip test. Review fix (r2): the
    /// original version of this test used `bval: [0, 0]` for every instance
    /// and never read `view.bval` back at all, so a `sv_set_wide` that
    /// silently dropped/zeroed the caller's `bval` (e.g. a copy-paste bug
    /// writing `aval` into both planes) would still pass; asserting on
    /// `bval` here as rigorously as `aval` closes that gap.
    #[test]
    fn sv_get_set_wide_slices_the_correct_word_range_per_instance() {
        let tmpl = TemplateKey {
            definition: 2,
            params_hash: 0,
        };
        let mut engine = engine_with_template("module m; logic [127:0] w; endmodule\n", tmpl);

        let handle_a = engine.allocate_instance(tmpl).expect("template registered");
        let handle_b = engine.allocate_instance(tmpl).expect("template registered");
        let h_a = handle_a.into_sim_handle();
        let h_b = handle_b.into_sim_handle();
        let slot = SlotId(0);

        let mut aval_a = [0xAAAA_AAAA_AAAA_AAAAu64, 0xBBBB_BBBB_BBBB_BBBBu64];
        let mut bval_a = [0x1111_1111_1111_1111u64, 0x2222_2222_2222_2222u64];
        let pattern_a = WideView {
            aval: aval_a.as_mut_ptr(),
            bval: bval_a.as_mut_ptr(),
            word_count: 2,
        };
        sv_set_wide(h_a, slot, pattern_a);

        let mut aval_b = [0xCCCC_CCCC_CCCC_CCCCu64, 0xDDDD_DDDD_DDDD_DDDDu64];
        let mut bval_b = [0x3333_3333_3333_3333u64, 0x4444_4444_4444_4444u64];
        let pattern_b = WideView {
            aval: aval_b.as_mut_ptr(),
            bval: bval_b.as_mut_ptr(),
            word_count: 2,
        };
        sv_set_wide(h_b, slot, pattern_b);

        let view_a = sv_get_wide(h_a, slot);
        // SAFETY: `view_a` was just returned by `sv_get_wide` above, backed
        // by this same test's still-live `engine`/`handle_a`; `word_count`
        // words are valid to read per `sv_get_wide`'s own contract, on both
        // the `aval` and `bval` planes.
        let read_a_aval = unsafe { std::slice::from_raw_parts(view_a.aval, 2) };
        let read_a_bval = unsafe { std::slice::from_raw_parts(view_a.bval, 2) };
        assert_eq!(read_a_aval, [aval_a[0], aval_a[1]]);
        assert_eq!(read_a_bval, [bval_a[0], bval_a[1]]);
        assert_ne!(
            read_a_aval,
            [aval_b[0], aval_b[1]],
            "instance A's aval read must never reflect instance B's pattern"
        );
        assert_ne!(
            read_a_bval,
            [bval_b[0], bval_b[1]],
            "instance A's bval read must never reflect instance B's pattern"
        );

        let view_b = sv_get_wide(h_b, slot);
        // SAFETY: same reasoning as above, applied to `handle_b`.
        let read_b_aval = unsafe { std::slice::from_raw_parts(view_b.aval, 2) };
        let read_b_bval = unsafe { std::slice::from_raw_parts(view_b.bval, 2) };
        assert_eq!(read_b_aval, [aval_b[0], aval_b[1]]);
        assert_eq!(read_b_bval, [bval_b[0], bval_b[1]]);

        // SAFETY: see the first test's identical reclaim comment.
        unsafe {
            drop(Box::from_raw(h_a.0 as *mut InstanceHandle));
            drop(Box::from_raw(h_b.0 as *mut InstanceHandle));
        }
    }

    /// ST-023 (review fix: the wide-tier sibling of
    /// `sv_set_scalar_reports_change_via_the_same_primitive_as_signal_access`,
    /// since the slicing test above only checks value round-trip, never that
    /// a change was actually detected/recorded). `sv_set_wide` with a
    /// pattern different from the slot's zero-initial value must register a
    /// change; the identical pattern written again must not append a new
    /// record. Fails if `sv_set_wide` were a bare write into
    /// `arena.wide_aval`/`wide_bval` that never calls into
    /// `commit_write_at`'s diff/append logic at all.
    ///
    /// Review fix (r2): the pattern's `bval` is now nonzero (was `[0, 0]`,
    /// indistinguishable from a dropped/zeroed `bval`), and the read-back
    /// `VcRecord::new` is asserted on its `bval` plane exactly as its `aval`
    /// plane already was (was destructured with `bval: ..`, discarding it)
    /// -- so a `sv_set_wide` that silently drops or zeroes the caller's
    /// `bval` before it ever reaches `commit_write_at` now fails this test.
    #[test]
    fn sv_set_wide_reports_change_via_the_same_primitive_as_signal_access() {
        let tmpl = TemplateKey {
            definition: 3,
            params_hash: 0,
        };
        let mut engine = engine_with_template("module m; logic [127:0] w; endmodule\n", tmpl);
        let handle = engine.allocate_instance(tmpl).expect("template registered");
        let cell = handle.cell_for_slot(0);
        let h = handle.into_sim_handle();
        let slot = SlotId(0);

        let mut aval = [0x1111_1111_1111_1111u64, 0x2222_2222_2222_2222u64];
        let mut bval = [0x5555_5555_5555_5555u64, 0x6666_6666_6666_6666u64];
        let pattern = WideView {
            aval: aval.as_mut_ptr(),
            bval: bval.as_mut_ptr(),
            word_count: 2,
        };

        sv_set_wide(h, slot, pattern);
        let after_first = last_vc_record_for(cell);
        assert!(
            after_first.is_some(),
            "the first wide write (from the zero default) must register a change"
        );
        match after_first.expect("checked is_some above").new {
            FourStateValue::Wide { aval: a, bval: b } => {
                assert_eq!(a, vec![aval[0], aval[1]]);
                assert_eq!(b, vec![bval[0], bval[1]]);
            }
            FourStateValue::Narrow(_) => panic!("expected Wide"),
        }

        // Reissue the identical pattern (same backing arrays, unchanged).
        let pattern_again = WideView {
            aval: aval.as_mut_ptr(),
            bval: bval.as_mut_ptr(),
            word_count: 2,
        };
        sv_set_wide(h, slot, pattern_again);
        let after_second = last_vc_record_for(cell).expect("still the first write's record");
        match after_second.new {
            FourStateValue::Wide { aval: a, bval: b } => {
                assert_eq!(
                    a,
                    vec![aval[0], aval[1]],
                    "the identical second write must not append a new record"
                );
                assert_eq!(
                    b,
                    vec![bval[0], bval[1]],
                    "the identical second write must not append a new record"
                );
            }
            FourStateValue::Narrow(_) => panic!("expected Wide"),
        }

        // SAFETY: see the first test's identical reclaim comment.
        unsafe {
            drop(Box::from_raw(h.0 as *mut InstanceHandle));
        }
    }

    /// ST-013: for one instance, write a value via `sv_set_scalar` (the ABI
    /// path) then read it back via `StateEngine`'s `SignalAccess::read` on
    /// the `StateCellId` Task 8 mints for that same concrete signal --
    /// proving STATE has exactly one canonical storage location reachable
    /// both ways, never two.
    #[test]
    fn signal_access_read_write_agree_with_the_accessor_fns_on_the_same_storage() {
        let tmpl = TemplateKey {
            definition: 4,
            params_hash: 0,
        };
        let mut engine = engine_with_template("module m; logic [7:0] x; endmodule\n", tmpl);
        let handle = engine.allocate_instance(tmpl).expect("template registered");
        let cell = handle.cell_for_slot(0);
        let h = handle.into_sim_handle();
        let slot = SlotId(0);

        sv_set_scalar(h, slot, narrow_word(0x7B, 0));

        match SignalAccess::read(&engine, cell) {
            FourStateValue::Narrow(w) => assert_eq!(w, narrow_word(0x7B, 0)),
            FourStateValue::Wide { .. } => panic!("expected Narrow"),
        }

        // SAFETY: see the first test's identical reclaim comment.
        unsafe {
            drop(Box::from_raw(h.0 as *mut InstanceHandle));
        }
    }

    /// Review fix (Task 9 r3, blocking finding 1): `sv_get_wide`'s returned
    /// `WideView` aliases `Arena::wide_aval`/`wide_bval`'s own live storage
    /// and is retained by the caller past the call -- before this fix, a
    /// later `allocate_instance` call for the same (or any) wide-slot
    /// template could grow those planes via `Arena::alloc_wide_words` enough
    /// to reallocate their backing `Vec<u64>`s, silently dangling every
    /// previously issued `WideView`'s `aval`/`bval` pointers (a genuine
    /// use-after-free with no compiler diagnostic -- confirmed via an
    /// isolated Miri repro of this exact pattern, per the finding). Allocate
    /// one wide-slot instance, obtain a `WideView` via `sv_get_wide`, then
    /// call `allocate_instance` again for the same template -- this must now
    /// panic (`Arena::alloc_wide_words`'s new seal check firing) rather than
    /// silently succeeding and leaving `view`'s pointers dangling. Mirrors
    /// `instance.rs`'s own `allocate_instance_called_many_more_times_leaves_
    /// the_first_handles_arena_pointer_valid` test's "force further growth,
    /// then read back through the first handle" shape, except here the
    /// correct outcome is a loud panic, not a successful read: no
    /// stable-address storage exists for the wide planes (see
    /// `Arena::wide_sealed`'s doc comment for why the `TemplateRegistry`
    /// per-entry-boxing fix doesn't apply to them), so the chosen fix is an
    /// enforced phase boundary instead.
    #[test]
    #[should_panic(expected = "refusing to grow the wide plane")]
    fn sv_get_wide_view_survives_no_further_allocate_instance_call_it_must_panic_not_dangle() {
        let tmpl = TemplateKey {
            definition: 5,
            params_hash: 0,
        };
        let mut engine = engine_with_template("module m; logic [127:0] w; endmodule\n", tmpl);

        let handle = engine.allocate_instance(tmpl).expect("template registered");
        let h = handle.into_sim_handle();
        let slot = SlotId(0);

        // Obtain a WideView that (per sv_get_wide's own contract, and this
        // module's own doc comment above) aliases the arena's live
        // wide_aval/wide_bval storage.
        let view = sv_get_wide(h, slot);
        assert_eq!(view.word_count, 2);

        // Any further wide-slot allocation must now be refused -- it would
        // otherwise be free to reallocate the very buffer `view` points
        // into. This call is expected to panic before returning.
        let _ = engine.allocate_instance(tmpl);

        // Unreachable: the panic above must fire first. Left here (rather
        // than omitted) so that if the seal is ever accidentally weakened to
        // a silent no-op instead of a panic, this test still fails loudly
        // (via the leaked, un-reclaimed `h`/`view` triggering nothing
        // useful) rather than passing by accident through an early return.
        unreachable!("allocate_instance after sv_get_wide must panic, not return");
    }

    /// Review fix (Task 9 r4, blocking finding): `sv_get_wide`'s returned
    /// `WideView` pointers are Undefined Behavior to dereference under
    /// Stacked Borrows as soon as *any* subsequent `Arena::wide_aval_mut`/
    /// `wide_bval_mut` reborrow happens anywhere in the same `Arena` --
    /// which the finding showed fires on the very next `sv_get_wide` call
    /// for a *different* instance/slot (no write required at all), or on
    /// the next wide-class `commit_write_at` write to any wide signal. The
    /// Task 9 r3 fix (`Arena::wide_sealed`/`seal_wide_plane`) only prevents
    /// the backing `Vec` from *reallocating* -- a real but different hazard
    /// -- and does nothing about this separate, far more easily triggered
    /// reborrow-invalidation hazard.
    ///
    /// This test exercises both of the finding's exact trigger shapes
    /// against a real `sv_get_wide`-returned `WideView`, then reads back
    /// through the *first* view -- the shape `sv_get_set_wide_slices_the_
    /// correct_word_range_per_instance` never covered, since it always
    /// fully consumed `view_a` before `view_b` ever came into existence.
    /// Built via [`engine_with_manual_wide_template`] (no `compile_source`/
    /// `sv_lang` FFI) specifically so it can run under Miri:
    ///
    /// ```text
    /// CARGO_TARGET_DIR=/mnt/bulk/vj-target-wA-state \
    ///   rustup run nightly cargo miri test -p vj-sim \
    ///   sv_get_wide_view_stays_valid_across_a_later_sv_get_wide_and_a_later_wide_class_write
    /// ```
    ///
    /// Before the Task 9 r4 fix (raw-base-pointer construction in
    /// `Arena::wide_aval_ptr`/`wide_bval_ptr`, used by `sv_get_wide` instead
    /// of `wide_aval_mut()[start..].as_mut_ptr()`), the above Miri
    /// invocation reproduced exactly the "tag does not exist in the borrow
    /// stack for this location" error the finding described, at the
    /// `view_a` read-backs below. Under `cargo test` (no Miri) this test
    /// also passes before the fix -- the UB is invisible without Miri,
    /// which is exactly why the fix needs Miri to validate, not just this
    /// test's ordinary pass/fail.
    #[test]
    fn sv_get_wide_view_stays_valid_across_a_later_sv_get_wide_and_a_later_wide_class_write() {
        let tmpl = TemplateKey {
            definition: 6,
            params_hash: 0,
        };
        let mut engine = engine_with_manual_wide_template(tmpl, 2);

        // Both instances are allocated up front, before any sv_get_wide
        // call -- exactly like sv_get_set_wide_slices_the_correct_word_
        // range_per_instance above -- so `seal_wide_plane` (fired by the
        // first sv_get_wide call below) never blocks either allocation.
        let handle_a = engine.allocate_instance(tmpl).expect("template registered");
        let handle_b = engine.allocate_instance(tmpl).expect("template registered");
        let h_a = handle_a.into_sim_handle();
        let h_b = handle_b.into_sim_handle();
        let slot = SlotId(0);

        // Seed instance A's wide slot with a known pattern via the ordinary
        // write path, then retain a WideView onto it via sv_get_wide -- the
        // exact "aliasing view retained past the call" shape the finding
        // describes.
        let mut seed_aval = [0x1111_1111_1111_1111u64, 0x2222_2222_2222_2222u64];
        let mut seed_bval = [0x3333_3333_3333_3333u64, 0x4444_4444_4444_4444u64];
        sv_set_wide(
            h_a,
            slot,
            WideView {
                aval: seed_aval.as_mut_ptr(),
                bval: seed_bval.as_mut_ptr(),
                word_count: 2,
            },
        );
        let view_a = sv_get_wide(h_a, slot);
        assert_eq!(view_a.word_count, 2);

        // Finding scenario (b): a second, read-only-shaped `sv_get_wide`
        // call for a *different* instance's slot, with zero intervening
        // writes. Before the fix, this alone invalidated `view_a`'s
        // pointers under Miri.
        let view_b_probe = sv_get_wide(h_b, slot);
        assert_eq!(view_b_probe.word_count, 2);

        // `view_a` must still be dereferenceable and correct afterward.
        // SAFETY: `view_a` aliases instance A's own wide-plane words,
        // reserved for it (Task 7's disjoint-base guarantee) and still live
        // for this same test's `engine`/`handle_a`.
        unsafe {
            assert_eq!(std::slice::from_raw_parts(view_a.aval, 2), seed_aval);
            assert_eq!(std::slice::from_raw_parts(view_a.bval, 2), seed_bval);
        }

        // Finding scenario (a): a later wide-class write to a *different*
        // wide signal (instance B's slot) via `sv_set_wide` -- reaches
        // `write::write_slot`'s `wide_aval_mut`/`wide_bval_mut`-based arm.
        // Before the fix, this also invalidated `view_a`'s pointers under
        // Miri.
        let mut other_aval = [0x5555_5555_5555_5555u64, 0x6666_6666_6666_6666u64];
        let mut other_bval = [0x7777_7777_7777_7777u64, 0x8888_8888_8888_8888u64];
        sv_set_wide(
            h_b,
            slot,
            WideView {
                aval: other_aval.as_mut_ptr(),
                bval: other_bval.as_mut_ptr(),
                word_count: 2,
            },
        );

        // `view_a` must STILL be valid, readable, and writable through its
        // own raw pointers after that unrelated write -- and a fresh
        // `sv_get_wide` call must observe a write made directly through the
        // retained view, proving it still addresses the arena's real live
        // storage.
        // SAFETY: same reasoning as above; instance B's own disjoint base
        // means its write never touches instance A's words.
        unsafe {
            assert_eq!(std::slice::from_raw_parts(view_a.aval, 2), seed_aval);
            assert_eq!(std::slice::from_raw_parts(view_a.bval, 2), seed_bval);
            *view_a.aval.add(0) = 0x9999_9999_9999_9999;
        }
        let view_a_again = sv_get_wide(h_a, slot);
        // SAFETY: a fresh view over the same still-live slot.
        unsafe {
            assert_eq!(*view_a_again.aval, 0x9999_9999_9999_9999);
        }

        // SAFETY: reclaim the two handles this test leaked via
        // `into_sim_handle`, exactly as this module's other tests do.
        unsafe {
            drop(Box::from_raw(h_a.0 as *mut InstanceHandle));
            drop(Box::from_raw(h_b.0 as *mut InstanceHandle));
        }
    }
}