ticit 0.2.0

Fast simulation of near-Clifford quantum circuits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
//! Stabilizer-frame Clifford and Pauli-rotation simulator.
//!
//! # State representation
//!
//! The engine tracks a single Clifford frame `R` (a `Frame`, the owned
//! preimage tableau) and a sparse complex amplitude map over destabilizer-coset
//! labels. Writing
//! `S_i = R Z_i R† = image_z(i)` (stabilizers) and `D_i = R X_i R† = image_x(i)`
//! (destabilizers),
//!
//! ```text
//! |ψ⟩ = Σ_c xvec[c] · D^c |ψ0⟩,   |ψ0⟩ = R|0…0⟩,   D^c = ∏_{i: c_i=1} D_i.
//! ```
//!
//! The clean way to see the whole scheme: `D^c|ψ0⟩ = R|c⟩`, so
//! `|ψ⟩ = R|χ⟩` with `|χ⟩ = Σ_c xvec[c]|c⟩` the *rotated state* `R†|ψ⟩`. The
//! amplitude map **is** `|χ⟩` in the computational basis. This gives every
//! operation directly:
//!
//! * A Clifford gate `G` sends `|ψ⟩ → G|ψ⟩`, i.e. `R → G·R` (a `left_mul`),
//!   and leaves `|χ⟩` — the amplitude map — untouched.
//! * `T_P` and measurement act on `|ψ⟩` as `T`/projector about `P`, which in
//!   the rotated frame is the same operation about `Q = R†PR = preimage(P)`,
//!   acting on the computational-basis vector `|χ⟩`.
//!
//! # Pauli decomposition in the frame
//!
//! For a Pauli `P`, `Q = R†PR = i^k · X^a Z^b` with `a` the x-bits, `b` the
//! z-bits and `k` the phase exponent of the **X-then-Z** normal form (not
//! `xyz_phase_exponent`). Then on a basis term,
//!
//! ```text
//! Q|c⟩ = i^k · (−1)^{⟨b,c⟩} · |c ⊕ a⟩.
//! ```
//!
//! # Width dispatch
//!
//! Everything that sweeps the amplitude map — `T`, both measurement branches,
//! the expectation reads — is generic over the label type (`LabelKey`) rather
//! than written against one runtime-width label. `Amps` holds the single
//! specialization the register calls for, and each entry point matches on it
//! *once* and hands the whole operation to a monomorphized body; nothing
//! dispatches per term. `Frame` does the same for its row width, off the same
//! rounding rule. The private `label` module documents why width is a type.

use std::f64::consts::{FRAC_1_SQRT_2, PI};
use std::hash::{BuildHasher, Hasher, RandomState};

use num_complex::Complex64;
use rustc_hash::FxHashMap;

use crate::pauli::measurement_phase_sign;
use crate::pauli::{Pauli, PauliBasis, PauliString};
use crate::random::rand_float;

/// The tableau oracle for [`TableauSimulator::apply_clifford`]; see there.
#[cfg(test)]
use paulimer::CliffordUnitary;

mod batch;
mod error;
mod frame;
mod label;

pub use batch::{BatchOutcome, Gate1Q, Instruction};
pub use error::SimError;

#[cfg(target_arch = "x86_64")]
use frame::has_popcnt;
use frame::{Axis, Frame, PauliWords, RowPauli};
use label::{Key, Label, LabelKey, Width};

/// The frame's view of a [`PauliString`] — its x/z words, borrowed.
///
/// One conversion site rather than a `From` impl on either side: `frame.rs` is
/// compiled standalone by `tests/frame_differential.rs` and so cannot name
/// `PauliString`, and `PauliString` has no business knowing about the frame.
#[inline]
fn words(pauli: &PauliString) -> PauliWords<'_> {
    PauliWords {
        x: pauli.x_words(),
        z: pauli.z_words(),
    }
}

/// Tolerance for "numerically deterministic" / "impossible to post-select"
/// decisions and internal reality checks.
const TOL: f64 = 1e-9;

/// Amplitudes this small are float-drift noise, not state. Sized for
/// correctness verification of small physical-circuit batches.
///
/// The pruning tests compare `norm_sqr()` against the square of this rather
/// than `norm()` against it: `Complex::norm` is a `hypot` call, which measured
/// at 5% of a profiled run, and squaring the threshold is exact enough here
/// (`1e-24` is nowhere near the subnormal range).
const DEFAULT_PRUNE_EPSILON: f64 = 1e-12;

/// Live-label ceiling: fails loudly long before memory is exhausted.
const DEFAULT_RANK_CAP: usize = 1 << 20;

/// Sign of the frame-compression rotation `exp(±iπ/4 · G)` applied to the
/// amplitude map in the random-measurement branch. It is fixed by
/// `paulimer`'s `left_mul_pauli_exp` convention and pinned by the dense
/// cross-validation tests; the value is a single global constant, not
/// per-case logic.
const PAULI_EXP_SIGN: f64 = -1.0;

/// Outcome of a Pauli measurement.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeasureResult {
    /// Sampled (or forced) eigenvalue bit: `false` = `+1`, `true` = `−1`.
    pub outcome: bool,
    /// Probability the engine assigned to `outcome` in the pre-measurement state.
    pub probability: f64,
    /// Whether the outcome was forced by the state (probability `≈ 0` or `1`).
    pub deterministic: bool,
}

/// A stim-`TableauSimulator`-style procedural quantum-state simulator.
///
/// Apply operations one at a time, read [`measure`](Self::measure) outcomes,
/// branch on them (feedforward), and continue. See the [module docs](self) for
/// the state representation.
///
/// # Naming
///
/// The method names are stim's wherever stim has one, so a circuit written
/// against `stim.TableauSimulator` transliterates: the single-qubit Cliffords
/// (`h`, `s`, `sqrt_x`, `c_xyz`, `h_xy`, …), the two-qubit `<A>C<B>` family
/// (`cx`/`cnot`/`zcx`, `cy`/`zcy`, `cz`/`zcz`, `xcx` … `ycz`) plus
/// `swap`/`iswap`, `measure`/`measure_observable`,
/// the `postselect_*` family, `reset`/`reset_x`/`reset_y`/`reset_z`, and
/// `peek_observable_expectation`/`peek_x`/`peek_y`/`peek_z`. Two departures:
/// the measurements return a
/// [`MeasureResult`] rather than a bare `bool` (the branch weight is computed
/// to sample from it, so reporting it is free), and observables are
/// [`PauliString`]s.
///
/// The Pauli-rotation extension keeps this workspace's names — `t`, `t_dag`,
/// `t_pauli`, `ccz` and `rank` — as does the batched `apply_batch` instruction
/// path.
#[derive(Clone, Debug)]
pub struct TableauSimulator {
    core: Core,
    /// `|χ⟩ = R†|ψ⟩` as a sparse computational-basis vector, in whichever
    /// label-width specialization the register calls for.
    amps: Amps,
}

/// The simulator minus its amplitude storage.
///
/// Split out purely so the width-dispatched routines can hold a `&mut` to the
/// frame, the RNG and the thresholds while the amplitude map — a *different*
/// field, and the generic one — is borrowed alongside them.
#[derive(Clone, Debug)]
struct Core {
    /// Qubit count (grows on demand via [`TableauSimulator::ensure_qubits`]).
    n: usize,
    /// `u64` words per label. Read from the frame, so the two always agree and
    /// masks pass between them without reslicing.
    words: usize,
    /// The Clifford frame `R`.
    r: Frame,
    /// SplitMix64 state; the crate's one generator (`crate::random`).
    rng: u64,
    /// Amplitudes at or below this modulus are dropped after each `T` and
    /// measurement projection. Exact arithmetic preserves the norm, so this only
    /// removes terms that cancelled to within rounding.
    prune_epsilon: f64,
    /// Maximum live-label count. A rotation/measurement that would exceed it fails
    /// with [`SimError::RankOverflow`] rather than exhausting memory.
    rank_cap: usize,
}

/// The amplitude map and its staging buffers, at one label width.
#[derive(Clone, Debug)]
struct Terms<K: LabelKey> {
    map: FxHashMap<K, Complex64>,
    /// Staging buffers for the coset-pair rewrites (`T` and projection).
    rotation: RotationScratch<K>,
}

impl<K: LabelKey> PartialEq for Terms<K> {
    /// Staging buffers are working memory, not state.
    fn eq(&self, other: &Self) -> bool {
        self.map == other.map
    }
}

/// The live amplitude map, specialized to the register's label width.
///
/// Growing past a width boundary swaps the variant; see [`Amps::widen`].
#[derive(Clone, Debug, PartialEq)]
enum Amps {
    W1(Terms<Key<1>>),
    W2(Terms<Key<2>>),
    W4(Terms<Key<4>>),
    W8(Terms<Key<8>>),
    Wide(Terms<Label>),
}

/// Run `$body` for the amplitude storage's actual width, with `$terms` bound to
/// the monomorphized [`Terms`] and `$core` to everything else.
///
/// The body is duplicated across the variants at expansion, so it has to stay a
/// call into generic code — the algorithms live in `impl<K> Terms<K>`, not
/// here. Destructuring `*$sim` is what makes the two borrows disjoint.
macro_rules! with_terms {
    ($sim:expr, |$core:ident, $terms:ident| $body:expr) => {{
        let TableauSimulator {
            core: ref mut $core,
            amps: ref mut storage,
        } = *$sim;
        match storage {
            Amps::W1($terms) => $body,
            Amps::W2($terms) => $body,
            Amps::W4($terms) => $body,
            Amps::W8($terms) => $body,
            Amps::Wide($terms) => $body,
        }
    }};
}

/// [`with_terms`] for the read-only paths.
macro_rules! with_terms_ref {
    ($sim:expr, |$core:ident, $terms:ident| $body:expr) => {{
        let TableauSimulator {
            core: ref $core,
            amps: ref storage,
        } = *$sim;
        match storage {
            Amps::W1($terms) => $body,
            Amps::W2($terms) => $body,
            Amps::W4($terms) => $body,
            Amps::W8($terms) => $body,
            Amps::Wide($terms) => $body,
        }
    }};
}

/// Where a coset-pair rewrite stages its result before committing it.
///
/// The buffers are held on the amplitude map and reused: a long circuit pays
/// for them once. They are always left cleared, so cloning a simulator does not
/// copy them.
#[derive(Clone, Debug)]
struct RotationScratch<K> {
    /// New amplitude of each live label, in amplitude-map iteration order.
    values: Vec<Complex64>,
    /// Coset partners the rotation adds to the map, with their amplitudes.
    inserts: Vec<(K, Complex64)>,
    /// Each live label's coset partner amplitude, or `None` where the map has
    /// no such label — in the same iteration order. Written by the
    /// expectation pass a measurement already has to run, read by the
    /// projection that follows it, so the pair is located once instead of
    /// twice. Unused by `T`, which has no expectation pass to piggyback on.
    partners: Vec<Option<Complex64>>,
}

/// Hand-written rather than derived: the buffers start empty whatever `K` is,
/// and a derived `Default` would demand `K: Default` for no reason.
impl<K> Default for RotationScratch<K> {
    fn default() -> Self {
        RotationScratch {
            values: Vec::new(),
            inserts: Vec::new(),
            partners: Vec::new(),
        }
    }
}

impl<K> RotationScratch<K> {
    /// Empty the buffers, keeping their capacity for the next operation.
    fn clear(&mut self) {
        self.values.clear();
        self.inserts.clear();
        self.partners.clear();
    }
}

/// `i^k` as a complex number, `k` taken mod 4.
#[inline]
fn i_pow(k: u8) -> Complex64 {
    match k & 3 {
        0 => Complex64::new(1.0, 0.0),
        1 => Complex64::new(0.0, 1.0),
        2 => Complex64::new(-1.0, 0.0),
        _ => Complex64::new(0.0, -1.0),
    }
}

/// The `(a, b, ζ)` frame decomposition of a Pauli: `Q = ζ · X^a Z^b`, with `a`
/// and `b` as label-width word masks (the coset shift and the sign mask).
///
/// The masks carry the amplitude map's own key type, so the frame can write
/// them in place and the innermost loops — one `xor` and one `dot_parity`
/// against these per term — run at the same fixed width as the terms.
struct Decomp<K> {
    /// X part — the coset shift `c ↦ c ⊕ a`.
    a: K,
    /// Z part — the sign mask `(−1)^{⟨b,c⟩}`.
    b: K,
    /// The phase exponent `k`, kept alongside `zeta` because the measurement
    /// path does exponent arithmetic on it (`G = i^{k+3}·X^a Z^{b⊕e_p}`).
    phase: u8,
    /// `i^k`.
    zeta: Complex64,
}

/// The per-term constants of the random-measurement pass, hoisted out of the
/// loop: the projector, the `Z_p^s` fold and the frame compression, composed.
///
/// The derivation is in [`Terms::measure_random`]; what matters here is the
/// shape it leaves behind. All four scattered products land back on the pair
/// `{c, c ⊕ a}`, so the whole composite is a coset-pair rewrite and
/// [`Projection::rewrite_pair`] is its kernel.
struct Projection<'a, K> {
    d: &'a Decomp<K>,
    /// `G`'s z-mask, `b ⊕ e_pivot`.
    gb: &'a K,
    pivot: usize,
    /// The sampled outcome bit, `s`.
    s: bool,
    /// `(−1)^s`.
    ssign: f64,
    /// `i·PAULI_EXP_SIGN/√2·ζ_G`, the compression's off-diagonal weight.
    compress: Complex64,
    /// `(−1)^{⟨gb,a⟩}`: how the `gb` parity of `c ⊕ a` differs from `c`'s.
    shift_flip: f64,
}

impl<K: LabelKey> Projection<'_, K> {
    /// The pair `{c, c ⊕ a}`'s two new amplitudes from its two old ones, `x`
    /// at `c` and `y` at the partner (`y = 0` where the map has no partner).
    ///
    /// Everything the partner needs is derived from `c`'s own three bit tests
    /// rather than repeated on the partner's label, which is what makes this
    /// one kernel per *pair* instead of two per *member*:
    ///
    /// * the pivot is a set bit of `a`, so the partner's pivot bit — the whole
    ///   of its `Z_p^s` factor — is `c`'s flipped;
    /// * `⟨b, c ⊕ a⟩` and `⟨b, c⟩` differ by the constant `⟨b, a⟩`, and
    ///   likewise for `gb`.
    ///
    /// Those parities are the expensive part: the workspace sets no target
    /// features, so each is a ~12-operation SWAR pop-count, and this loop is
    /// the engine's hottest.
    ///
    /// `inline(always)`, not `inline`: the caller discards the second half on
    /// the common branch, and out of line that costs both the call and the
    /// complex multiplies inlining lets the optimizer delete. As a standalone
    /// symbol its predecessor measured at 30% of a profiled run.
    #[inline(always)]
    fn rewrite_pair(&self, c: &K, x: Complex64, y: Complex64) -> (Complex64, Complex64) {
        let zc = if self.s && c.get(self.pivot) {
            -1.0
        } else {
            1.0
        };
        // `Z_p^s` at the partner. Only the `s = true` fold sees the pivot bit
        // at all, and then the partner's is the opposite of `c`'s.
        let zp = if self.s { -zc } else { 1.0 };
        let sb = if c.dot_parity(&self.d.b) { -1.0 } else { 1.0 };
        let sg = if c.dot_parity(self.gb) { -1.0 } else { 1.0 };
        // `⟨b,a⟩` from `⟨gb,a⟩`: `gb = b ⊕ e_pivot` and the pivot bit of `a`
        // is set, so the two parities are always opposite.
        let shift_b = -self.shift_flip;

        // Projector and fold, gathered by destination rather than scattered by
        // source: `u` is everything landing on `c`, `v` everything landing on
        // the partner. Each member sends half of itself across.
        let u = 0.5 * zc * x + (0.5 * self.ssign * (sb * shift_b) * zc) * self.d.zeta * y;
        let v = (0.5 * self.ssign * sb * zp) * self.d.zeta * x + 0.5 * zp * y;

        // The compression `(I ± iG)/√2` then mixes the pair once more.
        (
            FRAC_1_SQRT_2 * u + self.compress * (sg * self.shift_flip) * v,
            self.compress * sg * u + FRAC_1_SQRT_2 * v,
        )
    }
}

// ==============================================================================
// Public surface
// ==============================================================================

impl TableauSimulator {
    // --- Construction ---

    /// A fresh `|0…0⟩` simulator on `num_qubits` qubits with an OS-seeded RNG.
    #[must_use]
    pub fn new(num_qubits: usize) -> Self {
        Self::with_seed(num_qubits, RandomState::new().build_hasher().finish())
    }

    /// A fresh `|0…0⟩` simulator with a fixed RNG seed (reproducible sampling).
    #[must_use]
    pub fn with_seed(num_qubits: usize, seed: u64) -> Self {
        // The frame owns the rounding rule for the register width; taking it
        // from there is what guarantees labels and rows stay the same width.
        let r = Frame::identity(num_qubits);
        let words = r.words();
        TableauSimulator {
            core: Core {
                n: num_qubits,
                words,
                r,
                rng: seed,
                prune_epsilon: DEFAULT_PRUNE_EPSILON,
                rank_cap: DEFAULT_RANK_CAP,
            },
            amps: Amps::unit(words),
        }
    }

    /// Lowers the rank cap so a test can provoke [`SimError::RankOverflow`]
    /// without building a genuinely magic-heavy circuit.
    #[doc(hidden)]
    pub fn set_rank_cap(&mut self, cap: usize) {
        self.core.rank_cap = cap;
    }

    /// Raises the pruning threshold so a test can provoke
    /// [`SimError::EmptyStateAfterPruning`], which the default never reaches.
    #[doc(hidden)]
    pub fn set_prune_epsilon(&mut self, epsilon: f64) {
        self.core.prune_epsilon = epsilon;
    }

    /// Reseed the outcome RNG in place, leaving the quantum state alone.
    ///
    /// A `RepeatUntilSuccess` retry replays the same ops from the same state;
    /// without a fresh seed every attempt would sample the identical outcomes
    /// and the loop could never make progress.
    pub fn reseed_rng(&mut self, seed: u64) {
        self.core.rng = seed;
    }

    /// Adopt `snapshot`'s RNG position. Rolling a failed attempt's state back
    /// must not also roll the RNG back, or the retry repeats the same outcomes.
    pub fn restore_rng_from(&mut self, snapshot: &Self) {
        self.core.rng = snapshot.core.rng;
    }

    /// Current qubit count.
    #[must_use]
    pub fn num_qubits(&self) -> usize {
        self.core.n
    }

    /// Number of live amplitude terms (the stabilizer rank).
    #[must_use]
    pub fn rank(&self) -> usize {
        self.amps.len()
    }

    /// Ensure at least `need` qubits exist, growing `R` and widening labels.
    fn ensure_qubits(&mut self, need: usize) {
        if need <= self.core.n {
            return;
        }
        self.core.r.resize(need);
        let new_words = self.core.r.words();
        if new_words > self.core.words {
            self.amps.widen(new_words);
            self.core.words = new_words;
        }
        self.core.n = need;
        debug_assert_eq!(
            self.core.n,
            self.core.r.num_qubits(),
            "frame tracks register"
        );
        debug_assert_eq!(self.core.words, self.core.r.words(), "widths agree");
    }

    fn ensure_for(&mut self, pauli: &PauliString) {
        if let Some(max) = pauli.max_support() {
            self.ensure_qubits(max + 1);
        }
    }

    /// [`ensure_for`](Self::ensure_for) for an operator that has to be an
    /// observable. The phase is checked *before* the register grows, so a
    /// rejected axis leaves the engine exactly as it found it.
    fn ensure_for_observable(&mut self, pauli: &PauliString) -> Result<(), SimError> {
        measurement_phase_sign(pauli).map_err(|_| SimError::NonHermitianPauli)?;
        self.ensure_for(pauli);
        Ok(())
    }

    // --- Clifford gates — mutate R only, xvec untouched. ---

    /// Apply an arbitrary Clifford `cl` to `support` (`support[i]` is `cl`'s
    /// qubit `i`).
    ///
    /// Test-only, and deliberately not public: every gate this engine offers is
    /// reached by name or by Pauli axis in one or two frame row updates, and
    /// nothing in production has a `CliffordUnitary` to hand. What survives is
    /// the *oracle* role — the [`Gate1Q`] compositions are checked against the
    /// tableaux they advertise by running both through here.
    ///
    /// # Panics
    ///
    /// Panics if `support.len() != cl.num_qubits()` or `support` repeats an
    /// index, both caller errors in a test.
    #[cfg(test)]
    fn apply_clifford(&mut self, cl: &CliffordUnitary, support: &[usize]) {
        if let Some(&max) = support.iter().max() {
            self.ensure_qubits(max + 1);
        }
        self.core.r.left_clifford(cl, support);
    }

    /// Hadamard.
    pub fn h(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_h(q);
    }
    /// Phase gate `S = √Z`.
    pub fn s(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_s(q);
    }
    /// `S† = √Z†`.
    pub fn s_dag(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_s_dag(q);
    }
    /// Pauli `X`.
    pub fn x(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_x(q);
    }
    /// Pauli `Y`.
    pub fn y(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_y(q);
    }
    /// Pauli `Z`.
    pub fn z(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_z(q);
    }
    /// `√X`.
    pub fn sqrt_x(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_sqrt_x(q);
    }
    /// `√X†`.
    pub fn sqrt_x_dag(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_sqrt_x_dag(q);
    }
    /// `√Y`.
    pub fn sqrt_y(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_sqrt_y(q);
    }
    /// `√Y†`.
    pub fn sqrt_y_dag(&mut self, q: usize) {
        self.ensure_qubits(q + 1);
        self.core.r.left_sqrt_y_dag(q);
    }
    /// CNOT with `control`, `target`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn cx(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        if control == target {
            return Err(SimError::RepeatedQubit(control));
        }
        self.ensure_qubits(control.max(target) + 1);
        self.core.r.left_cx(control, target);
        Ok(())
    }
    /// Controlled-Z (symmetric).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn cz(&mut self, a: usize, b: usize) -> Result<(), SimError> {
        if a == b {
            return Err(SimError::RepeatedQubit(a));
        }
        self.ensure_qubits(a.max(b) + 1);
        self.core.r.left_cz(a, b);
        Ok(())
    }
    /// Swap.
    pub fn swap(&mut self, a: usize, b: usize) {
        self.ensure_qubits(a.max(b) + 1);
        self.core.r.left_swap(a, b);
    }

    /// `ISWAP`: swap `a` and `b`, with an `i` on the two odd-parity terms.
    ///
    /// `ISWAP = SWAP·CZ·(S⊗S)`. All three factors are symmetric and either
    /// diagonal or a permutation, so they commute and the order is free; the
    /// `CZ` goes first only because it is the fallible step, which keeps a
    /// rejected call from leaving half a gate behind.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn iswap(&mut self, a: usize, b: usize) -> Result<(), SimError> {
        self.cz(a, b)?;
        self.s(a);
        self.s(b);
        self.swap(a, b);
        Ok(())
    }

    /// `ISWAP†`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn iswap_dag(&mut self, a: usize, b: usize) -> Result<(), SimError> {
        self.cz(a, b)?;
        self.s_dag(a);
        self.s_dag(b);
        self.swap(a, b);
        Ok(())
    }

    /// `C_XYZ`: the order-three Pauli cycle `X → Y → Z → X`.
    pub fn c_xyz(&mut self, q: usize) {
        self.gate1(Gate1Q::Cxyz, q);
    }

    /// `C_ZYX`: the inverse cycle `X → Z → Y → X`.
    pub fn c_zyx(&mut self, q: usize) {
        self.gate1(Gate1Q::Czyx, q);
    }

    /// `H_XY`: the Hadamard-like exchange of `X` and `Y`.
    pub fn h_xy(&mut self, q: usize) {
        self.gate1(Gate1Q::Hxy, q);
    }

    /// `H_YZ`: the Hadamard-like exchange of `Y` and `Z`.
    pub fn h_yz(&mut self, q: usize) {
        self.gate1(Gate1Q::Hyz, q);
    }

    // --- The `<A>C<B>` family ---
    //
    // Nine one-liners over `gate2`, plus the two aliases stim also spells
    // without a control letter. They exist so a stim circuit transliterates
    // without the reader having to translate `zcy` into an axis pair; the work
    // is `gate2`'s, which reaches `CZ` conjugated by basis rotations.

    /// CNOT — stim's spelling of [`cx`](Self::cx).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn cnot(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.cx(control, target)
    }

    /// Controlled-`Y`, i.e. [`zcy`](Self::zcy).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn cy(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.zcy(control, target)
    }

    /// `XCX`: apply `X` to `target` when `control` is in the `−1` eigenstate
    /// of `X`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn xcx(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::X, PauliBasis::X, control, target)
    }

    /// `XCY`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn xcy(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::X, PauliBasis::Y, control, target)
    }

    /// `XCZ`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn xcz(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::X, PauliBasis::Z, control, target)
    }

    /// `YCX`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn ycx(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::Y, PauliBasis::X, control, target)
    }

    /// `YCY`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn ycy(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::Y, PauliBasis::Y, control, target)
    }

    /// `YCZ`.
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn ycz(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::Y, PauliBasis::Z, control, target)
    }

    /// `ZCX`, i.e. [`cx`](Self::cx).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn zcx(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.cx(control, target)
    }

    /// `ZCY`, i.e. [`cy`](Self::cy).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn zcy(&mut self, control: usize, target: usize) -> Result<(), SimError> {
        self.gate2(PauliBasis::Z, PauliBasis::Y, control, target)
    }

    /// `ZCZ`, i.e. [`cz`](Self::cz).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if both operands name the same qubit.
    pub fn zcz(&mut self, a: usize, b: usize) -> Result<(), SimError> {
        self.cz(a, b)
    }

    /// Apply a Pauli `P` to the state (`R → P·R`).
    pub fn pauli(&mut self, p: &PauliString) {
        self.ensure_for(p);
        self.core.r.left_pauli(words(p));
    }

    /// Apply `control`-conditioned `target` (both Paulis).
    ///
    /// # Errors
    /// [`SimError::NonCommutingControlledPaulis`] if the axes anticommute, or
    /// [`SimError::InvalidControlledPauli`] if either axis carries a sign or an
    /// imaginary coefficient — conditioning on `−P` is a different operation,
    /// and the frame update below only represents the positive one.
    pub fn controlled_pauli(
        &mut self,
        control: &PauliString,
        target: &PauliString,
    ) -> Result<(), SimError> {
        if !control.commutes_with(target) {
            return Err(SimError::NonCommutingControlledPaulis);
        }
        if measurement_phase_sign(control).ok() != Some(false)
            || measurement_phase_sign(target).ok() != Some(false)
        {
            return Err(SimError::InvalidControlledPauli);
        }
        self.ensure_for(control);
        self.ensure_for(target);
        self.core
            .r
            .left_controlled_pauli(words(control), words(target));
        Ok(())
    }

    // --- T gate ---

    /// Apply `T_P(±) = cos(π/8)·I ∓ i·sin(π/8)·P` about the Pauli axis `axis`
    /// (`adjoint = true` selects the `+` sign, i.e. `T†`).
    ///
    /// A [`PauliString`] is Hermitian by construction, so any axis is a legal
    /// rotation generator; the register grows to cover its support.
    ///
    /// # Errors
    ///
    /// [`SimError::RankOverflow`] if the term count exceeds the cap, or
    /// [`SimError::EmptyStateAfterPruning`] if pruning erases every term.
    ///
    /// # Examples
    ///
    /// ```
    /// use ticit::{PauliString, TableauSimulator};
    ///
    /// // T about Z on |+⟩ leaves ⟨X⟩ = ⟨Y⟩ = 1/√2.
    /// let mut sim = TableauSimulator::with_seed(1, 0);
    /// sim.h(0);
    /// sim.t_pauli(&PauliString::try_from("Z")?, false)?;
    /// let x = sim.peek_observable_expectation(&PauliString::try_from("X")?)?;
    /// assert!((x - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn t_pauli(&mut self, axis: &PauliString, adjoint: bool) -> Result<(), SimError> {
        self.ensure_for_observable(axis)?;
        with_terms!(self, |core, terms| {
            let d = core.decompose(axis)?;
            terms.t_decomposed(core, &d, adjoint)
        })
    }

    /// Apply `exp(-i * kernel_angle * axis)` about a Pauli axis.
    ///
    /// # Errors
    ///
    /// Returns [`SimError::InvalidRotationAngle`] for a non-finite angle,
    /// [`SimError::NonHermitianPauli`] for a non-observable axis, or the same
    /// rank and pruning errors as [`t_pauli`](Self::t_pauli).
    pub fn pauli_rotation(
        &mut self,
        axis: &PauliString,
        kernel_angle: f64,
    ) -> Result<(), SimError> {
        if !kernel_angle.is_finite() {
            return Err(SimError::InvalidRotationAngle(kernel_angle));
        }
        self.ensure_for_observable(axis)?;
        with_terms!(self, |core, terms| {
            let d = core.decompose(axis)?;
            terms.rotate_decomposed(core, &d, kernel_angle)
        })
    }

    /// `T = T_Z` on qubit `q`.
    ///
    /// # Errors
    /// Propagates [`t_pauli`](Self::t_pauli) errors.
    pub fn t(&mut self, q: usize) -> Result<(), SimError> {
        self.t_about(Axis::Z, q, false)
    }

    /// `T† = T_Z†` on qubit `q`.
    ///
    /// # Errors
    /// Propagates [`t_pauli`](Self::t_pauli) errors.
    pub fn t_dag(&mut self, q: usize) -> Result<(), SimError> {
        self.t_about(Axis::Z, q, true)
    }

    /// `T_axis(±)` on a single qubit, decomposing the basis axis straight out
    /// of the frame instead of building a `PauliString` to describe it.
    fn t_about(&mut self, axis: Axis, q: usize, adjoint: bool) -> Result<(), SimError> {
        self.ensure_qubits(q + 1);
        with_terms!(self, |core, terms| {
            let d = core.decompose_basis(axis, q);
            terms.t_decomposed(core, &d, adjoint)
        })
    }

    /// Apply a `CCZ` on qubits `a`, `b`, `c` (symmetric) via seven `π/8`
    /// rotations.
    ///
    /// `CCZ` has the phase-polynomial decomposition
    /// `exp(iπ/8·[−Z_a − Z_b − Z_c + Z_aZ_b + Z_aZ_c + Z_bZ_c − Z_aZ_bZ_c])`
    /// (global phase `e^{iπ/8}` unobservable), following clifft's
    /// `append_ccz_decomposition`
    /// ([github.com/unitaryfoundation/clifft](https://github.com/unitaryfoundation/clifft),
    /// `src/clifft/circuit/parser.cc`): `4abc = a + b + c − (a⊕b) − (a⊕c) −
    /// (b⊕c) + (a⊕b⊕c)`, i.e. 7 `T`s + 6 `CX`s. In the stabilizer frame the
    /// `CX` conjugations only retarget the `T` axes, so we apply the seven
    /// rotations directly on multi-qubit `Z` axes — no `CX`s needed:
    ///
    /// * `T` on `Z_a`, `Z_b`, `Z_c` (singles, `−` sign → non-adjoint),
    /// * `T†` on `Z_aZ_b`, `Z_aZ_c`, `Z_bZ_c` (pairs, `+` sign → adjoint),
    /// * `T` on `Z_aZ_bZ_c` (triple, `−` sign → non-adjoint).
    ///
    /// # Errors
    /// [`SimError::RepeatedQubit`] if `a`, `b`, `c` are not distinct;
    /// propagates [`t_pauli`](Self::t_pauli) errors (e.g. rank overflow — the
    /// seven axes lift the rank by at most `2^7` transiently before pruning).
    /// Errors leave the simulator unchanged.
    pub fn ccz(&mut self, a: usize, b: usize, c: usize) -> Result<(), SimError> {
        if a == b || a == c {
            return Err(SimError::RepeatedQubit(a));
        }
        if b == c {
            return Err(SimError::RepeatedQubit(b));
        }
        // Rolling a failure back by discarding a clone costs a full copy of the
        // frame and the amplitude map, so skip it when neither failure is
        // reachable. Seven `T`s at most double the rank each, so `2^7` of
        // headroom rules out [`SimError::RankOverflow`]; and at the default
        // pruning threshold nothing can be emptied either — a normalized state
        // of rank ≤ 2^20 has an amplitude of modulus ≥ 2^-10, and each `T`
        // preserves its coset pair's norm, so after seven of them the largest
        // surviving amplitude is still ≥ 2^-13.5 ≈ 9e-5, eight orders of
        // magnitude clear of `1e-12`.
        let safe = self.rank() <= self.core.rank_cap >> 7
            && self.core.prune_epsilon <= DEFAULT_PRUNE_EPSILON;
        if safe {
            return self.ccz_rotations(a, b, c);
        }
        let mut next = self.clone();
        next.ccz_rotations(a, b, c)?;
        *self = next;
        Ok(())
    }

    /// The seven `π/8` rotations of a `CCZ`, applied in place.
    ///
    /// The operands are distinct, so each axis is just `Z` on a subset of
    /// `{a, b, c}` — no Pauli product, and no phase to track. One buffer is
    /// rewritten between rotations rather than seven strings allocated: a
    /// `PauliString` is dense, so building each axis from scratch would be a
    /// larger share of a `CCZ` than the rotations themselves.
    fn ccz_rotations(&mut self, a: usize, b: usize, c: usize) -> Result<(), SimError> {
        self.ensure_qubits(a.max(b).max(c) + 1);
        let mut axis = PauliString::new(self.core.n);
        for (operands, adjoint) in [
            (&[a][..], false),
            (&[b][..], false),
            (&[c][..], false),
            (&[a, b][..], true),
            (&[a, c][..], true),
            (&[b, c][..], true),
            (&[a, b, c][..], false),
        ] {
            for site in [a, b, c] {
                axis.set(site, Pauli::I);
            }
            for &site in operands {
                axis.set(site, Pauli::Z);
            }
            self.t_pauli(&axis, adjoint)?;
        }
        Ok(())
    }

    // --- Measurement ---

    /// Measure qubit `q` in the `Z` basis, sampling the outcome and collapsing
    /// the state onto it. The register grows to cover `q`.
    ///
    /// The single-qubit case never builds an observable: `Z_q`'s preimage is a
    /// stored frame row, so this decomposes it directly. Use
    /// [`measure_observable`](Self::measure_observable) for a Pauli product.
    ///
    /// # Errors
    /// [`SimError::RankOverflow`] if the projection exceeds the rank cap.
    ///
    /// # Examples
    ///
    /// ```
    /// use ticit::TableauSimulator;
    ///
    /// let mut sim = TableauSimulator::with_seed(2, 7);
    /// sim.h(0);
    /// sim.cx(0, 1)?;
    /// let first = sim.measure(0)?;
    /// let second = sim.measure(1)?;
    /// assert_eq!(first.outcome, second.outcome, "a Bell pair agrees");
    /// assert!(second.deterministic, "the partner is pinned by the first read");
    /// # Ok::<(), ticit::SimError>(())
    /// ```
    pub fn measure(&mut self, q: usize) -> Result<MeasureResult, SimError> {
        self.measure_axis(Axis::Z, q, None)
    }

    /// Measure the Pauli observable `observable`, sampling the outcome. The
    /// register grows to cover its support.
    ///
    /// A [`PauliString`] is Hermitian by construction, so any string is a legal
    /// observable.
    ///
    /// # Errors
    /// [`SimError::RankOverflow`] if the projection exceeds the rank cap.
    ///
    /// # Examples
    ///
    /// ```
    /// use ticit::{PauliString, TableauSimulator};
    ///
    /// let mut sim = TableauSimulator::with_seed(2, 1);
    /// sim.h(0);
    /// sim.cx(0, 1)?;
    /// // `ZZ` stabilizes a Bell pair, so reading it disturbs nothing.
    /// let result = sim.measure_observable(&PauliString::try_from("ZZ")?)?;
    /// assert!(result.deterministic && !result.outcome);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn measure_observable(
        &mut self,
        observable: &PauliString,
    ) -> Result<MeasureResult, SimError> {
        self.ensure_for_observable(observable)?;
        with_terms!(self, |core, terms| {
            let d = core.decompose(observable)?;
            terms.measure_decomposed(core, &d, None)
        })
    }

    /// Force `observable`'s measurement to `desired_value` (`false` = `+1`)
    /// instead of sampling it, projecting the state onto that eigenspace.
    ///
    /// The returned [`MeasureResult::probability`] is the weight the branch had
    /// before the projection — what a caller weights the post-selected shot by.
    ///
    /// # Errors
    /// [`SimError::PostselectImpossible`] if `desired_value` has probability
    /// `≈ 0`, plus the
    /// [`measure_observable`](Self::measure_observable) errors.
    pub fn postselect_observable(
        &mut self,
        observable: &PauliString,
        desired_value: bool,
    ) -> Result<MeasureResult, SimError> {
        self.ensure_for_observable(observable)?;
        with_terms!(self, |core, terms| {
            let d = core.decompose(observable)?;
            terms.measure_decomposed(core, &d, Some(desired_value))
        })
    }

    /// Force qubit `q`'s `Z` measurement to `desired_value`: `false` selects
    /// `|0⟩`, `true` selects `|1⟩`.
    ///
    /// # Errors
    /// As [`postselect_observable`](Self::postselect_observable).
    pub fn postselect_z(
        &mut self,
        q: usize,
        desired_value: bool,
    ) -> Result<MeasureResult, SimError> {
        self.measure_axis(Axis::Z, q, Some(desired_value))
    }

    /// Force qubit `q`'s `X` measurement: `false` selects `|+⟩`, `true` `|−⟩`.
    ///
    /// # Errors
    /// As [`postselect_observable`](Self::postselect_observable).
    pub fn postselect_x(
        &mut self,
        q: usize,
        desired_value: bool,
    ) -> Result<MeasureResult, SimError> {
        self.measure_axis(Axis::X, q, Some(desired_value))
    }

    /// Force qubit `q`'s `Y` measurement: `false` selects `|i⟩`, `true` `|−i⟩`.
    ///
    /// # Errors
    /// As [`postselect_observable`](Self::postselect_observable).
    pub fn postselect_y(
        &mut self,
        q: usize,
        desired_value: bool,
    ) -> Result<MeasureResult, SimError> {
        self.measure_axis(Axis::Y, q, Some(desired_value))
    }

    /// Measure a single-qubit basis axis, sampling or forcing the outcome.
    ///
    /// The one body behind `measure`, the three `postselect_*` wrappers and the
    /// three resets: all six decompose a stored frame row rather than a Pauli.
    fn measure_axis(
        &mut self,
        axis: Axis,
        q: usize,
        forced: Option<bool>,
    ) -> Result<MeasureResult, SimError> {
        self.ensure_qubits(q + 1);
        with_terms!(self, |core, terms| {
            let d = core.decompose_basis(axis, q);
            terms.measure_decomposed(core, &d, forced)
        })
    }

    // --- Non-collapsing reads ---

    /// Non-collapsing expectation value `⟨P⟩ ∈ [−1, 1]` of `observable`,
    /// leaving both the state and the RNG untouched.
    ///
    /// This is the same `⟨Q⟩` the measurement path derives its outcome
    /// probability from (`p₊ = (1 + ⟨Q⟩)/2`), read out without projecting. On
    /// an eigenstate it is exactly `±1`; off an eigenstate it is the true
    /// expectation (e.g. `⟨X⟩ = ⟨Y⟩ = 1/√2` on `T|+⟩`).
    ///
    /// `observable`'s support must lie within the allocated qubits — being
    /// `&self`, this cannot grow the register.
    ///
    /// # Errors
    /// [`SimError::QubitIndexOutOfRange`] if the support exceeds the live
    /// register.
    ///
    /// # Examples
    ///
    /// ```
    /// use ticit::{PauliString, TableauSimulator};
    ///
    /// let mut sim = TableauSimulator::with_seed(2, 0);
    /// sim.h(0);
    /// sim.cx(0, 1)?;
    /// let xx = PauliString::try_from("XX")?;
    /// assert!((sim.peek_observable_expectation(&xx)? - 1.0).abs() < 1e-9);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn peek_observable_expectation(&self, observable: &PauliString) -> Result<f64, SimError> {
        with_terms_ref!(self, |core, terms| {
            let d = core.decompose(observable)?;
            Ok(terms.expectation_of(&d).clamp(-1.0, 1.0))
        })
    }

    /// `⟨Z_q⟩`, without measuring.
    ///
    /// # Errors
    /// [`SimError::QubitIndexOutOfRange`] if `q` is outside the live register.
    pub fn peek_z(&self, q: usize) -> Result<f64, SimError> {
        self.peek_axis(Axis::Z, q)
    }

    /// `⟨X_q⟩`, without measuring.
    ///
    /// # Errors
    /// [`SimError::QubitIndexOutOfRange`] if `q` is outside the live register.
    pub fn peek_x(&self, q: usize) -> Result<f64, SimError> {
        self.peek_axis(Axis::X, q)
    }

    /// `⟨Y_q⟩`, without measuring.
    ///
    /// # Errors
    /// [`SimError::QubitIndexOutOfRange`] if `q` is outside the live register.
    pub fn peek_y(&self, q: usize) -> Result<f64, SimError> {
        self.peek_axis(Axis::Y, q)
    }

    /// [`peek_observable_expectation`](Self::peek_observable_expectation) for a
    /// single-qubit basis axis. The range check is explicit because
    /// `decompose_basis` is infallible and asserts instead.
    fn peek_axis(&self, axis: Axis, q: usize) -> Result<f64, SimError> {
        if q >= self.core.n {
            return Err(SimError::QubitIndexOutOfRange {
                index: q,
                num_qubits: self.core.n,
            });
        }
        with_terms_ref!(self, |core, terms| {
            let d = core.decompose_basis(axis, q);
            Ok(terms.expectation_of(&d).clamp(-1.0, 1.0))
        })
    }

    // --- Reset ---

    /// Reset qubit `q` to `|0⟩` — stim's spelling of
    /// [`reset_z`](Self::reset_z).
    ///
    /// # Errors
    /// Propagates measurement errors.
    pub fn reset(&mut self, q: usize) -> Result<(), SimError> {
        self.reset_z(q)
    }

    /// Reset qubit `q` to `|0⟩`: measure `Z_q`, then apply `X_q` if the outcome
    /// was `−1`.
    ///
    /// # Errors
    /// Propagates measurement errors.
    pub fn reset_z(&mut self, q: usize) -> Result<(), SimError> {
        self.reset_about(Axis::Z, q, Axis::X)
    }

    /// Reset qubit `q` to `|+⟩`: measure `X_q`, correct with `Z_q` if `−1`.
    ///
    /// # Errors
    /// Propagates measurement errors.
    pub fn reset_x(&mut self, q: usize) -> Result<(), SimError> {
        self.reset_about(Axis::X, q, Axis::Z)
    }

    /// Reset qubit `q` to `|+i⟩`: measure `Y_q`, correct with `Z_q` if `−1`.
    ///
    /// # Errors
    /// Propagates measurement errors.
    pub fn reset_y(&mut self, q: usize) -> Result<(), SimError> {
        self.reset_about(Axis::Y, q, Axis::Z)
    }

    /// Measure a basis axis and, on a `−1` outcome, apply the Pauli that maps
    /// that eigenstate onto the `+1` one. One dispatch site for all three
    /// resets, which is also three fewer copies of the measurement body.
    fn reset_about(&mut self, axis: Axis, q: usize, correction: Axis) -> Result<(), SimError> {
        if self.measure_axis(axis, q, None)?.outcome {
            match correction {
                Axis::X => self.core.r.left_x(q),
                Axis::Y => self.core.r.left_y(q),
                Axis::Z => self.core.r.left_z(q),
            }
        }
        Ok(())
    }

    // --- Test/inspection hook ---

    /// Reconstruct the dense state vector `|ψ⟩` (length `2^n`).
    ///
    /// Replays the frame `R` (via its `image_x`/`image_z` images) against the
    /// amplitude map. This is `O(rank · n · 2^n)` and intended for testing and
    /// small `n` only.
    ///
    /// # Panics
    ///
    /// Panics unless `n < 64`, where the length stops fitting a `usize`. The
    /// check is an assertion rather than an error because the bound it enforces
    /// is nowhere near the one that matters: `2^n` amplitudes are 16 GiB by
    /// `n = 30`, so every caller that gets an answer at all is far below it.
    /// Without the check the shift wraps, and a release build hands back a
    /// vector of the wrong length instead of failing.
    #[must_use]
    pub fn state_vector(&self) -> Vec<Complex64> {
        let n = self.core.n;
        assert!(
            n < usize::BITS as usize,
            "state-vector reconstruction needs a 2^{n} length that fits a usize"
        );
        let dim = 1usize << n;

        // |ψ0⟩ is the stabilizer state with stabilizers S_i = image_z(i). Build
        // it by projecting a computational-basis fiducial through ∏(I+S_i)/2 =
        // |ψ0⟩⟨ψ0|; any fiducial with nonzero overlap works (global phase is
        // irrelevant to the up-to-phase comparison callers make).
        let stabs: Vec<RowPauli> = (0..n).map(|i| self.core.r.image_z(i)).collect();
        let mut psi0 = vec![Complex64::new(0.0, 0.0); dim];
        for fiducial in 0..dim {
            let mut v = vec![Complex64::new(0.0, 0.0); dim];
            v[fiducial] = Complex64::new(1.0, 0.0);
            for s in &stabs {
                let projected = apply_pauli_dense(&v, s);
                for (dst, add) in v.iter_mut().zip(projected) {
                    *dst = (*dst + add) * 0.5;
                }
            }
            let norm: f64 = v.iter().map(num_complex::Complex::norm_sqr).sum();
            if norm > TOL {
                let scale = norm.sqrt().recip();
                for (dst, src) in psi0.iter_mut().zip(v) {
                    *dst = src * scale;
                }
                break;
            }
        }

        // |ψ⟩ = Σ_c xvec[c] · D^c|ψ0⟩, D_i = image_x(i), applied per set bit.
        let destabs: Vec<RowPauli> = (0..n).map(|i| self.core.r.image_x(i)).collect();
        let mut out = vec![Complex64::new(0.0, 0.0); dim];
        match &self.amps {
            Amps::W1(t) => replay_terms(&t.map, &psi0, &destabs, &mut out),
            Amps::W2(t) => replay_terms(&t.map, &psi0, &destabs, &mut out),
            Amps::W4(t) => replay_terms(&t.map, &psi0, &destabs, &mut out),
            Amps::W8(t) => replay_terms(&t.map, &psi0, &destabs, &mut out),
            Amps::Wide(t) => replay_terms(&t.map, &psi0, &destabs, &mut out),
        }
        out
    }
}

// ==============================================================================
// Frame decomposition and outcome sampling
// ==============================================================================

impl Core {
    /// Decompose Pauli `p` in the frame: `Q = R†PR = ζ X^a Z^b`.
    ///
    /// The frame writes the two masks straight into the label words, so the
    /// only cost beyond the row product is the two (inline) labels.
    fn decompose<K: LabelKey>(&self, p: &PauliString) -> Result<Decomp<K>, SimError> {
        if let Some(index) = p.max_support().filter(|&index| index >= self.n) {
            return Err(SimError::QubitIndexOutOfRange {
                index,
                num_qubits: self.n,
            });
        }
        // `words` carries only the body, so the operator's own coefficient has
        // to be folded in here: a `−1` is `i^2`, and an imaginary one is not an
        // observable at all.
        let negated = measurement_phase_sign(p).map_err(|_| SimError::NonHermitianPauli)?;
        let mut a = K::zeros(self.words);
        let mut b = K::zeros(self.words);
        let phase = (self
            .r
            .preimage_into(words(p), a.as_mut_slice(), b.as_mut_slice())
            + 2 * u8::from(negated))
            & 3;
        Ok(Decomp {
            a,
            b,
            phase,
            zeta: i_pow(phase),
        })
    }

    /// [`decompose`](Self::decompose) for a single-qubit basis axis. `T`, the
    /// single-qubit measurements, the post-selections and the resets all go
    /// through here, which is what keeps them off the `PauliString` path: a
    /// basis preimage is a stored row.
    ///
    /// The caller must have grown the register past `qubit`; a basis axis
    /// cannot be non-Hermitian or out of range, so this is infallible.
    fn decompose_basis<K: LabelKey>(&self, axis: Axis, qubit: usize) -> Decomp<K> {
        let mut a = K::zeros(self.words);
        let mut b = K::zeros(self.words);
        let phase = self
            .r
            .preimage_basis_into(axis, qubit, a.as_mut_slice(), b.as_mut_slice());
        Decomp {
            a,
            b,
            phase,
            zeta: i_pow(phase),
        }
    }

    /// Sample or force an outcome. `p0` is the probability of the `+1` (`false`)
    /// outcome; the RNG draw matches `SOFT`'s `rand() >= p0 ? 1 : 0` (`>=` keeps
    /// `p0 = 0` deterministic — a `+1` of probability zero never samples).
    fn choose(&mut self, forced: Option<bool>, p0: f64) -> bool {
        match forced {
            Some(o) => o,
            None => {
                let r = rand_float(&mut self.rng);
                r >= p0
            }
        }
    }

    /// Reject a projected label count that exceeds the cap. Always called
    /// before the state is touched, so the failure is transactional.
    fn check_cap(&self, rank: usize) -> Result<(), SimError> {
        if rank > self.rank_cap {
            return Err(SimError::RankOverflow {
                rank,
                cap: self.rank_cap,
            });
        }
        Ok(())
    }
}

// ==============================================================================
// Amplitude storage — width selection
// ==============================================================================

impl Amps {
    /// The single-term map of a fresh `|0…0⟩` state.
    fn unit(words: usize) -> Self {
        match Width::for_words(words) {
            Width::W1 => Amps::W1(Terms::unit(words)),
            Width::W2 => Amps::W2(Terms::unit(words)),
            Width::W4 => Amps::W4(Terms::unit(words)),
            Width::W8 => Amps::W8(Terms::unit(words)),
            Width::Wide => Amps::Wide(Terms::unit(words)),
        }
    }

    fn width(&self) -> Width {
        match self {
            Amps::W1(_) => Width::W1,
            Amps::W2(_) => Width::W2,
            Amps::W4(_) => Width::W4,
            Amps::W8(_) => Width::W8,
            Amps::Wide(_) => Width::Wide,
        }
    }

    fn len(&self) -> usize {
        match self {
            Amps::W1(t) => t.map.len(),
            Amps::W2(t) => t.map.len(),
            Amps::W4(t) => t.map.len(),
            Amps::W8(t) => t.map.len(),
            Amps::Wide(t) => t.map.len(),
        }
    }

    /// Re-key the live terms for a register that has grown to `words` words.
    ///
    /// Inside one width class there is nothing to do: a fixed-width key's
    /// surplus words were already zero and stay zero, so the existing keys are
    /// still valid at the wider register. Only crossing into a wider class — or
    /// widening a runtime-width label, whose length *is* its width — changes the
    /// key, and then the map is rebuilt. Cold either way: growth only happens
    /// when an operation names a qubit past the current register.
    fn widen(&mut self, words: usize) {
        let target = Width::for_words(words);
        if target == self.width() && target != Width::Wide {
            return;
        }
        let live = self.drain_terms();
        *self = match target {
            Width::W1 => Amps::W1(Terms::rekeyed(live, words)),
            Width::W2 => Amps::W2(Terms::rekeyed(live, words)),
            Width::W4 => Amps::W4(Terms::rekeyed(live, words)),
            Width::W8 => Amps::W8(Terms::rekeyed(live, words)),
            Width::Wide => Amps::Wide(Terms::rekeyed(live, words)),
        };
    }

    /// Every live term as raw words plus its amplitude.
    fn drain_terms(&mut self) -> Vec<(Vec<u64>, Complex64)> {
        fn collect<K: LabelKey>(map: &mut FxHashMap<K, Complex64>) -> Vec<(Vec<u64>, Complex64)> {
            map.drain()
                .map(|(key, value)| (key.as_slice().to_vec(), value))
                .collect()
        }
        match self {
            Amps::W1(t) => collect(&mut t.map),
            Amps::W2(t) => collect(&mut t.map),
            Amps::W4(t) => collect(&mut t.map),
            Amps::W8(t) => collect(&mut t.map),
            Amps::Wide(t) => collect(&mut t.map),
        }
    }

    /// The single-word specialization, for tests that spell labels out by hand.
    #[cfg(test)]
    fn narrow(&mut self) -> &mut Terms<Key<1>> {
        match self {
            Amps::W1(terms) => terms,
            other => panic!("expected a one-word map, got {:?}", other.width()),
        }
    }
}

// ==============================================================================
// The amplitude engine, monomorphized per label width
// ==============================================================================

impl<K: LabelKey> Terms<K> {
    /// The single-term map of a fresh `|0…0⟩` state.
    fn unit(words: usize) -> Self {
        let mut map = FxHashMap::default();
        map.insert(K::zeros(words), Complex64::new(1.0, 0.0));
        Terms {
            map,
            rotation: RotationScratch::default(),
        }
    }

    /// Adopt terms drained from a narrower width.
    fn rekeyed(live: Vec<(Vec<u64>, Complex64)>, words: usize) -> Self {
        Terms {
            map: live
                .into_iter()
                .map(|(bits, value)| (K::from_words(&bits, words), value))
                .collect(),
            rotation: RotationScratch::default(),
        }
    }

    // --- T ---

    /// `T_P(±)` about an axis already decomposed in the frame — the one place
    /// the rotation lives, shared by [`TableauSimulator::t_pauli`] and the basis-axis
    /// entry points that never build a `PauliString`.
    fn t_decomposed(&mut self, core: &Core, d: &Decomp<K>, adjoint: bool) -> Result<(), SimError> {
        let cos = (PI / 8.0).cos();
        let sin = (PI / 8.0).sin();
        self.rotation_decomposed(
            core,
            d,
            cos,
            Complex64::new(0.0, if adjoint { sin } else { -sin }),
        )
    }

    /// Arbitrary-angle counterpart of [`t_decomposed`](Self::t_decomposed).
    fn rotate_decomposed(
        &mut self,
        core: &Core,
        d: &Decomp<K>,
        kernel_angle: f64,
    ) -> Result<(), SimError> {
        self.rotation_decomposed(
            core,
            d,
            kernel_angle.cos(),
            Complex64::new(0.0, -kernel_angle.sin()),
        )
    }

    fn rotation_decomposed(
        &mut self,
        core: &Core,
        d: &Decomp<K>,
        cos: f64,
        branch: Complex64,
    ) -> Result<(), SimError> {
        #[cfg(target_arch = "x86_64")]
        if has_popcnt() {
            // SAFETY: `has_popcnt` probes exactly the enabled target feature.
            #[allow(unsafe_code)]
            return unsafe { self.rotation_decomposed_popcnt(core, d, cos, branch) };
        }
        self.rotation_decomposed_inner(core, d, cos, branch)
    }

    /// [`rotation_decomposed`](Self::rotation_decomposed)'s `popcnt` twin. See
    /// [`frame::has_popcnt`] for why these exist.
    ///
    /// The body must be `inline(always)`: a `#[target_feature]` function only
    /// carries the feature into code inlined *into* it, so a twin LLVM
    /// declines to inline compiles to a `jmp` and selects the same
    /// instructions as the plain path. That failure reads as "no gain" in a
    /// benchmark, so both surviving twins are checked with
    /// `objdump -d target/release/… | grep popcnt` rather than by timing
    /// alone.
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "popcnt")]
    fn rotation_decomposed_popcnt(
        &mut self,
        core: &Core,
        d: &Decomp<K>,
        cos: f64,
        branch: Complex64,
    ) -> Result<(), SimError> {
        self.rotation_decomposed_inner(core, d, cos, branch)
    }

    #[inline(always)]
    fn rotation_decomposed_inner(
        &mut self,
        core: &Core,
        d: &Decomp<K>,
        cos: f64,
        branch: Complex64,
    ) -> Result<(), SimError> {
        if d.a.is_zero() {
            return self.t_diagonal(core, d, cos, branch);
        }
        // The staging buffers live on `self`, so they have to be moved out for
        // the duration; every exit path hands them back, cleared but with their
        // capacity intact.
        let mut scratch = std::mem::take(&mut self.rotation);
        let result = self.t_paired(core, d, cos, branch, &mut scratch);
        scratch.clear();
        self.rotation = scratch;
        result
    }

    /// `T` about a frame-diagonal axis (`a = 0`), where both branches land on
    /// the same label and the rotation collapses to a per-label factor
    /// `cos ∓ i·sin·ζ·(−1)^{⟨b,c⟩}`.
    ///
    /// `ζ` is real (`±1`) here — a Hermitian `Q = ζ Z^b` forces an even phase
    /// exponent — so every factor is `cos ± i·sin`, of modulus one. Labels,
    /// individual moduli and the total norm therefore all survive untouched,
    /// which is what lets this path skip the map rebuild, the pruning and the
    /// renormalization that the general case needs.
    fn t_diagonal(
        &mut self,
        core: &Core,
        d: &Decomp<K>,
        cos: f64,
        branch: Complex64,
    ) -> Result<(), SimError> {
        debug_assert!(
            d.zeta.im.abs() < TOL,
            "diagonal T axis has a non-real phase"
        );
        // The rank cannot grow here, but a cap lowered under the live rank must
        // still be reported, and reported before anything is touched.
        core.check_cap(self.map.len())?;
        let plus = Complex64::new(cos, branch.im * d.zeta.re);
        let minus = plus.conj();
        for (c, value) in &mut self.map {
            *value *= if c.dot_parity(&d.b) { minus } else { plus };
        }
        Ok(())
    }

    /// `T` about an off-diagonal axis (`a ≠ 0`). Labels split into cosets
    /// `{c, c ⊕ a}` that the rotation mixes only with themselves, so every live
    /// label keeps its slot: its new amplitude is written back in place and the
    /// map only grows by the coset partners it was missing.
    fn t_paired(
        &mut self,
        core: &Core,
        d: &Decomp<K>,
        cos: f64,
        branch: Complex64,
        scratch: &mut RotationScratch<K>,
    ) -> Result<(), SimError> {
        let (removals, norm) = self.stage_t_rotation(core, d, cos, branch, scratch);
        // `T_P` is unitary, so each pair's norm is preserved exactly and only a
        // pruned amplitude can cost the state its normalization.
        self.commit_pair_rewrite(core, scratch, removals, norm)
    }

    /// Install a staged coset-pair rewrite, rescaled to unit norm by `norm`.
    ///
    /// Both operations that mix a label with its coset partner — the `T`
    /// rotation and the random-measurement projection — recompute every live
    /// label's amplitude from its own and its partner's, so both stage
    /// positionally into `scratch` and commit the same way. `removals` is how
    /// many staged amplitudes pruned away to nothing, and `norm` the `Σ|x|²`
    /// the survivors carry — `None` where the operation is norm-preserving and
    /// nothing was pruned, so there is nothing to rescale.
    ///
    /// One sweep does all three of writing back, pruning and rescaling.
    /// Rescaling used to be its own pass (measure the norm, then divide),
    /// which is redundant once the staging pass hands its own sum over: a
    /// projection is precisely the operation whose norm cannot be assumed, and
    /// it is also the one that has just computed every surviving modulus.
    ///
    /// The rank is vetted before a single slot is written, which is what makes
    /// a [`SimError::RankOverflow`] transactional: the caller can still be
    /// holding a frame update it has not applied yet.
    fn commit_pair_rewrite(
        &mut self,
        core: &Core,
        scratch: &mut RotationScratch<K>,
        removals: usize,
        norm: Option<f64>,
    ) -> Result<(), SimError> {
        let rank = self.map.len() + scratch.inserts.len() - removals;
        if rank == 0 {
            return Err(SimError::EmptyStateAfterPruning {
                epsilon: core.prune_epsilon,
            });
        }
        core.check_cap(rank)?;

        let scale = match norm {
            Some(total) if total > 0.0 => total.sqrt().recip(),
            _ => 1.0,
        };
        debug_assert_eq!(scratch.values.len(), self.map.len());
        if removals == 0 {
            // Nothing has touched the map since the staging pass, so
            // `values_mut` walks the same slots in the same order the staging
            // `iter` did.
            for (slot, &value) in self.map.values_mut().zip(&scratch.values) {
                *slot = value * scale;
            }
        } else {
            // `retain` walks that same order, and hashbrown erases in place
            // without moving a survivor, so the writeback and the prune are
            // one sweep. The keep test is spelled against the *staged*
            // modulus, not the rescaled one it just stored, so it agrees with
            // `removals` bit for bit rather than merely algebraically.
            let eps_sq = core.prune_epsilon.powi(2);
            let mut staged = scratch.values.iter();
            self.map.retain(|_, slot| {
                let &value = staged
                    .next()
                    .expect("one staged amplitude per live label, in map order");
                *slot = value * scale;
                value.norm_sqr() > eps_sq
            });
        }
        self.map.reserve(scratch.inserts.len());
        for (label, value) in scratch.inserts.drain(..) {
            self.map.insert(label, value * scale);
        }
        // A projection routinely halves the rank, and the table it collapsed
        // out of would otherwise be walked in full by every later pass.
        if removals > 0 {
            shrink_if_sparse(&mut self.map, rank);
        }
        Ok(())
    }

    /// Compute every live label's post-`T` amplitude and the partners the
    /// rotation adds. Returns the number of live labels that prune away to
    /// nothing, and the norm to rescale by — `None` unless something was
    /// pruned, since the rotation is otherwise exactly norm-preserving (a
    /// partner dropped below the threshold costs norm without removing a
    /// label, so the two are not the same condition).
    ///
    /// Read-only, so the caller can vet the resulting rank before committing
    /// any of it. The staged amplitudes are positional — the applying pass
    /// relies on them lining up with the amplitude map's iteration order.
    fn stage_t_rotation(
        &self,
        core: &Core,
        d: &Decomp<K>,
        cos: f64,
        branch: Complex64,
        scratch: &mut RotationScratch<K>,
    ) -> (usize, Option<f64>) {
        // On the pair `{c, p = c ⊕ a}` the rotation acts as
        //
        //   new_c = cos·x_c + g·sign_p·x_p,   g = ∓i·sin·ζ,  sign_w = (−1)^{⟨b,w⟩},
        //
        // so a live label's new amplitude needs nothing but its partner's old
        // one. The two signs differ by the constant `(−1)^{⟨b,a⟩}`, which saves
        // a parity per term. A missing partner counts as `x_p = 0`, and the
        // pair then gains it at `g·sign_c·x_c`.
        let g = branch * d.zeta;
        let flip = if d.a.dot_parity(&d.b) { -1.0 } else { 1.0 };
        let eps_sq = core.prune_epsilon.powi(2);
        let mut removals = 0;
        let mut pruned = false;
        let mut norm = 0.0;

        scratch.values.clear();
        scratch.inserts.clear();
        scratch.values.reserve(self.map.len());
        for (c, &x) in &self.map {
            let sign_c = if c.dot_parity(&d.b) { -1.0 } else { 1.0 };
            let partner = c.xor(&d.a);
            let value = match self.map.get(&partner) {
                Some(&y) => cos * x + g * (sign_c * flip) * y,
                None => {
                    let added = g * sign_c * x;
                    let weight = added.norm_sqr();
                    if weight > eps_sq {
                        scratch.inserts.push((partner, added));
                        norm += weight;
                    } else {
                        pruned = true;
                    }
                    cos * x
                }
            };
            let weight = value.norm_sqr();
            if weight <= eps_sq {
                removals += 1;
                pruned = true;
            } else {
                norm += weight;
            }
            scratch.values.push(value);
        }
        (removals, pruned.then_some(norm))
    }

    // --- Measurement ---

    /// Measure an observable already decomposed in the frame. The branch is
    /// decided by `a`: zero means every term is an eigenstate, non-zero means
    /// the outcome is genuinely random. Shared with the reset entry points,
    /// which decompose their basis axis directly.
    fn measure_decomposed(
        &mut self,
        core: &mut Core,
        d: &Decomp<K>,
        forced: Option<bool>,
    ) -> Result<MeasureResult, SimError> {
        self.measure_decomposed_inner(core, d, forced)
    }

    #[inline(always)]
    fn measure_decomposed_inner(
        &mut self,
        core: &mut Core,
        d: &Decomp<K>,
        forced: Option<bool>,
    ) -> Result<MeasureResult, SimError> {
        if d.a.is_zero() {
            self.measure_frame_deterministic(core, d, forced)
        } else {
            self.measure_random(core, d, forced)
        }
    }

    /// Case A: `a = 0`, every term is a `±1` eigenstate. `R` is
    /// unchanged; we split by eigenvalue and keep the winning class.
    fn measure_frame_deterministic(
        &mut self,
        core: &mut Core,
        d: &Decomp<K>,
        forced: Option<bool>,
    ) -> Result<MeasureResult, SimError> {
        // ζ = i^k is real (±1) because a Hermitian diagonal Pauli has even k.
        debug_assert!(
            d.zeta.im.abs() < TOL,
            "diagonal observable has non-real phase"
        );
        let zsign = d.zeta.re;

        // p₊ = (1 + ⟨Q⟩)/2 with ⟨Q⟩ the (real) diagonal expectation shared
        // with [`TableauSimulator::expectation`].
        let p_plus = ((1.0 + self.expectation_of(d)) / 2.0).clamp(0.0, 1.0);
        let deterministic = !(TOL..=1.0 - TOL).contains(&p_plus);

        let outcome = core.choose(forced, p_plus);
        let probability = if outcome { 1.0 - p_plus } else { p_plus };
        if forced.is_some() && probability < TOL {
            return Err(SimError::PostselectImpossible {
                outcome,
                probability,
            });
        }

        // Projection is a filter on the existing labels, so it runs in place.
        // The survivors are counted (and their norm accumulated for the
        // rescale) in a read-only pass first: an empty result is an error, and
        // a failed projection must leave the state exactly as it was.
        let keep_plus = !outcome;
        let eps_sq = core.prune_epsilon.powi(2);
        let keep = |label: &K, amplitude: &Complex64| {
            eig_plus(label, &d.b, zsign) == keep_plus && amplitude.norm_sqr() > eps_sq
        };
        let mut live = 0;
        let mut total = 0.0;
        for (label, amplitude) in &self.map {
            if keep(label, amplitude) {
                live += 1;
                total += amplitude.norm_sqr();
            }
        }
        if live == 0 {
            return Err(SimError::EmptyStateAfterPruning {
                epsilon: core.prune_epsilon,
            });
        }
        core.check_cap(live)?;
        // Measuring an eigenstate — the common case in verification circuits —
        // keeps every label, and then there is nothing to walk the table for.
        if live < self.map.len() {
            self.map.retain(|label, amplitude| keep(label, amplitude));
            shrink_if_sparse(&mut self.map, live);
        }
        self.rescale(total);

        Ok(MeasureResult {
            outcome,
            probability,
            deterministic,
        })
    }

    /// Case B: `a ≠ 0`, a genuinely random outcome. The amplitude map is
    /// projected onto the `Q`-eigenspace and the frame re-compressed:
    ///
    /// ```text
    /// |χ⟩ ← exp(−iπ/4·G) · Z_p^s · Π_s^Q |χ⟩,   R ← R · Z_p^s · exp(iπ/4·G).
    /// ```
    ///
    /// The two rotations are inverses of one another and the two `Z_p^s` sit on
    /// opposite sides of them, so `R|χ⟩` telescopes back to `Π_s^P|ψ⟩` — which
    /// is the whole correctness condition, and the reason both sides must read
    /// `G` from the same place. (`exp(−iπ/4·G) = (I − iG)/√2` is where
    /// [`PAULI_EXP_SIGN`] comes from.)
    ///
    /// # Where `G` comes from
    ///
    /// `pauliverse` updates the frame from the *left*, as
    /// `R ← S_p^s · exp(iπ/4·pa)·R` with `S_p = R Z_p R†` the stabilizer at the
    /// pivot and `pa = −i·P·S_p`. Both factors move to the right of `R`, which
    /// is what lets this path skip `S_p` — an image, i.e. a column gather over
    /// the whole tableau plus a phase solve — altogether:
    ///
    /// ```text
    /// exp(iπ/4·pa)·R = R·exp(iπ/4·G)   with G = R†·pa·R,
    /// S_p·(R·V)      = R·Z_p·V         for any V, since R†S_pR = Z_p exactly.
    /// ```
    ///
    /// Mind the order: `S_p` was applied *after* the rotation on the left, so
    /// `Z_p` lands *before* it on the right. That is not a free choice — the
    /// pivot is a set bit of `a`, so `Z_p` anticommutes with `G` and the two
    /// orders differ by `exp(iπ/2·G) = iG`, which would leave the state off by
    /// a Pauli.
    ///
    /// `G` itself needs no frame work at all. With `Q = R†PR = i^k·X^a Z^b`
    /// already in hand from `d`,
    ///
    /// ```text
    /// G = R†(−i·P·S_p)R = −i·Q·Z_p = i^{k+3}·X^a·Z^{b ⊕ e_p},
    /// ```
    ///
    /// because `Z^b·Z_p = Z^{b⊕e_p}` costs no phase. The `−i` is what makes `G`
    /// Hermitian: `P` anticommutes with `S_p` here, so their product is
    /// anti-Hermitian. `+i` would serve as well — the amplitude side derives
    /// its rotation from the same `G`, so the two sign choices cancel — but
    /// `−i` is what `paulimer`'s update picks, and one source of truth for `G`
    /// is what keeps the two sides consistent.
    fn measure_random(
        &mut self,
        core: &mut Core,
        d: &Decomp<K>,
        forced: Option<bool>,
    ) -> Result<MeasureResult, SimError> {
        // The staging buffers live on `self`, so they are moved out for the
        // duration and handed back cleared, capacity intact.
        let mut scratch = std::mem::take(&mut self.rotation);
        let result = self.measure_random_staged(core, d, forced, &mut scratch);
        scratch.clear();
        self.rotation = scratch;
        result
    }

    /// [`measure_random`](Self::measure_random) with its staging buffers in
    /// hand, so every exit path hands them back through one place.
    fn measure_random_staged(
        &mut self,
        core: &mut Core,
        d: &Decomp<K>,
        forced: Option<bool>,
        scratch: &mut RotationScratch<K>,
    ) -> Result<MeasureResult, SimError> {
        let pivot = d.a.first_set_bit().expect("random branch has nonzero a");

        // ⟨Q⟩ = Σ_c Re( ζ·(−1)^{⟨b,c⟩}·xvec[c]·conj(xvec[c⊕a]) ), the
        // off-diagonal branch of [`TableauSimulator::expectation`] — run here in the
        // variant that records where it found each pair, because the
        // projection below needs exactly the same pairing and the map does not
        // move between the two passes.
        let p0 = ((1.0 + self.expectation_paired(d, &mut scratch.partners)) / 2.0).clamp(0.0, 1.0);

        let outcome = core.choose(forced, p0);
        let probability = if outcome { 1.0 - p0 } else { p0 };
        if forced.is_some() && probability < TOL {
            return Err(SimError::PostselectImpossible {
                outcome,
                probability,
            });
        }
        let s = outcome;

        // `G = i^{k+3}·X^a·Z^{b⊕e_p}`, derived above. `Z_p` contributes no `X`
        // part, so `G` and `Q` share their coset shift `a` by construction —
        // that is what keeps the compression on the same pair of labels the
        // projection uses, below.
        let g_phase = (d.phase + 3) & 3;
        let gzeta = i_pow(g_phase);
        let mut gb = d.b.clone();
        gb.flip(pivot);

        // Projection `Π_s^Q = ½(I + (−1)^s Q)`, the `Z_p^s` fold and the frame
        // compression `(I ± iG)/√2` all in one pass. As scatters, the first two
        // send an amplitude `x` at label `c` to
        //
        //   y0 = ½·z(c)·x                              at c,
        //   y1 = ½·(−1)^s·ζ·(−1)^{⟨b,c⟩}·z(c⊕a)·x      at c ⊕ a,
        //
        // writing `z(k) = (−1)^{s·k_p}` for `Z_p^s`, and the third sends `y` at
        // `k` to `y/√2` at `k` and `w·(−1)^{⟨gb,k⟩}·y` at `k ⊕ a`, with
        // `w = i·PAULI_EXP_SIGN/√2·ζ_g`. Composing them, all four products land
        // back on `{c, c⊕a}` — which is the whole reason this can run in place,
        // exactly like the `T` rotation: a label's new amplitude is a function
        // of its own and its coset partner's, so it keeps its slot and the map
        // is never rebuilt.
        let projection = Projection {
            d,
            gb: &gb,
            pivot,
            s,
            ssign: if s { -1.0 } else { 1.0 },
            compress: Complex64::new(0.0, PAULI_EXP_SIGN * FRAC_1_SQRT_2) * gzeta,
            shift_flip: if gb.dot_parity(&d.a) { -1.0 } else { 1.0 },
        };
        debug_assert_ne!(
            gb.dot_parity(&d.a),
            d.b.dot_parity(&d.a),
            "the pivot bit of `a` is set, so `gb` and `b` differ in their `a` parity"
        );

        // A projection is not norm-preserving — what it removes is the weight
        // of the eigenspace it rejected — so the staged norm always feeds the
        // commit's rescale.
        let (removals, norm) = self.stage_projection(core, &projection, scratch);
        // Commit the amplitude map before touching `R`: the commit is fallible
        // (`RankOverflow`) and returns without modifying the map on that path,
        // so deferring the `R` update keeps the two atomic — a frame advanced
        // past an un-committed map would be unrecoverable.
        self.commit_pair_rewrite(core, scratch, removals, Some(norm))?;

        // Update R to match the committed map: `R ← R·Z_p^s·exp(iπ/4·G)`, the
        // right-multiplied form of the frame update (see above).
        if s {
            core.r.right_pauli_z(pivot);
        }
        core.r
            .right_pauli_exp(d.a.as_slice(), gb.as_slice(), g_phase);

        // A frame-random observable can still be a state eigenvalue (e.g. X on
        // |+⟩): report determinism from the probability, not the branch.
        let deterministic = !(TOL..=1.0 - TOL).contains(&p0);
        Ok(MeasureResult {
            outcome,
            probability,
            deterministic,
        })
    }

    /// Compute every live label's post-projection amplitude and the partners
    /// the projection brings into the map, returning how many live labels
    /// prune away to nothing and the `Σ|x|²` the survivors carry.
    ///
    /// The mirror of [`stage_t_rotation`](Self::stage_t_rotation): read-only
    /// and positional. Unlike it, this pass does not probe the map at all —
    /// [`expectation_paired`](Self::expectation_paired) has just located every
    /// coset partner for it.
    fn stage_projection(
        &self,
        core: &Core,
        projection: &Projection<'_, K>,
        scratch: &mut RotationScratch<K>,
    ) -> (usize, f64) {
        let eps_sq = core.prune_epsilon.powi(2);
        let mut removals = 0;
        let mut norm = 0.0;

        let RotationScratch {
            values,
            inserts,
            partners,
        } = scratch;
        values.clear();
        inserts.clear();
        values.reserve(self.map.len());
        debug_assert_eq!(partners.len(), self.map.len());
        for ((c, &x), partner) in self.map.iter().zip(partners.iter()) {
            let value = match *partner {
                Some(y) => projection.rewrite_pair(c, x, y).0,
                None => {
                    // A missing partner contributes nothing to `c` and gains
                    // the whole of what `c` sends across.
                    let (kept, sent) = projection.rewrite_pair(c, x, Complex64::new(0.0, 0.0));
                    let weight = sent.norm_sqr();
                    if weight > eps_sq {
                        inserts.push((c.xor(&projection.d.a), sent));
                        norm += weight;
                    }
                    kept
                }
            };
            let weight = value.norm_sqr();
            if weight <= eps_sq {
                removals += 1;
            } else {
                norm += weight;
            }
            values.push(value);
        }
        (removals, norm)
    }

    // --- Shared helpers ---

    /// The (real) expectation `⟨Q⟩` of a frame-decomposed observable. Diagonal
    /// terms (`a = 0`) are `±1` eigenstates weighted by `|xvec[c]|²`;
    /// off-diagonal terms (`a ≠ 0`) pair each label with its coset partner
    /// `c ⊕ a`. Shared by [`TableauSimulator::measure`] and [`TableauSimulator::expectation`]
    /// — the one place the algebra lives.
    fn expectation_of(&self, d: &Decomp<K>) -> f64 {
        #[cfg(target_arch = "x86_64")]
        if has_popcnt() {
            // SAFETY: as in `t_decomposed`.
            #[allow(unsafe_code)] // the statement, not the function
            return unsafe { self.expectation_of_popcnt(d) };
        }
        self.expectation_of_inner(d)
    }

    /// [`expectation_of`](Self::expectation_of)'s `popcnt` twin.
    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "popcnt")]
    fn expectation_of_popcnt(&self, d: &Decomp<K>) -> f64 {
        self.expectation_of_inner(d)
    }

    #[inline(always)]
    fn expectation_of_inner(&self, d: &Decomp<K>) -> f64 {
        if d.a.is_zero() {
            let zsign = d.zeta.re;
            self.map
                .iter()
                .map(|(c, &x)| {
                    let signed = if c.dot_parity(&d.b) { -zsign } else { zsign };
                    signed * x.norm_sqr()
                })
                .sum()
        } else {
            // Hermiticity of `Q = ζ X^a Z^b` forces `ζ̄·(−1)^{⟨a,b⟩} = ζ`, which
            // makes a pair's two terms equal, so half the probes could be
            // skipped by visiting only the member with the pivot bit clear and
            // doubling. Benchmarked at rank 4096: that trades a well-predicted
            // probe for a coin-flip branch and lands ~6% slower, so both
            // members are visited.
            let mut ev = 0.0;
            for (c, &x) in &self.map {
                if let Some(&y) = self.map.get(&c.xor(&d.a)) {
                    let sign = if c.dot_parity(&d.b) { -1.0 } else { 1.0 };
                    ev += (d.zeta * sign * x * y.conj()).re;
                }
            }
            ev
        }
    }

    /// [`expectation_of`](Self::expectation_of)'s off-diagonal branch, writing
    /// down where it found each term's coset partner.
    ///
    /// Every random measurement runs this expectation to get its outcome
    /// probability and then projects onto the same cosets, so without the
    /// record the projection would locate the identical pairing a second time
    /// — a full hash probe per term. `partners` is positional and the map is
    /// not touched between the two passes, which is what makes a plain `Vec`
    /// (rather than anything holding into the table) the right handle.
    ///
    /// No `popcnt` twin, unlike its sibling: this branch is probe-bound, and
    /// the feature measured at +0.8% — noise — on `expectation/off-diagonal`.
    fn expectation_paired(&self, d: &Decomp<K>, partners: &mut Vec<Option<Complex64>>) -> f64 {
        partners.clear();
        partners.reserve(self.map.len());
        let mut ev = 0.0;
        for (c, &x) in &self.map {
            let partner = self.map.get(&c.xor(&d.a)).copied();
            if let Some(y) = partner {
                let sign = if c.dot_parity(&d.b) { -1.0 } else { 1.0 };
                ev += (d.zeta * sign * x * y.conj()).re;
            }
            partners.push(partner);
        }
        ev
    }

    /// Rescale the amplitude map to unit norm from an already-measured `Σ|x|²`.
    fn rescale(&mut self, total: f64) {
        if total > 0.0 {
            let scale = total.sqrt().recip();
            for v in self.map.values_mut() {
                *v *= scale;
            }
        }
    }
}

// ==============================================================================
// Free helpers
// ==============================================================================

/// Hand capacity back once a map has outgrown its contents fourfold.
///
/// The amplitude map and its staging buffer are reused rather than rebuilt, and
/// a hash map never shrinks on its own. Since iteration walks the whole bucket
/// array, a map that peaked at a million labels would keep charging that on
/// every pass long after a measurement collapsed the rank back to one. The 4×
/// hysteresis keeps ordinary growth off the reallocation path.
fn shrink_if_sparse<K: LabelKey>(map: &mut FxHashMap<K, Complex64>, live: usize) {
    let target = live.max(16);
    if map.capacity() > 4 * target {
        map.shrink_to(2 * target);
    }
}

/// Eigenvalue-`+1` test for a diagonal frame term: `ζ·(−1)^{⟨b,c⟩} > 0`.
#[inline]
fn eig_plus<K: LabelKey>(c: &K, b: &K, zsign: f64) -> bool {
    let signed = if c.dot_parity(b) { -zsign } else { zsign };
    signed > 0.0
}

/// Accumulate `Σ_c xvec[c]·D^c|ψ0⟩` into `out` — the amplitude-map half of
/// [`TableauSimulator::state_vector`], split out so it can be monomorphized per width
/// like everything else that reads a label.
fn replay_terms<K: LabelKey>(
    map: &FxHashMap<K, Complex64>,
    psi0: &[Complex64],
    destabs: &[RowPauli],
    out: &mut [Complex64],
) {
    for (c, &amp) in map {
        let mut term = psi0.to_vec();
        for (i, d_i) in destabs.iter().enumerate() {
            if c.get(i) {
                term = apply_pauli_dense(&term, d_i);
            }
        }
        for (dst, t) in out.iter_mut().zip(term) {
            *dst += amp * t;
        }
    }
}

/// Apply a signed dense Pauli `P = i^k X^a Z^b` to a state vector:
/// `(P v)[y ⊕ a] = i^k·(−1)^{⟨b,y⟩}·v[y]`. Small-`n` test support.
fn apply_pauli_dense(v: &[Complex64], p: &RowPauli) -> Vec<Complex64> {
    /// A frame row's mask as a state-vector index mask. Reconstruction is
    /// `O(2^n)`, so `n` never reaches the second word.
    fn index_mask(mask: &[u64]) -> usize {
        debug_assert!(
            mask[1..].iter().all(|&word| word == 0),
            "state-vector reconstruction is unreachable past 64 qubits"
        );
        mask[0] as usize
    }

    let zeta = i_pow(p.phase);
    let amask = index_mask(&p.x);
    let bmask = index_mask(&p.z);
    let mut out = vec![Complex64::new(0.0, 0.0); v.len()];
    for (y, &val) in v.iter().enumerate() {
        let sign = if (y & bmask).count_ones() & 1 == 1 {
            -1.0
        } else {
            1.0
        };
        out[y ^ amask] += zeta * sign * val;
    }
    out
}

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

    use crate::pauli::{neg, pauli_string, pauli_x, pauli_z};

    /// A signed observable is a legal measurement; an imaginary one is not an
    /// observable at all, and rejecting it must not have grown the register.
    #[test]
    fn signed_observables_work_and_non_hermitian_inputs_do_not_grow() {
        let mut sim = TableauSimulator::with_seed(1, 0);
        let measured = sim
            .measure_observable(&neg(pauli_z(1, 0)))
            .expect("negative Z is Hermitian");
        assert!(measured.outcome && measured.deterministic);

        let mut invalid = pauli_x(5, 4);
        invalid.phase_shift(1);
        assert_eq!(
            sim.measure_observable(&invalid),
            Err(SimError::NonHermitianPauli)
        );
        assert_eq!(sim.num_qubits(), 1);
    }

    /// A signed axis is a distinct controlled operation, not a global phase, so
    /// the frame update refuses it rather than silently dropping the sign.
    #[test]
    fn controlled_paulis_reject_signed_axes() {
        let mut sim = TableauSimulator::with_seed(2, 0);
        assert_eq!(
            sim.controlled_pauli(&neg(pauli_z(2, 0)), &pauli_x(2, 1)),
            Err(SimError::InvalidControlledPauli)
        );
        assert_eq!(
            sim.controlled_pauli(&pauli_z(2, 0), &neg(pauli_x(2, 1))),
            Err(SimError::InvalidControlledPauli)
        );
    }

    #[test]
    fn measurement_can_drive_external_control_flow() {
        let mut sim = TableauSimulator::with_seed(2, 7);
        sim.h(0);
        sim.cx(0, 1).expect("distinct qubits");
        if sim.measure(0).expect("measurement succeeds").outcome {
            sim.x(1);
        }
        let second = sim.measure(1).expect("measurement succeeds");
        assert!(!second.outcome);
        assert!(second.deterministic);
    }

    #[test]
    fn pauli_rotation_and_expectation_use_existing_pauli_strings() {
        let mut sim = TableauSimulator::with_seed(1, 0);
        sim.h(0);
        sim.t_pauli(&pauli_z(1, 0), false)
            .expect("rotation succeeds");
        let x = sim
            .peek_observable_expectation(&pauli_string("X").expect("valid Pauli"))
            .expect("X is in range");
        assert!((x - FRAC_1_SQRT_2).abs() < TOL);
    }

    #[test]
    fn deterministic_measurement_pruning_error_is_transactional() {
        let mut sim = TableauSimulator::with_seed(1, 0);
        sim.set_prune_epsilon(0.7);
        let words = sim.core.words;
        {
            let terms = sim.amps.narrow();
            terms.map.clear();
            terms
                .map
                .insert(Key::zeros(words), Complex64::new(0.6, 0.0));
            terms.map.insert(
                Key::mask_from_support(words, [0].into_iter()),
                Complex64::new(0.8, 0.0),
            );
        }
        let amps_before = sim.amps.clone();
        let diagonal_z = Decomp {
            a: Key::<1>::zeros(words),
            b: Key::<1>::mask_from_support(words, [0].into_iter()),
            phase: 0,
            zeta: Complex64::new(1.0, 0.0),
        };

        let TableauSimulator {
            ref mut core,
            ref mut amps,
        } = sim;
        let err = amps
            .narrow()
            .measure_frame_deterministic(core, &diagonal_z, Some(false))
            .expect_err("the retained 0.6 amplitude is below the pruning threshold");
        assert_eq!(err, SimError::EmptyStateAfterPruning { epsilon: 0.7 });
        assert_eq!(sim.amps, amps_before, "failed projection must not commit");
    }

    /// D01 regression: a `RankOverflow` from `finalize` inside `measure_random`
    /// must leave the simulator untouched, never half-updated.
    ///
    /// The pre-fix ordering advanced the frame `R` (`left_mul_pauli_exp`)
    /// *before* the fallible `finalize`, so an overflow committed the frame while
    /// the amplitude map stayed behind — `R` and the map then described different
    /// states, a corruption no later operation could undo.
    ///
    /// Reaching that path needs deliberate setup: a projective measurement never
    /// grows the compressed rank (confirmed by fuzzing 200k random Clifford+T
    /// circuits), so it cannot overflow from a within-cap state. We build a valid
    /// rank-4 state, then drop `rank_cap` beneath the post-measurement rank so
    /// `finalize` rejects the already-computed map.
    #[test]
    fn measure_random_rank_overflow_leaves_state_unchanged() {
        // `h; t` per qubit gives a rank-4 magic state; `Z_0` measures the
        // Hadamard-rotated qubit 0, which is off-diagonal (random) in the frame.
        let observable = PauliString::single(2, 0, Pauli::Z);
        let build = || {
            let mut sim = TableauSimulator::with_seed(2, 0);
            sim.h(0);
            sim.t(0).expect("off-diagonal T stays within the cap");
            sim.h(1);
            sim.t(1).expect("off-diagonal T stays within the cap");
            sim
        };

        // Only the random branch (`a != 0`) runs `finalize`; assert we are on it.
        let dry_run = build();
        let d = dry_run
            .core
            .decompose::<Key<1>>(&observable)
            .expect("Z is Hermitian");
        assert!(
            !d.a.is_zero(),
            "test must exercise the random-measurement branch"
        );

        // Learn the post-measurement rank with a generous cap — the
        // exact label count `finalize` rejects once the cap is lowered below it.
        let mut dry_run = dry_run;
        dry_run
            .postselect_observable(&observable, false)
            .expect("+1 outcome is achievable");
        let post_rank = dry_run.rank();
        assert!(
            post_rank >= 2,
            "need a post-rank a cap can sit below, got {post_rank}"
        );

        // Real run: cap one below `post_rank` forces the overflow. Snapshot the
        // frame and map first so we can prove the failure changed neither.
        let mut sim = build();
        sim.set_rank_cap(post_rank - 1);
        let frame_before = sim.core.r.clone();
        let amps_before = sim.amps.clone();

        let err = sim
            .postselect_observable(&observable, false)
            .expect_err("the lowered cap must overflow");
        assert_eq!(
            err,
            SimError::RankOverflow {
                rank: post_rank,
                cap: post_rank - 1,
            }
        );
        assert_eq!(
            sim.core.r, frame_before,
            "R must be untouched when finalize errors"
        );
        assert_eq!(
            sim.amps, amps_before,
            "amps must be untouched when finalize errors"
        );
    }

    #[test]
    fn ccz_rank_overflow_leaves_state_unchanged() {
        let mut sim = TableauSimulator::with_seed(2, 0);
        sim.set_rank_cap(2);
        for q in 0..2 {
            sim.h(q);
        }
        let qubits_before = sim.num_qubits();
        let frame_before = sim.core.r.clone();
        let amps_before = sim.amps.clone();

        assert_eq!(
            sim.ccz(0, 1, 2),
            Err(SimError::RankOverflow { rank: 4, cap: 2 })
        );
        assert_eq!(sim.num_qubits(), qubits_before);
        assert_eq!(sim.core.r, frame_before);
        assert_eq!(sim.amps, amps_before);
    }

    /// The `&self` reads cannot grow the register, so they must reject a qubit
    /// past it rather than silently answering for one that does not exist.
    #[test]
    fn peeks_reject_support_outside_live_register() {
        let sim = TableauSimulator::with_seed(1, 0);
        let out_of_range = Err(SimError::QubitIndexOutOfRange {
            index: 1,
            num_qubits: 1,
        });
        assert_eq!(
            sim.peek_observable_expectation(&PauliString::single(2, 1, Pauli::Z)),
            out_of_range
        );
        assert_eq!(sim.peek_z(1), out_of_range);
        assert_eq!(sim.peek_x(1), out_of_range);
        assert_eq!(sim.peek_y(1), out_of_range);
    }

    #[test]
    fn invalid_operands_do_not_mutate_or_grow() {
        let mut sim = TableauSimulator::with_seed(1, 0);
        sim.x(0);
        let frame_before = sim.core.r.clone();
        let amps_before = sim.amps.clone();

        assert_eq!(sim.cx(5, 5), Err(SimError::RepeatedQubit(5)));
        assert_eq!(sim.cz(6, 6), Err(SimError::RepeatedQubit(6)));

        // Two distinct axes on one qubit anticommute.
        let control = PauliString::single(9, 8, Pauli::X);
        let target = PauliString::single(9, 8, Pauli::Z);
        assert_eq!(
            sim.controlled_pauli(&control, &target),
            Err(SimError::NonCommutingControlledPaulis)
        );

        assert_eq!(sim.num_qubits(), 1);
        assert_eq!(sim.core.r, frame_before);
        assert_eq!(sim.amps, amps_before);
    }

    /// The label width and the frame's row width come from two separate
    /// rounding rules — `Width::for_words` in `label.rs` and `words_for` in
    /// `frame.rs`, which cannot share code because the frame is compiled
    /// standalone by `tests/frame_differential.rs`. They must agree, or the
    /// masks the decomposition writes are the wrong length and `preimage_into`
    /// asserts. This pins both, at every class boundary.
    #[test]
    fn width_class_tracks_the_register() {
        for (n, want) in [
            (1usize, Width::W1),
            (64, Width::W1),
            (65, Width::W2),
            (128, Width::W2),
            (129, Width::W4),
            (256, Width::W4),
            (257, Width::W8),
            (512, Width::W8),
            (513, Width::Wide),
        ] {
            let sim = TableauSimulator::with_seed(n, 0);
            assert_eq!(sim.amps.width(), want, "n = {n}");
            assert_eq!(sim.core.words, sim.core.r.words(), "n = {n}");
        }
    }

    /// `1usize << 64` wraps rather than trapping in a release build, so an
    /// unchecked reconstruction handed back a *one*-amplitude vector for a
    /// 64-qubit register — a wrong answer with no diagnostic. It has to fail,
    /// and fail the same way in both profiles.
    #[test]
    #[should_panic(expected = "fits a usize")]
    fn state_vector_refuses_a_register_it_cannot_index() {
        let _ = TableauSimulator::with_seed(64, 0).state_vector();
    }
}