tradefloor 0.11.0

A reproducible evaluation environment for financial AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
//! Conditional volatility for the SHARED market factor — the structural
//! change finding 14 named, and the escape from the trade it measured.
//!
//! # Why the factor needs its own variance process
//!
//! The market factor was drawn iid Gaussian at constant sigma. Because of
//! that, its contribution to cross-sectional correlation WAS its share of
//! variance, and every point of share it took both Gaussian-diluted the
//! fat tails the per-name GARCH produces and added to total volatility.
//! The eight-point sweep behind finding 14 proved the real correlation
//! band (0.25–0.35) unreachable by that constant at any value: the band
//! arrives only at sigma ≈ 0.021, where excess kurtosis has collapsed to
//! 1.26 against a band floor of 3. Correlation was being bought with
//! kurtosis at a fixed rate.
//!
//! A factor whose variance is itself persistent and shock-driven inverts
//! the trade. Variance mixing makes the factor's unconditional
//! distribution fat-tailed, so the correlated share of every name's
//! return now CONTRIBUTES kurtosis instead of spending it; the variance
//! persistence is market-wide volatility clustering, which the per-name
//! GARCH alone could never produce (the factor's share of every name was
//! iid by construction and actively diluted the per-name clustering); and
//! a high-variance factor regime is a high-correlation regime, which is
//! what crisis correlation is. The increase in the factor's share is
//! FUNDED: [`IDIO_SIGMA_SCALE`] scales the per-name idiosyncratic noise
//! down, so total volatility falls rather than absorbing the new factor
//! variance on top.
//!
//! Measured at the shipped constants (six-seed medians, the published
//! method, committed in `tools/calibration/results/market-factor-vol-*`):
//! cross-sectional correlation **0.260** and excess kurtosis **3.14** —
//! both inside their real bands for the first time in this model's
//! history — with volatility clustering 0.245 (in band), pooled
//! volatility 41.8% (down from 48.3%), and the leverage effect intact at
//! −0.094. The constant-sigma sweep bought correlation 0.089 at the same
//! kurtosis floor; the process does not move along that curve, it
//! dissolves it.
//!
//! # The process
//!
//! GARCH(1,1) on the factor's own daily innovation, at daily scale,
//! reverting to the baseline [`MARKET_FACTOR_SIGMA`](crate::market::tick::MARKET_FACTOR_SIGMA)²:
//!
//! ```text
//! v' = (1 − α − β)·target + α·ε² + β·v      then clamped to
//!      [FLOOR_MULTIPLE·base, CEILING_MULTIPLE·base]
//! ```
//!
//! where ε is the day's accumulated market factor — the sum of the tick
//! draws, whose conditional variance over a 390-tick session is exactly
//! `v` — and `target` is the baseline variance scaled by (VIX/anchor)²:
//! VIX read as the factor's implied volatility, per
//! [`MARKET_VOL_VIX_COUPLING`]. The coupling ships ON (1.0) — the era
//! decision that closed finding 6's open question; the constant's doc
//! carries the measurement and the argument.
//!
//! # Draw schedule: ZERO new draws
//!
//! The state is a function of values already drawn (the tick's market
//! factor, accumulated) and of macro state already evolved (VIX, when
//! coupled). The market stream's schedule — 1 normal per tick for the
//! factor, drawn in `simulate_market_tick` — is untouched in count, kind
//! and position. This is the same trick the per-name GARCH uses in
//! `daily.rs`, and it is what keeps the 2026-08 stream split's alignment
//! guarantee intact: the schedule remains a pure function of (status,
//! active set, sector count).
//!
//! # Stationarity, with the arithmetic — and one condition knowingly traded
//!
//! - **Mean reversion / covariance stationarity of the recursion**:
//!   α + β = 0.45 + 0.5 = 0.95 < 1. The unclamped process reverts to the
//!   target with a shock half-life of ln(2)/ln(1/0.95) ≈ 13.5 days —
//!   volatile stretches are two-to-five-week regimes, several per year.
//! - **Boundedness**: the clamp confines the state to
//!   [0.05·base, 8·base] absolutely, so every moment of the SHIPPED
//!   process exists trivially, and the quiet-run fixed point
//!   ω/(1−β) = 0.1·base sits ABOVE the floor — the floor is unreachable
//!   from any admissible state (v' ≥ ω + β·floor = 0.075·base) and is a
//!   pure worst-case guarantee, not a regime the process lives in.
//! - **The condition deliberately not satisfied**: the unclamped fourth-
//!   moment condition (α+β)² + 2α² < 1 evaluates to 0.9025 + 0.405 =
//!   1.31 — violated, so the UNCLAMPED factor's kurtosis would diverge;
//!   the ceiling is load-bearing for the fourth moment, and it does bind
//!   in bursts at these parameters (a 2σ day from twice-baseline variance
//!   reaches it in two steps). This is a measured trade, not an
//!   oversight: the realism panel measures ONE 252-day window, the factor
//!   is one shared path per seed, and every parameterisation satisfying
//!   the fourth-moment condition was measured to deliver a median
//!   one-year SAMPLE kurtosis of at most ~1.7 (α 0.15–0.25 at
//!   persistence 0.95–0.985, ceilings 5–20, standalone recursion over 300
//!   windows) — the asymptotic tails such processes do have live at
//!   horizons the panel cannot see. The shipped α trades asymptotic
//!   niceness for tails that EXIST in the year being measured, and the
//!   clamp supplies the boundedness the dropped condition used to.
//!
//! The same trade is why α = 0.45 sits far above real index-GARCH
//! estimates (~0.1): a real index's kurtosis is estimated across decades;
//! this factor must express its tails inside the single year the panel
//! sees. The per-name GARCH (α 0.09, near-unit-root persistence) keeps
//! the long-memory role; the factor's process is deliberately the bursty
//! one.
//!
//! # Tier 1
//!
//! Multiplies, adds, one `mathx::max`/`min` pair, and a `sqrt`
//! (IEEE-exact on every platform) at the day boundary. No
//! transcendentals, no RNG — the same discipline as `garch.rs`, and the
//! reason GARCH was chosen over an EGARCH/log-variance form, which would
//! have dragged `exp`/`log` into the daily state chain.
//!
//! That is the path every shipped preset takes. Two dials add a
//! transcendental when a custom vector switches them on: the VIX response
//! goes through `mathx::pow`, and `market_vol_alpha_excursion` through
//! `mathx::log`. Both are `mathx`, never the platform's libm, and
//! `tests/platform_maths.rs` fails on any call that is not.

use crate::mathx;

#[cfg(test)]
use super::tick::MARKET_FACTOR_SIGMA;

/// Weight on the day's squared factor innovation — the surprise term.
///
/// Far above the per-name ALPHA (0.09), deliberately: the factor is one
/// shared path, and its fat tails must arrive within the one-year window
/// the realism panel measures. See the module header for the
/// window-sampling measurement behind the choice and the fourth-moment
/// condition it knowingly trades away.
pub const MARKET_VOL_ALPHA: f64 = 0.45;

/// Weight on yesterday's factor variance — the persistence term.
///
/// α + β = 0.95: a factor-variance shock half-decays in ~13.5 days, so a
/// volatile stretch is a multi-week regime and a year contains several,
/// which is exactly what lets the panel's window see them.
pub const MARKET_VOL_BETA: f64 = 0.5;

/// Ceiling as a multiple of the baseline variance `MARKET_FACTOR_SIGMA`².
///
/// Load-bearing, not cosmetic: the unclamped fourth moment diverges at
/// the shipped α and β (module header), so the ceiling is what bounds
/// the factor's tail — crisis sigma at most √8 ≈ 2.8x baseline. It binds
/// in bursts at these parameters; sweeping it at shapes where it never
/// binds produced bit-identical panels (ceil 16 vs 20, committed in the
/// stage results), which is how "never binds" was measured rather than
/// assumed.
pub const MARKET_VOL_CEILING_MULTIPLE: f64 = 8.0;

/// Floor as a multiple of the baseline variance.
///
/// A worst-case guarantee only: the quiet-run fixed point ω/(1−β) is
/// 0.1·base and v' ≥ ω + β·floor = 0.075·base, so the floor is
/// unreachable at the shipped shape. It is kept — and kept LOW — because
/// a floor above the quiet fixed point (the 0.25 the per-name process
/// uses) was measured to pin calm periods and destroy the variance
/// dispersion the factor's kurtosis is made of.
pub const MARKET_VOL_FLOOR_MULTIPLE: f64 = 0.05;

/// How much the process's reversion target follows VIX², 0 (autonomous)
/// to 1 (target fully proportional to VIX², i.e. VIX read as the
/// factor's implied volatility).
///
/// **Ships at 1.0 — coupled. This is the era decision that closed
/// finding 6's open question ("should VIX drive the variance
/// process?"), taken on the committed measurement rather than on the
/// name.** Both variants were measured at the shipped constants
/// (`results/market-factor-vol-2026-08-22-stageJ-coupled.json` beside
/// the autonomous stage results):
///
/// - On the ENDOGENOUS panel the two are statistically
///   indistinguishable — correlation 0.253 vs 0.254, kurtosis 3.03 vs
///   3.04, clustering 0.214 vs 0.216 — because endogenous VIX spans only
///   ~13–21 (measured mean 15.1, hard ceiling 26.57), a mild variance
///   modulation the process's own innovations dwarf. Coupling therefore
///   costs the in-band panel nothing.
/// - Under PINNED crisis VIX they are different models: coupled reaches
///   crisis correlation 0.664 at VIX 45 and 0.727 at VIX 65 — the real
///   crisis band (0.6+) this model has never reached by any other
///   mechanism — against 0.365/0.361 autonomous, with crisis volatility
///   82–99% annualised for a HELD pin at those levels.
///
/// **The coupling is undamped, and the ceiling is why that is safe.**
/// The unclamped stationary variance of the recursion equals its target,
/// so a held pin saturates the state at the ceiling once
/// (VIX/anchor)² > `MARKET_VOL_CEILING_MULTIPLE` — above VIX ≈ 42 the
/// response is flat, and a pinned VIX 100 buys essentially the VIX-65
/// market, not a quadratically more violent one. Inside the plausible
/// band the response is quadratic, which is what reading VIX as implied
/// volatility means; a damping factor would make the model realise less
/// volatility than its own implied level says, re-creating in softer
/// form the exact falsehood the coupling removes. A test pins the
/// saturation arithmetic so a recalibration that moves the anchor or the
/// ceiling revisits this argument deliberately.
///
/// The flip landed together with what it falsified: `tradefloor.scenario`'s
/// "What a VIX path actually moves" and `docs/scenarios.md`'s "VIX does
/// not drive volatility" were rewritten in the same change, their tests
/// re-grounded, and the KAT bumped — a constant that silently inverted
/// shipped documentation would have been a lie regardless of what it
/// bought.
pub const MARKET_VOL_VIX_COUPLING: f64 = 1.0;

/// The VIX level at which a coupled target equals the baseline variance.
///
/// Measured, not assumed: mean endogenous VIX over the published panel
/// method (`Universe.random(40, seed=111)`, 252 days, seeds 1–3) is
/// 15.1, range 12.9–21.0. Anchoring at the endogenous mean makes the
/// coupled and autonomous processes agree on the unconditional level, so
/// the coupling question stays isolated from a level change.
///
/// THAT FIGURE NO LONGER REPRODUCES. The same protocol on the shipped
/// preset reads a mean of 18.7, range 12.4 to 27.6, so the anchor sits
/// well below the endogenous mean it was chosen to equal and the
/// coupled and autonomous processes no longer agree on the level.
///
/// The gap is NOT attributable to the universe generator reconciling a
/// drawn roster to its own fair value, which is when it was noticed. That
/// change moved realised volatility by 0.01 of its own across-seed noise,
/// and this quantity tracks realised volatility. The 15.1 names no preset
/// and no commit, and the default has moved several times since it was
/// written, so what it drifted against cannot be recovered from the figure
/// itself. The constant is left where it is: moving it moves every
/// trajectory, and the question of what it should be is a calibration
/// question rather than a provenance one.
pub const MARKET_VOL_VIX_ANCHOR: f64 = 15.0;

/// Scale on the per-name idiosyncratic GARCH sigma — the FUNDING side of
/// the reallocation.
///
/// The factor's variance share rises from ~8% to ~26% of a typical
/// name's realised variance; left unfunded that would land on top of a
/// total volatility already above its band. This constant moves variance
/// OUT of the idiosyncratic per-name noise instead — 0.84 on sigma is
/// ~29% off idiosyncratic variance — which is why pooled volatility FELL
/// from 48.3% to 41.8% while the correlated share tripled. Applied in
/// `factors.rs::calculate_live_factors`, to the idiosyncratic term only;
/// news, flow and squeeze are untouched. At 1.0 the multiply is
/// bit-inert.
///
/// The value comes from the same sweep as `MARKET_FACTOR_SIGMA`; change
/// the pair together or not at all.
pub const IDIO_SIGMA_SCALE: f64 = 0.84;

/// One day's update of the market-factor variance, at daily scale.
///
/// `day_factor` is the day's accumulated market factor (the sum of the
/// per-tick draws); `vix` is the macro VIX at the close. Pure and
/// draw-free.
pub fn update_market_variance(current_variance: f64, day_factor: f64, vix: f64) -> f64 {
    update_market_variance_with(&crate::params::PT_V1, current_variance, day_factor, vix)
}

/// [`update_market_variance`] under explicit model parameters (the runtime
/// seam). At [`crate::params::PT_V1`] this is the
/// shipped arithmetic bit for bit: same values, same operations, same
/// order — the constants above remain the definition of the preset.
pub fn update_market_variance_with(
    params: &crate::params::ModelParams,
    current_variance: f64,
    day_factor: f64,
    vix: f64,
) -> f64 {
    update_market_variance_at(
        params, params.market_vol_vix_anchor, current_variance, day_factor, vix)
}

/// [`update_market_variance_with`] against an EXPLICIT anchor.
///
/// The anchor is the VIX at which the coupled target equals the baseline
/// variance, and under `vix_level_identity` it is DERIVED from the index's
/// own unconditional variance rather than read from the dial -- so the
/// engine has to be able to say which one this update reads. Every caller
/// that is not the engine passes `params.market_vol_vix_anchor`, which is
/// the expression that stood here, so the arithmetic is unchanged to the
/// bit for every preset before pt-v19.
pub fn update_market_variance_at(
    params: &crate::params::ModelParams,
    vix_anchor: f64,
    current_variance: f64,
    day_factor: f64,
    vix: f64,
) -> f64 {
    let base = params.market_factor_sigma * params.market_factor_sigma;
    // The reversion target: baseline variance, VIX-scaled when coupled.
    // The blend form is kept even at coupling 1.0 because the constant is
    // the calibration seam the sweep patches; the evaluation order is
    // contractual. Two exactness properties anchor it: at coupling 0 the
    // parenthesised blend is exactly 1.0 and `base * 1.0` is `base` to
    // the bit (the autonomous branch stays measurable with no arithmetic
    // residue), and at `vix == MARKET_VOL_VIX_ANCHOR` the ratio is
    // exactly 1.0 at any coupling, so an anchor-level VIX reproduces the
    // autonomous update bit-for-bit — tests pin both.
    let vix_ratio = vix / vix_anchor;
    let target = base
        * (1.0 - params.market_vol_vix_coupling
            + params.market_vol_vix_coupling * vix_response(params, vix_ratio));
    update_toward_with(params, current_variance, day_factor, target)
}

/// The GARCH step against an explicit target, so the coupling decision is
/// testable on both branches without recompiling a constant.
#[cfg(test)]
fn update_toward(current_variance: f64, day_factor: f64, target_variance: f64) -> f64 {
    update_toward_with(
        &crate::params::PT_V1,
        current_variance,
        day_factor,
        target_variance,
    )
}

/// One variance component's GARCH step against a shared target.
///
/// Both components of the two-timescale process use this, with their own
/// `(alpha, beta)`; the persistence of a component is `alpha + beta`, so
/// its autocorrelation decays at that rate and its half-life is
/// `ln(0.5)/ln(alpha+beta)`.
///
/// Why a MIXTURE and not an additive deviation. The first version of this
/// added `weight * (slow - base)` on top of the fast update, and a sweep
/// killed it in ninety seconds: over a 504-day window a 17-day component
/// is nearly constant, so an additive term acts as a LEVEL SHIFT and adds
/// roughly the same autocorrelation at every lag. The measured curve came
/// out flat -- 0.070 at lag 20 against 0.044 at lag 60, where real markets
/// read 0.029 and 0.005 -- and the parameters barely moved it, which is
/// the signature of a dial that is not connected to the thing it names.
///
/// A mixture `w_f*c_f + w_s*c_s` of two components reverting to the SAME
/// target genuinely superposes two decay rates, which is what the fitted
/// structure needs.
fn component_step(
    current: f64,
    day_factor: f64,
    target: f64,
    alpha: f64,
    beta: f64,
    gamma: f64,
) -> f64 {
    // The GJR term, spelled exactly as `update_toward_with` spells it: a
    // down day loads `alpha + gamma`, omega gives back `gamma/2`. The slow
    // component passes 0.0 on every shipped preset, and 0.0 makes every
    // term bit-identical to the symmetric step; `market_vol_slow_gamma`
    // off zero passes its own gamma with `beta` reduced by half of it (see
    // `slow_step`), because the index's leverage lasts weeks to months and
    // not only the fast component's same week.
    let leverage = if day_factor < 0.0 { gamma } else { 0.0 };
    (1.0 - alpha - beta - 0.5 * gamma) * target
        + (alpha + leverage) * day_factor * day_factor
        + beta * current
}

/// The slow component's `(alpha, beta)`, from its persistence and the
/// share of that persistence carried by the shock term.
///
/// Parameterised this way because the fitted quantity is the HALF-LIFE --
/// the analytic fit against real markets wants 1 day fast and 17 days slow
/// -- and a half-life is a statement about `alpha + beta`, not about
/// either one alone.
fn slow_alpha_beta(params: &crate::params::ModelParams) -> (f64, f64) {
    let rho = params.market_vol_slow_persistence;
    let share = params.market_vol_slow_gain;
    (share * rho, (1.0 - share) * rho)
}

/// The slow component's step, clamped.
///
/// At `market_vol_slow_gamma` 0.0 -- every shipped preset -- this is a
/// BRANCH that makes the call the close always made, symmetric, with
/// gamma 0.0. Off zero, a down day loads `a_s + gamma` on the squared shock
/// and the carried share gives back `gamma/2`: `component_step` with
/// `(a_s, b_s - gamma/2, gamma)`, whose omega term is
/// `1 - a_s - (b_s - gamma/2) - gamma/2 = 1 - a_s - b_s`, so the resting
/// level and the persistence `a_s + b_s` are unchanged. See
/// `ModelParams::market_vol_slow_gamma`.
fn slow_step(
    params: &crate::params::ModelParams,
    current: f64,
    day_factor: f64,
    target: f64,
) -> f64 {
    let (sa, sb) = slow_alpha_beta(params);
    let g = params.market_vol_slow_gamma;
    if g == 0.0 {
        clamp_variance(params, component_step(current, day_factor, target, sa, sb, 0.0))
    } else {
        clamp_variance(params, component_step(current, day_factor, target, sa, sb - 0.5 * g, g))
    }
}

/// The return memory's per-session carry, `0.5^(1 / half_life)`. Read only
/// while `market_vol_leverage` is set, where validation holds the half-life
/// positive.
fn leverage_phi(params: &crate::params::ModelParams) -> f64 {
    mathx::pow(0.5, 1.0 / params.market_vol_leverage_half_life)
}

/// The fast return memory's per-session carry, `0.5^(1 / half_life)`. Read
/// only while `market_vol_leverage_fast` is set, where validation holds its
/// half-life positive.
fn leverage_fast_phi(params: &crate::params::ModelParams) -> f64 {
    mathx::pow(0.5, 1.0 / params.market_vol_leverage_fast_half_life)
}

/// The variance of one day's memory input `u` at the baseline, for a
/// memory that ignores `down` of an up day: the half-normal arithmetic both
/// return memories' stationary spreads are built from.
fn leverage_input_variance(params: &crate::params::ModelParams) -> f64 {
    let a = params.market_vol_leverage_down;
    0.5 * (1.0 + (1.0 - a) * (1.0 - a)) - a * a / (2.0 * std::f64::consts::PI)
}

/// The fast return memory's input variance at the baseline. With
/// `market_vol_leverage_fast_up` at 0.0 the slower memory's
/// ([`leverage_input_variance`]); off it, the same half-normal arithmetic with
/// that share of a FALL ignored, which by the normal's symmetry is the
/// expression with `down` replaced by the share.
fn leverage_fast_input_variance(params: &crate::params::ModelParams) -> f64 {
    let b = params.market_vol_leverage_fast_up;
    if b == 0.0 {
        return leverage_input_variance(params);
    }
    0.5 * (1.0 + (1.0 - b) * (1.0 - b)) - b * b / (2.0 * std::f64::consts::PI)
}

/// The VIX's window, in sessions, over which the identity's read-back takes
/// the fast return memory's expected multiplier (`market_vol_leverage_fast`):
/// the 30 calendar days the VIX prices.
pub const VIX_WINDOW_SESSIONS: usize = 21;

/// The shared clamp: a variance stays inside its floor and ceiling
/// multiples of the baseline, in the bound order `garch.rs` uses.
fn clamp_variance(params: &crate::params::ModelParams, v: f64) -> f64 {
    let base = params.market_factor_sigma * params.market_factor_sigma;
    mathx::max(
        mathx::min(v, base * params.market_vol_ceiling_multiple),
        base * params.market_vol_floor_multiple,
    )
}


/// The VIX ratio raised to the response exponent. At exactly 2.0 -- every
/// preset before the dial -- this is the literal `r * r` the shipped
/// update has always computed, bit for bit; `powf` never runs there.
/// Round 100: along the real covid path the square is too convex through
/// mid-VIX, and the exponent (with the coupling re-fit to preserve the
/// held-VIX ratio) is the shape the driven window asks for.
pub(crate) fn vix_response(params: &crate::params::ModelParams, vix_ratio: f64) -> f64 {
    // The calm side's own exponent. Guarded, so at 0.0 -- every preset --
    // this branch is never taken and the arithmetic below is unchanged to
    // the bit. See `ModelParams::market_vol_vix_exponent_below`.
    let below = params.market_vol_vix_exponent_below;
    if below != 0.0 && vix_ratio < 1.0 {
        return if below == 2.0 {
            vix_ratio * vix_ratio
        } else {
            mathx::pow(vix_ratio, below)
        };
    }
    if params.market_vol_vix_exponent == 2.0 {
        vix_ratio * vix_ratio
    } else {
        mathx::pow(vix_ratio, params.market_vol_vix_exponent)
    }
}

/// The shock share and the carried share for this close, after the factor's
/// own variance excursion has moved them.
///
/// `delta = excursion * ln(variance / target)`, `alpha + delta` against
/// `beta - delta`. The sum is invariant, so persistence, the unconditional
/// level and omega's mean reversion are all untouched and only the SPLIT
/// moves. `delta` is clamped by the GJR fourth-moment coefficient
/// `3a^2 + 3ag + 1.5g^2 + 2ab + bg + b^2`, held at 0.999 and solved here from
/// `beta` and `gamma` rather than written down, so a preset that moves either
/// cannot lose the finite fourth moment silently.
///
/// Returns the dialled pair unchanged at `market_vol_alpha_excursion == 0.0`,
/// which is the bit-identity branch every preset before 0.8.0 takes.
fn alpha_beta_at(
    params: &crate::params::ModelParams,
    current_variance: f64,
    target_variance: f64,
) -> (f64, f64) {
    let alpha = params.market_vol_alpha;
    let beta = params.market_vol_beta;
    let k = params.market_vol_alpha_excursion;
    if k == 0.0 || target_variance <= 0.0 || current_variance <= 0.0 {
        return (alpha, beta);
    }
    // `mathx::log`, not `f64::ln`: a dial a user sets with `with_override`
    // must not reach the platform's libm, or their custom market stops being
    // the same market on every platform. No shipped preset reaches this line.
    let delta = k * mathx::log(current_variance / target_variance);
    // The largest rotation the fourth moment allows, from
    // `3a^2 + a(3g + 2b') + (1.5g^2 + b'g + b'^2) = 0.999` with the rotation
    // b' = beta - d and a = alpha + d substituted; solved numerically by
    // bisection because the substitution is quadratic in `d` with
    // coefficients in `beta` and `gamma`, and a closed form here would be a
    // second spelling of the same condition for a reader to get wrong.
    //
    // THE BOUND IS THE SINGLE COMPONENT'S AND THIS FUNCTION RUNS ON THE FAST
    // ONE OF TWO. That is conservative rather than wrong, and the direction
    // matters: the composed mixture's own fourth-moment operator allows a
    // rotation of about 0.1285 where this allows 0.0280,
    // so the clamp binds
    // 4.6 times earlier than the condition it is protecting requires. It
    // refuses rotations the mixture would tolerate and never permits one it
    // would not.
    //
    // It is left as it is on purpose. Deriving the mixture bound here would
    // be new arithmetic in a hot path for a dial that ships at 0.0 and that
    // the `alphax2` box REFUTED -- six settings from 0.0 to 0.40 moved the
    // clustering response it was built for by less than a twentieth of its
    // own value. A conservative bound on a mechanism nobody turns on is the
    // cheapest correct thing; a reader who turns it on should read the
    // design note before trusting the headroom this reports.
    let g = params.market_vol_gamma;
    let m4 = |d: f64| {
        let (a, b) = (alpha + d, beta - d);
        3.0 * a * a + 3.0 * a * g + 1.5 * g * g + 2.0 * a * b + b * g + b * b
    };
    let (mut lo, mut hi) = (0.0_f64, 0.5_f64);
    if m4(0.0) >= 0.999 {
        // The shipped triple is already at the bound; no rotation is safe.
        return (alpha, beta);
    }
    for _ in 0..60 {
        let mid = 0.5 * (lo + hi);
        if m4(mid) < 0.999 {
            lo = mid;
        } else {
            hi = mid;
        }
    }
    let bound = lo;
    let d = mathx::max(-bound, mathx::min(delta, bound));
    (alpha + d, beta - d)
}

fn update_toward_with(
    params: &crate::params::ModelParams,
    current_variance: f64,
    day_factor: f64,
    target_variance: f64,
) -> f64 {
    let base = params.market_factor_sigma * params.market_factor_sigma;
    // GJR leverage on the common factor: a down day loads `alpha + gamma`
    // on the squared shock, an up day `alpha` alone, and omega gives back
    // `gamma/2` so the unconditional level stays on target -- the dial
    // redistributes variance between down and up states rather than adding
    // any. At gamma 0.0 every term below is bit-identical to the
    // symmetric update, which is what every preset before the dial ships.
    let gamma = params.market_vol_gamma;
    let leverage = if day_factor < 0.0 { gamma } else { 0.0 };
    // THE SHOCK SHARE MOVES WITH THE FACTOR'S OWN EXCURSION, which is what
    // the tape's clustering does and a constant share cannot say: see
    // `ModelParams::market_vol_alpha_excursion` for the measurement and for
    // why the pair ROTATES rather than the share lifting. At 0.0 -- every
    // preset before 0.8.0 -- `delta` is zero, `alpha` and `beta` are the
    // dialled pair and every term below is the arithmetic that predates
    // this, to the bit.
    let (alpha, beta) = alpha_beta_at(params, current_variance, target_variance);
    let omega = (1.0 - alpha - beta - 0.5 * gamma) * target_variance;
    let new_var = omega
        + (alpha + leverage) * day_factor * day_factor
        + beta * current_variance;
    // `max(min(x, ceiling), floor)` — the same bound order as
    // `garch.rs`, which is contractual there because it is visible when
    // the bounds cross. The bounds here are multiples of a positive
    // compile-time constant so they cannot cross, but two spellings of
    // one idiom in one codebase is how the next reader gets it wrong.
    mathx::max(
        mathx::min(new_var, base * params.market_vol_ceiling_multiple),
        base * params.market_vol_floor_multiple,
    )
}

/// The market factor's conditional-variance state, held by the engine.
///
/// Two numbers: today's variance (fixed for the whole session — the tick
/// reads sigma from the previous close's update, so the factor is
/// conditionally Gaussian within a day) and the day's accumulated factor,
/// which becomes the innovation at the close.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MarketVarianceState {
    /// The MIXTURE — what the tick draws against. Equals `fast_variance`
    /// exactly whenever the slow component is off.
    variance: f64,
    day_factor: f64,
    /// The fast component's own level.
    fast_variance: f64,
    /// The slow component's own level.
    slow_variance: f64,
    /// EMA of the VIX the variance target reads, when
    /// `market_vol_vix_smooth` is on. `None` until the first smoothed
    /// close, and never touched while the dial is 0.0.
    smoothed_vix: Option<f64>,
    /// Yesterday's accumulated day factor, recorded at close for the
    /// lagged transmission wire. Purely observational: nothing in the
    /// variance process reads it.
    prev_day_factor: f64,
    /// The return memory `market_vol_leverage` reads: an exponentially
    /// weighted memory of the day factor in baseline sd units, a fall
    /// counted positive. Exactly 0.0, and never written, while the dial is
    /// 0.0; the snapshot and the state hash carry it only while it is set.
    leverage_memory: f64,
    /// The fast return memory `market_vol_leverage_fast` reads, counted as
    /// `leverage_memory` is at its own half-life. Exactly 0.0, and never
    /// written, while that dial is 0.0; the snapshot and the state hash carry
    /// it only while it is set.
    leverage_fast_memory: f64,
}

impl Default for MarketVarianceState {
    fn default() -> Self {
        Self::new()
    }
}

impl MarketVarianceState {
    /// A fresh state at the baseline: day one of every engine draws the
    /// factor at exactly `MARKET_FACTOR_SIGMA`, so the first session of
    /// the conditional process is bit-identical to the constant-sigma
    /// model at the same baseline.
    pub fn new() -> Self {
        Self::new_with(&crate::params::PT_V1)
    }

    /// A fresh state at a given preset's baseline. See [`Self::new`]; the
    /// day-one bit-identity property holds for any baseline, because
    /// `sqrt(x*x)` returns `x`'s bits for any positive finite `x` whose
    /// square neither overflows nor underflows.
    pub fn new_with(params: &crate::params::ModelParams) -> Self {
        let base = params.market_factor_sigma * params.market_factor_sigma;
        Self {
            variance: base,
            day_factor: 0.0,
            fast_variance: base,
            slow_variance: base,
            smoothed_vix: None,
            prev_day_factor: 0.0,
            leverage_memory: 0.0,
            leverage_fast_memory: 0.0,
        }
    }

    /// This state with today's accumulated factor replaced, for a projection
    /// of the close on a copy (`rate_intraday_live`).
    pub fn with_day_factor(mut self, day_factor: f64) -> Self {
        self.day_factor = day_factor;
        self
    }

    /// Whether yesterday's session accumulated a DOWN market factor. For
    /// the lagged transmission wire; false before the first close.
    pub fn prev_day_down(&self) -> bool {
        self.prev_day_factor < 0.0
    }

    /// Yesterday's whole-session accumulated market factor, the signed
    /// quantity `prev_day_down` thresholds. Exposed beside the boolean for
    /// `market_beta_down_asym_lag_live`, which needs the MAGNITUDE to
    /// decay yesterday's tail across today's session. Already in
    /// `snapshot()`; this is an accessor, not new state.
    pub fn prev_day_factor(&self) -> f64 {
        self.prev_day_factor
    }

    /// TODAY's running accumulated market factor, as it stands right now.
    /// Read by `market_beta_down_asym_lag_live` BEFORE the current tick's
    /// own factor is accumulated (`engine.rs` accumulates after the tick
    /// returns), which is what makes that wire a function of strictly
    /// earlier draws and therefore mean-preserving. Already in
    /// `snapshot()`; this is an accessor, not new state.
    pub fn day_factor(&self) -> f64 {
        self.day_factor
    }

    /// The return memory `market_vol_leverage` reads. 0.0 on every model
    /// with the dial off.
    pub fn leverage_memory(&self) -> f64 {
        self.leverage_memory
    }

    /// Put the return memory back, for checkpoints. See
    /// [`crate::params::ModelParams::market_vol_leverage`].
    pub fn set_leverage_memory(&mut self, value: f64) {
        self.leverage_memory = value;
    }

    /// The fast return memory `market_vol_leverage_fast` reads. 0.0 on every
    /// model with that dial off.
    pub fn leverage_fast_memory(&self) -> f64 {
        self.leverage_fast_memory
    }

    /// Put the fast return memory back, for checkpoints. See
    /// [`crate::params::ModelParams::market_vol_leverage_fast`].
    pub fn set_leverage_fast_memory(&mut self, value: f64) {
        self.leverage_fast_memory = value;
    }

    /// The fast memory's stationary variance at the baseline, `s_f^2`.
    pub(crate) fn leverage_fast_s2(params: &crate::params::ModelParams) -> f64 {
        let phi = leverage_fast_phi(params);
        (1.0 - phi) / (1.0 + phi) * leverage_fast_input_variance(params)
    }

    /// The fast return memory's variance multiplier at memory `l`,
    /// `exp(k_f * l - k_f^2 * s_f^2 / 2)`. Read only while
    /// `market_vol_leverage_fast` is set.
    fn leverage_fast_multiplier(params: &crate::params::ModelParams, l: f64) -> f64 {
        let k = params.market_vol_leverage_fast;
        mathx::exp(k * l - 0.5 * k * k * Self::leverage_fast_s2(params))
    }

    /// The fast memory's multiplier as the VIX prices it: its expected value
    /// over the VIX's window of [`VIX_WINDOW_SESSIONS`] sessions from the
    /// next one, under the memory's own decay,
    /// `(1/21) sum_{j=0..20} exp(k_f phi_f^j l - k_f^2 s_f^2 phi_f^(2j) / 2)`.
    /// See [`crate::params::ModelParams::market_vol_leverage_fast`].
    pub fn leverage_fast_window_multiplier(params: &crate::params::ModelParams, l: f64) -> f64 {
        let k = params.market_vol_leverage_fast;
        let phi = leverage_fast_phi(params);
        let s2 = Self::leverage_fast_s2(params);
        let mut sum = 0.0;
        let mut d = 1.0;
        for _ in 0..VIX_WINDOW_SESSIONS {
            sum += mathx::exp(k * d * l - 0.5 * k * k * s2 * d * d);
            d *= phi;
        }
        sum / VIX_WINDOW_SESSIONS as f64
    }

    /// The ratio of the fast memory's window multiplier to its multiplier
    /// tomorrow, at this state's fast memory: what the VIX's read-back scales
    /// tomorrow's factor variance by. Exactly 1.0 with
    /// `market_vol_leverage_fast` at 0.0. Read by the forecast, whose factor
    /// variances are not this state's own.
    pub fn vix_window_ratio(&self, params: &crate::params::ModelParams) -> f64 {
        if params.market_vol_leverage_fast == 0.0 {
            return 1.0;
        }
        let l = self.leverage_fast_memory;
        let now = Self::leverage_fast_multiplier(params, l);
        if !(now > 0.0) {
            return 1.0;
        }
        Self::leverage_fast_window_multiplier(params, l) / now
    }

    /// The variance the VIX's read-back takes: [`Self::variance`] itself, the
    /// same f64, with `market_vol_leverage_fast` at 0.0; off it, the
    /// variance with the fast memory's multiplier replaced by its expected
    /// mean over the VIX's window ([`Self::leverage_fast_window_multiplier`]),
    /// clamped as the variance is.
    pub fn vix_window_variance(&self, params: &crate::params::ModelParams) -> f64 {
        if params.market_vol_leverage_fast == 0.0 {
            return self.variance;
        }
        let l = self.leverage_fast_memory;
        let now = Self::leverage_fast_multiplier(params, l);
        if !(now > 0.0) {
            return self.variance;
        }
        clamp_variance(
            params, self.variance / now * Self::leverage_fast_window_multiplier(params, l))
    }

    /// The return memory's variance multiplier at memory `l`,
    /// `exp(k * l - k^2 * s^2 / 2)`, with `s^2` the memory's stationary
    /// variance at the baseline. See
    /// [`crate::params::ModelParams::market_vol_leverage`]. Read only while
    /// the dial is set.
    fn leverage_multiplier(params: &crate::params::ModelParams, l: f64) -> f64 {
        let k = params.market_vol_leverage;
        let phi = leverage_phi(params);
        let a = params.market_vol_leverage_down;
        let var_u = 0.5 * (1.0 + (1.0 - a) * (1.0 - a))
            - a * a / (2.0 * std::f64::consts::PI);
        let s2 = (1.0 - phi) / (1.0 + phi) * var_u;
        mathx::exp(k * l - 0.5 * k * k * s2)
    }

    /// The component mixture the variance is built from: the clamped
    /// weighted sum of the two components, or the one component on a
    /// single-component model. Equal to `variance` whenever the return
    /// memory is off; with it on, `variance` is this times the memory's
    /// multiplier (clamped), and on the session after a forced close it is
    /// this exactly.
    fn mixture(&self, params: &crate::params::ModelParams) -> f64 {
        let w = params.market_vol_slow_weight;
        if w == 0.0 {
            self.fast_variance
        } else {
            clamp_variance(params, (1.0 - w) * self.fast_variance + w * self.slow_variance)
        }
    }

    /// The day factor in the components' own units: the day was drawn at
    /// `variance`, the components are a mixture of `mixture`, so the shock
    /// they are fed is `F * sqrt(mixture / variance)`. That is `F / sqrt(m)`
    /// for the multiplier `m` the day was drawn at, and exactly `F` on the
    /// session after a forced close, which draws at the mixture itself.
    /// Read only while the return memory is on.
    fn component_shock(&self, params: &crate::params::ModelParams) -> f64 {
        let mix = self.mixture(params);
        if self.variance > 0.0 && mix > 0.0 {
            self.day_factor * mathx::sqrt(mix / self.variance)
        } else {
            self.day_factor
        }
    }

    /// [`Self::component_shock`] for a given day factor, for the tests.
    #[cfg(test)]
    fn day_factor_scaled_for_test(&self, params: &crate::params::ModelParams, f: f64) -> f64 {
        let mut s = *self;
        s.day_factor = f;
        s.component_shock(params)
    }

    /// One step of the return memory on the day's factor, at the variance
    /// the day was drawn at. See
    /// [`crate::params::ModelParams::market_vol_leverage`]. Called only
    /// while the dial is set.
    fn step_leverage_memory(&mut self, params: &crate::params::ModelParams) {
        let x = self.leverage_input(params);
        let phi = leverage_phi(params);
        self.leverage_memory = phi * self.leverage_memory + (1.0 - phi) * x;
    }

    /// One step of the fast return memory on the day's factor, on the input
    /// the slower memory takes. Called only while
    /// `market_vol_leverage_fast` is set.
    fn step_leverage_fast_memory(&mut self, params: &crate::params::ModelParams) {
        // Its own sign treatment (`market_vol_leverage_fast_up`), or, at 0.0,
        // the input the slower memory takes, to the bit.
        let x = if params.market_vol_leverage_fast_up == 0.0 {
            self.leverage_input(params)
        } else {
            self.leverage_fast_rise_input(params)
        };
        let phi = leverage_fast_phi(params);
        self.leverage_fast_memory = phi * self.leverage_fast_memory + (1.0 - phi) * x;
    }

    /// The fast memory's input with `market_vol_leverage_fast_up` set: the day
    /// factor in the memory's unit (`market_vol_leverage_standardise`), a fall
    /// counted positive, with that share `b` of a FALL ignored, re-centred on
    /// the mean the ignored share takes away: `u = -F / unit` on a rise,
    /// `-(1 - b) F / unit` on a fall, less `-b sqrt(v) / unit / sqrt(2 pi)`. At
    /// `b` 1.0 only a rise moves the memory: a rally lowers the variance the
    /// next sessions draw at, and a fall leaves it to the other channels.
    fn leverage_fast_rise_input(&self, params: &crate::params::ModelParams) -> f64 {
        let base = params.market_factor_sigma * params.market_factor_sigma;
        let b = params.market_vol_leverage_fast_up;
        let f = self.day_factor;
        let s = params.market_vol_leverage_standardise;
        let unit = if s == 0.0 {
            mathx::sqrt(base)
        } else {
            mathx::pow(base, 0.5 * (1.0 - s)) * mathx::pow(self.variance, 0.5 * s)
        };
        let u = if f > 0.0 { -f / unit } else { -(1.0 - b) * f / unit };
        let centre = -b * mathx::sqrt(self.variance) / unit / mathx::sqrt(2.0 * std::f64::consts::PI);
        u - centre
    }

    /// The day's input to a return memory, `u - centre`: the day factor in
    /// the memory's unit, a fall counted positive, re-centred on the mean an
    /// ignored up day adds. Read before the close writes the variance, so
    /// `variance` is the one the day was drawn at.
    fn leverage_input(&self, params: &crate::params::ModelParams) -> f64 {
        let b = params.market_factor_sigma * params.market_factor_sigma;
        let a = params.market_vol_leverage_down;
        let f = self.day_factor;
        // THE UNIT THE DAY IS COUNTED IN. At `market_vol_leverage_standardise`
        // 0.0 -- the form that stood -- the baseline sd, so a fall on a day
        // drawn at twice the baseline sd counts twice and the memory's own
        // spread grows with the variance it drives. At 1.0 the sd the day
        // was drawn at, so the memory takes the day's z-score, its spread is
        // the baseline's at every level and the multiplier's mean is one in
        // a storm as in a calm. In between, `sd_b^(1-s) * sd_v^s`. A branch,
        // so at 0.0 the arithmetic is the expression that stood, to the bit.
        // See `ModelParams::market_vol_leverage_standardise`.
        let s = params.market_vol_leverage_standardise;
        let unit = if s == 0.0 {
            mathx::sqrt(b)
        } else {
            mathx::pow(b, 0.5 * (1.0 - s)) * mathx::pow(self.variance, 0.5 * s)
        };
        let u = if f < 0.0 { -f / unit } else { -(1.0 - a) * f / unit };
        // The mean the asymmetry adds at the variance the day was drawn at:
        // `E[u] = a * sqrt(v) / unit / sqrt(2 pi)` for `F ~ N(0, v)`, which is
        // `a * sqrt(v / b) / sqrt(2 pi)` at standardise 0.0.
        let centre = if a == 0.0 {
            0.0
        } else if s == 0.0 {
            a * mathx::sqrt(self.variance / b) / mathx::sqrt(2.0 * std::f64::consts::PI)
        } else {
            a * mathx::sqrt(self.variance) / unit / mathx::sqrt(2.0 * std::f64::consts::PI)
        };
        u - centre
    }

    /// Today's factor sigma at DAILY scale — what the tick multiplies by
    /// `1/√390` to draw at per-tick scale.
    pub fn sigma_daily(&self) -> f64 {
        mathx::sqrt(self.variance)
    }

    /// Today's factor VARIANCE, the state itself.
    ///
    /// Beside `sigma_daily` rather than derived from it: `sqrt(v)` squared
    /// is not `v`, and the index-variance identity reads this state
    /// alongside variances that were never square-rooted, so a round trip
    /// through the square root would put a rounding difference on one term
    /// of a sum and not the others.
    pub fn variance(&self) -> f64 {
        self.variance
    }

    /// Accumulate one tick's market factor into the day's innovation.
    pub fn accumulate(&mut self, market_factor: f64) {
        self.day_factor += market_factor;
    }

    /// Market-open reset of the day accumulator, mirroring the engine's
    /// per-day attribution reset: a day abandoned without a close must
    /// not leak its partial innovation into the next day's update.
    pub fn open_day(&mut self) {
        self.day_factor = 0.0;
    }

    /// Close-of-day update. Consumes the accumulated innovation exactly
    /// once; a second close before any tick sees a zero innovation, which
    /// is the same quiet-day decay the per-name GARCH exhibits.
    pub fn close_day(&mut self, vix: f64) -> (f64, Option<f64>) {
        self.close_day_with(&crate::params::PT_V1, vix)
    }

    /// [`Self::close_day`] under explicit model parameters. What the engine
    /// calls; at [`crate::params::PT_V1`] it is the shipped update bit for
    /// bit.
    pub fn close_day_with(
        &mut self, params: &crate::params::ModelParams, vix: f64,
    ) -> (f64, Option<f64>) {
        self.close_day_at(params, params.market_vol_vix_anchor, vix)
    }

    /// [`Self::close_day_with`] against an EXPLICIT denominator for the VIX
    /// ratio -- what the engine calls, so that `vix_level_identity`'s
    /// derived anchor reaches the forward map. At
    /// `params.market_vol_vix_anchor` this is the arithmetic that stood
    /// here, to the bit.
    ///
    /// **It is a DENOMINATOR and not an anchor**, and the two stopped being
    /// the same thing at `market_vol_vix_excursion`. This argument is the
    /// only use either ever had here: `vix / denominator` is formed once
    /// and handed to `vix_response`, and nothing else in this function or
    /// in `update_market_variance_at` reads it. Under the excursion switch
    /// the engine passes the identity's own read-back instead of a
    /// constant, which makes the ratio a fear excursion rather than a
    /// level; see [`crate::params::ModelParams::market_vol_vix_excursion`].
    /// The name is `vix_ratio_denominator` so a reader cannot take it for
    /// the dial.
    /// Returns the variance TARGETS this close reverted toward:
    /// `(fast, slow)`, with `slow` absent when there is no slow component.
    ///
    /// Returned rather than stored, so nothing is added to
    /// [`MarketVarianceState`] — no new field, no change to `snapshot`,
    /// `restore`, `PartialEq` or the state hash. The engine keeps the pair
    /// if it wants it; see [`crate::engine::Engine::market_variance_target`].
    ///
    /// **The slow target is `None` at `market_vol_slow_weight == 0.0`, and
    /// that is not a convenience.** The fast target is computed
    /// unconditionally below, before the early return, so it exists on
    /// both paths. The slow one is computed only after that return, so on
    /// the single-component branch there is no slow target in existence to
    /// report. Returning `(target, target)` there would rest on every
    /// `slow_weight` 0.0 preset also shipping `slow_vix_damp` 0.0 — true
    /// of today's presets, not an invariant, and a future preset would
    /// break it silently while the name still claimed a reading from the
    /// close.
    ///
    /// On a single-component preset the first element is THE target, not a
    /// "fast" one: `fast` only means something when there is a slow
    /// component to be fast relative to.
    pub fn close_day_at(
        &mut self,
        params: &crate::params::ModelParams,
        vix_ratio_denominator: f64,
        vix: f64,
    ) -> (f64, Option<f64>) {
        self.close_day_scaled(params, vix_ratio_denominator, vix, 1.0)
    }

    /// The close, with the session's SLOW VARIANCE LEVEL applied.
    ///
    /// `level` multiplies the baseline variance the targets are built from,
    /// so BOTH components' targets move together and neither component's
    /// `alpha`, `beta` or `gamma` moves at all. That is the point of the
    /// form: the fourth-moment operator reads the coefficients and not
    /// `omega`, so a level cannot spend the moment condition's margin. See
    /// `ModelParams::market_vol_level_persistence`.
    ///
    /// The CLAMPS are deliberately left on the unscaled baseline. They say
    /// what this factor's variance may physically be, in multiples of its
    /// calm level, and that is a statement about the market rather than
    /// about the era: a level excursion that would take the variance past
    /// the ceiling is a level excursion that gets clipped. At the derived
    /// pair the clamp is nowhere near binding on the level alone -- two
    /// standard deviations of `log L` is a factor of four against a
    /// ceiling multiple of 32 -- so it binds only where it already did,
    /// which is inside a VIX spike.
    ///
    /// At `level == 1.0` every path below is the arithmetic that predates
    /// the level, to the bit, and the single-component branch is not
    /// merely equivalent but the SAME CALL.
    pub fn close_day_scaled(
        &mut self,
        params: &crate::params::ModelParams,
        vix_ratio_denominator: f64,
        vix: f64,
        level: f64,
    ) -> (f64, Option<f64>) {
        // The fear the target reads, not necessarily today's print. Real
        // volatility follows sustained fear with inertia; a model that
        // transmits every VIX print one-for-one into the variance target
        // injects the print-to-print churn straight into daily returns,
        // which round 99 measured as the whole of the driven excess. At
        // `market_vol_vix_smooth` = 0 -- every shipped preset -- the print
        // is read raw and this state never updates, bit for bit.
        let vix = if params.market_vol_vix_smooth == 0.0 {
            vix
        } else {
            let alpha = 2.0 / (params.market_vol_vix_smooth + 1.0);
            let prev = self.smoothed_vix.unwrap_or(vix);
            let sm = prev + alpha * (vix - prev);
            self.smoothed_vix = Some(sm);
            sm
        };
        let base = params.market_factor_sigma * params.market_factor_sigma;
        // The slow level scales the baseline the targets revert to. The
        // branch rather than an unconditional multiply because `x * 1.0`
        // being exact is a property of IEEE-754 that a reader has to know
        // to trust, and the zero arm of this mechanism is a CONTROL.
        let base = if level == 1.0 { base } else { base * level };
        let vix_ratio = vix / vix_ratio_denominator;
        let target = base
            * (1.0 - params.market_vol_vix_coupling
                + params.market_vol_vix_coupling * vix_response(params, vix_ratio));

        let w = params.market_vol_slow_weight;

        // The zero-weight branch is a BRANCH and not arithmetic on purpose.
        // Every preset before pt-v4 must reproduce the single-component
        // update to the bit, and this is the only spelling that owes
        // nothing to an argument about how floats behave.
        // THE RETURN MEMORY. A branch, so at `market_vol_leverage` 0.0 --
        // every shipped preset -- nothing below it moves and no field it
        // owns is written. See `ModelParams::market_vol_leverage`.
        if params.market_vol_leverage != 0.0 || params.market_vol_leverage_fast != 0.0 {
            return self.close_with_leverage_memory(params, target, base, vix_ratio);
        }

        if w == 0.0 {
            // `update_market_variance_at` recomputes the baseline from the
            // dials and so cannot see the level; at 1.0 it is called, so
            // every preset that takes this branch is bit-identical by
            // CALLING THE SAME FUNCTION rather than by an argument about
            // two spellings agreeing. At any other level the target
            // computed above -- the same expression, with the scaled
            // baseline -- is handed to the step directly.
            self.variance = if level == 1.0 {
                update_market_variance_at(
                    params, vix_ratio_denominator, self.variance, self.day_factor, vix)
            } else {
                update_toward_with(params, self.variance, self.day_factor, target)
            };
            self.fast_variance = self.variance;
            self.prev_day_factor = self.day_factor;
            self.day_factor = 0.0;
            // No slow component exists on this branch. See the docstring.
            return (target, None);
        }

        // THE FAST COMPONENT'S SHOCK SHARE MOVES WITH ITS OWN EXCURSION.
        // `alpha_beta_at` returns the dialled pair unchanged at
        // `market_vol_alpha_excursion` 0.0, which is every preset before
        // 0.8.0 and is bit-identical.
        //
        // It is applied HERE and not only in `update_toward_with`, which was
        // the first place it went and was the wrong one: that function is the
        // SINGLE-component path, reached only at `market_vol_slow_weight`
        // 0.0, and no shipped preset takes it. The `alphax1` box measured six
        // settings of the dial and got six bit-identical trajectories, which
        // is what a dial wired to a branch nothing runs looks like.
        //
        // The SLOW component is deliberately left alone. It carries the
        // autonomous level on a damped VIX coupling and its own
        // `slow_alpha_beta`; the tape's response decays with the window
        // (+0.094 at a week against +0.019 at a year), so the mechanism
        // belongs on the fast component and putting it on both would spend
        // the same measurement twice.
        let (fast_alpha, fast_beta) = alpha_beta_at(params, self.fast_variance, target);
        let fast = clamp_variance(
            params,
            component_step(self.fast_variance, self.day_factor, target,
                           fast_alpha, fast_beta,
                           params.market_vol_gamma),
        );
        // The slow component may revert to a LESS VIX-coupled target than
        // the fast one, which is the whole point of having two.
        //
        // With a shared target, adding a slow component makes the mixture
        // track a VIX spike more sluggishly than the fast component alone --
        // the opposite of what the scenario transient needs. The measured
        // defect is exactly that: pt-v3 retains 95.2% of pt-v1's STEADY-STATE
        // VIX lever and only 27.6% of its TRANSIENT, because one variance
        // timescale is doing two jobs. Within-year clustering wants long
        // memory; tracking a twenty-day spike wants short.
        //
        // Damping the slow component's coupling separates them: the fast
        // component chases VIX, the slow one carries the autonomous level and
        // the long memory. At 0.0 the two targets are the same expression and
        // the branch is skipped, so every preset before pt-v4 is untouched.
        let slow_target = if params.market_vol_slow_vix_damp == 0.0 {
            target
        } else {
            let c = params.market_vol_vix_coupling
                * (1.0 - params.market_vol_slow_vix_damp);
            base * (1.0 - c + c * vix_response(params, vix_ratio))
        };
        let slow = slow_step(params, self.slow_variance, self.day_factor, slow_target);

        self.fast_variance = fast;
        self.slow_variance = slow;
        // Both components revert to the SAME target, so the mixture's
        // autocorrelation is the weighted sum of two decay rates rather
        // than one decay plus a level.
        self.variance = clamp_variance(params, (1.0 - w) * fast + w * slow);
        self.prev_day_factor = self.day_factor;
        self.day_factor = 0.0;
        (target, Some(slow_target))
    }

    /// [`Self::close_day_scaled`] with the return memory on
    /// (`market_vol_leverage` non-zero). Separate so the path every shipped
    /// preset takes is the code that stood there, untouched.
    ///
    /// The same steps as the free close, with three differences: the
    /// components are fed the day factor in their own units
    /// ([`Self::component_shock`]); the memory takes one step on the day's
    /// factor at the variance the day was drawn at; and the variance the
    /// next session draws with is the mixture times the memory's
    /// multiplier, clamped. The single-component branch steps its one
    /// component through `update_toward_with` against the target the
    /// caller computed, which at level 1.0 is the target
    /// `update_market_variance_at` would compute.
    fn close_with_leverage_memory(
        &mut self,
        params: &crate::params::ModelParams,
        target: f64,
        base: f64,
        vix_ratio: f64,
    ) -> (f64, Option<f64>) {
        let shock = self.component_shock(params);
        let w = params.market_vol_slow_weight;
        let slow_target = if w == 0.0 {
            None
        } else if params.market_vol_slow_vix_damp == 0.0 {
            Some(target)
        } else {
            let c = params.market_vol_vix_coupling * (1.0 - params.market_vol_slow_vix_damp);
            Some(base * (1.0 - c + c * vix_response(params, vix_ratio)))
        };
        if w == 0.0 {
            self.fast_variance = update_toward_with(params, self.fast_variance, shock, target);
        } else {
            let (fast_alpha, fast_beta) = alpha_beta_at(params, self.fast_variance, target);
            self.fast_variance = clamp_variance(
                params,
                component_step(self.fast_variance, shock, target,
                               fast_alpha, fast_beta, params.market_vol_gamma),
            );
            self.slow_variance = slow_step(
                params, self.slow_variance, shock, slow_target.unwrap_or(target));
        }
        // Each memory steps only while its own dial is set, so either alone
        // is the arithmetic that stood for it, to the bit.
        if params.market_vol_leverage != 0.0 {
            self.step_leverage_memory(params);
        }
        if params.market_vol_leverage_fast != 0.0 {
            self.step_leverage_fast_memory(params);
        }
        let mix = self.mixture(params);
        let m = if params.market_vol_leverage != 0.0 {
            Self::leverage_multiplier(params, self.leverage_memory)
        } else {
            1.0
        };
        let m = if params.market_vol_leverage_fast != 0.0 {
            m * Self::leverage_fast_multiplier(params, self.leverage_fast_memory)
        } else {
            m
        };
        self.variance = clamp_variance(params, mix * m);
        self.prev_day_factor = self.day_factor;
        self.day_factor = 0.0;
        (target, slow_target)
    }

    /// The two targets a close at this VIX reverts toward, `(fast, slow)`,
    /// spelled as [`Self::close_day_scaled`] spells them. The slow one is
    /// the fast one whenever `market_vol_slow_vix_damp` is 0.0.
    ///
    /// Read only by the FORCED close below, so nothing that runs on a
    /// free-running session goes through it and the arithmetic there is not
    /// touched.
    fn forced_targets(
        params: &crate::params::ModelParams,
        vix_ratio_denominator: f64,
        vix: f64,
        level: f64,
    ) -> (f64, f64) {
        let base = params.market_factor_sigma * params.market_factor_sigma;
        let base = if level == 1.0 { base } else { base * level };
        let vix_ratio = vix / vix_ratio_denominator;
        let response = vix_response(params, vix_ratio);
        let target = base
            * (1.0 - params.market_vol_vix_coupling
                + params.market_vol_vix_coupling * response);
        let slow_target = if params.market_vol_slow_vix_damp == 0.0 {
            target
        } else {
            let c = params.market_vol_vix_coupling
                * (1.0 - params.market_vol_slow_vix_damp);
            base * (1.0 - c + c * response)
        };
        (target, slow_target)
    }

    /// The factor variance a forced close at this denominator would set:
    /// the clamped mixture of the two clamped targets, or the clamped single
    /// target on a one-component preset. Moves no state.
    ///
    /// The engine reads it to find the denominator a forced close should
    /// use when the denominator is itself a function of this variance
    /// (`market_vol_vix_excursion`); see `Engine::forced_vix_denominator`.
    pub fn forced_level(
        params: &crate::params::ModelParams,
        vix_ratio_denominator: f64,
        vix: f64,
        level: f64,
    ) -> f64 {
        let (target, slow_target) =
            Self::forced_targets(params, vix_ratio_denominator, vix, level);
        let w = params.market_vol_slow_weight;
        if w == 0.0 {
            return clamp_variance(params, target);
        }
        let fast = clamp_variance(params, target);
        let slow = clamp_variance(params, slow_target);
        clamp_variance(params, (1.0 - w) * fast + w * slow)
    }

    /// The close on a session whose VIX a scenario FORCED, with the
    /// scenario's `vix_sets_variance` switch on: the variance is SET to the
    /// level the variance law implies at that VIX instead of stepping one
    /// session toward it.
    ///
    /// # What "the level the law implies" is
    ///
    /// Each component's GARCH step is, in expectation over the day's factor,
    /// `E[v'] = (1 - p) * target + p * v` (see [`Self::warm_to_level`]), so a
    /// VIX held for ever takes each component to ITS OWN target and the
    /// mixture to `(1 - w) * fast_target + w * slow_target`. That is what
    /// this close writes, clamped exactly as a free close clamps. Nothing
    /// new is introduced: no coefficient, no half-life, no target other
    /// than the two the free close already computes.
    ///
    /// # Why this and not a shorter half-life
    ///
    /// A free close approaches the target at `1 - p` of the gap a session,
    /// and the fast component's `p` of 0.979 is a 33-session half-life,
    /// which is why an imposed VIX path used to arrive in the market's
    /// volatility weeks late. Shortening `p` while forced would need a
    /// second pair of persistences (one per component) that the model does
    /// not have and the tape does not give for the slow component, and it
    /// would still lag a spike that builds in three weeks. Setting the
    /// state to the fixed point has no free parameter.
    ///
    /// # Why release does not jolt
    ///
    /// The state this leaves is the fixed point of the free recursion at
    /// this VIX, so the first free close after the force, at the same VIX,
    /// has an expected step of zero: `E[v'] = (1 - p) * T + p * T = T`.
    /// The market goes on from the level the free law would itself have
    /// reached under a held VIX; what it does next is the free law's.
    ///
    /// # What it gives up while forced
    ///
    /// The day's squared factor does not feed the variance components on a
    /// forced close. The return memory (`market_vol_leverage`, when set)
    /// does take the day's factor, because the returns happened; the
    /// variance written here carries no multiplier from it.
    /// The forced VIX is the fear the scenario asserts, and letting the
    /// model's own shocks move the variance off it would mean the scenario
    /// did not set it. The per-name GARCH, the sector state and the jumps
    /// are untouched and keep clustering on their own shocks.
    ///
    /// The VIX is read RAW, not through `market_vol_vix_smooth`'s EMA: the
    /// EMA of a held VIX converges to it, so its fixed point is the raw
    /// level. The EMA itself is still advanced, so a release hands the free
    /// close a primed state rather than a stale one. The day accumulator is
    /// rolled exactly as a free close rolls it.
    ///
    /// Returns the targets, as [`Self::close_day_scaled`] does.
    pub fn close_day_forced(
        &mut self,
        params: &crate::params::ModelParams,
        vix_ratio_denominator: f64,
        vix: f64,
        level: f64,
    ) -> (f64, Option<f64>) {
        if params.market_vol_vix_smooth != 0.0 {
            let alpha = 2.0 / (params.market_vol_vix_smooth + 1.0);
            let prev = self.smoothed_vix.unwrap_or(vix);
            self.smoothed_vix = Some(prev + alpha * (vix - prev));
        }
        let (target, slow_target) =
            Self::forced_targets(params, vix_ratio_denominator, vix, level);
        let w = params.market_vol_slow_weight;
        // The return memory remembers a forced session's factor like any
        // other -- the returns happened -- but the variance below is the
        // law's level at the forced VIX, without the memory's multiplier:
        // the scenario asserted that fear. A branch, so nothing moves at
        // `market_vol_leverage` 0.0.
        if params.market_vol_leverage != 0.0 {
            self.step_leverage_memory(params);
        }
        // The fast memory the same way, on its own dial.
        if params.market_vol_leverage_fast != 0.0 {
            self.step_leverage_fast_memory(params);
        }
        self.prev_day_factor = self.day_factor;
        self.day_factor = 0.0;
        if w == 0.0 {
            // One component: the slow level is not a state here and is left
            // where a free close leaves it, untouched.
            self.variance = clamp_variance(params, target);
            self.fast_variance = self.variance;
            return (target, None);
        }
        let fast = clamp_variance(params, target);
        let slow = clamp_variance(params, slow_target);
        self.fast_variance = fast;
        self.slow_variance = slow;
        self.variance = clamp_variance(params, (1.0 - w) * fast + w * slow);
        (target, Some(slow_target))
    }

    /// Warm the variance components to the slow LEVEL the run opens on,
    /// before session one.
    ///
    /// # What is cold and why it matters
    ///
    /// `new_with` seeds both components at the UNSCALED baseline
    /// `market_factor_sigma^2`, which is where a run with no level belongs.
    /// The level opens from its own stationary distribution, so at the
    /// shipped `sd(log L)` of 1.25 the target the components must reach is
    /// displaced by a factor whose log has a standard deviation of 1.25 --
    /// and they reach it on their own memory, 48 sessions for the fast
    /// component and 115 for the slow. MEASURED, that transient is the
    /// whole of the 252/504 gap the level's calibration was read through.
    ///
    /// # The recursion, and why it is the MEAN one
    ///
    /// `component_step` is
    /// `(1 - a - b - g/2) * target + (a + lev) * f^2 + b * v`. Take the
    /// expectation over the day's factor, which is conditionally
    /// `N(0, v)`, so `E[f^2] = v`, and over the sign of that factor, which
    /// is symmetric, so the GJR arm loads `g/2`:
    ///
    /// ```text
    /// E[v'] = (1 - p) * target + p * v,    p = a + b + g/2
    /// ```
    ///
    /// That is a linear recursion in `v` with the same fixed point and the
    /// same memory as the stochastic one, and it is what "run in" means for
    /// a state whose stochastic part is stationary from session one
    /// anyway. Nothing is drawn, here or anywhere, at any setting of the
    /// dial. The draw schedule cannot move; see
    /// `ModelParams::market_burn_in_sessions`.
    ///
    /// `alpha_beta_at`'s rotation is not applied, and that is exact rather
    /// than an omission: the rotation is volume-preserving in
    /// `alpha + beta`, so `p` -- the only thing this recursion reads -- is
    /// invariant to it.
    ///
    /// # The level's path
    ///
    /// `log_level` is the level the run OPENS on, drawn at this close from
    /// the level's stationary distribution. The path before it is not
    /// known and does not need to be: for an AR(1),
    /// `E[log L_{1-k} | log L_1] = phi^k log L_1`, so the warm-up walks
    /// that expected path forwards, arriving at `log_level` on the last
    /// warm-up session. The normalisation `- stationary_var / 4` is the
    /// same square-root normalisation the close applies, passed in rather
    /// than recomputed so that the two cannot drift apart.
    ///
    /// # The VIX
    ///
    /// Held at the value the close is about to read, for the whole warm-up.
    /// The VIX reverts at `vix_mean_reversion` -- a relaxation of about
    /// three sessions on the shipped 0.27 -- so it is two orders of
    /// magnitude faster than the states being warmed and is already at
    /// whatever the opening asks for; treating it as a constant over the
    /// warm-up is the same approximation that measurement makes
    /// in the other direction when it treats the LEVEL as flat over the
    /// engine's relaxation.
    ///
    /// The clamps apply on every warm-up session exactly as they do on a
    /// real one, so a warm-up cannot deliver a state the close could not
    /// have reached.
    pub fn warm_to_level(
        &mut self,
        params: &crate::params::ModelParams,
        vix_ratio_denominator: f64,
        vix: f64,
        log_level: f64,
        stationary_var: f64,
        sessions: i64,
    ) {
        if sessions <= 0 {
            return;
        }
        let base0 = params.market_factor_sigma * params.market_factor_sigma;
        let c = params.market_vol_vix_coupling;
        let response = vix_response(params, vix / vix_ratio_denominator);
        let coupled = 1.0 - c + c * response;
        let damped = if params.market_vol_slow_vix_damp == 0.0 {
            coupled
        } else {
            let cd = c * (1.0 - params.market_vol_slow_vix_damp);
            1.0 - cd + cd * response
        };
        let phi = params.market_vol_level_persistence;
        let p_fast =
            params.market_vol_alpha + params.market_vol_beta + 0.5 * params.market_vol_gamma;
        let (sa, sb) = slow_alpha_beta(params);
        let p_slow = sa + sb;
        let w = params.market_vol_slow_weight;
        let mut fast = self.fast_variance;
        let mut slow = self.slow_variance;
        for step in 0..sessions {
            // `k` sessions before session one, counting down to zero, so
            // the last warm-up session sits on the level the close is
            // about to use.
            let k = (sessions - 1 - step) as f64;
            let log_l = mathx::pow(phi, k) * log_level;
            let base = base0 * mathx::exp(log_l - 0.25 * stationary_var);
            fast = clamp_variance(params, (1.0 - p_fast) * (base * coupled) + p_fast * fast);
            if w != 0.0 {
                slow = clamp_variance(params, (1.0 - p_slow) * (base * damped) + p_slow * slow);
            }
        }
        self.fast_variance = fast;
        // The single-component branch of `close_day_scaled` carries no slow
        // component at all, so there is none to warm and the mixture IS the
        // fast state. `slow_variance` is left exactly where the close would
        // leave it -- untouched -- because it is in the state hash and a
        // warm-up that wrote a field the close does not write would make a
        // warmed engine unreachable by running.
        if w == 0.0 {
            self.variance = fast;
        } else {
            self.slow_variance = slow;
            self.variance = clamp_variance(params, (1.0 - w) * fast + w * slow);
        }
        // With the return memory on, the session draws at the mixture times
        // the memory's multiplier, which is what a close would leave. A
        // branch: nothing moves at `market_vol_leverage` 0.0.
        if params.market_vol_leverage != 0.0 {
            self.variance = clamp_variance(
                params, self.variance * Self::leverage_multiplier(params, self.leverage_memory));
        }
    }

    /// The state numbers, for checkpoints: `(variance, day_factor,
    /// fast_variance, slow_variance, prev_day_factor, smoothed_vix)`.
    /// `smoothed_vix` is a VIX-scale positive number while primed;
    /// a negative value is the None sentinel (JSON carries no NaN).
    pub fn snapshot(&self) -> (f64, f64, f64, f64, f64, f64) {
        (self.variance, self.day_factor, self.fast_variance,
         self.slow_variance, self.prev_day_factor,
         self.smoothed_vix.unwrap_or(-1.0))
    }

    /// Restore from a checkpoint. Values are adopted verbatim, like every
    /// other restored column: the snapshot is trusted to be one this
    /// engine wrote.
    pub fn restore(variance: f64, day_factor: f64) -> Self {
        // A two-value checkpoint predates the slow component. Adopting the
        // variance as the slow level is the only choice that keeps such a
        // checkpoint replaying identically under a legacy preset, where the
        // slow level is inert and never read.
        Self {
            variance,
            day_factor,
            fast_variance: variance,
            slow_variance: variance,
            // Pre-dial checkpoints carry no smoothed fear; the EMA
            // re-seeds from the first smoothed close after restore.
            smoothed_vix: None,
            prev_day_factor: 0.0,
            leverage_memory: 0.0,
            leverage_fast_memory: 0.0,
        }
    }

    /// Restore including the slow component, for checkpoints that carry it.
    pub fn restore_with_components(
        variance: f64,
        day_factor: f64,
        fast_variance: f64,
        slow_variance: f64,
        prev_day_factor: f64,
        smoothed_vix: f64,
    ) -> Self {
        // A checkpoint from before the lagged wire carries no
        // prev_day_factor; the caller passes 0.0 and the wire simply does
        // not fire on the first restored session, which is what those
        // checkpoints' era did anyway. Same for the smoothed fear: a
        // negative sentinel means unprimed, and the EMA re-seeds from the
        // first smoothed close -- bit-identical for every checkpoint
        // written while the dial was inert.
        Self {
            variance, day_factor, fast_variance, slow_variance,
            smoothed_vix: if smoothed_vix < 0.0 { None } else { Some(smoothed_vix) },
            prev_day_factor,
            // Carried under its own snapshot key, only while the return
            // memory is on; the engine puts it back after this.
            leverage_memory: 0.0,
            // The same for the fast return memory.
            leverage_fast_memory: 0.0,
        }
    }
}

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

    const BASE: f64 = MARKET_FACTOR_SIGMA * MARKET_FACTOR_SIGMA;

    #[test]
    fn the_recursion_reverts_and_the_clamp_carries_the_fourth_moment() {
        // The module header's arithmetic, pinned as it is actually argued.
        // Mean reversion of the unclamped recursion:
        let persistence = MARKET_VOL_ALPHA + MARKET_VOL_BETA;
        assert!(
            persistence < 1.0,
            "alpha + beta = {persistence}: at or above 1 the factor variance is non-stationary"
        );
        // The unclamped fourth-moment condition is KNOWINGLY violated --
        // the ceiling bounds the tail instead. Assert the violation, so
        // that if a recalibration ever moves back inside the condition,
        // whoever did it revisits the ceiling's load-bearing role (and
        // this test) rather than inheriting a clamp it no longer needs.
        let fourth = persistence * persistence + 2.0 * MARKET_VOL_ALPHA * MARKET_VOL_ALPHA;
        assert!(
            fourth > 1.0,
            "(a+b)^2 + 2a^2 = {fourth}: the shipped shape trades the unclamped fourth-moment \
             condition for in-window tails; if this now holds, the ceiling's role changed"
        );
        // And the boundedness that replaces it: ordered bounds, and a
        // quiet-run fixed point ABOVE the floor, so the floor is a
        // worst-case guarantee rather than a regime.
        const { assert!(MARKET_VOL_FLOOR_MULTIPLE < MARKET_VOL_CEILING_MULTIPLE) };
        let quiet_fixed_point = (1.0 - persistence) / (1.0 - MARKET_VOL_BETA);
        assert!(
            quiet_fixed_point > MARKET_VOL_FLOOR_MULTIPLE,
            "quiet fixed point {quiet_fixed_point} at or below the floor pins calm periods \
             and destroys the variance dispersion kurtosis is made of (measured; see module doc)"
        );
    }

    #[test]
    fn a_violent_market_day_raises_tomorrows_factor_variance() {
        // The defining property, exactly as garch.rs states it for the
        // per-name process.
        let calm = update_market_variance(BASE, 0.0005, 15.0);
        let shocked = update_market_variance(BASE, 0.04, 15.0);
        assert!(
            shocked > calm,
            "a 4% market day must raise factor variance above a 0.05% day: {shocked} vs {calm}"
        );
    }

    #[test]
    fn factor_variance_clusters_rather_than_resetting() {
        let mut shocked = update_market_variance(BASE, 0.04, 15.0);
        for _ in 0..3 {
            shocked = update_market_variance(shocked, 0.0, 15.0);
        }
        let mut never = BASE;
        for _ in 0..4 {
            never = update_market_variance(never, 0.0, 15.0);
        }
        assert!(
            shocked > never * 1.2,
            "three days after a 4% market day the factor variance must still be elevated: \
             {shocked} vs {never}"
        );
    }

    #[test]
    fn a_quiet_run_settles_at_the_fixed_point_above_the_floor() {
        // ω/(1−β) = 0.1·base — the floor at 0.05 is deliberately BELOW
        // it, so calm markets keep a live, dispersed factor variance
        // instead of being pinned flat (the pinning was measured to
        // destroy the factor's kurtosis; see the floor's doc).
        let mut v = update_market_variance(BASE, 0.06, 15.0);
        for _ in 0..400 {
            v = update_market_variance(v, 0.0, 15.0);
        }
        let fixed_point =
            BASE * (1.0 - MARKET_VOL_ALPHA - MARKET_VOL_BETA) / (1.0 - MARKET_VOL_BETA);
        assert!(
            (v - fixed_point).abs() < fixed_point * 1e-9,
            "400 quiet days should settle at the fixed point {fixed_point}, got {v}"
        );
        assert!(v > BASE * MARKET_VOL_FLOOR_MULTIPLE);
    }

    #[test]
    fn the_variance_stays_inside_its_bounds_however_hard_it_is_driven() {
        let mut v = BASE;
        for day in 0..1000 {
            let eps = if day % 2 == 0 { 0.5 } else { 0.0 };
            v = update_market_variance(v, eps, 15.0);
            assert!(
                v <= BASE * MARKET_VOL_CEILING_MULTIPLE * 1.000001,
                "day {day}: variance {v} escaped the ceiling"
            );
            assert!(
                v >= BASE * MARKET_VOL_FLOOR_MULTIPLE * 0.999999,
                "day {day}: variance {v} fell through the floor"
            );
        }
    }

    #[test]
    fn the_ceiling_is_reachable_in_a_burst_so_it_is_a_bound_and_not_a_prop() {
        // The ceiling carries the fourth moment, so it must actually be
        // reachable by the dynamics it bounds. Two hard days from an
        // already-elevated regime must hit it.
        let mut v = BASE * 2.0;
        v = update_market_variance(v, 2.0 * mathx::sqrt(v), 15.0); // a 2-sigma day
        v = update_market_variance(v, 2.0 * mathx::sqrt(v), 15.0); // another
        assert!(
            v >= BASE * MARKET_VOL_CEILING_MULTIPLE * 0.999999,
            "two 2-sigma days from twice-baseline variance should reach the ceiling, got \
             {} x base",
            v / BASE
        );
    }

    #[test]
    fn the_shipped_coupling_is_on_so_vix_moves_the_variance_target() {
        // The era decision, pinned from the other side: this test's
        // predecessor asserted VIX 5 and VIX 65 produce bit-identical
        // updates while the coupling shipped at zero. The flip that
        // closed finding 6's open question inverts it -- a crisis VIX
        // must now pull tomorrow's factor variance ABOVE what a calm VIX
        // leaves, at every innovation. If this fails, the coupling was
        // turned back off, which un-answers a question the era answered
        // by measurement and re-falsifies the scenario/docs claims that
        // were rewritten to match; see the constant's doc.
        assert_eq!(MARKET_VOL_VIX_COUPLING, 1.0);
        for eps in [0.0, 0.01, 0.04] {
            let calm = update_market_variance(BASE * 2.0, eps, 5.0);
            let crisis = update_market_variance(BASE * 2.0, eps, 65.0);
            assert!(
                crisis > calm,
                "eps {eps}: VIX 65 must raise the variance target above VIX 5, \
                 got {crisis} vs {calm}"
            );
        }
    }

    #[test]
    fn an_anchor_level_vix_reproduces_the_autonomous_update_to_the_bit() {
        // The coupling is a pure modulation around the anchor: at
        // VIX == MARKET_VOL_VIX_ANCHOR the ratio is exactly 1.0, the
        // blend is exactly 1.0 at ANY coupling, and the update must equal
        // the explicit-target form at the baseline bit-for-bit. This is
        // what keeps the coupling question separated from a level change
        // -- the same isolation the anchor's own doc argues.
        for (v, eps) in [(BASE, 0.0), (BASE * 2.0, 0.01), (BASE * 0.5, 0.04)] {
            let coupled = update_market_variance(v, eps, MARKET_VOL_VIX_ANCHOR);
            let autonomous = update_toward(v, eps, BASE);
            assert_eq!(coupled.to_bits(), autonomous.to_bits(), "v {v} eps {eps}");
        }
    }

    #[test]
    fn a_held_crisis_pin_saturates_at_the_ceiling_so_the_response_is_flat_above_it() {
        // The damping argument, as arithmetic. The unclamped stationary
        // variance of the recursion equals its target, so once
        // (VIX/anchor)^2 exceeds the ceiling multiple the state pins at
        // the ceiling and the response to a harder pin is FLAT: a held
        // VIX 45 and a held VIX 100 bound the factor identically, and the
        // measured 82-99% crisis volatility is a ceiling regime, not the
        // start of a quadratic ramp. The coupling ships undamped BECAUSE
        // this holds; if the anchor or the ceiling moves, this test drags
        // the saturation point back into view.
        let saturation_vix = MARKET_VOL_VIX_ANCHOR * mathx::sqrt(MARKET_VOL_CEILING_MULTIPLE);
        assert!(
            saturation_vix < 45.0,
            "saturation at VIX {saturation_vix}: a held VIX 45 no longer pins the \
             ceiling, so the held-pin volatility argument needs re-measuring"
        );
        // And the state genuinely cannot exceed the ceiling under the
        // hardest coupled pin, however hard the innovations drive it.
        let mut v = BASE;
        for _ in 0..300 {
            v = update_market_variance(v, 3.0 * mathx::sqrt(v), 100.0);
            assert!(v <= BASE * MARKET_VOL_CEILING_MULTIPLE * 1.000001);
        }
        assert!(
            v >= BASE * MARKET_VOL_CEILING_MULTIPLE * 0.999999,
            "a relentless VIX-100 pin should hold the state at the ceiling, got {} x base",
            v / BASE
        );
    }

    #[test]
    fn a_coupled_target_scales_with_vix_squared_and_stays_clamped() {
        // The seam form the sweep patches, exercised explicitly: a larger
        // target raises the update, and a crisis-sized target cannot push
        // the state past the ceiling that bounds the process everywhere.
        let anchored = update_toward(BASE, 0.0, BASE);
        let doubled = update_toward(BASE, 0.0, BASE * 4.0);
        assert!(doubled > anchored);
        let extreme = update_toward(BASE * MARKET_VOL_CEILING_MULTIPLE, 0.06, BASE * 20.0);
        assert!(extreme <= BASE * MARKET_VOL_CEILING_MULTIPLE * 1.000001);
    }

    #[test]
    fn the_calm_exponent_reshapes_only_below_the_anchor() {
        let mut p = crate::params::PT_V1.clone();
        p.market_vol_vix_exponent = 4.0;
        let at_zero: Vec<f64> = [0.3, 0.7, 1.0, 1.6].iter().map(|&r| vix_response(&p, r)).collect();
        p.market_vol_vix_exponent_below = 2.0;
        assert_eq!(vix_response(&p, 0.5), 0.25);
        assert_eq!(vix_response(&p, 1.0), at_zero[2]);
        assert_eq!(vix_response(&p, 1.6), at_zero[3], "the crisis side must not move");
        assert!(vix_response(&p, 0.7) > at_zero[1]);
        p.market_vol_vix_exponent_below = 2.5;
        assert!((vix_response(&p, 0.49) - 0.49f64.powf(2.5)).abs() < 1e-12);
    }

    #[test]
    fn the_state_accumulates_a_day_and_consumes_it_exactly_once() {
        let mut state = MarketVarianceState::new();
        state.accumulate(0.02);
        state.accumulate(0.02);
        state.close_day(15.0);
        let after_shock = state.snapshot().0;
        assert!(
            after_shock > BASE,
            "a 4% accumulated day must raise the variance: {after_shock}"
        );
        // The innovation was consumed: a second close decays instead of
        // double-counting.
        let mut again = state;
        again.close_day(15.0);
        assert!(again.snapshot().0 < after_shock);
    }

    #[test]
    fn an_abandoned_day_does_not_leak_into_the_next_innovation() {
        let mut state = MarketVarianceState::new();
        state.accumulate(0.05);
        state.open_day(); // day abandoned without a close
        state.close_day(15.0);
        let mut clean = MarketVarianceState::new();
        clean.close_day(15.0);
        assert_eq!(state.snapshot().0.to_bits(), clean.snapshot().0.to_bits());
    }

    #[test]
    fn a_fresh_state_draws_at_exactly_the_baseline_sigma() {
        // Day one of the conditional process is the constant-sigma model:
        // sqrt of the squared constant must return the constant's bits.
        assert_eq!(
            MarketVarianceState::new().sigma_daily().to_bits(),
            MARKET_FACTOR_SIGMA.to_bits()
        );
    }

    #[test]
    fn snapshot_and_restore_round_trip_exactly() {
        let mut state = MarketVarianceState::new();
        state.accumulate(0.007);
        state.close_day(22.0);
        state.accumulate(-0.003);
        let (v, df, fast, slow, pdf, sv) = state.snapshot();
        let restored = MarketVarianceState::restore_with_components(v, df, fast, slow, pdf, sv);
        assert_eq!(state, restored);
    }

    #[test]
    fn a_two_value_checkpoint_still_replays_under_a_legacy_preset() {
        // Checkpoints written before the slow component carry two numbers,
        // so the slow level cannot be reconstructed from them. That is
        // harmless exactly where it has to be: under any preset with the
        // slow component off the level is never read, so the RESTORED
        // state prices identically even though it is not `==` to the
        // original. This pins the property that matters -- the
        // trajectory -- rather than the struct equality that does not.
        let params = &crate::params::PT_V1;
        assert_eq!(params.market_vol_slow_weight, 0.0);

        let mut original = MarketVarianceState::new_with(params);
        original.accumulate(0.011);
        original.close_day_with(params, 31.0);
        original.accumulate(-0.004);

        let (v, df, _fast, _slow, _pdf, _sv) = original.snapshot();
        let mut restored = MarketVarianceState::restore(v, df);

        for day in 0..12 {
            let vix = 15.0 + day as f64;
            let mut a = original;
            let mut b = restored;
            a.close_day_with(params, vix);
            b.close_day_with(params, vix);
            assert_eq!(a.sigma_daily(), b.sigma_daily(), "day {day}");
            original = a;
            restored = b;
        }
    }

    #[test]
    fn the_slow_component_is_inert_at_its_legacy_values() {
        // The bit-identity contract for every preset before pt-v4: with
        // the slow component off, the composed update must equal the
        // single-component update exactly, not approximately.
        let params = &crate::params::PT_V1;
        let mut composed = MarketVarianceState::new_with(params);
        let mut variance = params.market_factor_sigma * params.market_factor_sigma;

        for day in 0..40 {
            let innovation = 0.004 * ((day % 7) as f64 - 3.0);
            let vix = 12.0 + (day % 11) as f64;
            composed.accumulate(innovation);
            composed.close_day_with(params, vix);
            variance = update_market_variance_with(params, variance, innovation, vix);
            assert_eq!(composed.sigma_daily(), mathx::sqrt(variance), "day {day}");
        }
    }
}

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

    /// The dial off is the symmetric step to the bit, whatever the sign
    /// of the day.
    #[test]
    fn gamma_zero_is_the_symmetric_step_bit_for_bit() {
        for d in [-0.02, -0.001, 0.0, 0.001, 0.02] {
            let sym = (1.0 - 0.28 - 0.69) * 4e-4 + 0.28 * d * d + 0.69 * 3e-4;
            let gjr = component_step(3e-4, d, 4e-4, 0.28, 0.69, 0.0);
            assert_eq!(sym.to_bits(), gjr.to_bits(), "day_factor {d}");
        }
    }

    /// A down day loads more variance than an up day of the same size,
    /// and omega's gamma/2 rebate keeps the two-sided average on the
    /// symmetric step: the dial redistributes, it does not add.
    #[test]
    /// A down day loads more variance than an up day of the same size.
    /// The gamma/2 rebate in omega makes the two-sided average equal the
    /// symmetric step exactly at the stationary point, and differ by
    /// (gamma/2)(d^2 - t) elsewhere -- both pinned below.
    fn gamma_redistributes_between_down_and_up_without_adding() {
        let (a, b, g, v, t) = (0.28, 0.69, 0.10, 3e-4, 4e-4);
        // At the stationary point (shock at target) the gamma/2 rebate is
        // exact: the two-sided average equals the symmetric step, so in
        // equilibrium the dial redistributes variance between down and up
        // states rather than adding any.
        let at_target = crate::mathx::sqrt(t);
        let down = component_step(v, -at_target, t, a, b, g);
        let up = component_step(v, at_target, t, a, b, g);
        let sym = component_step(v, at_target, t, a, b, 0.0);
        assert!(down > up, "leverage must load the down side");
        let two_sided = 0.5 * (down + up);
        assert!(
            (two_sided - sym).abs() < 1e-18,
            "at the stationary point the rebate is exact: {two_sided} vs {sym}"
        );
        // Off target the gap is (gamma/2)(d^2 - t) by construction.
        let d = 0.015;
        let gap = 0.5
            * (component_step(v, -d, t, a, b, g) + component_step(v, d, t, a, b, g))
            - component_step(v, d, t, a, b, 0.0);
        assert!(
            (gap - 0.5 * g * (d * d - t)).abs() < 1e-18,
            "gap {gap} must be (gamma/2)(d^2 - t)"
        );
    }
}

#[cfg(test)]
mod close_day_targets {
    use super::*;
    use crate::params::ModelParams;

    /// THE FIRST ELEMENT MEANS THE SAME THING ON BOTH BRANCHES.
    ///
    /// `close_day_at` returns `(fast, slow)` and its docstring claims that
    /// on a single-component preset the first element is THE target rather
    /// than a "fast" one — which is only honest if the branch does not
    /// change the value. Asserted on bits: same dials, same state, same
    /// VIX, `market_vol_slow_weight` the only difference.
    #[test]
    fn the_first_target_does_not_depend_on_whether_a_slow_component_exists() {
        for &damp in &[0.0, 0.5] {
            for &vix in &[12.0, 19.5, 34.0] {
                let mut none = ModelParams::pt_v1();
                none.market_vol_slow_weight = 0.0;
                none.market_vol_slow_vix_damp = damp;
                let mut some = none.clone();
                some.market_vol_slow_weight = 0.35;

                let a = MarketVarianceState::new_with(&none)
                    .close_day_at(&none, none.market_vol_vix_anchor, vix);
                let b = MarketVarianceState::new_with(&some)
                    .close_day_at(&some, some.market_vol_vix_anchor, vix);
                assert_eq!(a.0.to_bits(), b.0.to_bits(),
                           "the fast target moved with the slow weight at                             damp {damp}, vix {vix}");
            }
        }
    }

    /// The slow target is absent exactly when there is no slow component,
    /// and present exactly when there is. Not "usually".
    #[test]
    fn the_slow_target_is_present_exactly_when_the_component_is() {
        for &w in &[0.0, 0.35] {
            let mut p = ModelParams::pt_v1();
            p.market_vol_slow_weight = w;
            let got = MarketVarianceState::new_with(&p)
                .close_day_at(&p, p.market_vol_vix_anchor, 20.0);
            assert_eq!(got.1.is_some(), w != 0.0,
                       "slow weight {w} reported slow target {:?}", got.1);
        }
    }

    /// **THE STABILITY PROPERTY `market_vol_vix_excursion` BUYS, asserted
    /// on the arithmetic rather than on a census.**
    ///
    /// At a PINNED VIX the old form's target is a CONSTANT in the variance:
    /// the denominator is the anchor, so however far the factor excurses
    /// the target it is pulled toward does not move, and nothing in the map
    /// argues the excursion back down. Under the excursion switch the
    /// denominator is the read-back, which RISES with the variance, so the
    /// target FALLS. That is the sign that makes the fixed point unique and
    /// attracting: an increasing function of the variance (the variance
    /// itself) meets a decreasing one (its target) exactly once.
    ///
    /// Asserted here on `close_day_at` directly, at a ladder of
    /// denominators standing in for a ladder of variances, because that is
    /// the function the engine hands the choice to. Which denominator the
    /// engine picks is `engine.rs`'s branch and the 85-of-85 digest's
    /// business.
    #[test]
    fn the_excursion_form_makes_the_target_fall_as_the_read_back_rises() {
        let mut p = ModelParams::pt_v19();
        p.market_vol_slow_weight = 0.0; // the single-component branch: one target, no mixture
        let base = p.market_factor_sigma * p.market_factor_sigma;
        let vix = 80.0;

        // A rising read-back is a rising conditional variance. The anchor
        // is where the two forms agree by construction.
        let denominators = [
            p.market_vol_vix_anchor,
            2.0 * p.market_vol_vix_anchor,
            4.0 * p.market_vol_vix_anchor,
            8.0 * p.market_vol_vix_anchor,
        ];
        let mut previous = f64::INFINITY;
        for &d in denominators.iter() {
            let (target, _) = MarketVarianceState::new_with(&p).close_day_at(&p, d, vix);
            assert!(
                target < previous,
                "the target did not fall when the read-back rose to {d}: {target} \
                 against {previous}. Without this sign the excursion switch is not \
                 a stability result, it is a relabelling."
            );
            previous = target;
        }

        // And it falls TOWARD the uncoupled floor `base * (1 - coupling)`
        // rather than through it, because the response is non-negative.
        let floor = base * (1.0 - p.market_vol_vix_coupling);
        assert!(
            previous > floor,
            "the target fell to {previous}, at or under the uncoupled floor {floor}"
        );

        // The CONTROL, and it is what makes the assertion above mean
        // something: at the anchor denominator the target does not depend
        // on the variance at all, which is the old form's whole problem.
        let a = MarketVarianceState::new_with(&p)
            .close_day_at(&p, p.market_vol_vix_anchor, vix).0;
        let b = MarketVarianceState::new_with(&p)
            .close_day_at(&p, p.market_vol_vix_anchor, vix).0;
        assert_eq!(a.to_bits(), b.to_bits());
    }

    /// When the VIX is EXACTLY what the variance implies there is no fear
    /// excursion, and the target is EXACTLY the baseline variance -- to the
    /// bit, at any coupling, which is the property that makes the rest
    /// point the identity's own rather than a dial's.
    ///
    /// The same exactness the anchor branch has always had at
    /// `vix == market_vol_vix_anchor`, moved onto a denominator that
    /// changes every day. `1.0 - c + c * 1.0` must be exactly 1.0 and
    /// `base * 1.0` exactly `base`; at coupling 0.9540498202999739 that is
    /// a claim about floating point and not about algebra, so it is
    /// asserted on the bits.
    #[test]
    fn a_vix_at_its_own_read_back_targets_the_baseline_exactly() {
        let base_params = ModelParams::pt_v19();
        let base = base_params.market_factor_sigma * base_params.market_factor_sigma;
        for &coupling in &[0.0, 0.5, 0.9540498202999739, 1.0] {
            for &vix in &[10.0, 19.53, 23.7212, 55.0, 80.0] {
                let mut p = base_params.clone();
                p.market_vol_vix_coupling = coupling;
                p.market_vol_slow_weight = 0.0;
                // denominator == vix: the VIX is exactly its read-back.
                let (target, _) = MarketVarianceState::new_with(&p).close_day_at(&p, vix, vix);
                assert_eq!(
                    target.to_bits(),
                    base.to_bits(),
                    "at coupling {coupling} and vix {vix} a zero excursion targeted \
                     {target} rather than the baseline {base}"
                );
            }
        }
    }

    /// The warm-up lands on the state the mean recursion has as its fixed
    /// point, which is the TARGET -- not `omega / (1 - beta)`, which is
    /// where a zero-shock relaxation would land and is a fifth of it.
    ///
    /// Run at a level of exactly 1.0 (`log_level` 0 at a stationary
    /// variance of 0) so the fixed point is a closed expression and the
    /// assertion is about the recursion rather than about the level.
    #[test]
    fn the_warm_up_lands_on_the_target_and_not_on_the_zero_shock_rest_point() {
        let p = ModelParams::pt_v19();
        let base = p.market_factor_sigma * p.market_factor_sigma;
        let vix = p.market_vol_vix_anchor;
        let mut s = MarketVarianceState::new_with(&p);
        s.warm_to_level(&p, p.market_vol_vix_anchor, vix, 0.0, 0.0, 2000);
        // At the anchor the coupled target is exactly `base`.
        // `(variance, day_factor, fast, slow, ...)` -- the day factor is
        // the second element, so the components are 2 and 3.
        let (v, _, f, sl, ..) = s.snapshot();
        for (name, got) in [("mixture", v), ("fast", f), ("slow", sl)] {
            assert!(
                (got / base - 1.0).abs() < 1e-9,
                "the {name} warmed to {got} against a target of {base}"
            );
        }
        // The zero-shock rest point, for contrast: `omega / (1 - beta)` on
        // the fast component is well under the target, so a warm-up that
        // iterated the close with a zero day factor would have arrived
        // somewhere else entirely and this test would fail.
        let a = p.market_vol_alpha;
        let b = p.market_vol_beta;
        let g = p.market_vol_gamma;
        let zero_shock = (1.0 - a - b - 0.5 * g) * base / (1.0 - b);
        assert!(zero_shock < 0.5 * base,
                "the contrast has gone: {zero_shock} against {base}");
    }

    /// The warm-up carries the level's own conditional-mean share, and the
    /// share is `(1 - p) / (1 - p phi)` -- DERIVED in
    /// `ModelParams::market_burn_in_sessions`, asserted here on the state
    /// rather than on the derivation.
    #[test]
    fn the_warmed_components_carry_their_own_share_of_the_opening_level() {
        let p = ModelParams::pt_v19();
        let base = p.market_factor_sigma * p.market_factor_sigma;
        let vix = p.market_vol_vix_anchor;
        // A small level, so the linearisation the share is derived under
        // is the thing being tested and the exponential's curvature is not.
        let log_level = 0.01;
        let mut s = MarketVarianceState::new_with(&p);
        s.warm_to_level(&p, p.market_vol_vix_anchor, vix, log_level, 0.0, 4000);
        let (_, _, fast, slow, ..) = s.snapshot();
        let phi = p.market_vol_level_persistence;
        let p_fast = p.market_vol_alpha + p.market_vol_beta + 0.5 * p.market_vol_gamma;
        let (sa, sb) = slow_alpha_beta(&p);
        let p_slow = sa + sb;
        for (name, got, pers) in [
            ("fast", fast, p_fast),
            ("slow", slow, p_slow),
        ] {
            let want = (1.0 - pers) / (1.0 - pers * phi);
            let read = (got / base).ln() / log_level;
            assert!(
                (read - want).abs() < 0.01,
                "the {name} component carried {read} of the opening level \
                 where (1-p)/(1-p phi) says {want}"
            );
        }
    }

    /// Nothing is warmed when there is nothing to warm to, and the state is
    /// the constructor's to the bit. The guard that matters is the engine's
    /// (`market_burn_in_sessions > 0.0`); this is the function's own.
    #[test]
    fn a_warm_up_of_no_sessions_is_the_state_that_stood_before_it() {
        let p = ModelParams::pt_v19();
        let before = MarketVarianceState::new_with(&p);
        let mut after = MarketVarianceState::new_with(&p);
        after.warm_to_level(&p, p.market_vol_vix_anchor, 20.0, 1.5, 1.57, 0);
        assert_eq!(before, after);
    }

    // ---- the forced close (`vix_sets_variance`) ---------------------------

    /// pt-v19 off the excursion, so the denominator is the anchor and the
    /// law's level is an explicit function of the VIX, as on the candidate.
    fn forced_params() -> ModelParams {
        let mut p = ModelParams::pt_v19();
        p.market_vol_vix_excursion = 0.0;
        p.market_vol_vix_exponent = 4.0;
        p
    }

    /// A forced close writes each component's own target and the mixture of
    /// the two, clamped as a free close clamps, whatever the state was.
    #[test]
    fn a_forced_close_sets_each_component_to_its_own_target() {
        let p = forced_params();
        let base = p.market_factor_sigma * p.market_factor_sigma;
        let anchor = p.market_vol_vix_anchor;
        for start in [0.2 * base, base, 5.0 * base] {
            let mut s = MarketVarianceState::new_with(&p);
            s.fast_variance = start;
            s.slow_variance = start;
            s.variance = start;
            s.accumulate(0.03);
            let (t, ts) = s.close_day_forced(&p, anchor, 30.0, 1.0);
            let ts = ts.expect("pt-v19 has a slow component");
            let w = p.market_vol_slow_weight;
            assert_eq!(s.fast_variance, clamp_variance(&p, t));
            assert_eq!(s.slow_variance, clamp_variance(&p, ts));
            assert_eq!(
                s.variance,
                clamp_variance(&p, (1.0 - w) * s.fast_variance + w * s.slow_variance)
            );
            // The targets are the ones a free close at the same VIX reverts to.
            let mut free = MarketVarianceState::new_with(&p);
            let (ft, fts) = free.close_day_scaled(&p, anchor, 30.0, 1.0);
            assert_eq!((t, Some(ts)), (ft, fts));
            // and `forced_level` says what the close wrote.
            assert_eq!(MarketVarianceState::forced_level(&p, anchor, 30.0, 1.0), s.variance);
        }
    }

    /// Release does not jolt: from the state a forced close leaves, the free
    /// close at the same VIX takes an expected step of zero on each
    /// component. The expectation over the day's factor, which is
    /// conditionally N(0, v), is the mean of an up and a down day of size
    /// sqrt(v) -- that is exactly E[f^2] = v with the GJR arm at half weight.
    #[test]
    fn the_first_free_close_after_a_forced_one_expects_no_step() {
        let p = forced_params();
        let anchor = p.market_vol_vix_anchor;
        // VIX 30 on this law is well inside the clamps, so the fixed point
        // is the unclamped target and the identity is exact up to rounding.
        let mut forced = MarketVarianceState::new_with(&p);
        forced.close_day_forced(&p, anchor, 30.0, 1.0);
        let ceiling = p.market_factor_sigma * p.market_factor_sigma * p.market_vol_ceiling_multiple;
        assert!(forced.fast_variance < ceiling && forced.slow_variance < ceiling);
        let mut up = forced;
        let mut down = forced;
        up.accumulate(forced.fast_variance.sqrt());
        down.accumulate(-forced.fast_variance.sqrt());
        up.close_day_scaled(&p, anchor, 30.0, 1.0);
        down.close_day_scaled(&p, anchor, 30.0, 1.0);
        let mean_fast = 0.5 * (up.fast_variance + down.fast_variance);
        assert!(
            (mean_fast / forced.fast_variance - 1.0).abs() < 1e-12,
            "fast: forced {} -> expected free step to {}", forced.fast_variance, mean_fast
        );
        // The slow component has no GJR arm, so its step from a shock of the
        // SLOW level's own size is exact on either sign.
        let mut slow_up = forced;
        slow_up.accumulate(forced.slow_variance.sqrt());
        slow_up.close_day_scaled(&p, anchor, 30.0, 1.0);
        assert!(
            (slow_up.slow_variance / forced.slow_variance - 1.0).abs() < 1e-12,
            "slow: forced {} -> free step to {}", forced.slow_variance, slow_up.slow_variance
        );
    }

    /// The same, against the free law run for a long time: a VIX held on a
    /// free run takes the mean recursion to the forced close's level.
    #[test]
    fn a_held_vix_run_free_arrives_where_the_forced_close_starts() {
        let p = forced_params();
        let anchor = p.market_vol_vix_anchor;
        let mut forced = MarketVarianceState::new_with(&p);
        forced.close_day_forced(&p, anchor, 30.0, 1.0);
        // The expected path of the free close: warm_to_level IS the mean
        // recursion of `component_step`, at level 1 (log level 0).
        let mut free = MarketVarianceState::new_with(&p);
        free.warm_to_level(&p, anchor, 30.0, 0.0, 0.0, 20_000);
        for (name, a, b) in [
            ("fast", free.fast_variance, forced.fast_variance),
            ("slow", free.slow_variance, forced.slow_variance),
            ("mixture", free.variance, forced.variance),
        ] {
            assert!((a / b - 1.0).abs() < 1e-9, "{name}: free run settles at {a}, forced close sets {b}");
        }
    }

    /// The forced close consumes the day as a free close does: the day's
    /// factor becomes yesterday's, and today's accumulator is cleared.
    #[test]
    fn a_forced_close_rolls_the_day_like_a_free_one() {
        let p = forced_params();
        let mut s = MarketVarianceState::new_with(&p);
        s.accumulate(-0.02);
        s.close_day_forced(&p, p.market_vol_vix_anchor, 45.0, 1.0);
        assert_eq!(s.day_factor(), 0.0);
        assert_eq!(s.prev_day_factor(), -0.02);
        assert!(s.prev_day_down());
    }

    /// A forced VIX past what the ceiling allows is clipped where a free
    /// close's would be.
    #[test]
    fn a_forced_close_is_clamped_like_a_free_one() {
        let p = forced_params();
        let base = p.market_factor_sigma * p.market_factor_sigma;
        let mut s = MarketVarianceState::new_with(&p);
        s.close_day_forced(&p, p.market_vol_vix_anchor, 200.0, 1.0);
        assert_eq!(s.fast_variance, base * p.market_vol_ceiling_multiple);
        assert!(s.variance <= base * p.market_vol_ceiling_multiple);
        let mut t = MarketVarianceState::new_with(&p);
        t.close_day_forced(&p, p.market_vol_vix_anchor, 0.5, 1.0);
        assert!(t.variance >= base * p.market_vol_floor_multiple);
    }

    /// On a one-component preset the slow level is not a state and a forced
    /// close leaves it where a free one would, untouched.
    #[test]
    fn a_forced_close_on_one_component_leaves_the_slow_level_alone() {
        let p = crate::params::PT_V1;
        let mut s = MarketVarianceState::new_with(&p);
        let slow_before = s.slow_variance;
        let (t, ts) = s.close_day_forced(&p, p.market_vol_vix_anchor, 30.0, 1.0);
        assert_eq!(ts, None);
        assert_eq!(s.variance, clamp_variance(&p, t));
        assert_eq!(s.fast_variance, s.variance);
        assert_eq!(s.slow_variance, slow_before);
    }
}

/// The crash-vol-state dials: `market_vol_slow_gamma` (GJR on the slow
/// component) and the return memory (`market_vol_leverage`, its half-life
/// and its down share). See their entries in `ModelParams`.
#[cfg(test)]
mod crash_vol_state {
    use super::*;
    use crate::params::ModelParams;

    fn pt_v20() -> ModelParams {
        crate::params::PT_V20
    }

    fn with_memory(k: f64, h: f64, down: f64) -> ModelParams {
        let mut p = pt_v20();
        p.market_vol_leverage = k;
        p.market_vol_leverage_half_life = h;
        p.market_vol_leverage_down = down;
        p
    }

    fn close_after(p: &ModelParams, state: &MarketVarianceState, f: f64) -> MarketVarianceState {
        let mut s = *state;
        s.accumulate(f);
        s.close_day_scaled(p, p.market_vol_vix_anchor, 19.0, 1.0);
        s
    }

    #[test]
    fn slow_gamma_zero_is_the_symmetric_call() {
        let p = pt_v20();
        assert_eq!(p.market_vol_slow_gamma, 0.0);
        let (sa, sb) = slow_alpha_beta(&p);
        for &f in &[-0.03, -0.004, 0.0, 0.004, 0.03] {
            let direct = clamp_variance(&p, component_step(4e-5, f, 5e-5, sa, sb, 0.0));
            assert_eq!(slow_step(&p, 4e-5, f, 5e-5).to_bits(), direct.to_bits());
        }
    }

    #[test]
    fn slow_gamma_loads_only_down_days_and_keeps_persistence() {
        let mut p = pt_v20();
        p.market_vol_slow_gamma = 0.6;
        let q = pt_v20();
        let (v, t) = (4e-5, 5e-5);
        let d = 0.009;
        // A fall loads the slow component more than a rise of the same size.
        let down = slow_step(&p, v, -d, t);
        let up = slow_step(&p, v, d, t);
        assert!(down > up, "a fall must load the slow component: {down} vs {up}");
        // The rise loads LESS than the symmetric step: the rebate is taken
        // from the carried share on every day.
        assert!(up < slow_step(&q, v, d, t));
        // With the shock at the component's own level, the two-sided mean is
        // the symmetric step: the resting level and the persistence are
        // unchanged, `E[v'] = (1 - p) t + p v`.
        let at_level = crate::mathx::sqrt(v);
        let two_sided = 0.5 * (slow_step(&p, v, -at_level, t) + slow_step(&p, v, at_level, t));
        let (sa, sb) = slow_alpha_beta(&p);
        let persistence = sa + sb;
        let expected = (1.0 - persistence) * t + persistence * v;
        assert!((two_sided - expected).abs() < 1e-18, "{two_sided} vs {expected}");
        // The whole mixture: the next session's variance after a fall is
        // higher with the dial than without, after a rise lower.
        let s0 = MarketVarianceState::new_with(&p);
        assert!(close_after(&p, &s0, -0.02).variance() > close_after(&q, &s0, -0.02).variance());
        assert!(close_after(&p, &s0, 0.02).variance() < close_after(&q, &s0, 0.02).variance());
    }

    #[test]
    fn slow_gamma_is_unread_on_a_single_component_model() {
        let mut q = pt_v20();
        q.market_vol_slow_weight = 0.0;
        let mut p = q.clone();
        p.market_vol_slow_gamma = 0.6;
        let s0 = MarketVarianceState::new_with(&q);
        for &f in &[-0.02, 0.02] {
            assert_eq!(close_after(&p, &s0, f), close_after(&q, &s0, f));
        }
    }

    #[test]
    fn the_memory_is_never_written_while_off() {
        let p = pt_v20();
        let mut s = MarketVarianceState::new_with(&p);
        for &f in &[-0.05, 0.03, -0.02] {
            s = close_after(&p, &s, f);
            assert_eq!(s.leverage_memory().to_bits(), 0.0_f64.to_bits());
        }
    }

    #[test]
    fn a_fall_raises_and_a_rise_lowers_the_next_session_variance() {
        let p = with_memory(3.0, 40.0, 0.0);
        let s0 = MarketVarianceState::new_with(&p);
        let quiet = close_after(&p, &s0, 0.0);
        let fell = close_after(&p, &s0, -0.01);
        let rose = close_after(&p, &s0, 0.01);
        assert!(fell.leverage_memory() > 0.0 && rose.leverage_memory() < 0.0);
        assert!(fell.variance() > quiet.variance(), "{} vs {}", fell.variance(), quiet.variance());
        // The GJR components raise the variance after a rise too; the
        // memory keeps it below the fall's.
        assert!(rose.variance() < fell.variance());
        // Linear in the path at down 0.0: a rise and a fall of the same size
        // leave memories of opposite sign and equal size.
        assert!((fell.leverage_memory() + rose.leverage_memory()).abs() < 1e-15);
    }

    #[test]
    fn the_memory_decays_at_its_half_life_with_zero_shocks() {
        for &h in &[10.0, 40.0] {
            let p = with_memory(3.0, h, 0.0);
            let mut s = close_after(&p, &MarketVarianceState::new_with(&p), -0.02);
            let l0 = s.leverage_memory();
            for _ in 0..(h as usize) {
                s = close_after(&p, &s, 0.0);
            }
            let ratio = s.leverage_memory() / l0;
            assert!((ratio - 0.5).abs() < 1e-12, "half-life {h}: ratio {ratio}");
        }
    }

    #[test]
    fn down_one_counts_falls_only_and_is_centred() {
        let p = with_memory(3.0, 40.0, 1.0);
        let s0 = MarketVarianceState::new_with(&p);
        let fell = close_after(&p, &s0, -0.01);
        let rose = close_after(&p, &s0, 0.01);
        let quiet = close_after(&p, &s0, 0.0);
        // A rise and a quiet day are the same to the memory: both only
        // subtract the centre.
        assert_eq!(rose.leverage_memory().to_bits(), quiet.leverage_memory().to_bits());
        assert!(quiet.leverage_memory() < 0.0 && fell.leverage_memory() > 0.0);
    }

    /// A small deterministic normal stream for the moment checks.
    struct Normals(u64);
    impl Normals {
        fn uniform(&mut self) -> f64 {
            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64
        }
        fn next(&mut self) -> f64 {
            let (u1, u2) = (self.uniform(), self.uniform());
            crate::mathx::sqrt(-2.0 * u1.ln()) * (2.0 * std::f64::consts::PI * u2).cos()
        }
    }

    #[test]
    fn the_multiplier_averages_about_one_under_its_own_shocks() {
        for &(k, h, down) in &[(3.0, 40.0, 0.0), (4.0, 10.0, 1.0), (2.0, 20.0, 0.5)] {
            let p = with_memory(k, h, down);
            let b = p.market_factor_sigma * p.market_factor_sigma;
            let mut s = MarketVarianceState::new_with(&p);
            s.variance = b;
            let mut z = Normals(20260926);
            let (mut sum, mut n) = (0.0, 0u32);
            for i in 0..400_000 {
                s.day_factor = crate::mathx::sqrt(b) * z.next();
                s.step_leverage_memory(&p);
                if i >= 2_000 {
                    sum += MarketVarianceState::leverage_multiplier(&p, s.leverage_memory);
                    n += 1;
                }
            }
            let mean = sum / n as f64;
            assert!((mean - 1.0).abs() < 0.02, "k {k}, H {h}, down {down}: E[m] {mean}");
        }
    }

    #[test]
    fn the_components_are_fed_the_shock_in_their_own_units() {
        // A state whose variance is exactly twice its mixture was drawn at a
        // multiplier of 2, so the components must see the day factor over
        // sqrt(2): the same step a memory-off state at the mixture takes on
        // that smaller shock.
        let p = with_memory(3.0, 40.0, 0.0);
        let mut s = MarketVarianceState::new_with(&p);
        let mix = s.mixture(&p);
        s.variance = 2.0 * mix;
        let f = -0.02;
        let fed = s.day_factor_scaled_for_test(&p, f);
        assert!((fed - f / crate::mathx::sqrt(2.0)).abs() < 1e-15);
    }

    #[test]
    fn a_forced_close_moves_the_memory_but_not_the_forced_level() {
        let p = with_memory(3.0, 40.0, 0.0);
        let anchor = p.market_vol_vix_anchor;
        let mut forced = MarketVarianceState::new_with(&p);
        forced.accumulate(-0.03);
        forced.close_day_forced(&p, anchor, 30.0, 1.0);
        assert!(forced.leverage_memory() > 0.0);
        let level = MarketVarianceState::forced_level(&p, anchor, 30.0, 1.0);
        assert_eq!(forced.variance().to_bits(), level.to_bits());
        // Off, the forced close is the one that stood.
        let q = pt_v20();
        let mut plain = MarketVarianceState::new_with(&q);
        plain.accumulate(-0.03);
        plain.close_day_forced(&q, anchor, 30.0, 1.0);
        assert_eq!(plain.leverage_memory(), 0.0);
        assert_eq!(plain.variance().to_bits(),
                   MarketVarianceState::forced_level(&q, anchor, 30.0, 1.0).to_bits());
    }

    #[test]
    fn standardise_zero_is_the_baseline_unit_to_the_bit() {
        // The dial at 0.0 takes the branch that stood: a memory stepped on a
        // day drawn off the baseline is the baseline-unit memory, bit for bit.
        let p = with_memory(3.0, 40.0, 0.5);
        assert_eq!(p.market_vol_leverage_standardise, 0.0);
        let b = p.market_factor_sigma * p.market_factor_sigma;
        let mut s = MarketVarianceState::new_with(&p);
        s.variance = 3.0 * b;
        s.day_factor = -0.017;
        s.step_leverage_memory(&p);
        let phi = leverage_phi(&p);
        let sd_b = crate::mathx::sqrt(b);
        let u = 0.017 / sd_b
            - 0.5 * crate::mathx::sqrt(3.0 * b / b) / crate::mathx::sqrt(2.0 * std::f64::consts::PI);
        assert_eq!(s.leverage_memory().to_bits(), ((1.0 - phi) * u).to_bits());
    }

    #[test]
    fn standardised_memory_counts_a_day_in_its_own_sd() {
        // At 1.0 a fall drawn at four times the baseline variance moves the
        // memory as far as half that fall drawn at the baseline: the z-score.
        let mut p = with_memory(3.0, 40.0, 0.0);
        p.market_vol_leverage_standardise = 1.0;
        let b = p.market_factor_sigma * p.market_factor_sigma;
        let mut storm = MarketVarianceState::new_with(&p);
        storm.variance = 4.0 * b;
        storm.day_factor = -0.02;
        storm.step_leverage_memory(&p);
        let mut calm = MarketVarianceState::new_with(&p);
        calm.variance = b;
        calm.day_factor = -0.01;
        calm.step_leverage_memory(&p);
        assert!((storm.leverage_memory() - calm.leverage_memory()).abs() < 1e-15);
        // Down 1.0: a rise counts nothing and the centre is the z-score's,
        // the same at every variance.
        p.market_vol_leverage_down = 1.0;
        let mut up_storm = MarketVarianceState::new_with(&p);
        up_storm.variance = 9.0 * b;
        up_storm.day_factor = 0.03;
        up_storm.step_leverage_memory(&p);
        let mut up_calm = MarketVarianceState::new_with(&p);
        up_calm.variance = b;
        up_calm.day_factor = 0.001;
        up_calm.step_leverage_memory(&p);
        assert!((up_storm.leverage_memory() - up_calm.leverage_memory()).abs() < 1e-15);
    }

    #[test]
    fn the_standardised_multiplier_averages_one_in_a_storm_too() {
        // Drawn at four times the baseline variance, the baseline-unit memory
        // overshoots its normalisation and the multiplier's mean runs over
        // one; the z-score memory's does not.
        for &(std, over) in &[(0.0, true), (1.0, false)] {
            let mut p = with_memory(3.0, 15.0, 0.0);
            p.market_vol_leverage_standardise = std;
            let b = p.market_factor_sigma * p.market_factor_sigma;
            let mut s = MarketVarianceState::new_with(&p);
            s.variance = 4.0 * b;
            let mut z = Normals(20260927);
            let (mut sum, mut n) = (0.0, 0u32);
            for i in 0..200_000 {
                s.day_factor = 2.0 * crate::mathx::sqrt(b) * z.next();
                s.step_leverage_memory(&p);
                if i >= 2_000 {
                    sum += MarketVarianceState::leverage_multiplier(&p, s.leverage_memory);
                    n += 1;
                }
            }
            let mean = sum / n as f64;
            if over {
                assert!(mean > 1.2, "baseline units in a storm: E[m] {mean}");
            } else {
                assert!((mean - 1.0).abs() < 0.02, "z-score units in a storm: E[m] {mean}");
            }
        }
    }

    #[test]
    fn the_single_component_model_runs_the_memory_too() {
        let mut p = with_memory(3.0, 40.0, 0.0);
        p.market_vol_slow_weight = 0.0;
        let s0 = MarketVarianceState::new_with(&p);
        let fell = close_after(&p, &s0, -0.01);
        let rose = close_after(&p, &s0, 0.01);
        assert!(fell.leverage_memory() > 0.0);
        assert!(fell.variance() > rose.variance());
    }
}

/// The fast return memory (`market_vol_leverage_fast`, its half-life). See its
/// entry in `ModelParams`.
#[cfg(test)]
mod fast_leverage {
    use super::*;
    use crate::params::ModelParams;

    fn base() -> ModelParams {
        let mut p = crate::params::PT_V20;
        p.market_vol_leverage = 2.25;
        p.market_vol_leverage_half_life = 15.0;
        p.market_vol_leverage_standardise = 1.0;
        p
    }

    fn with_fast(k: f64, h: f64) -> ModelParams {
        let mut p = base();
        p.market_vol_leverage_fast = k;
        p.market_vol_leverage_fast_half_life = h;
        p
    }

    fn close_after(p: &ModelParams, state: &MarketVarianceState, f: f64) -> MarketVarianceState {
        let mut s = *state;
        s.accumulate(f);
        s.close_day_scaled(p, p.market_vol_vix_anchor, 19.0, 1.0);
        s
    }

    #[test]
    fn off_is_the_slower_memory_alone_to_the_bit() {
        let p = base();
        let mut q = base();
        q.market_vol_leverage_fast_half_life = 5.0; // unread with the gain at 0.0
        let mut a = MarketVarianceState::new_with(&p);
        let mut b = a;
        for &f in &[-0.03, 0.01, -0.004, 0.02, 0.0, -0.05] {
            a = close_after(&p, &a, f);
            b = close_after(&q, &b, f);
            assert_eq!(a, b);
            assert_eq!(a.leverage_fast_memory().to_bits(), 0.0_f64.to_bits());
            assert_eq!(a.vix_window_variance(&p).to_bits(), a.variance().to_bits());
            assert_eq!(a.vix_window_ratio(&p), 1.0);
        }
    }

    #[test]
    fn a_fall_raises_and_a_rise_lowers_the_next_session_more_with_it() {
        let p = with_fast(2.0, 5.0);
        let q = base();
        let s0 = MarketVarianceState::new_with(&p);
        let fell = close_after(&p, &s0, -0.01);
        let rose = close_after(&p, &s0, 0.01);
        assert!(fell.leverage_fast_memory() > 0.0 && rose.leverage_fast_memory() < 0.0);
        assert!(fell.variance() > close_after(&q, &s0, -0.01).variance());
        assert!(rose.variance() < close_after(&q, &s0, 0.01).variance());
        // The slower memory moves exactly as it does without the fast one.
        assert_eq!(fell.leverage_memory().to_bits(), close_after(&q, &s0, -0.01).leverage_memory().to_bits());
    }

    #[test]
    fn the_memory_decays_at_its_half_life() {
        let p = with_fast(2.0, 5.0);
        let mut s = close_after(&p, &MarketVarianceState::new_with(&p), -0.02);
        let l0 = s.leverage_fast_memory();
        for _ in 0..5 {
            s = close_after(&p, &s, 0.0);
        }
        assert!((s.leverage_fast_memory() / l0 - 0.5).abs() < 1e-12);
    }

    #[test]
    fn the_vix_window_takes_a_burst_at_part_of_its_size() {
        let p = with_fast(2.0, 5.0);
        let s = close_after(&p, &MarketVarianceState::new_with(&p), -0.02);
        let l = s.leverage_fast_memory();
        let now = MarketVarianceState::leverage_fast_multiplier(&p, l);
        let window = MarketVarianceState::leverage_fast_window_multiplier(&p, l);
        assert!(now > 1.0 && window > 1.0 && window < now, "now {now}, window {window}");
        assert!(s.vix_window_variance(&p) < s.variance());
        // The window's mean is the average of the expected multipliers.
        let phi = leverage_fast_phi(&p);
        let s2 = MarketVarianceState::leverage_fast_s2(&p);
        let k = p.market_vol_leverage_fast;
        let direct: f64 = (0..VIX_WINDOW_SESSIONS)
            .map(|j| {
                let d = phi.powi(j as i32);
                (k * d * l - 0.5 * k * k * s2 * d * d).exp()
            })
            .sum::<f64>()
            / VIX_WINDOW_SESSIONS as f64;
        assert!((window / direct - 1.0).abs() < 1e-12);
    }

    #[test]
    fn a_forced_close_moves_the_memory_and_not_the_variance() {
        let p = with_fast(2.0, 5.0);
        let q = base();
        let mut a = MarketVarianceState::new_with(&p);
        let mut b = a;
        a.accumulate(-0.02);
        b.accumulate(-0.02);
        a.close_day_forced(&p, p.market_vol_vix_anchor, 30.0, 1.0);
        b.close_day_forced(&q, q.market_vol_vix_anchor, 30.0, 1.0);
        assert!(a.leverage_fast_memory() > 0.0);
        assert_eq!(a.variance().to_bits(), b.variance().to_bits());
    }
}

/// The fast return memory counting rises only (`market_vol_leverage_fast_up`).
#[cfg(test)]
mod fast_leverage_rises {
    use super::*;
    use crate::params::ModelParams;

    fn with_fast(k: f64, h: f64, up: f64) -> ModelParams {
        let mut p = crate::params::PT_V20;
        p.market_vol_leverage = 2.25;
        p.market_vol_leverage_half_life = 15.0;
        p.market_vol_leverage_standardise = 1.0;
        p.market_vol_leverage_fast = k;
        p.market_vol_leverage_fast_half_life = h;
        p.market_vol_leverage_fast_up = up;
        p
    }

    fn close_after(p: &ModelParams, state: &MarketVarianceState, f: f64) -> MarketVarianceState {
        let mut s = *state;
        s.accumulate(f);
        s.close_day_scaled(p, p.market_vol_vix_anchor, 19.0, 1.0);
        s
    }

    #[test]
    fn a_rise_lowers_it_and_a_fall_moves_it_by_the_centre_alone() {
        let p = with_fast(2.0, 3.0, 1.0);
        let s0 = MarketVarianceState::new_with(&p);
        let rose = close_after(&p, &s0, 0.01);
        let fell = close_after(&p, &s0, -0.01);
        let fell_more = close_after(&p, &s0, -0.03);
        assert!(rose.leverage_fast_memory() < 0.0);
        // A fall of any size moves it by the same re-centring step.
        assert!(fell.leverage_fast_memory() > 0.0);
        assert_eq!(fell.leverage_fast_memory().to_bits(), fell_more.leverage_fast_memory().to_bits());
        // The input's two-sided mean at the day's own sd is zero.
        let sd = s0.variance().sqrt();
        let up = close_after(&p, &s0, sd).leverage_fast_memory();
        let dn = close_after(&p, &s0, -sd).leverage_fast_memory();
        let phi = leverage_fast_phi(&p);
        // E[u] over the half-normal: a rise of size x moves (1 - phi) (-x / sd + c),
        // a fall (1 - phi) c, c = 1 / sqrt(2 pi); a rise of the mean size
        // E|X| = sd sqrt(2 / pi) and a fall average to zero.
        let x = sd * (2.0 / std::f64::consts::PI).sqrt();
        let up_mean = close_after(&p, &s0, x).leverage_fast_memory();
        assert!(((up_mean + dn) / (1.0 - phi)).abs() < 1e-12, "{up_mean} {dn}");
        assert!(up < 0.0 && dn > 0.0);
    }

    #[test]
    fn at_zero_it_is_the_both_signs_memory_to_the_bit() {
        let p = with_fast(2.0, 5.0, 0.0);
        let mut a = MarketVarianceState::new_with(&p);
        let mut b = a;
        for &f in &[-0.03, 0.01, -0.004, 0.02] {
            a = close_after(&p, &a, f);
            let mut s = b;
            s.accumulate(f);
            let x = s.leverage_input(&p);
            let phi = leverage_fast_phi(&p);
            let expected = phi * b.leverage_fast_memory() + (1.0 - phi) * x;
            b = close_after(&p, &b, f);
            assert_eq!(a.leverage_fast_memory().to_bits(), expected.to_bits());
        }
    }
}