celox 0.11.0

Celox HDL 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
mod builder;
#[cfg(feature = "host-runtime")]
mod checkpoint;
mod error;
#[cfg(feature = "systemverilog")]
pub(crate) mod mixed;
#[cfg(feature = "host-runtime")]
mod state_file;

#[cfg(all(
    feature = "host-runtime",
    any(
        target_arch = "x86_64",
        feature = "arm64-codegen",
        target_arch = "aarch64"
    )
))]
pub use builder::NativeCompilation;
#[cfg(feature = "host-runtime")]
pub use builder::{DeadStorePolicy, SimulatorBuilder, SimulatorOptions, TierPromotion};
pub use builder::{compile_frontend_to_sir, compile_to_sir};
#[cfg(feature = "systemverilog")]
pub use builder::{compile_mixed_to_sir, compile_sv_to_sir};
#[cfg(feature = "host-runtime")]
pub use checkpoint::{Checkpoint, CheckpointError, StateImage};
pub use error::render_diagnostic;
pub use error::{CodegenError, CompilationWarning, SimulatorError, SimulatorErrorKind};
#[cfg(feature = "host-runtime")]
pub use state_file::{StateError, StateMismatch, StateSchema};

#[cfg(feature = "host-runtime")]
mod host {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

    use crate::backend::RuntimeEventBuffer;
    #[cfg(any(
        target_arch = "x86_64",
        feature = "arm64-codegen",
        target_arch = "aarch64"
    ))]
    use crate::backend::native::{NativeBackend, SharedNativeCode};
    use crate::{
        IOContext, RuntimeErrorCode,
        backend::{JitBackend, MemoryLayout, SharedJitCode, SimBackend},
        ir::{
            DisplaySizing, InitialMemoryData, InitialMemoryWriteRun, InstancePath,
            RuntimeEventKind, RuntimeEventSite, RuntimeProgram, SignalRef, VariableInfo,
        },
    };
    use celox_testbench::{
        DisplayFormatArg, FieldSpec, format_sv_display_arg, format_veryl_display_arg,
        pad_veryl_field,
    };
    use num_bigint::BigUint;

    /// Hierarchical instance tree with resolved signals.
    #[derive(Debug, Clone)]
    pub struct InstanceHierarchy {
        pub module_name: String,
        /// The index of this instance under its name: its element index in
        /// an instance array or generate loop, 0 otherwise.
        pub index: usize,
        /// Whether this instance's name takes an index (an instance array or
        /// generate loop), even when it is the only instance under the name.
        pub indexed: bool,
        pub signals: Vec<NamedSignal>,
        pub children: Vec<(String, Vec<InstanceHierarchy>)>,
    }

    /// A named signal with its resolved memory reference and metadata.
    #[derive(Debug, Clone)]
    pub struct NamedSignal {
        pub name: String,
        pub signal: SignalRef,
        pub info: VariableInfo,
        /// For reset signals, the name of the associated clock (from FfDeclaration).
        pub associated_clock: Option<String>,
    }

    /// A named event with its resolved ID and event reference.
    #[derive(Debug, Clone)]
    pub struct NamedEvent<B: SimBackend = crate::DefaultBackend> {
        pub name: String,
        pub id: usize,
        pub event_ref: B::Event,
    }

    /// The core logic evaluation engine.
    ///
    /// Encapsulates the backend, the original SIR program,
    /// and an optional VCD writer. Provides low-level, event-driven control.
    ///
    /// The default type parameter `B = DefaultBackend` means that bare `Simulator`
    /// uses the custom native backend on a matching host and Cranelift for
    /// cross-codegen builds or unsupported hosts.
    pub struct Simulator<B: SimBackend = crate::DefaultBackend> {
        pub(crate) backend: B,
        pub(crate) program: RuntimeProgram,
        pub(crate) vcd_writer: Option<crate::VcdWriter>,
        pub(crate) dirty: bool,
        pub(crate) warnings: Vec<CompilationWarning>,
        pub(crate) components: crate::component::ComponentRuntime,
        pub(crate) component_simulation: Option<celox_runtime::SimulationState<B>>,
        runtime_event_read_seq: Arc<AtomicU64>,
        runtime_event_drain_active: Arc<AtomicBool>,
        pub(super) comb_observer_snapshots: Vec<Vec<(BigUint, BigUint)>>,
        pub(super) comb_observer_initial_eval: bool,
        /// Identity of the state layout, computed on first checkpoint use.
        pub(super) checkpoint_fingerprint: std::sync::OnceLock<u64>,
        /// State objects as state files name them, built on first use.
        pub(super) state_schema: std::sync::OnceLock<Arc<state_file::StateSchema>>,
        pub(crate) diagnostics: crate::RuntimeDiagnostics,
        tick_timing_ticks: u64,
        tick_timing_eval_apply_ns: u64,
        tick_timing_eval_comb_ns: u64,
    }

    /// Why [`Simulator::try_dump`] failed.
    #[derive(Debug, thiserror::Error)]
    pub enum DumpError {
        #[error("evaluating combinational logic failed: {0}")]
        Runtime(RuntimeErrorCode),
        #[error(transparent)]
        Io(std::io::Error),
    }

    /// HDL output is an arbitrary sequence of 8-bit character codes.
    /// Message payloads are byte-exact; decode explicitly if text is required.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub enum RuntimeEvent {
        Display {
            message: Vec<u8>,
        },
        Write {
            message: Vec<u8>,
        },
        AssertContinue {
            message: Vec<u8>,
        },
        AssertFatal {
            message: Vec<u8>,
        },
        /// The design executed `$finish`. The host decides whether to stop.
        Finish,
        Missed {
            count: u64,
        },
    }

    #[derive(Debug, Clone, Copy, Default)]
    pub struct RuntimeFormatContext<'a> {
        pub tb_time: Option<u64>,
        pub scope: Option<&'a str>,
    }

    pub struct RuntimeEventDrain {
        buffer: Arc<RuntimeEventBuffer>,
        layout: MemoryLayout,
        sites: Vec<RuntimeEventSite>,
        read_seq: u64,
        shared_read_seq: Arc<AtomicU64>,
        active: Arc<AtomicBool>,
    }

    impl RuntimeEventDrain {
        pub fn drain(&mut self) -> Vec<RuntimeEvent> {
            self.drain_with_context(RuntimeFormatContext::default())
        }

        pub fn drain_with_context(&mut self, ctx: RuntimeFormatContext<'_>) -> Vec<RuntimeEvent> {
            let events = drain_raw_runtime_events_from_buffer(
                &self.buffer,
                &self.layout,
                &self.sites,
                &mut self.read_seq,
            );
            self.shared_read_seq.store(self.read_seq, Ordering::Release);
            events
                .into_iter()
                .filter_map(|raw| render_raw_runtime_event(raw, &self.sites, ctx))
                .collect()
        }
    }

    impl Drop for RuntimeEventDrain {
        fn drop(&mut self) {
            self.shared_read_seq.store(self.read_seq, Ordering::Release);
            self.active.store(false, Ordering::Release);
        }
    }

    impl<B: SimBackend> std::fmt::Debug for Simulator<B> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("Simulator").finish()
        }
    }

    #[derive(Clone)]
    struct RuntimeEventArgValue {
        values: Vec<u64>,
        masks: Vec<u64>,
        width: usize,
        signed: bool,
        is_string: bool,
    }

    #[derive(Clone)]
    enum RawRuntimeEvent {
        Event {
            site_id: usize,
            args: Vec<RuntimeEventArgValue>,
        },
        Missed {
            count: u64,
        },
    }

    fn runtime_event_words_to_biguint(words: &[u64], width: usize) -> BigUint {
        let mut value = BigUint::from(0u8);
        for (idx, word) in words.iter().enumerate() {
            value |= BigUint::from(*word) << (idx * 64);
        }
        if width > 0 {
            value & ((BigUint::from(1u8) << width) - BigUint::from(1u8))
        } else {
            BigUint::from(0u8)
        }
    }

    fn mask_width(value: BigUint, width: usize) -> BigUint {
        if width == 0 {
            BigUint::from(0u8)
        } else {
            value & ((BigUint::from(1u8) << width) - BigUint::from(1u8))
        }
    }

    fn slice_biguint(value: &BigUint, lsb: usize, msb: usize) -> BigUint {
        if msb < lsb {
            return BigUint::from(0u8);
        }
        mask_width(value >> lsb, msb - lsb + 1)
    }

    fn write_bits_to_memory(mem: &mut [u8], dst_bit_offset: usize, bit_width: usize, src: &[u8]) {
        write_bits_to_memory_from(mem, dst_bit_offset, bit_width, src, 0);
    }

    fn write_bits_to_memory_from(
        mem: &mut [u8],
        dst_bit_offset: usize,
        bit_width: usize,
        src: &[u8],
        src_bit_offset: usize,
    ) {
        for bit in 0..bit_width {
            let src_bit_index = src_bit_offset + bit;
            let src_bit = (src[src_bit_index / 8] >> (src_bit_index % 8)) & 1;
            let dst_idx = (dst_bit_offset + bit) / 8;
            let dst_mask = 1u8 << ((dst_bit_offset + bit) % 8);
            if src_bit == 0 {
                mem[dst_idx] &= !dst_mask;
            } else {
                mem[dst_idx] |= dst_mask;
            }
        }
    }

    fn write_initial_run_to_plane(
        mem: &mut [u8],
        signal: SignalRef,
        mask_plane: bool,
        run: &InitialMemoryWriteRun,
        src: &[u8],
    ) {
        let Some(array) = signal.array_layout else {
            let plane_size = signal.width.div_ceil(8);
            let plane_bit_offset =
                (signal.offset + usize::from(mask_plane) * plane_size) * 8 + run.bit_offset;
            write_bits_to_memory(mem, plane_bit_offset, run.bit_width, src);
            return;
        };

        let plane_offset = signal.offset + usize::from(mask_plane) * array.plane_size;
        let mut consumed = 0usize;
        while consumed < run.bit_width {
            let logical_offset = run.bit_offset + consumed;
            let element = logical_offset / array.element_width;
            let intra_element = logical_offset % array.element_width;
            let part_width = (run.bit_width - consumed).min(array.element_width - intra_element);
            let destination_bit_offset =
                (plane_offset + element * array.element_stride) * 8 + intra_element;

            if consumed.is_multiple_of(8)
                && destination_bit_offset.is_multiple_of(8)
                && part_width.is_multiple_of(8)
            {
                let src_byte = consumed / 8;
                let dst_byte = destination_bit_offset / 8;
                let byte_width = part_width / 8;
                mem[dst_byte..dst_byte + byte_width]
                    .copy_from_slice(&src[src_byte..src_byte + byte_width]);
            } else {
                write_bits_to_memory_from(mem, destination_bit_offset, part_width, src, consumed);
            }
            consumed += part_width;
        }
    }

    fn runtime_event_format_arg(
        arg: &RuntimeEventArgValue,
        spec: char,
        sizing: DisplaySizing,
        field: FieldSpec,
    ) -> Vec<u8> {
        let value = runtime_event_words_to_biguint(&arg.values, arg.width);
        let mask = runtime_event_words_to_biguint(&arg.masks, arg.width);
        let arg = DisplayFormatArg {
            value: &value,
            mask: Some(&mask),
            width: arg.width,
            signed: arg.signed,
            is_string: arg.is_string,
        };
        match sizing {
            DisplaySizing::Veryl => format_veryl_display_arg(&arg, spec, field),
            DisplaySizing::Ieee => format_sv_display_arg(&arg, spec, field),
        }
    }

    fn render_runtime_event_message(
        site: &RuntimeEventSite,
        args: &[RuntimeEventArgValue],
        ctx: RuntimeFormatContext<'_>,
    ) -> Vec<u8> {
        let Some(template) = site.template.as_deref() else {
            let default_spec = match site.kind {
                // Veryl prints arguments without a format string in hexadecimal.
                RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish
                    if site.sizing == DisplaySizing::Veryl =>
                {
                    'x'
                }
                RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish => {
                    'd'
                }
                RuntimeEventKind::AssertContinue | RuntimeEventKind::AssertFatal => {
                    if args.is_empty() {
                        return b"assertion failed".to_vec();
                    }
                    'x'
                }
            };
            return args
                .iter()
                .map(|arg| {
                    runtime_event_format_arg(arg, default_spec, site.sizing, FieldSpec::default())
                })
                .collect::<Vec<_>>()
                .join(&b' ');
        };
        let mut out = Vec::new();
        let mut arg_idx = 0usize;
        let mut chars = template.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch != '%' {
                out.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes());
                continue;
            }
            if matches!(chars.peek(), Some('%')) {
                chars.next();
                out.push(b'%');
                continue;
            }
            let field = FieldSpec::parse(&mut chars, true);
            let spec = chars.next().unwrap_or('d');
            match spec {
                'x' | 'h' | 'X' | 'H' | 'b' | 'B' | 'o' | 'O' | 'c' | 'C' | 's' | 'S' => {
                    let Some(arg) = args.get(arg_idx) else {
                        arg_idx += 1;
                        continue;
                    };
                    out.extend_from_slice(&runtime_event_format_arg(arg, spec, site.sizing, field));
                    arg_idx += 1;
                }
                'd' | 'D' | 'i' | 'I' => {
                    let Some(arg) = args.get(arg_idx) else {
                        arg_idx += 1;
                        continue;
                    };
                    out.extend_from_slice(&runtime_event_format_arg(arg, spec, site.sizing, field));
                    arg_idx += 1;
                }
                't' | 'T' if site.sizing == DisplaySizing::Ieee => {
                    let Some(arg) = args.get(arg_idx) else {
                        arg_idx += 1;
                        continue;
                    };
                    let field = FieldSpec {
                        width: Some(field.width.unwrap_or(20)),
                        ..field
                    };
                    out.extend_from_slice(&runtime_event_format_arg(arg, 'd', site.sizing, field));
                    arg_idx += 1;
                }
                't' | 'T' | 'm' | 'M' => {
                    let text = if matches!(spec, 't' | 'T') {
                        ctx.tb_time.unwrap_or(0).to_string()
                    } else {
                        ctx.scope
                            .or(site.scope.as_deref())
                            .unwrap_or("<hierarchy>")
                            .to_string()
                    };
                    out.extend_from_slice(&match site.sizing {
                        DisplaySizing::Veryl => pad_veryl_field(text.into_bytes(), spec, field),
                        DisplaySizing::Ieee => text.into_bytes(),
                    });
                }
                other => {
                    out.push(b'%');
                    out.extend_from_slice(other.encode_utf8(&mut [0; 4]).as_bytes());
                }
            }
        }
        out
    }

    fn render_raw_runtime_event(
        raw: RawRuntimeEvent,
        sites: &[RuntimeEventSite],
        ctx: RuntimeFormatContext<'_>,
    ) -> Option<RuntimeEvent> {
        match raw {
            RawRuntimeEvent::Missed { count } => Some(RuntimeEvent::Missed { count }),
            RawRuntimeEvent::Event { site_id, args } => {
                let site = sites.get(site_id)?;
                let message = render_runtime_event_message(site, &args, ctx);
                Some(match site.kind {
                    RuntimeEventKind::Display => RuntimeEvent::Display { message },
                    RuntimeEventKind::Write => RuntimeEvent::Write { message },
                    RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message },
                    RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message },
                    RuntimeEventKind::Finish => RuntimeEvent::Finish,
                })
            }
        }
    }

    fn collect_runtime_events(
        layout: &MemoryLayout,
        sites: &[RuntimeEventSite],
        read_seq: &mut u64,
        buffer_size: usize,
        mut read_payload_u64: impl FnMut(usize) -> u64,
        mut read_seq_u64: impl FnMut(usize) -> u64,
    ) -> Vec<RawRuntimeEvent> {
        use crate::backend::memory_layout::{
            RUNTIME_EVENT_HEADER_SIZE, RUNTIME_EVENT_SLOT_ARG_COUNT_OFFSET,
            RUNTIME_EVENT_SLOT_PAYLOAD_OFFSET, RUNTIME_EVENT_SLOT_SEQ_OFFSET,
            RUNTIME_EVENT_SLOT_SITE_OFFSET, RUNTIME_EVENT_WRITING,
        };

        if RUNTIME_EVENT_HEADER_SIZE > buffer_size || layout.runtime_event_capacity == 0 {
            return Vec::new();
        }

        // Ring-buffer synchronization protocol:
        // - writers store event payload/site/arg fields normally;
        // - writers publish slot/global sequence words with release semantics;
        // - readers acquire-load sequence words, then read payload normally;
        // - readers re-check the slot sequence after reading payload to reject races.
        let write_seq = read_seq_u64(0);
        let mut events = Vec::new();
        let capacity = layout.runtime_event_capacity as u64;
        if *read_seq + capacity < write_seq {
            let new_read = write_seq - capacity;
            events.push(RawRuntimeEvent::Missed {
                count: new_read - *read_seq,
            });
            *read_seq = new_read;
        }

        while *read_seq < write_seq {
            let seq = *read_seq;
            let slot = (seq as usize) & (layout.runtime_event_capacity - 1);
            let slot_base = RUNTIME_EVENT_HEADER_SIZE + slot * layout.runtime_event_slot_size;
            let published = read_seq_u64(slot_base + RUNTIME_EVENT_SLOT_SEQ_OFFSET);
            if published == RUNTIME_EVENT_WRITING || published != seq {
                break;
            }

            let site_id = read_payload_u64(slot_base + RUNTIME_EVENT_SLOT_SITE_OFFSET) as usize;
            let site = sites.get(site_id);
            let site_layout = layout.runtime_event_site_layouts.get(site_id);
            let arg_count =
                read_payload_u64(slot_base + RUNTIME_EVENT_SLOT_ARG_COUNT_OFFSET) as usize;
            let arg_count = site
                .map(|site| arg_count.min(site.arg_widths.len()))
                .unwrap_or(0);
            let mut args = Vec::with_capacity(arg_count);
            if let Some(site_layout) = site_layout {
                for idx in 0..arg_count {
                    let Some(arg_layout) = site_layout.args.get(idx) else {
                        break;
                    };
                    let mut values = Vec::with_capacity(arg_layout.word_count);
                    let mut masks = Vec::with_capacity(arg_layout.word_count);
                    for word_idx in 0..arg_layout.word_count {
                        values.push(read_payload_u64(
                            slot_base
                                + RUNTIME_EVENT_SLOT_PAYLOAD_OFFSET
                                + (arg_layout.value_word_offset + word_idx) * 8,
                        ));
                        masks.push(read_payload_u64(
                            slot_base
                                + RUNTIME_EVENT_SLOT_PAYLOAD_OFFSET
                                + (arg_layout.mask_word_offset + word_idx) * 8,
                        ));
                    }
                    args.push(RuntimeEventArgValue {
                        values,
                        masks,
                        width: site
                            .and_then(|site| site.arg_widths.get(idx).copied())
                            .unwrap_or(64),
                        signed: site
                            .and_then(|site| site.arg_signed.get(idx).copied())
                            .unwrap_or(false),
                        is_string: site
                            .and_then(|site| site.arg_is_string.get(idx).copied())
                            .unwrap_or(false),
                    });
                }
            }

            let published_after = read_seq_u64(slot_base + RUNTIME_EVENT_SLOT_SEQ_OFFSET);
            if published_after == RUNTIME_EVENT_WRITING || published_after != seq {
                break;
            }

            if site.is_some() {
                events.push(RawRuntimeEvent::Event { site_id, args });
            }
            *read_seq += 1;
        }

        events
    }

    fn drain_raw_runtime_events_from_buffer(
        buffer: &RuntimeEventBuffer,
        layout: &MemoryLayout,
        sites: &[RuntimeEventSite],
        read_seq: &mut u64,
    ) -> Vec<RawRuntimeEvent> {
        use std::sync::atomic::Ordering;

        collect_runtime_events(
            layout,
            sites,
            read_seq,
            buffer.byte_size(),
            |offset| buffer.read_u64(offset),
            |offset| buffer.load_atomic_u64(offset, Ordering::Acquire),
        )
    }

    #[cfg(any(
        target_arch = "x86_64",
        feature = "arm64-codegen",
        target_arch = "aarch64"
    ))]
    pub(crate) fn runtime_event_write_seq_for_backend<B: SimBackend>(backend: &B) -> u64 {
        if let Some(buffer) = backend.runtime_event_buffer() {
            buffer.load_atomic_u64(0, std::sync::atomic::Ordering::Acquire)
        } else {
            let (pointer, size) = backend.runtime_event_buffer_as_ptr();
            if size < std::mem::size_of::<u64>() {
                return 0;
            }
            // Safety: the backend contract exposes `size` readable bytes.
            unsafe { std::ptr::read_volatile(pointer.cast::<u64>()) }
        }
    }

    #[cfg(any(
        target_arch = "x86_64",
        feature = "arm64-codegen",
        target_arch = "aarch64"
    ))]
    pub(crate) fn collect_runtime_events_for_backend<B: SimBackend>(
        backend: &B,
        sites: &[RuntimeEventSite],
        read_seq: &mut u64,
        context: RuntimeFormatContext<'_>,
    ) -> Vec<RuntimeEvent> {
        let layout = backend.layout();
        let raw = if let Some(buffer) = backend.runtime_event_buffer() {
            collect_runtime_events(
                layout,
                sites,
                read_seq,
                buffer.byte_size(),
                |offset| buffer.read_u64(offset),
                |offset| buffer.load_atomic_u64(offset, std::sync::atomic::Ordering::Acquire),
            )
        } else {
            let (pointer, size) = backend.runtime_event_buffer_as_ptr();
            let read_u64 = |offset: usize| -> u64 {
                // Safety: `collect_runtime_events` bounds every access by `size`.
                unsafe { std::ptr::read_volatile(pointer.add(offset).cast::<u64>()) }
            };
            collect_runtime_events(layout, sites, read_seq, size, read_u64, read_u64)
        };
        raw.into_iter()
            .filter_map(|event| render_raw_runtime_event(event, sites, context))
            .collect()
    }

    // ── Generic methods available for any backend ────────────────────────
    impl<B: SimBackend> Simulator<B> {
        pub(crate) fn decorate_runtime_error(&self, err: RuntimeErrorCode) -> RuntimeErrorCode {
            match err {
                RuntimeErrorCode::DetectedTrueLoopCode(code) => {
                    if self.comb_fatal_site(code).is_some() {
                        return RuntimeErrorCode::Runtime {
                            message: "Fatal assertion (runtime event record overwritten)"
                                .to_string(),
                            signals: Vec::new(),
                        };
                    }
                    let Some(info) = self.program.runtime_schema.runtime_errors.get(&code) else {
                        return RuntimeErrorCode::DetectedTrueLoop;
                    };
                    let signals = info
                        .signals
                        .iter()
                        .map(|addr| self.program.get_path(addr))
                        .collect::<Vec<_>>();
                    if info.message == "Detected True Loop" {
                        RuntimeErrorCode::DetectedTrueLoopAt { signals }
                    } else {
                        RuntimeErrorCode::Runtime {
                            message: info.message.clone(),
                            signals,
                        }
                    }
                }
                other => other,
            }
        }

        pub fn with_backend_and_program(
            backend: B,
            program: RuntimeProgram,
            warnings: Vec<CompilationWarning>,
        ) -> Self {
            let mut sim = Self {
                backend,
                program,
                vcd_writer: None,
                dirty: false,
                warnings,
                components: Default::default(),
                component_simulation: None,
                runtime_event_read_seq: Arc::new(AtomicU64::new(0)),
                runtime_event_drain_active: Arc::new(AtomicBool::new(false)),
                comb_observer_snapshots: Vec::new(),
                comb_observer_initial_eval: true,
                checkpoint_fingerprint: std::sync::OnceLock::new(),
                state_schema: std::sync::OnceLock::new(),
                diagnostics: crate::RuntimeDiagnostics::default(),
                tick_timing_ticks: 0,
                tick_timing_eval_apply_ns: 0,
                tick_timing_eval_comb_ns: 0,
            };
            sim.comb_observer_snapshots = sim.snapshot_all_comb_observers();
            sim
        }

        fn record_tick_timing(&mut self, eval_apply_ns: u64, eval_comb_ns: u64) {
            let Some(every) = self.diagnostics.tick_timing_every else {
                return;
            };
            if every == 0 {
                return;
            }
            self.tick_timing_ticks = self.tick_timing_ticks.saturating_add(1);
            self.tick_timing_eval_apply_ns =
                self.tick_timing_eval_apply_ns.saturating_add(eval_apply_ns);
            self.tick_timing_eval_comb_ns =
                self.tick_timing_eval_comb_ns.saturating_add(eval_comb_ns);
            if self.tick_timing_ticks.is_multiple_of(every) {
                tracing::debug!(
                    "[tick-timing] ticks={} eval_apply_ms={:.3} eval_comb_ms={:.3} avg_apply_us={:.3} avg_comb_us={:.3}",
                    self.tick_timing_ticks,
                    self.tick_timing_eval_apply_ns as f64 / 1_000_000.0,
                    self.tick_timing_eval_comb_ns as f64 / 1_000_000.0,
                    self.tick_timing_eval_apply_ns as f64 / self.tick_timing_ticks as f64 / 1_000.0,
                    self.tick_timing_eval_comb_ns as f64 / self.tick_timing_ticks as f64 / 1_000.0,
                );
            }
        }

        pub(crate) fn apply_initial_values(&mut self) {
            let mut applied = false;
            let initial_memory_values = self.program.design.take_initial_state();
            for init in &initial_memory_values {
                applied = true;
                let signal = self.backend.resolve_signal(&init.address);
                match &init.data {
                    InitialMemoryData::Packed {
                        value,
                        mask,
                        written_mask,
                    } => {
                        let width_mask = if signal.width == 0 {
                            BigUint::default()
                        } else {
                            (BigUint::from(1u8) << signal.width) - BigUint::from(1u8)
                        };
                        let preserve_mask = &width_mask ^ (written_mask & &width_mask);
                        let (current_value, current_mask) = self.backend.get_four_state(signal);
                        let value = (current_value & &preserve_mask) | (value & written_mask);
                        let mask = (current_mask & &preserve_mask) | (mask & written_mask);
                        if self.backend.layout().four_state && signal.is_4state {
                            self.backend.set_four_state(signal, value, mask);
                        } else {
                            let known_mask = &width_mask ^ (&mask & &width_mask);
                            self.backend.set_wide(signal, value & known_mask);
                        }
                    }
                    InitialMemoryData::Writes(runs) => {
                        self.apply_initial_memory_writes(signal, runs);
                    }
                }
            }
            if applied {
                self.dirty = true;
            }
            self.program
                .design
                .restore_initial_state(initial_memory_values);
        }

        pub(crate) fn apply_testbench_memory_writes(
            &mut self,
            signal: SignalRef,
            runs: &[InitialMemoryWriteRun],
        ) {
            self.apply_initial_memory_writes(signal, runs);
            self.dirty = true;
        }

        fn apply_initial_memory_writes(
            &mut self,
            signal: SignalRef,
            runs: &[InitialMemoryWriteRun],
        ) {
            let value_byte_size = signal.width.div_ceil(8);
            let write_mask = self.backend.layout().four_state && signal.is_4state;
            // Initial writes precede the first full dump; no mutable view escapes.
            let (ptr, mem_len) = self.backend.memory_as_ptr();
            let ptr = ptr.cast_mut();
            let mem = unsafe { std::slice::from_raw_parts_mut(ptr, mem_len) };

            for run in runs {
                if run.bit_width == 0 {
                    continue;
                }
                if signal.array_layout.is_some() {
                    write_initial_run_to_plane(mem, signal, false, run, &run.value_bytes);
                    if write_mask {
                        write_initial_run_to_plane(mem, signal, true, run, &run.mask_bytes);
                    }
                    continue;
                }
                if run.bit_offset % 8 == 0 && run.bit_width % 8 == 0 {
                    let byte_offset = run.bit_offset / 8;
                    let byte_width = run.bit_width / 8;
                    let value_offset = signal.offset + byte_offset;
                    mem[value_offset..value_offset + byte_width]
                        .copy_from_slice(&run.value_bytes[..byte_width]);
                    if write_mask {
                        let mask_offset = signal.offset + value_byte_size + byte_offset;
                        mem[mask_offset..mask_offset + byte_width]
                            .copy_from_slice(&run.mask_bytes[..byte_width]);
                    }
                    continue;
                }

                write_bits_to_memory(
                    mem,
                    signal.offset * 8 + run.bit_offset,
                    run.bit_width,
                    &run.value_bytes,
                );
                if write_mask {
                    write_bits_to_memory(
                        mem,
                        (signal.offset + value_byte_size) * 8 + run.bit_offset,
                        run.bit_width,
                        &run.mask_bytes,
                    );
                }
            }
        }

        /// Drain runtime events, lazily evaluating dirty combinational logic.
        /// Fatal assertions encountered during evaluation are returned as
        /// [`RuntimeEvent::AssertFatal`] records so the host can handle them.
        pub fn drain_runtime_events(&mut self) -> Vec<RuntimeEvent> {
            self.drain_runtime_events_with_context(RuntimeFormatContext::default())
        }

        pub fn drain_runtime_events_with_context(
            &mut self,
            ctx: RuntimeFormatContext<'_>,
        ) -> Vec<RuntimeEvent> {
            assert!(
                !self.runtime_event_drain_active.load(Ordering::Acquire),
                "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active",
            );
            if self.dirty {
                self.eval_comb_for_runtime_event_drain().unwrap();
            }
            self.collect_formatted_runtime_events(ctx)
        }

        pub(crate) fn drain_runtime_events_deferred_with_context(
            &mut self,
            ctx: RuntimeFormatContext<'_>,
        ) -> Vec<RuntimeEvent> {
            assert!(
                !self.runtime_event_drain_active.load(Ordering::Acquire),
                "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active",
            );
            if !self.program.runtime_schema.comb_observers.is_empty() && self.dirty {
                self.eval_comb_for_runtime_event_drain().unwrap();
            }
            self.collect_formatted_runtime_events(ctx)
        }

        fn eval_comb_for_runtime_event_drain(&mut self) -> Result<(), RuntimeErrorCode> {
            let (result, _) = self.eval_comb_capturing_events();
            self.check_comb_backend_result(result)?;
            self.dirty = false;
            Ok(())
        }

        fn check_comb_backend_result(
            &self,
            result: Result<(), RuntimeErrorCode>,
        ) -> Result<(), RuntimeErrorCode> {
            // The status itself identifies a fatal capture even when its
            // record has been overwritten in the bounded event buffer.
            match result {
                Err(RuntimeErrorCode::DetectedTrueLoopCode(code))
                    if self.comb_fatal_site(code).is_some() =>
                {
                    Ok(())
                }
                other => other.map_err(|error| self.decorate_runtime_error(error)),
            }
        }

        fn comb_fatal_site(&self, code: i64) -> Option<&RuntimeEventSite> {
            let site = self
                .program
                .runtime_schema
                .runtime_event_sites
                .get(celox_runtime::comb_fatal_site(code)? as usize)?;
            matches!(site.kind, RuntimeEventKind::AssertFatal).then_some(site)
        }

        fn collect_formatted_runtime_events(
            &mut self,
            ctx: RuntimeFormatContext<'_>,
        ) -> Vec<RuntimeEvent> {
            if self.runtime_event_read_seq.load(Ordering::Acquire) == self.runtime_event_write_seq()
            {
                return Vec::new();
            }
            self.collect_backend_runtime_events()
                .into_iter()
                .filter_map(|raw| {
                    render_raw_runtime_event(
                        raw,
                        &self.program.runtime_schema.runtime_event_sites,
                        ctx,
                    )
                })
                .collect()
        }

        fn collect_backend_runtime_events(&mut self) -> Vec<RawRuntimeEvent> {
            let layout = self.backend.layout();
            let mut read_seq = self.runtime_event_read_seq.load(Ordering::Acquire);
            if let Some(buffer) = self.backend.runtime_event_buffer() {
                let events = collect_runtime_events(
                    layout,
                    &self.program.runtime_schema.runtime_event_sites,
                    &mut read_seq,
                    buffer.byte_size(),
                    |offset| buffer.read_u64(offset),
                    |offset| buffer.load_atomic_u64(offset, std::sync::atomic::Ordering::Acquire),
                );
                self.runtime_event_read_seq
                    .store(read_seq, Ordering::Release);
                events
            } else {
                let (ptr, size) = self.backend.runtime_event_buffer_as_ptr();
                let read_u64 = |offset: usize| -> u64 {
                    unsafe { std::ptr::read_volatile(ptr.add(offset) as *const u64) }
                };
                let events = collect_runtime_events(
                    layout,
                    &self.program.runtime_schema.runtime_event_sites,
                    &mut read_seq,
                    size,
                    read_u64,
                    read_u64,
                );
                self.runtime_event_read_seq
                    .store(read_seq, Ordering::Release);
                events
            }
        }

        fn runtime_event_write_seq(&self) -> u64 {
            if let Some(buffer) = self.backend.runtime_event_buffer() {
                buffer.load_atomic_u64(0, std::sync::atomic::Ordering::Acquire)
            } else {
                let (ptr, _size) = self.backend.runtime_event_buffer_as_ptr();
                unsafe { std::ptr::read_volatile(ptr as *const u64) }
            }
        }

        fn peek_backend_runtime_events_from(&self, read_seq: u64) -> Vec<RawRuntimeEvent> {
            let mut read_seq = read_seq;
            let layout = self.backend.layout();
            if let Some(buffer) = self.backend.runtime_event_buffer() {
                collect_runtime_events(
                    layout,
                    &self.program.runtime_schema.runtime_event_sites,
                    &mut read_seq,
                    buffer.byte_size(),
                    |offset| buffer.read_u64(offset),
                    |offset| buffer.load_atomic_u64(offset, std::sync::atomic::Ordering::Acquire),
                )
            } else {
                let (ptr, size) = self.backend.runtime_event_buffer_as_ptr();
                let read_u64 = |offset: usize| -> u64 {
                    unsafe { std::ptr::read_volatile(ptr.add(offset) as *const u64) }
                };
                collect_runtime_events(
                    layout,
                    &self.program.runtime_schema.runtime_event_sites,
                    &mut read_seq,
                    size,
                    read_u64,
                    read_u64,
                )
            }
        }

        pub fn runtime_event_drain(&mut self) -> Option<RuntimeEventDrain> {
            let buffer = self.backend.runtime_event_buffer()?;
            self.runtime_event_drain_active
                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
                .ok()?;
            Some(RuntimeEventDrain {
                buffer,
                layout: self.backend.layout().clone(),
                sites: self.program.runtime_schema.runtime_event_sites.clone(),
                read_seq: self.runtime_event_read_seq.load(Ordering::Acquire),
                shared_read_seq: Arc::clone(&self.runtime_event_read_seq),
                active: Arc::clone(&self.runtime_event_drain_active),
            })
        }

        /// Returns a reference to the compiled SIR program.
        pub fn program(&self) -> &RuntimeProgram {
            &self.program
        }

        /// Returns a reference to the backend (for signal/event resolution).
        pub fn backend_ref(&self) -> &B {
            &self.backend
        }

        /// Returns warnings emitted during compilation.
        pub fn warnings(&self) -> &[CompilationWarning] {
            &self.warnings
        }

        /// Captures the current state of all signals and writes them to the VCD file.
        ///
        /// # Panics
        ///
        /// Panics where [`Self::try_dump`] returns an error.
        pub fn dump(&mut self, timestamp: u64) {
            if let Err(error) = self.try_dump(timestamp) {
                panic!("VCD dump at {timestamp} failed: {error}");
            }
        }

        /// Captures the current state of all signals and writes them to the
        /// VCD file. Fails if combinational evaluation or writing fails, or
        /// if `timestamp` is earlier than the last dumped timestamp.
        pub fn try_dump(&mut self, timestamp: u64) -> Result<(), DumpError> {
            if self.dirty {
                self.eval_comb_checked().map_err(DumpError::Runtime)?;
                self.dirty = false;
            }
            let component_traces = self.components.trace_values();
            if let Some(ref mut writer) = self.vcd_writer {
                writer
                    .dump_backend(timestamp, &mut self.backend, &component_traces)
                    .map_err(DumpError::Io)?;
            }
            Ok(())
        }

        /// Dump unless `timestamp` precedes what the VCD file already
        /// records, as after `run_until` to an earlier time.
        pub(crate) fn dump_unless_rewound(&mut self, timestamp: u64) {
            let rewound = self
                .vcd_writer
                .as_ref()
                .and_then(|writer| writer.last_timestamp())
                .is_some_and(|last| timestamp < last);
            if !rewound {
                self.dump(timestamp);
            }
        }

        /// Reject a return to `time` if the VCD file has already passed it.
        pub(crate) fn check_vcd_rewind(&self, time: u64) -> Result<(), CheckpointError> {
            match self
                .vcd_writer
                .as_ref()
                .and_then(|writer| writer.last_timestamp())
            {
                Some(last_dumped) if time < last_dumped => {
                    Err(CheckpointError::VcdRewind { time, last_dumped })
                }
                _ => Ok(()),
            }
        }

        /// Finish the current VCD file and continue the waveform in a new
        /// file at `path`, whose timestamps start over. Use it to record a
        /// simulation rewound by a restore. Fails if the simulator was built
        /// without VCD output.
        pub fn switch_vcd(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
            let writer = self.vcd_writer.as_mut().ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "VCD output was not enabled when the simulator was built",
                )
            })?;
            writer.restart(path)
        }

        /// Make buffered waveform output visible and report write errors.
        pub fn flush_vcd(&mut self) -> std::io::Result<()> {
            if let Some(writer) = self.vcd_writer.as_mut() {
                writer.flush()?;
            }
            Ok(())
        }

        pub fn vcd_statistics(&self) -> Option<celox_runtime::VcdStatistics> {
            self.vcd_writer.as_ref().map(crate::VcdWriter::statistics)
        }

        /// Sets a signal value and marks combinational logic as dirty.
        /// Copies the value's little-endian bytes, zero-extending shorter
        /// values and truncating bits beyond the signal width. Integer type
        /// size does not need to match the signal storage size.
        pub fn set<T: Copy>(&mut self, signal: SignalRef, val: T) {
            self.backend.set(signal, val);
            self.dirty = true;
            self.settle_dirty_for_runtime_event_drain();
        }

        /// Sets a wide signal value and marks combinational logic as dirty.
        pub fn set_wide(&mut self, signal: SignalRef, val: BigUint) {
            self.backend.set_wide(signal, val);
            self.dirty = true;
            self.settle_dirty_for_runtime_event_drain();
        }

        /// Sets a four-state signal value and marks combinational logic as dirty.
        pub fn set_four_state(&mut self, signal: SignalRef, val: BigUint, mask: BigUint) {
            self.backend.set_four_state(signal, val, mask);
            self.dirty = true;
            self.settle_dirty_for_runtime_event_drain();
        }

        /// Modifies internal state via a callback and marks combinational logic as dirty.
        pub fn modify<F>(&mut self, f: F) -> Result<(), RuntimeErrorCode>
        where
            F: FnOnce(&mut IOContext<B>),
        {
            let mut ctx = IOContext {
                backend: &mut self.backend,
            };
            f(&mut ctx);
            self.dirty = true;
            if self.runtime_event_drain_active.load(Ordering::Acquire) {
                self.eval_comb_for_runtime_event_drain()?;
            }
            Ok(())
        }

        pub(super) fn settle_dirty_for_runtime_event_drain(&mut self) {
            if self.runtime_event_drain_active.load(Ordering::Acquire) {
                self.eval_comb_for_runtime_event_drain().unwrap();
            }
        }

        pub(crate) fn eval_comb_checked(&mut self) -> Result<(), RuntimeErrorCode> {
            let (result, events) = self.eval_comb_capturing_events();
            let fatal_status = matches!(
                &result,
                Err(RuntimeErrorCode::DetectedTrueLoopCode(code)) if self.comb_fatal_site(*code).is_some()
            );
            // Check the original backend code before formatting fatal records:
            // another parallel lane may have reported a loop or internal error.
            self.check_comb_backend_result(result)?;
            if let Some(error) = self.fatal_comb_capture_error(&events) {
                return Err(error);
            }
            if fatal_status {
                return Err(RuntimeErrorCode::Runtime {
                    message: "Fatal assertion (runtime event record overwritten)".to_string(),
                    signals: Vec::new(),
                });
            }
            Ok(())
        }

        fn eval_comb_capturing_events(
            &mut self,
        ) -> (Result<(), RuntimeErrorCode>, Vec<RawRuntimeEvent>) {
            if self.program.runtime_schema.runtime_event_sites.is_empty() {
                return (self.backend.eval_comb(), Vec::new());
            }
            let runtime_event_start_seq = self.runtime_event_write_seq();
            if self.program.runtime_schema.comb_observers.is_empty() {
                let result = self.backend.eval_comb();
                let events = self.peek_backend_runtime_events_from(runtime_event_start_seq);
                return (result, events);
            }

            let before = self.snapshot_all_comb_observers();
            let active_before: Vec<bool> = before
                .iter()
                .zip(&self.comb_observer_snapshots)
                .map(|(now, prev)| now != prev)
                .collect();
            let mut active_sites =
                vec![false; self.program.runtime_schema.runtime_event_sites.len()];
            for (observer, is_active) in self
                .program
                .runtime_schema
                .comb_observers
                .iter()
                .zip(active_before.iter().copied())
            {
                if is_active || self.comb_observer_initial_eval {
                    let group = observer.activation_group;
                    for group_observer in &self.program.runtime_schema.comb_observers {
                        if group_observer.activation_group == group {
                            active_sites[group_observer.site_id as usize] = true;
                        }
                    }
                }
            }
            self.backend.set_comb_capture_event_enabled(&active_sites);
            let eval_result = self.backend.eval_comb();
            let after = self.snapshot_all_comb_observers();
            let runtime_events = self.peek_backend_runtime_events_from(runtime_event_start_seq);
            self.backend.set_comb_capture_event_enabled(&vec![
                false;
                self.program
                    .runtime_schema
                    .runtime_event_sites
                    .len()
            ]);
            self.comb_observer_snapshots = after;
            self.comb_observer_initial_eval = false;
            (eval_result, runtime_events)
        }

        pub(super) fn snapshot_all_comb_observers(&self) -> Vec<Vec<(BigUint, BigUint)>> {
            self.program
                .runtime_schema
                .comb_observers
                .iter()
                .map(|observer| {
                    observer
                        .sensitivity
                        .iter()
                        .map(|atom| {
                            let signal = self.backend.resolve_signal(&atom.id);
                            let (value, mask) = if signal.is_4state {
                                self.backend.get_four_state(signal)
                            } else {
                                (self.backend.get(signal), BigUint::default())
                            };
                            (
                                slice_biguint(&value, atom.access.lsb, atom.access.msb),
                                slice_biguint(&mask, atom.access.lsb, atom.access.msb),
                            )
                        })
                        .collect()
                })
                .collect()
        }

        fn fatal_comb_capture_error(&self, events: &[RawRuntimeEvent]) -> Option<RuntimeErrorCode> {
            events.iter().find_map(|raw| {
                let RawRuntimeEvent::Event { site_id, args } = raw else {
                    return None;
                };
                let site = self
                    .program
                    .runtime_schema
                    .runtime_event_sites
                    .get(*site_id)?;
                if !matches!(site.kind, RuntimeEventKind::AssertFatal) {
                    return None;
                }
                Some(RuntimeErrorCode::Runtime {
                    message: message_diagnostic(&render_runtime_event_message(
                        site,
                        args,
                        RuntimeFormatContext::default(),
                    )),
                    signals: Vec::new(),
                })
            })
        }

        pub(crate) fn eval_apply_ff_at_checked(
            &mut self,
            event: B::Event,
        ) -> Result<(), RuntimeErrorCode> {
            self.backend
                .eval_apply_ff_at(event)
                .map_err(|e| self.decorate_runtime_error(e))
        }

        pub(crate) fn eval_comb_apply_ff_at_checked(
            &mut self,
            event: B::Event,
        ) -> Result<(), RuntimeErrorCode> {
            self.backend
                .eval_comb_apply_ff_at(event)
                .map_err(|e| self.decorate_runtime_error(e))
        }

        pub(crate) fn eval_only_ff_at_checked(
            &mut self,
            event: B::Event,
        ) -> Result<(), RuntimeErrorCode> {
            self.backend
                .eval_only_ff_at(event)
                .map_err(|e| self.decorate_runtime_error(e))
        }

        pub(crate) fn apply_ff_at_checked(
            &mut self,
            event: B::Event,
        ) -> Result<(), RuntimeErrorCode> {
            self.backend
                .apply_ff_at(event)
                .map_err(|e| self.decorate_runtime_error(e))
        }

        /// Manually triggers a clock or event to process sequential logic.
        pub fn tick(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> {
            let timing_enabled = self.diagnostics.tick_timing_every.is_some();
            let mut eval_comb_ns = 0u64;
            let mut eval_apply_ns = 0u64;
            if self.dirty {
                if timing_enabled {
                    let start = crate::timing::now();
                    self.eval_comb_checked()?;
                    eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64);
                    let start = crate::timing::now();
                    self.eval_apply_ff_at_checked(event)?;
                    eval_apply_ns = eval_apply_ns.saturating_add(start.elapsed().as_nanos() as u64);
                } else {
                    self.eval_comb_checked()?;
                    self.eval_apply_ff_at_checked(event)?;
                }
                self.dirty = false;
            } else {
                if timing_enabled {
                    let start = crate::timing::now();
                    self.eval_apply_ff_at_checked(event)?;
                    eval_apply_ns = eval_apply_ns.saturating_add(start.elapsed().as_nanos() as u64);
                } else {
                    self.eval_apply_ff_at_checked(event)?;
                }
            }
            if timing_enabled {
                let start = crate::timing::now();
                self.eval_comb_checked()?;
                eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64);
                self.record_tick_timing(eval_apply_ns, eval_comb_ns);
            } else {
                self.eval_comb_checked()?;
            }
            self.dirty = false;
            Ok(())
        }

        /// Advance several events as one coincident edge.
        ///
        /// Every triggered domain samples the state settled before the edge,
        /// then all of them update, then combinational logic settles once.
        /// This is the behaviour of clocks that share an edge in hardware,
        /// such as a divided clock and its source, which sequential
        /// [`Self::tick`] calls cannot express: each of them would settle
        /// the design between the domains. Events of the same domain are
        /// applied once. A single event behaves like [`Self::tick`].
        pub fn tick_events(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> {
            use celox_runtime::backend::EventHandle;
            // Deduplicate domains before requiring split kernels: a design
            // with a single domain has no split kernels, and aliases of one
            // domain are an ordinary tick.
            let mut unique: Vec<(crate::ir::AbsoluteAddr, B::Event)> =
                Vec::with_capacity(events.len());
            for event in events {
                let addr = self.backend.id_to_addr_slice()[event.id()];
                let canonical = self.program.design.events.canonical(addr);
                if unique.iter().all(|(existing, _)| *existing != canonical) {
                    unique.push((canonical, *event));
                }
            }
            // Split kernels exist for every active domain once a design has
            // more than one. A domain without them drives no FF, unless the
            // design has at most one active domain and no split kernels at
            // all; then ticking each event in turn is exact, because at most
            // one of them changes state.
            let mut domains = Vec::with_capacity(unique.len());
            let mut unsplit = Vec::new();
            for (canonical, event) in unique {
                match (
                    self.backend.resolve_eval_only_event(&canonical),
                    self.backend.resolve_apply_event(&canonical),
                ) {
                    (Some(eval_only), Some(apply)) => domains.push((event, eval_only, apply)),
                    _ => unsplit.push(event),
                }
            }
            match domains.as_slice() {
                [] => {
                    for event in unsplit {
                        self.tick(event)?;
                    }
                    return Ok(());
                }
                [(event, _, _)] => return self.tick(*event),
                _ => {}
            }
            let timing_enabled = self.diagnostics.tick_timing_every.is_some();
            let mut eval_comb_ns = 0u64;
            let mut eval_apply_ns = 0u64;
            if self.dirty {
                let start = timing_enabled.then(crate::timing::now);
                self.eval_comb_checked()?;
                if let Some(start) = start {
                    eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64);
                }
                self.dirty = false;
            }
            let start = timing_enabled.then(crate::timing::now);
            for (_, eval_only, _) in &domains {
                self.eval_only_ff_at_checked(*eval_only)?;
            }
            for (_, _, apply) in &domains {
                self.apply_ff_at_checked(*apply)?;
            }
            if let Some(start) = start {
                eval_apply_ns = eval_apply_ns.saturating_add(start.elapsed().as_nanos() as u64);
            }
            let start = timing_enabled.then(crate::timing::now);
            self.eval_comb_checked()?;
            if let Some(start) = start {
                eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64);
                self.record_tick_timing(eval_apply_ns, eval_comb_ns);
            }
            self.dirty = false;
            Ok(())
        }

        /// Advance one event while deferring the post-edge combinational settle.
        /// Native testbenches use this between observable expressions so the
        /// preceding comb phase and this FF phase can share one compiled function.
        pub(crate) fn tick_deferred_comb(
            &mut self,
            event: B::Event,
        ) -> Result<(), RuntimeErrorCode> {
            if !self.program.runtime_schema.comb_observers.is_empty() {
                return self.tick(event);
            }
            if self.dirty {
                self.eval_comb_apply_ff_at_checked(event)?;
            } else {
                self.eval_apply_ff_at_checked(event)?;
            }
            self.dirty = true;
            Ok(())
        }

        /// Advance a run of identical deferred-comb ticks. Native code may keep
        /// the loop inside the generated function, but must return after publishing
        /// a runtime event so host-side observation remains tick-accurate.
        pub(crate) fn tick_deferred_comb_many(
            &mut self,
            event: B::Event,
            count: u64,
        ) -> (u64, Result<(), RuntimeErrorCode>) {
            if count == 0 {
                return (0, Ok(()));
            }
            if !self.program.runtime_schema.comb_observers.is_empty() || !self.dirty {
                return (1, self.tick_deferred_comb(event));
            }
            let (completed, result) = self.backend.eval_comb_apply_ff_many_at(event, count);
            self.dirty = true;
            (
                completed,
                result.map_err(|error| self.decorate_runtime_error(error)),
            )
        }

        /// Resolves a signal path into a performance-optimized [`SignalRef`].
        /// This handle allows for direct memory access without `HashMap` lookups.
        ///
        /// # Panics
        ///
        /// Panics when the path does not resolve, including when the dead
        /// store elimination policy does not guarantee the signal; see
        /// [`Self::try_signal`].
        pub fn signal(&self, path: &str) -> SignalRef {
            self.try_signal(path)
                .unwrap_or_else(|error| panic!("cannot resolve signal: {error}"))
        }

        /// Resolve a port name to an event handle.
        pub fn event(&self, port: &str) -> B::Event {
            let addr = self.program.get_addr(&[], &[port]).unwrap();
            self.backend.resolve_event(&addr)
        }

        /// Try to resolve a signal path. Returns `Err` if the path is not found or ambiguous.
        pub fn try_signal(&self, path: &str) -> Result<SignalRef, crate::ir::AddrLookupError> {
            self.try_child_signal(&[], path)
        }

        /// Try to resolve a port name to an event handle.
        /// Returns an error if the path is missing, ambiguous, or has no registered event.
        pub fn try_event(&self, port: &str) -> Result<B::Event, crate::ir::AddrLookupError> {
            let addr = self.program.get_addr(&[], &[port])?;
            self.backend.resolve_event_opt(&addr).ok_or_else(|| {
                crate::ir::AddrLookupError::NotAnEvent {
                    path: port.to_string(),
                }
            })
        }

        /// Retrieves the current value as a fixed-size type without `BigUint` allocation.
        /// Lazily evaluates combinational logic if the state is dirty.
        pub fn get_as<T: Default + Copy>(&mut self, signal: SignalRef) -> T {
            if self.dirty {
                self.eval_comb_checked().unwrap();
                self.dirty = false;
            }
            self.backend.get_as(signal)
        }

        /// Retrieves the current value of a variable using a pre-resolved [`SignalRef`] handle.
        /// Lazily evaluates combinational logic if the state is dirty.
        pub fn get(&mut self, signal: SignalRef) -> BigUint {
            if self.dirty {
                self.eval_comb_checked().unwrap();
                self.dirty = false;
            }
            self.backend.get(signal)
        }

        /// Retrieves the current 4-state value (value, mask) of a variable using a [`SignalRef`] handle.
        /// Lazily evaluates combinational logic if the state is dirty.
        pub fn get_four_state(&mut self, signal: SignalRef) -> (BigUint, BigUint) {
            if self.dirty {
                self.eval_comb_checked().unwrap();
                self.dirty = false;
            }
            self.backend.get_four_state(signal)
        }

        /// Directly execute combinational logic evaluation.
        pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> {
            self.eval_comb_checked()?;
            self.dirty = false;
            Ok(())
        }

        /// Returns a raw pointer to the backend memory and its total size in bytes.
        pub fn memory_as_ptr(&self) -> (*const u8, usize) {
            self.backend.memory_as_ptr()
        }

        /// Returns a mutable raw pointer to the backend memory and its total size in bytes.
        pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) {
            self.backend.memory_as_mut_ptr()
        }

        /// Returns an opaque owner that keeps the backend memory allocation alive.
        pub fn memory_owner(&self) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
            self.backend.memory_owner()
        }

        /// Returns the stable region size in bytes.
        pub fn stable_region_size(&self) -> usize {
            self.backend.stable_region_size()
        }

        /// Returns a reference to the memory layout.
        pub fn layout(&self) -> &MemoryLayout {
            self.backend.layout()
        }

        /// Take ownership of the VCD writer, if one was configured at build time.
        ///
        /// Builders create the writer themselves so that layout selection can
        /// account for VCD recording; callers building handles around a backend
        /// use this to keep tracing alive without rebuilding descriptors.
        pub fn take_vcd_writer(&mut self) -> Option<crate::VcdWriter> {
            self.vcd_writer.take()
        }

        /// Build VCD signal descriptors for all instances.
        ///
        /// The returned descriptors are self-contained (no IR references) and can
        /// be cached alongside [`SharedJitCode`] so that VCD works on cache-hit
        /// paths without the original [`RuntimeProgram`].
        pub fn build_vcd_descs(&self, four_state_mode: bool) -> Vec<crate::VcdSignalDesc> {
            let mut descs = Vec::new();
            let mut sorted_instances = self.program.design.instances().collect::<Vec<_>>();
            sorted_instances.sort_by_key(|instance| instance.id);

            for instance in sorted_instances {
                let scope = format!("{}", instance.id);

                let mut sorted_vars: Vec<_> = instance
                    .state_addresses()
                    .iter()
                    .filter_map(|address| self.program.design.variable(address))
                    .filter(|variable| instance.resolves_path_to(&variable.path, variable.address))
                    .collect();
                sorted_vars.sort_by(|a, b| a.path.cmp(&b.path));

                for variable in sorted_vars {
                    let name = variable.path.join(".");
                    let signal = self.backend.resolve_signal(&variable.address);

                    descs.push(crate::VcdSignalDesc {
                        scope: scope.clone(),
                        name,
                        offset: signal.offset,
                        width: signal.width,
                        is_4state: four_state_mode && signal.is_4state,
                    });
                }
            }
            descs
        }

        /// Returns all ports of the top-level module with their resolved signal references.
        pub fn named_signals(&self) -> Vec<NamedSignal> {
            let top_instance = self
                .program
                .design
                .root_instance()
                .expect("top-level instance not found");
            self.build_signals_for_instance(top_instance.id)
        }

        /// Returns all signals for the instance at the given hierarchical path.
        ///
        /// The path is specified as a slice of `(instance_name, index)` pairs.
        /// Returns an empty `Vec` if the path does not exist.
        pub fn instance_signals(&self, instance_path: &[(&str, usize)]) -> Vec<NamedSignal> {
            let path: Vec<_> = instance_path
                .iter()
                .map(|(name, idx)| ((*name).to_string(), *idx))
                .collect();
            match self.program.design.instance_at_path(&InstancePath(path)) {
                Some(instance) => self.build_signals_for_instance(instance.id),
                None => Vec::new(),
            }
        }

        /// Builds the list of named signals for a given instance.
        ///
        /// Variables with ambiguous VarPaths (multiple scoped locals sharing the
        /// same name) are excluded — they cannot be addressed by path and would
        /// cause silent overwrites in name-keyed maps such as the layout JSON.
        fn build_signals_for_instance(
            &self,
            instance_id: crate::ir::InstanceId,
        ) -> Vec<NamedSignal> {
            let instance = self.program.design.instance(instance_id).unwrap();
            let in_root = self
                .program
                .design
                .root_instance()
                .is_some_and(|root| root.id == instance.id);

            let mut result = Vec::new();
            for address in instance.state_addresses() {
                let variable = self.program.design.variable(address).unwrap();
                // Skip variables whose VarPath is ambiguous (None in the path index).
                if !instance.resolves_path_to(&variable.path, *address) {
                    continue;
                }
                // Enumeration exposes the same handles path lookup would.
                if !self.observable_under_dead_store_policy(*address, in_root) {
                    continue;
                }
                let name = variable.path.join(".");
                let signal = self.backend.resolve_signal(address);

                // Resolve associated clock for reset signals
                let associated_clock = self
                    .program
                    .design
                    .events
                    .reset_clocks
                    .get(address)
                    .map(|clock_addr| self.program.get_path(clock_addr));

                result.push(NamedSignal {
                    name,
                    signal,
                    info: self.program.design.variable_info(address).unwrap(),
                    associated_clock,
                });
            }
            result
        }

        /// Returns all events (clock/reset signals) with their IDs and event references.
        pub fn named_events(&self) -> Vec<NamedEvent<B>> {
            let mut result = Vec::new();
            for (id, addr) in self.backend.id_to_addr_slice().iter().enumerate() {
                let name = self.program.get_path(addr);
                if let Some(ev) = self.backend.resolve_event_opt(addr) {
                    result.push(NamedEvent {
                        name,
                        id,
                        event_ref: ev,
                    });
                }
            }
            result
        }

        /// Triggers a clock/event by its numeric ID.
        ///
        /// # Errors
        ///
        /// Returns [`RuntimeErrorCode::NotAnEvent`] if `event_id` is not a
        /// known event ID, or a runtime error if evaluating the event fails.
        pub fn tick_by_id(&mut self, event_id: usize) -> Result<(), RuntimeErrorCode> {
            let event = self
                .backend
                .id_to_event_slice()
                .get(event_id)
                .copied()
                .ok_or_else(|| RuntimeErrorCode::NotAnEvent(format!("event_id={event_id}")))?;
            self.tick(event)
        }

        /// Triggers a clock/event N times by its numeric ID.
        /// Avoids repeated cross-boundary calls when used from FFI.
        /// The event ID is validated even when `count` is zero.
        ///
        /// # Errors
        ///
        /// Returns [`RuntimeErrorCode::NotAnEvent`] if `event_id` is not a
        /// known event ID, or a runtime error if evaluating an event fails.
        pub fn tick_by_id_n(
            &mut self,
            event_id: usize,
            count: u32,
        ) -> Result<(), RuntimeErrorCode> {
            let event = self
                .backend
                .id_to_event_slice()
                .get(event_id)
                .copied()
                .ok_or_else(|| RuntimeErrorCode::NotAnEvent(format!("event_id={event_id}")))?;
            for _ in 0..count {
                self.tick(event)?;
            }
            Ok(())
        }

        /// Resolves a signal inside a child instance.
        pub fn child_signal(&self, instance_path: &[(&str, usize)], var: &str) -> SignalRef {
            self.try_child_signal(instance_path, var)
                .unwrap_or_else(|error| panic!("cannot resolve signal: {error}"))
        }

        /// Try to resolve a signal inside a child instance.
        ///
        /// [`Self::named_signals`], [`Self::instance_signals`] and
        /// [`Self::named_hierarchy`] omit the same signals.
        ///
        /// Under a dead store elimination policy, only state the policy
        /// guarantees to keep resolves: ports the policy preserves, signals
        /// listed with `live_signal()`, and state no combinational logic
        /// writes. Anything else may have lost its stores, and a handle to it
        /// would only read memory that never updates.
        pub fn try_child_signal(
            &self,
            instance_path: &[(&str, usize)],
            var: &str,
        ) -> Result<SignalRef, crate::ir::AddrLookupError> {
            let addr = self.program.get_addr(instance_path, &[var])?;
            let in_root = self
                .program
                .design
                .root_instance()
                .is_some_and(|root| root.state_addresses().contains(&addr));
            if !self.observable_under_dead_store_policy(addr, in_root) {
                let path = instance_path
                    .iter()
                    .map(|(name, index)| format!("{name}[{index}]."))
                    .chain(std::iter::once(var.to_string()))
                    .collect::<String>();
                return Err(crate::ir::AddrLookupError::DeadStoreEliminated { path });
            }
            Ok(self.backend.resolve_signal(&addr))
        }

        /// Whether the dead store elimination policy guarantees that `addr`
        /// stays current. `in_root` says whether it belongs to the top
        /// instance, whose ports `PreserveTopPorts` keeps.
        fn observable_under_dead_store_policy(
            &self,
            addr: crate::ir::AbsoluteAddr,
            in_root: bool,
        ) -> bool {
            use crate::DeadStorePolicy;
            let schema = &self.program.runtime_schema;
            if schema.dead_store_policy == DeadStorePolicy::Off
                || !schema.comb_writes.contains(&addr)
                || schema.live_signals.contains(&addr)
                || schema.testbench_read_roots.contains(&addr)
            {
                return true;
            }
            let is_port = self
                .program
                .design
                .variable(&addr)
                .is_some_and(|variable| variable.var_kind.is_port());
            match schema.dead_store_policy {
                DeadStorePolicy::Off => true,
                DeadStorePolicy::PreserveListedSignals => false,
                DeadStorePolicy::PreserveTopPorts => in_root && is_port,
                DeadStorePolicy::PreserveAllPorts => is_port,
            }
        }

        /// Returns the full instance hierarchy starting from the top module.
        pub fn named_hierarchy(&self) -> InstanceHierarchy {
            self.build_hierarchy(&[])
        }

        fn build_hierarchy(&self, current_path: &[(String, usize)]) -> InstanceHierarchy {
            let instance = self
                .program
                .design
                .instance_at_path(&InstancePath(current_path.to_vec()))
                .expect("instance not found");
            let module_name = instance.module_name.clone();
            let indexed = instance
                .display_path
                .last()
                .is_some_and(|segment| segment.ends_with(']'));

            let signals = self.build_signals_for_instance(instance.id);

            // Find direct children: instance paths that extend current by exactly 1 segment
            let current_len = current_path.len();
            let mut children_map: crate::HashMap<String, Vec<(usize, InstanceHierarchy)>> =
                crate::HashMap::default();

            for child in self.program.design.instances() {
                if child.path.0.len() == current_len + 1 && child.path.0.starts_with(current_path) {
                    let (child_name, child_index) = &child.path.0[current_len];
                    let child_hierarchy = self.build_hierarchy(&child.path.0);
                    children_map
                        .entry(child_name.clone())
                        .or_default()
                        .push((*child_index, child_hierarchy));
                }
            }

            // Sort children by index within each group
            let mut children: Vec<(String, Vec<InstanceHierarchy>)> = children_map
                .into_iter()
                .map(|(name, mut instances)| {
                    instances.sort_by_key(|(idx, _)| *idx);
                    let sorted = instances.into_iter().map(|(_, h)| h).collect();
                    (name, sorted)
                })
                .collect();
            children.sort_by(|(a, _), (b, _)| a.cmp(b));

            InstanceHierarchy {
                module_name,
                index: current_path.last().map_or(0, |(_, index)| *index),
                indexed,
                signals,
                children,
            }
        }
    }

    // ── JitBackend-specific methods ──────────────────────────────────────
    impl Simulator {
        pub fn builder<'a>(code: &'a str, top: &'a str) -> SimulatorBuilder<'a, Simulator> {
            SimulatorBuilder::<Simulator>::new(code, top)
        }

        pub fn from_sources<'a>(
            sources: Vec<(&'a str, &'a std::path::Path)>,
            top: &'a str,
        ) -> SimulatorBuilder<'a, Simulator> {
            SimulatorBuilder::<Simulator>::from_sources(sources, top)
        }

        /// Low-level adapter hook for an elaborated external frontend artifact.
        ///
        /// Frontend crates should wrap this with a constructor named for their
        /// own artifact type instead of exposing
        /// [`celox_frontend_sdk::FrontendArtifact`] to applications.
        pub fn from_frontend(
            artifact: celox_frontend_sdk::FrontendArtifact,
        ) -> SimulatorBuilder<'static, Simulator> {
            SimulatorBuilder::<Simulator>::from_frontend(artifact)
        }

        /// Low-level adapter hook for a Veryl testbench around an external module.
        pub fn from_frontend_with_testbench<'a>(
            artifact: celox_frontend_sdk::FrontendArtifact,
            sources: Vec<(&'a str, &'a std::path::Path)>,
            top: &'a str,
        ) -> SimulatorBuilder<'a, Simulator> {
            SimulatorBuilder::<Simulator>::from_frontend_with_testbench(artifact, sources, top)
        }

        /// Build a simulator directly from SystemVerilog sources.
        #[cfg(feature = "systemverilog")]
        pub fn from_sv_sources<'a>(
            sources: Vec<(&'a str, &'a std::path::Path)>,
            top: &'a str,
        ) -> SimulatorBuilder<'a, Simulator> {
            SimulatorBuilder::<Simulator>::from_sv_sources(sources, top)
        }

        /// Build a mixed Veryl/SystemVerilog hierarchy with a top in either language.
        #[cfg(feature = "systemverilog")]
        pub fn from_mixed_sources<'a>(
            sources: Vec<(&'a str, &'a std::path::Path)>,
            sv_sources: Vec<(&'a str, &'a std::path::Path)>,
            top: &'a str,
        ) -> SimulatorBuilder<'a, Simulator> {
            SimulatorBuilder::<Simulator>::from_mixed_sources(sources, sv_sources, top)
        }
    }

    impl Simulator<JitBackend> {
        /// Returns the shared compiled JIT code, allowing it to be reused
        /// for creating additional simulator instances without recompilation.
        pub fn shared_code(&self) -> Arc<SharedJitCode> {
            self.backend.shared_code()
        }

        /// Consume the simulator and return the inner JIT backend.
        pub fn into_backend(self) -> JitBackend {
            self.backend
        }
    }

    impl Simulator<crate::backend::wasm_runtime::WasmBackend> {
        /// Consume the simulator and return the inner Wasmtime backend.
        pub fn into_backend(self) -> crate::backend::wasm_runtime::WasmBackend {
            self.backend
        }
    }

    impl Simulator<crate::backend::TieredBackend> {
        /// Whether this tiered simulation has adopted its compiled tier.
        ///
        /// False while background compilation is still running or after it
        /// failed (the interpreter then remains the permanent tier).
        pub fn is_compiled(&self) -> bool {
            self.backend.is_compiled()
        }

        /// Return deterministic tier lifecycle and evaluation measurements.
        ///
        /// The snapshot contains counts rather than ad-hoc wall-clock samples;
        /// use a statistical benchmark harness to measure elapsed time.
        pub fn tiered_execution_stats(&self) -> crate::TieredExecutionStats {
            self.backend.execution_stats()
        }

        /// Start opt-in wall-clock measurement from workload execution to
        /// promotion. Ordinary tiered simulation does not read the host clock.
        pub fn start_tiered_execution_timing(&mut self) {
            self.backend.start_execution_timing();
        }

        /// Stop tiered execution timing and return the promotion interval.
        pub fn finish_tiered_execution_timing(&mut self) -> Option<crate::TieredExecutionTiming> {
            self.backend.finish_execution_timing()
        }

        /// Why promotion has not happened yet, for diagnostics.
        pub fn promotion_error(&self) -> Option<&SimulatorError> {
            self.backend.promotion_error()
        }

        /// Request cancellation of background compilation.
        ///
        /// The simulation stays on the interpreter permanently and
        /// [`Simulator::promotion_error`] reports the cancellation. Returns
        /// whether a background compilation was still pending.
        pub fn cancel_background_compilation(&mut self) -> bool {
            self.backend.cancel_background_compilation()
        }

        /// Consume the simulator and return the inner tiered backend.
        pub fn into_backend(self) -> crate::backend::TieredBackend {
            self.backend
        }
    }

    #[cfg(any(
        target_arch = "x86_64",
        feature = "arm64-codegen",
        target_arch = "aarch64"
    ))]
    impl Simulator<NativeBackend> {
        /// Returns the shared compiled native code, allowing it to be reused
        /// for creating additional simulator instances without recompilation.
        pub fn shared_code(&self) -> Arc<SharedNativeCode> {
            self.backend.shared_code()
        }

        /// Start measuring time spent inside generated native simulator functions.
        ///
        /// The measurement is disabled by default, so ordinary simulation does not
        /// read the host clock. Native tick loops are measured once per host-side
        /// batch rather than once per simulated tick.
        pub fn start_native_execution_timing(&mut self) {
            self.backend.start_execution_timing();
        }

        /// Stop native execution timing and return the accumulated measurement.
        pub fn finish_native_execution_timing(
            &mut self,
        ) -> Option<crate::native_backend::NativeExecutionTiming> {
            self.backend.finish_execution_timing()
        }

        /// Create a simulator from pre-compiled shared native code.
        pub fn from_shared(
            shared: Arc<SharedNativeCode>,
            program: crate::ir::OptimizedSir,
        ) -> Self {
            let backend = NativeBackend::from_shared(shared);
            let mut sim = Self::with_backend_and_program(backend, program.into_runtime(), vec![]);
            sim.apply_initial_values();
            sim
        }

        /// Consume the simulator and return the inner native backend.
        pub fn into_backend(self) -> NativeBackend {
            self.backend
        }
    }

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

        #[test]
        fn comb_fatal_records_do_not_mask_unrelated_backend_errors() {
            let mut sim = Simulator::builder(
                r#"module Top {
                    always_comb {
                        $display("before");
                        $assert(1'd0, "fatal");
                    }
                }"#,
                "Top",
            )
            .build_interpreter()
            .unwrap();
            let (result, events) = sim.eval_comb_capturing_events();
            assert!(matches!(
                result,
                Err(RuntimeErrorCode::DetectedTrueLoopCode(-2))
            ));
            assert!(sim.check_comb_backend_result(result).is_ok());
            assert!(sim.fatal_comb_capture_error(&events).is_some());

            // These are the raw outcomes another parallel lane can report while
            // the fatal assertion's record is present in the shared buffer.
            for error in [
                RuntimeErrorCode::InternalError,
                RuntimeErrorCode::DetectedTrueLoop,
                RuntimeErrorCode::DetectedTrueLoopCode(1),
                RuntimeErrorCode::DetectedTrueLoopCode(2000),
                RuntimeErrorCode::Runtime {
                    message: "fatal".to_string(),
                    signals: Vec::new(),
                },
            ] {
                let expected = sim.decorate_runtime_error(error.clone());
                assert_eq!(sim.check_comb_backend_result(Err(error)), Err(expected));
            }
            // A fatal status remains identifiable after losing its record.
            assert!(
                sim.check_comb_backend_result(Err(RuntimeErrorCode::DetectedTrueLoopCode(
                    celox_runtime::comb_fatal_code(1)
                )),)
                    .is_ok()
            );
            // A display site, missing site, or internal failure is not fatal.
            for code in [
                celox_runtime::comb_fatal_code(0),
                celox_runtime::comb_fatal_code(99),
                i64::MIN,
            ] {
                assert!(
                    sim.check_comb_backend_result(Err(RuntimeErrorCode::DetectedTrueLoopCode(
                        code
                    )),)
                        .is_err()
                );
            }
        }

        #[test]
        fn comb_fatal_status_survives_overwritten_event_records() {
            use celox_state_layout::{
                RUNTIME_EVENT_HEADER_SIZE, RUNTIME_EVENT_SLOT_ARG_COUNT_OFFSET,
                RUNTIME_EVENT_SLOT_SEQ_OFFSET, RUNTIME_EVENT_SLOT_SITE_OFFSET,
            };
            let mut sim = Simulator::builder(
                r#"module Top {
                    always_comb {
                        $display("before");
                        $assert(1'd0, "fatal");
                    }
                }"#,
                "Top",
            )
            .build_interpreter()
            .unwrap();
            let (result, _) = sim.eval_comb_capturing_events();
            let buffer = sim.backend.runtime_event_buffer().unwrap();
            let layout = sim.backend.layout();
            let start = sim.runtime_event_write_seq();
            // Model the other lanes that finish publishing display records
            // after the fatal lane has returned. The simulator is idle here.
            for seq in start..start + layout.runtime_event_capacity as u64 {
                let slot = seq as usize & (layout.runtime_event_capacity - 1);
                let base = RUNTIME_EVENT_HEADER_SIZE + slot * layout.runtime_event_slot_size;
                unsafe {
                    let ptr = buffer.as_mut_ptr();
                    ptr.add(base + RUNTIME_EVENT_SLOT_SITE_OFFSET)
                        .cast::<u64>()
                        .write(0);
                    ptr.add(base + RUNTIME_EVENT_SLOT_ARG_COUNT_OFFSET)
                        .cast::<u64>()
                        .write(0);
                    (*ptr
                        .add(base + RUNTIME_EVENT_SLOT_SEQ_OFFSET)
                        .cast::<AtomicU64>())
                    .store(seq, Ordering::Release);
                    (*ptr.cast::<AtomicU64>()).store(seq + 1, Ordering::Release);
                }
            }
            let events = sim.peek_backend_runtime_events_from(0);
            assert!(matches!(
                events.first(),
                Some(RawRuntimeEvent::Missed { count: 2 })
            ));
            assert!(sim.fatal_comb_capture_error(&events).is_none());
            assert!(sim.check_comb_backend_result(result.clone()).is_ok());
            assert!(matches!(sim.decorate_runtime_error(result.unwrap_err()),
                RuntimeErrorCode::Runtime { message, .. } if message.contains("overwritten")));
            let drained = sim.drain_runtime_events();
            assert!(matches!(
                drained.first(),
                Some(RuntimeEvent::Missed { count: 2 })
            ));
            assert_eq!(
                drained.len(),
                1 + sim.backend.layout().runtime_event_capacity
            );
            assert!(sim.drain_runtime_events().is_empty());
        }
    }
}

#[cfg(feature = "host-runtime")]
pub use host::*;

/// Human-readable diagnostics are separate from the byte-exact event payload.
#[cfg(feature = "host-runtime")]
pub(crate) fn message_diagnostic(bytes: &[u8]) -> String {
    match std::str::from_utf8(bytes) {
        Ok(text) => text.to_owned(),
        Err(_) => bytes.escape_ascii().to_string(),
    }
}