optionchain_simulator 0.2.0

OptionChain-Simulator is a lightweight REST API service that simulates an evolving option chain with every request. It is designed for developers building or testing trading systems, backtesters, and visual tools that depend on option data streams but want to avoid relying on live data feeds.
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
//! The market-factor tape for v2 rolling simulations.
//!
//! A **factor row** is the whole market state at one step that is *not* an
//! option: the simulated instant, the underlying price, and the base implied
//! volatility that will price every chain at that step. The tape is the ordered
//! sequence of those rows, and it is the deterministic source both the snapshot
//! builder (#46) and the export (#49) read from.
//!
//! # Why a separate tape at all
//!
//! v1 caches a `RandomWalk<Positive, OptionChain>`, so the entire chain tape is
//! materialised up front and the walk stops when its one expiry reaches zero
//! (`src/domain/simulator.rs`). Neither works for a rolling simulation. The
//! factor tape splits the two concerns: the market path runs for the **whole**
//! requested horizon regardless of what expires along the way, and chains are
//! built on demand from a row. Memory is `O(steps)` in small rows rather than
//! `O(steps × expiries × strikes)` in contracts.
//!
//! # What makes it reproducible
//!
//! Three properties, each of them tested:
//!
//! - **The tape is a pure function of the effective parameters.** Same seed,
//!   same start, same model ⇒ the same rows, on any machine. One caveat, stated
//!   because it is real: building the seeding chain reaches upstream code that
//!   reads `Utc::now()` while stamping a calendar date. That value cannot reach
//!   a row — only the chain's `underlying_price` flows into the walk, and it is
//!   `initial_price` verbatim — so the rows stay clock-free even though the
//!   call is not.
//! - **Expiration schedules cannot perturb it.** `build` never reads the
//!   schedule at all, so adding, removing or reordering rules leaves every row
//!   byte-identical — which is what lets a client change its expiration
//!   inventory and still compare two runs' underlying paths. The tests here
//!   guard that cheaply; the *load-bearing* version of the property, that
//!   building snapshots' chains cannot consume the walker's stream either,
//!   belongs where those chains are built (#46).
//! - **The walk kernels are the ones v1 already uses.** The tape asks the same
//!   seeded [`Walker`] for the same `WalkParams` v1 builds, and reads the price
//!   path from `generate_with_vol`. It does not reimplement the mathematics, so
//!   there is no second copy to diverge.
//!
//! # Historical volatility is estimated, causally
//!
//! A `Historical` walk carries no volatility of its own — it is a price series,
//! and `WalkType::volatility()` returns `None` for it. Upstream leaves the
//! per-step estimate to the caller (`WalkTypeAble::generate_with_vol` says so,
//! and returns `vols: None` for the variant); v1's caller is `walk_steps_par`,
//! which estimates it over an expanding window so that step `i` is priced by
//! what had been observed by step `i` and nothing later.
//!
//! v2 never enters that driver, so [`expanding_window_volatilities`] is v2's
//! caller-side answer. It is **composed from public upstream primitives rather
//! than copied out of the private estimator**: upstream's expanding kernel
//! inlines its own prefix-sum variance, but records that the result is
//! algebraically identical to `constant_volatility`, which is public — so the
//! window here writes an indexing policy over upstream mathematics instead of a
//! second copy of it. See that function for the indexing and the cost. A
//! historical tape therefore carries a volatility per step, causally, and the
//! request's own `volatility` field prices none of it (see
//! [`resolve_base_volatility`]).
//!
//! Every value read is inside the horizon, the seeding chain's included: a
//! historical walk replays `prices[..steps]`, and nothing here reduces more
//! than that. A horizon of fewer than three steps has no dispersion to measure
//! and is refused rather than priced from observations it could not have seen.
//!
//! Parity with v1 is numeric, not bit-exact: upstream accumulates the window
//! with prefix sums while `constant_volatility` centres in two passes, and the
//! two agree algebraically but not in the last `Decimal` digits. The tolerance
//! is pinned by a test. ADR 0001 §8 records the contract.

use crate::domain::Walker;
use crate::domain::simulator::{
    DEFAULT_CHAIN_SIZE, DEFAULT_SKEW_SLOPE, DEFAULT_SMILE_CURVE, DEFAULT_SPREAD,
};
use crate::session::{SimulationMethod, SimulationParametersV2};
use crate::utils::ChainError;
use chrono::{DateTime, Utc};
use optionstratlib::ExpirationDate;
use optionstratlib::chains::{
    OptionChainBuildParams, chain::OptionChain, utils::OptionDataPriceParams,
};
use optionstratlib::simulation::steps::{Step, Xstep, Ystep};
use optionstratlib::simulation::{WalkParams, WalkTypeAble};
use optionstratlib::utils::TimeFrame;
use optionstratlib::volatility::{adjust_volatility, constant_volatility};
use positive::Positive;
use rust_decimal::{Decimal, MathematicalOps};
use tracing::{debug, instrument};

/// One step of the market path: everything a snapshot needs that is not an
/// option contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FactorRow {
    /// The 0-based step index this row describes.
    pub(crate) step: usize,
    /// The simulated instant of the step, derived from the effective start and
    /// the cursor — never from the wall clock.
    pub(crate) simulated_at: DateTime<Utc>,
    /// The underlying price at this step.
    pub(crate) spot: Positive,
    /// The **canonical** base implied volatility used to price every chain at
    /// this step.
    ///
    /// Three cases, one field. For a constant-volatility model this is the
    /// model's volatility at every row. For `Garch`, `Heston`, `Custom` and
    /// `Telegraph` it is the annualised volatility prevailing at this step,
    /// index-aligned with `spot`, as upstream's `generate_with_vol` reports it.
    /// For `Historical` it is the realized volatility of the walked prices up
    /// to and including this step, estimated here because upstream leaves it to
    /// the caller — see [`expanding_window_volatilities`].
    pub(crate) base_volatility: Positive,
}

/// The ordered market path of a simulation, one row per requested step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FactorTape {
    rows: Vec<FactorRow>,
}

impl FactorTape {
    /// Builds the tape for `parameters`, using `method` as the resolved walk
    /// model.
    ///
    /// `method` is passed in rather than read from `parameters` because a
    /// `Historical` walk has to be resolved against the database first — a
    /// seeded symbol-and-date selection that already lives in
    /// [`crate::domain::Simulator`]. Keeping the resolution outside leaves this
    /// function synchronous and free of I/O, and therefore directly testable
    /// for the reproducibility properties that matter. It is not clock-free:
    /// the seeding chain stamps an expiration date through `Utc::now()`, as the
    /// module docs explain, but that value reaches no row. A caller with
    /// nothing to resolve passes `&parameters.method`.
    ///
    /// # Errors
    ///
    /// Returns [`ChainError::Validation`] when the parameters are invalid, when
    /// the model's volatility disagrees with the parameters' (see
    /// [`resolve_base_volatility`]), when a `Historical` series is too short for
    /// the horizon or carries a zero price, when a volatility — a
    /// stochastic-volatility path's or a historical estimate's — leaves the
    /// range an option chain can be priced at, when a historical window cannot
    /// be reduced or annualised, or when the simulated clock overflows; and
    /// [`ChainError::Internal`] when the resolved method is not the one the
    /// parameters name, when the initial chain cannot be built, or when the
    /// walk returns fewer points than requested.
    ///
    /// A historical simulation is refused *lazily*, when its tape is first
    /// built, because creation does not build one. A series whose realized
    /// volatility leaves the priceable range therefore creates successfully and
    /// fails at the first peek — see ADR 0001 §8.1.
    #[instrument(skip(parameters, method), level = "debug")]
    pub(crate) fn build(
        parameters: &SimulationParametersV2,
        method: &SimulationMethod,
    ) -> Result<Self, ChainError> {
        // `SimulationParametersV2` is public with public fields, so a crate
        // caller can hand this a struct literal that never passed a validating
        // constructor. `steps: 0` is the one that bites: two of the mirrored
        // kernels compute `size - 1`, which panics in debug and wraps to an
        // unbounded loop in release.
        parameters.validate()?;
        ensure_method_matches(parameters, method)?;
        ensure_historical_series_covers_the_horizon(parameters, method)?;
        let base_volatility = resolve_base_volatility(parameters, method)?;
        reject_unpriceable_volatility(base_volatility, None, volatility_source(method))?;
        let walker = Walker::new_with_seed(parameters.seed);

        // The walk starts from an `OptionChain` because that is the shape v1's
        // `WalkParams` takes, and reusing it verbatim is what guarantees the
        // price path is the one v1 would produce for the same seed and
        // parameters. Exactly one chain is built, to seed the walk; the tape
        // itself stores none.
        let initial_chain = build_initial_chain(parameters, base_volatility)?;

        let walk_params = WalkParams {
            size: parameters.steps,
            init_step: Step {
                x: Xstep::new(
                    Positive::ONE,
                    parameters.time_frame,
                    // A nominal relative expiration for the seeding step only.
                    // The tape carries no expiration of its own — every real
                    // one comes from the planner — and this value never reaches
                    // a price. It is safe only because the generation below is
                    // called directly: never route this `WalkParams` through a
                    // `walk_steps` driver, which advances the expiry per step
                    // and would truncate the walk at the first one.
                    ExpirationDate::Days(Positive::ONE),
                ),
                y: Ystep::new(0, initial_chain),
            },
            walk_type: method.clone(),
            // `WalkParams` owns a walker, but the path below is generated by
            // calling `generate_with_vol` on ours. The clone shares the same
            // `Arc<Mutex<StdRng>>`, so there is exactly one stream either way.
            walker: Box::new(walker.clone()),
        };

        let path = walker.generate_with_vol(&walk_params).map_err(|e| {
            ChainError::Internal(format!("Failed to generate the factor tape: {e}"))
        })?;

        // Every kernel — upstream and mirrored — pushes the initial value and
        // then loops `1..size`, so the path holds **exactly** `size` points,
        // element 0 duplicating the walk's initial value. Row 0 is therefore
        // the simulation's starting state and `prices[0..steps]` consumes the
        // whole path with no slack. The guard below is the exact bound: there
        // is no spare element to shift into, and a `prices[1..=steps]` "fix"
        // would truncate the tape or fail outright.
        if path.prices.len() < parameters.steps {
            return Err(ChainError::Internal(format!(
                "the walk produced {} points but {} steps were requested",
                path.prices.len(),
                parameters.steps
            )));
        }

        // Where each step's volatility comes from, in v1's order of precedence
        // (`walk_steps_par`): a stochastic-volatility model reports its own
        // path, index-aligned with the prices; a historical walk reports none,
        // so it is estimated causally from the path itself; everything else is
        // the model's constant.
        let step_volatilities = match path.vols {
            Some(ref vols) => Some(vols.clone()),
            None => match method {
                SimulationMethod::Historical { timeframe, .. } => {
                    expanding_window_volatilities(&path.prices, *timeframe)?
                }
                _ => None,
            },
        };

        let mut rows = Vec::with_capacity(parameters.steps);
        for step in 0..parameters.steps {
            let spot = *path.prices.get(step).ok_or_else(|| {
                ChainError::Internal(format!("the walk has no price for step {step}"))
            })?;

            let row_volatility = match step_volatilities {
                Some(ref vols) => *vols.get(step).ok_or_else(|| {
                    ChainError::Internal(format!("the walk has no volatility for step {step}"))
                })?,
                None => base_volatility,
            };

            reject_unpriceable_volatility(row_volatility, Some(step), volatility_source(method))?;

            rows.push(FactorRow {
                step,
                simulated_at: parameters.simulated_at(step)?,
                spot,
                base_volatility: row_volatility,
            });
        }

        debug!(
            steps = rows.len(),
            seed = parameters.seed,
            "Built the factor tape"
        );
        Ok(Self { rows })
    }

    /// The rows, in step order.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "the whole-tape accessor the tests compare against; the service reads \
                      one row at a time through `row`"
        )
    )]
    pub(crate) fn rows(&self) -> &[FactorRow] {
        &self.rows
    }

    /// The number of steps the tape covers.
    #[must_use]
    pub(crate) fn len(&self) -> usize {
        self.rows.len()
    }

    /// Whether the tape is empty. A built tape never is — `steps >= 1` is
    /// validated at the request boundary — but the accessor keeps clippy and
    /// callers honest.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "clippy's len_without_is_empty requires this alongside `len`; a built \
                      tape is never empty, since `steps >= 1` is validated at creation"
        )
    )]
    pub(crate) fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// The row at `step`, or `None` past the end of the tape.
    #[must_use]
    pub(crate) fn row(&self, step: usize) -> Option<&FactorRow> {
        self.rows.get(step)
    }
}

/// Rejects a resolved method that is not the one the stored parameters name.
///
/// `build` takes the method separately so a `Historical` walk can be resolved
/// against the database first, but that flexibility would otherwise let a
/// caller build a `Brownian` tape for parameters that say `Heston` — a tape
/// nothing could reproduce from the persisted replay inputs, which is precisely
/// what ADR 0001 §8 promises. A `Historical` method is compared by variant
/// rather than by value, because resolution is exactly what fills in its
/// symbol and prices.
///
/// # Errors
///
/// Returns [`ChainError::Internal`] naming both methods when they disagree.
/// Internal rather than validation: no request can produce this, only a
/// mis-wired caller.
fn ensure_method_matches(
    parameters: &SimulationParametersV2,
    method: &SimulationMethod,
) -> Result<(), ChainError> {
    let agrees = match (&parameters.method, method) {
        (SimulationMethod::Historical { .. }, SimulationMethod::Historical { .. }) => true,
        (stored, resolved) => stored == resolved,
    };

    if agrees {
        Ok(())
    } else {
        Err(ChainError::Internal(format!(
            "the resolved walk method does not match the simulation's parameters: \
             parameters say {:?}, the caller passed {method:?}",
            parameters.method
        )))
    }
}

/// Rejects a historical series that cannot be walked or priced.
///
/// Two client mistakes, both of which would otherwise surface as a `500`:
///
/// - **Too short for the horizon.** Upstream's `historical` kernel errors when
///   the embedded series is shorter than the walk — a request embedding five
///   prices and asking for a hundred steps — so it is caught here and named,
///   the way v1 avoids the problem entirely by refetching from the database.
/// - **A zero price inside the walked window.** A log return divides by the
///   previous price and takes the log of the ratio, and *both* panic on a zero
///   rather than returning an error, so one zero close would take down the
///   thread building the tape. `SimulationParametersV2::validate` already
///   rejects it on the stored series, but the method passed here is the
///   **resolved** one — the whole reason the argument exists is that a
///   `Historical` walk may have been filled in from the database since — and
///   that series has passed no validation at all.
///
/// # Errors
///
/// Returns [`ChainError::Validation`] naming `method.prices`.
fn ensure_historical_series_covers_the_horizon(
    parameters: &SimulationParametersV2,
    method: &SimulationMethod,
) -> Result<(), ChainError> {
    let SimulationMethod::Historical { prices, .. } = method else {
        return Ok(());
    };

    if prices.len() < parameters.steps {
        return Err(ChainError::Validation {
            field: "method.prices".to_string(),
            reason: format!(
                "must carry at least one price per step: {} supplied for {} steps",
                prices.len(),
                parameters.steps
            ),
        });
    }

    // Only the walked window, for the same reason nothing else reads past it: a
    // zero at index `steps + 50` is touched by no division, no logarithm and no
    // reduction, and refusing the request over it would be exactly the
    // look-ahead this module removed.
    let window = prices
        .get(..parameters.steps)
        .ok_or_else(|| ChainError::Internal("the horizon guard above did not hold".to_string()))?;
    if let Some(index) = window.iter().position(|price| price.is_zero()) {
        return Err(ChainError::Validation {
            field: "method.prices".to_string(),
            reason: format!(
                "must be strictly positive: the price at index {index} is zero, and a log \
                 return divides by the previous price and takes the log of the ratio"
            ),
        });
    }
    Ok(())
}

/// Determines the one authoritative base volatility for a simulation, and
/// rejects a request that specifies two different ones.
///
/// v1 leaves this ambiguous: the top-level `volatility` prices step zero while
/// the selected `WalkType` carries its own volatility for every later step, so
/// a request naming `volatility: 0.18` and `Brownian { volatility: 0.35 }` is
/// accepted and silently produces a chain priced at one number and a path
/// driven by another. #45 exists partly to remove that.
///
/// The agreement itself is enforced at the boundary, by
/// `SimulationParametersV2::validate`, which runs on both the request and the
/// stored-document path. The check is repeated here because this function is
/// what would silently pick a winner otherwise, and a domain type that depends
/// on an invariant should say so rather than assume it.
///
/// The rule: for the nine synthetic walk types the model's volatility is
/// authoritative, and the parameters' must agree with it. For `Historical`
/// there is no model volatility — `WalkType::volatility()` returns `None` — so
/// the series itself is authoritative and the value is **estimated** from it by
/// [`historical_constant_volatility`], exactly as v1 does.
///
/// # What the request's `volatility` means for a `Historical` walk
///
/// Nothing. A price series already prices itself, and inventing a second answer
/// would put the tape and the chains on different numbers again — the very
/// thing this function exists to prevent. The field is not silently swallowed:
/// the values actually used are the per-step ones in every row, which the
/// snapshot and export surfaces report, so a client reads back what priced its
/// chains rather than what it asked for. Dropping the field for this one
/// variant is a DTO change and is deliberately not made here.
///
/// # Only the walked window is read
///
/// The estimate covers `prices[..steps]` — the prefix upstream's historical
/// kernel actually replays — and not the whole embedded series. Reducing the
/// series would let an observation *past* the horizon price the simulation, or
/// refuse it, in a change whose entire point is that nothing later may reach an
/// earlier step. It is a deliberate divergence from v1, which reduces the whole
/// series for its own fallback.
///
/// A consequence worth stating: a horizon shorter than three steps has at most
/// one return and therefore no dispersion to measure, so the estimate is zero
/// and [`reject_unpriceable_volatility`] refuses the simulation. v1 would have
/// priced it from data it could not have seen; issue #63 lists refusing as an
/// accepted answer, and it is the honest one.
///
/// # Errors
///
/// Returns [`ChainError::Validation`] naming `volatility` when a synthetic
/// model's volatility and the parameters' disagree, or `method.prices` when the
/// walked window cannot be reduced to a volatility.
fn resolve_base_volatility(
    parameters: &SimulationParametersV2,
    method: &SimulationMethod,
) -> Result<Positive, ChainError> {
    match method.volatility() {
        Some(model_volatility) => {
            if model_volatility != parameters.volatility {
                return Err(ChainError::Validation {
                    field: "volatility".to_string(),
                    reason: format!(
                        "must match the walk model's volatility ({model_volatility}), got {}; \
                         a simulation has exactly one base volatility",
                        parameters.volatility
                    ),
                });
            }
            Ok(model_volatility)
        }
        None => match method {
            SimulationMethod::Historical {
                timeframe, prices, ..
            } => {
                // The length is guaranteed by
                // `ensure_historical_series_covers_the_horizon`, which runs
                // first; the checked slice keeps a future reordering from
                // becoming a panic.
                let window =
                    prices
                        .get(..parameters.steps)
                        .ok_or_else(|| ChainError::Validation {
                            field: "method.prices".to_string(),
                            reason: format!(
                                "must carry at least one price per step: {} supplied for {} steps",
                                prices.len(),
                                parameters.steps
                            ),
                        })?;
                historical_constant_volatility(window, *timeframe)
            }
            // `volatility()` returns `None` only for `Historical`; the match is
            // exhaustive over what can reach here, and a future variant that
            // also returns `None` lands on the requested value rather than
            // silently borrowing a historical estimator that does not apply.
            _ => Ok(parameters.volatility),
        },
    }
}

/// The single volatility of a stretch of historical prices, annualised.
///
/// Composed from the same three public upstream functions v1's own whole-series
/// fallback (`walk_driver::walk_volatility`) composes itself from: log returns,
/// the sample standard deviation of those returns, and a rescaling from the
/// series' timeframe to a year.
///
/// Callers pass the walked window, never the whole embedded series — see
/// [`resolve_base_volatility`] for why. It prices the seeding chain, and it is
/// what a window too short for an expanding estimate reduces to.
///
/// # Errors
///
/// Returns [`ChainError::Validation`] naming `volatility` when the reduction or
/// the annualisation fails. Prices are a precondition, not an error case — see
/// [`log_returns`].
fn historical_constant_volatility(
    prices: &[Positive],
    timeframe: TimeFrame,
) -> Result<Positive, ChainError> {
    let returns = log_returns(prices)?;
    let volatility = constant_volatility(&returns).map_err(|e| ChainError::Validation {
        field: "volatility".to_string(),
        reason: format!("the historical series has no usable volatility: {e}"),
    })?;
    annualise(volatility, timeframe)
}

/// The causal expanding-window volatility of a walked price path, one estimate
/// per point.
///
/// # Why this exists
///
/// v1 prices a historical chain at step `i` with the volatility of everything
/// observed **up to** `i`, never the whole series: `walk_steps_par` calls
/// upstream's `expanding_window_vols`. A tape priced at one constant is a
/// different, non-causal simulation — it lets a backtest see, at step 3, the
/// turbulence of step 900. Issue #63.
///
/// # Why it composes rather than copies
///
/// Upstream's estimator is private to its driver, but its three ingredients are
/// public, and upstream's own comment records that its prefix-sum variance is
/// *algebraically identical to the two-pass form in `constant_volatility`*. So
/// the window below writes the indexing policy and the backfill and **no
/// mathematics**: there is no second copy of an upstream kernel in this repo to
/// drift out of sync, which is the property the module docs above claim.
///
/// The cost of composing is quadratic time — `constant_volatility` reduces a
/// whole slice and upstream's prefix-sum recurrence is not reachable from
/// outside — where upstream is linear. It runs once per tape and only for
/// `Historical`; the nine synthetic models never reach it. optionstratlib#423
/// asks for the estimator to be exposed, which would make this a single call.
///
/// # Indexing
///
/// `prices[p]` has seen the returns `returns[..p]`, so an estimate needs
/// `p >= 2` — one return has no dispersion. Points 0 and 1 are backfilled with
/// the first computable estimate, matching upstream, so the vector is aligned
/// index-by-index with `prices` and has no holes. Fewer than three prices leave
/// nothing to expand over and return `None`, which is the caller's signal to
/// fall back to the constant.
///
/// The `p >= 2` guard is explicit rather than delegated: `constant_volatility`
/// answers `Positive::ZERO` for a shorter slice instead of refusing, and a
/// zero volatility is an answer, not an absence.
///
/// # Errors
///
/// Returns [`ChainError::Validation`] when a window cannot be reduced or
/// annualised. Prices are a precondition, not an error case — see
/// [`log_returns`].
fn expanding_window_volatilities(
    prices: &[Positive],
    timeframe: TimeFrame,
) -> Result<Option<Vec<Positive>>, ChainError> {
    // Two prices give one return, which has no sample dispersion; the first
    // window that does is the one over `prices[..3]`.
    if prices.len() < 3 {
        return Ok(None);
    }

    let returns = log_returns(prices)?;
    let mut volatilities = Vec::with_capacity(prices.len());
    let mut first_computable: Option<Positive> = None;

    for point in 0..prices.len() {
        if point < 2 {
            // Backfilled below, once the first real estimate is known.
            continue;
        }

        let window = returns.get(..point).ok_or_else(|| ChainError::Validation {
            field: "method.prices".to_string(),
            reason: format!(
                "the historical series yielded {} returns for {} prices, too few to \
                     estimate the volatility at point {point}",
                returns.len(),
                prices.len()
            ),
        })?;

        let volatility = constant_volatility(window).map_err(|e| ChainError::Validation {
            field: "volatility".to_string(),
            reason: format!("the historical window ending at point {point} has no volatility: {e}"),
        })?;
        let annualised = annualise(volatility, timeframe)?;

        if first_computable.is_none() {
            first_computable = Some(annualised);
        }
        volatilities.push(annualised);
    }

    let Some(fill) = first_computable else {
        // Unreachable: `prices.len() >= 3` guarantees one pass through the loop
        // body. Answering `None` rather than asserting keeps a future change to
        // the guard above from turning a bad bound into a panic.
        return Ok(None);
    };

    // Points 0 and 1 carry the first computable estimate, so the vector aligns
    // with `prices` index by index.
    let mut aligned = vec![fill; 2];
    aligned.append(&mut volatilities);
    Ok(Some(aligned))
}

/// The log returns of a price series as decimals.
///
/// Computed here rather than through upstream's `calculate_log_returns`, which
/// divides two `Positive`s: that operator panics on a zero divisor **and on a
/// ratio it cannot represent**, and it never returns an error for either. Both
/// operands come straight from a request, and a `Decimal` holds about 29
/// significant digits, so a series stepping from `1e-28` to `7e28` is a
/// perfectly legal pair of strictly positive prices whose ratio is not
/// representable. A request must not be able to abort the process, so the
/// division is checked and an unrepresentable ratio is a rejection naming the
/// field.
///
/// The log itself is taken on the `Decimal`, which is what recovers the true
/// sign: `Positive::ln` builds its result without revalidating, so a falling
/// price would otherwise yield a negative value wearing a `Positive`.
///
/// # Errors
///
/// Returns [`ChainError::Validation`] naming `method.prices` when a ratio is
/// not representable, when a price is zero, or when the log of a ratio is not
/// representable.
fn log_returns(prices: &[Positive]) -> Result<Vec<Decimal>, ChainError> {
    let unusable = |reason: String| ChainError::Validation {
        field: "method.prices".to_string(),
        reason,
    };

    let mut returns = Vec::with_capacity(prices.len().saturating_sub(1));
    for (index, pair) in prices.windows(2).enumerate() {
        let [previous, current] = pair else {
            // `windows(2)` yields pairs; destructuring keeps it indexing-free.
            continue;
        };

        let previous = previous.to_dec();
        let current = current.to_dec();
        if previous.is_zero() {
            return Err(unusable(format!(
                "the price at index {index} is zero, so the series has no return at {}",
                index + 1
            )));
        }

        let ratio = current.checked_div(previous).ok_or_else(|| {
            unusable(format!(
                "the price ratio at index {} is not representable ({current} over {previous})",
                index + 1
            ))
        })?;

        let log = ratio.checked_ln().ok_or_else(|| {
            unusable(format!(
                "the log return at index {} is not representable (ratio {ratio})",
                index + 1
            ))
        })?;

        returns.push(log);
    }

    Ok(returns)
}

/// Rescales a volatility from the series' timeframe to a year.
///
/// # Errors
///
/// Returns [`ChainError::Validation`] naming `volatility` when the rescaling
/// fails.
fn annualise(volatility: Positive, timeframe: TimeFrame) -> Result<Positive, ChainError> {
    adjust_volatility(volatility, timeframe, TimeFrame::Year).map_err(|e| ChainError::Validation {
        field: "volatility".to_string(),
        reason: format!("the historical volatility cannot be annualised from {timeframe}: {e}"),
    })
}

/// Which of the two a walk method's volatility comes from.
fn volatility_source(method: &SimulationMethod) -> VolatilitySource {
    match method {
        SimulationMethod::Historical { .. } => VolatilitySource::Series,
        _ => VolatilitySource::Model,
    }
}

/// Where a volatility that failed the priceable range came from, so the error
/// names a field the client can actually act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VolatilitySource {
    /// The walk model's own volatility, or the request's, which must agree.
    Model,
    /// Estimated from a historical price series, where the request's
    /// `volatility` prices nothing and lowering it would change nothing.
    Series,
}

impl VolatilitySource {
    /// The request field to name.
    fn field(self) -> &'static str {
        match self {
            Self::Model => "volatility",
            Self::Series => "method.prices",
        }
    }

    /// What the client has to change to get under the upper bound.
    fn remedy_too_high(self) -> &'static str {
        match self {
            Self::Model => "lower the model's volatility or shorten the horizon",
            Self::Series => Self::SERIES_REMEDY,
        }
    }

    /// What the client has to change to get off zero. Telling a model to lower
    /// its volatility here would make the zero *more* likely, not less.
    fn remedy_zero(self) -> &'static str {
        match self {
            Self::Model => {
                "raise the model's volatility, or change the parameters that let its variance \
                 collapse to zero"
            }
            Self::Series => Self::SERIES_REMEDY,
        }
    }

    /// The same either way: the request's `volatility` is not the input.
    const SERIES_REMEDY: &'static str = "the volatility is estimated from the series, so it is the series that has to change — \
         the request's volatility prices nothing for a historical walk";
}

/// Rejects a volatility no option chain can be priced at.
///
/// Upstream refuses anything above 1.0 annualised **and anything equal to
/// zero**, so without this a run whose volatility leaves that range fails with
/// an internal error the first time a chain is built — at creation for a
/// constant model, and halfway through the horizon for a stochastic or
/// historical one, at whatever step crosses first. All of them become one 400
/// naming a field, at tape build, where the whole path is in hand.
///
/// The lower bound is not theoretical for a historical walk, and it fires on
/// **a flat opening, not only a flat series**: the estimate needs two returns,
/// so points 0 and 1 carry the first computable one, and if the first three
/// prices are equal that value is zero. A series that is flat for three ticks
/// and lively afterwards is refused at step 0. v1 fails on the same input, from
/// inside the chain builder and as a `500`; this is the same refusal with a
/// status and a field a client can act on.
///
/// Rejecting rather than clamping: a clamped path is a different tape, and the
/// seed would no longer reproduce it.
fn reject_unpriceable_volatility(
    volatility: Positive,
    step: Option<usize>,
    source: VolatilitySource,
) -> Result<(), ChainError> {
    if volatility.is_zero() {
        return Err(ChainError::Validation {
            field: source.field().to_string(),
            reason: format!(
                "the volatility is zero{}, and an option chain priced at zero volatility is a \
                 chain of zero-value options; {}",
                at_step(step),
                source.remedy_zero()
            ),
        });
    }

    if volatility <= Positive::ONE {
        return Ok(());
    }

    Err(ChainError::Validation {
        field: source.field().to_string(),
        reason: format!(
            "the volatility reaches {volatility}{}, above the 1.0 maximum an option chain can \
             be priced at; {}",
            at_step(step),
            source.remedy_too_high()
        ),
    })
}

/// Names the step in an error, when there is one. Built only on the failing
/// path — the check above runs once per row.
fn at_step(step: Option<usize>) -> String {
    match step {
        Some(step) => format!(" at step {step}"),
        None => String::new(),
    }
}

/// Builds one option chain from a simulation's shape and a point in the market
/// path.
///
/// The single place the v2 stack turns parameters into an
/// [`OptionChainBuildParams`], so the factor tape's seeding chain and every
/// snapshot chain apply the same defaults, the same decimal precision and the
/// same volume — and so there is one place to look when a chain does not come
/// out as expected.
///
/// Mirrors v1's wiring in [`crate::domain::Simulator`] field for field, which
/// is what makes the seeding chain identical to the one v1 would build.
///
/// # A field upstream derives from the host clock
///
/// The chain is stamped with a `YYYY-MM-DD` expiration string that upstream
/// computes in `ExpirationDate::get_date_string()`. For the `Days` variant that
/// goes through `get_date_with_options(true)`, which reads `Utc::now()` and
/// **ignores** the thread-local reference, so the stamp reflects the host's
/// calendar rather than the simulated one and there is no upstream hook to
/// change that.
///
/// Everything that reaches a price is unaffected: `get_years()` divides the
/// `Days` value directly and `get_days()` returns it verbatim, so premiums,
/// Greeks and the derived strike interval are pure functions of the value
/// passed here. The stamp is therefore treated as upstream metadata that the
/// v2 surface does not expose — the authoritative expiration a client sees is
/// the absolute `expires_at` the planner produced.
///
/// # Errors
///
/// Returns [`ChainError::Internal`] when the default spread is not a valid
/// `Positive` — unreachable, it is a compile-time constant — or when upstream
/// cannot build the chain.
pub(crate) fn build_chain(
    parameters: &SimulationParametersV2,
    spot: Positive,
    volatility: Positive,
    expiration: ExpirationDate,
) -> Result<OptionChain, ChainError> {
    let chain_size = parameters.chain_size.unwrap_or(DEFAULT_CHAIN_SIZE);
    let skew_slope = parameters.skew_slope.unwrap_or(DEFAULT_SKEW_SLOPE);
    let smile_curve = parameters.smile_curve.unwrap_or(DEFAULT_SMILE_CURVE);
    let spread = match parameters.spread {
        Some(spread) => spread,
        None => Positive::new_decimal(DEFAULT_SPREAD).map_err(|e| {
            ChainError::Internal(format!("the default spread is not a valid Positive: {e}"))
        })?,
    };

    let price_params = OptionDataPriceParams::new(
        Some(Box::new(spot)),
        Some(expiration),
        Some(parameters.risk_free_rate),
        Some(parameters.dividend_yield),
        Some(parameters.symbol.clone()),
    );

    let build_params = OptionChainBuildParams::new(
        parameters.symbol.clone(),
        Some(Positive::ONE),
        chain_size,
        parameters.strike_interval,
        skew_slope,
        smile_curve,
        spread,
        2,
        price_params,
        volatility,
    );

    OptionChain::build_chain(&build_params)
        .map_err(|e| ChainError::Internal(format!("Failed to build the option chain: {e}")))
}

/// Builds the single option chain that seeds the walk.
///
/// The seeding chain needs *an* expiration; the real ones come from the
/// planner, per snapshot. One day keeps it well-conditioned, and the value
/// never reaches a served price — the walk starts from the chain's
/// `underlying_price`, which upstream copies verbatim from the price
/// parameters, so this nominal expiry changes the seeding ladder's shape and
/// nothing else.
fn build_initial_chain(
    parameters: &SimulationParametersV2,
    base_volatility: Positive,
) -> Result<OptionChain, ChainError> {
    build_chain(
        parameters,
        parameters.initial_price,
        base_volatility,
        ExpirationDate::Days(Positive::ONE),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::rest::models::{ApiTimeFrame, ApiWalkType};
    use crate::api::rest::requests_v2::CreateSimulationRequest;
    use crate::session::{ExpiryRule, ExpiryRuleKind};
    use chrono::{TimeZone, Weekday};
    use optionstratlib::error::SimulationError;
    use optionstratlib::simulation::walk_steps_par;
    use std::sync::Mutex;

    /// The reference market path: a modest daily Brownian walk over the
    /// simulated clock ADR 0001 §14 uses.
    fn request(steps: usize, method: ApiWalkType, volatility: f64) -> CreateSimulationRequest {
        let start_at = match Utc.with_ymd_and_hms(2026, 1, 5, 14, 30, 0).single() {
            Some(instant) => instant,
            None => panic!("the test instant must be valid"),
        };

        CreateSimulationRequest {
            symbol: "SPX".to_string(),
            steps,
            start_at: Some(start_at),
            step_interval_seconds: Some(86_400),
            timezone: "America/New_York".to_string(),
            calendar: None,
            expiration_time: "17:00".to_string(),
            schedules: vec![rule("zero_dte", ExpiryRuleKind::Daily, 1)],
            initial_price: 5000.0,
            volatility,
            risk_free_rate: 0.04,
            dividend_yield: 0.0,
            method,
            time_frame: ApiTimeFrame::Day,
            // A small ladder keeps the seeding chain cheap; the tape stores none.
            chain_size: Some(3),
            strike_interval: Some(25.0),
            skew_slope: None,
            smile_curve: None,
            spread: Some(0.02),
            seed: Some(42),
        }
    }

    fn rule(id: &str, kind: ExpiryRuleKind, count: usize) -> ExpiryRule {
        match ExpiryRule::new(id, kind, count) {
            Ok(rule) => rule,
            Err(error) => panic!("the test rule must be valid: {error}"),
        }
    }

    fn brownian(volatility: f64) -> ApiWalkType {
        ApiWalkType::Brownian {
            dt: 1.0 / 252.0,
            drift: 0.0,
            volatility,
        }
    }

    fn garch(volatility: f64) -> ApiWalkType {
        ApiWalkType::Garch {
            dt: 1.0 / 252.0,
            drift: 0.0,
            volatility,
            alpha: 0.1,
            beta: 0.85,
        }
    }

    fn heston(volatility: f64) -> ApiWalkType {
        ApiWalkType::Heston {
            dt: 1.0 / 252.0,
            drift: 0.0,
            volatility,
            kappa: 2.0,
            theta: 0.04,
            xi: 0.3,
            rho: -0.7,
        }
    }

    fn parameters(request: CreateSimulationRequest) -> SimulationParametersV2 {
        match SimulationParametersV2::try_from(request) {
            Ok(parameters) => parameters,
            Err(error) => panic!("the request must convert: {error}"),
        }
    }

    fn tape(parameters: &SimulationParametersV2) -> FactorTape {
        match FactorTape::build(parameters, &parameters.method) {
            Ok(tape) => tape,
            Err(error) => panic!("the tape must build: {error}"),
        }
    }

    // ---- shape and alignment ---------------------------------------------

    /// The tape has exactly one row per requested step, indexed from zero.
    #[test]
    fn test_tape_has_exactly_one_row_per_step() {
        let parameters = parameters(request(20, brownian(0.18), 0.18));

        let tape = tape(&parameters);

        assert_eq!(tape.len(), 20);
        assert!(!tape.is_empty());
        for (index, row) in tape.rows().iter().enumerate() {
            assert_eq!(row.step, index);
        }
        assert!(tape.row(20).is_none(), "the tape must end at its last step");
    }

    /// Row zero is the simulation's starting state: the effective start and the
    /// requested initial price.
    #[test]
    fn test_first_row_is_the_starting_state() {
        let parameters = parameters(request(5, brownian(0.18), 0.18));

        let tape = tape(&parameters);
        let first = match tape.row(0) {
            Some(row) => row,
            None => panic!("the tape must have a first row"),
        };

        assert_eq!(first.simulated_at, parameters.effective_start);
        assert_eq!(first.spot, parameters.initial_price);
    }

    /// Each row's instant follows the simulated clock, not the wall clock.
    #[test]
    fn test_row_instants_follow_the_simulated_clock() {
        let parameters = parameters(request(10, brownian(0.18), 0.18));

        let tape = tape(&parameters);

        for row in tape.rows() {
            match parameters.simulated_at(row.step) {
                Ok(expected) => assert_eq!(row.simulated_at, expected),
                Err(error) => panic!("the clock must resolve: {error}"),
            }
        }
    }

    /// A simulation spanning years still produces exactly `steps` rows, even
    /// though the short-dated options of §14's reference schedule would expire
    /// hundreds of times over that horizon.
    ///
    /// This is the property v1 cannot offer: its walk truncates when its one
    /// expiry reaches zero.
    #[test]
    fn test_a_multi_year_horizon_produces_every_requested_row() {
        // 800 daily steps is a little over three simulated years.
        let parameters = parameters(request(800, brownian(0.18), 0.18));

        let tape = tape(&parameters);

        assert_eq!(tape.len(), 800);
        let last = match tape.rows().last() {
            Some(row) => row,
            None => panic!("the tape must have a last row"),
        };
        let span = last.simulated_at - parameters.effective_start;
        assert!(
            span > chrono::Duration::days(365 * 2),
            "the horizon must span more than two years, got {span}"
        );
    }

    // ---- determinism ------------------------------------------------------

    /// The same effective parameters produce byte-identical tapes, rebuild
    /// after rebuild — which is what makes a cache eviction or a process
    /// restart invisible.
    #[test]
    fn test_same_parameters_produce_identical_tapes() {
        let parameters = parameters(request(50, brownian(0.18), 0.18));

        assert_eq!(tape(&parameters), tape(&parameters));
    }

    /// Two simulations with the same seed but built independently agree on
    /// every field of every row, not merely on the spot path.
    #[test]
    fn test_same_seed_agrees_on_full_rows() {
        let first = tape(&parameters(request(30, brownian(0.18), 0.18)));
        let second = tape(&parameters(request(30, brownian(0.18), 0.18)));

        assert_eq!(first.rows(), second.rows());
    }

    /// A different seed produces a different tape.
    #[test]
    fn test_a_different_seed_produces_a_different_tape() {
        let mut other = request(30, brownian(0.18), 0.18);
        other.seed = Some(43);

        let baseline = tape(&parameters(request(30, brownian(0.18), 0.18)));
        let different = tape(&parameters(other));

        assert_ne!(baseline.rows(), different.rows());
        // The starting state is shared by construction; the divergence must be
        // in the walk itself.
        assert_eq!(
            baseline.row(0).map(|row| row.spot),
            different.row(0).map(|row| row.spot)
        );
        assert_ne!(
            baseline.rows().last().map(|row| row.spot),
            different.rows().last().map(|row| row.spot)
        );
    }

    /// The tape is independent of the expiration schedule.
    ///
    /// This is the load-bearing isolation property: the planner draws no
    /// randomness, so a client can add, remove or reorder expiration rules and
    /// still compare two runs' underlying paths. What this test catches is
    /// `build` starting to read `parameters.schedule` at all; the version that
    /// covers snapshot building consuming the walker's RNG belongs with the
    /// snapshots themselves, in #46.
    #[test]
    fn test_the_schedule_cannot_perturb_the_tape() {
        let baseline = tape(&parameters(request(40, brownian(0.18), 0.18)));

        let mut richer = request(40, brownian(0.18), 0.18);
        richer.schedules = vec![
            rule(
                "monthlies",
                ExpiryRuleKind::Monthly {
                    weekday: Weekday::Fri,
                },
                12,
            ),
            rule(
                "weeklies",
                ExpiryRuleKind::weekly([Weekday::Mon, Weekday::Wed, Weekday::Fri]),
                3,
            ),
            rule("zero_dte", ExpiryRuleKind::Daily, 1),
        ];

        assert_eq!(baseline.rows(), tape(&parameters(richer)).rows());
    }

    /// Reordering the same rules cannot perturb it either.
    #[test]
    fn test_rule_order_cannot_perturb_the_tape() {
        let mut forwards = request(20, brownian(0.18), 0.18);
        forwards.schedules = vec![
            rule("zero_dte", ExpiryRuleKind::Daily, 1),
            rule("weeklies", ExpiryRuleKind::weekly([Weekday::Fri]), 2),
        ];
        let mut backwards = request(20, brownian(0.18), 0.18);
        backwards.schedules = vec![
            rule("weeklies", ExpiryRuleKind::weekly([Weekday::Fri]), 2),
            rule("zero_dte", ExpiryRuleKind::Daily, 1),
        ];

        assert_eq!(
            tape(&parameters(forwards)).rows(),
            tape(&parameters(backwards)).rows()
        );
    }

    /// A different effective start shifts every instant but leaves the market
    /// path alone: the walk depends on the seed, not on when the simulation is
    /// said to begin.
    #[test]
    fn test_a_different_start_shifts_instants_without_changing_the_path() {
        let baseline = tape(&parameters(request(15, brownian(0.18), 0.18)));

        let mut later = request(15, brownian(0.18), 0.18);
        later.start_at = match Utc.with_ymd_and_hms(2030, 6, 3, 9, 0, 0).single() {
            Some(instant) => Some(instant),
            None => panic!("the test instant must be valid"),
        };
        let shifted = tape(&parameters(later));

        let baseline_spots: Vec<Positive> = baseline.rows().iter().map(|row| row.spot).collect();
        let shifted_spots: Vec<Positive> = shifted.rows().iter().map(|row| row.spot).collect();
        assert_eq!(baseline_spots, shifted_spots);
        assert_ne!(
            baseline.row(0).map(|row| row.simulated_at),
            shifted.row(0).map(|row| row.simulated_at)
        );
    }

    // ---- volatility -------------------------------------------------------

    /// A constant-volatility model reports the same base volatility at every
    /// row, and it is the one the request asked for.
    #[test]
    fn test_constant_volatility_stays_constant() {
        let parameters = parameters(request(25, brownian(0.18), 0.18));

        let tape = tape(&parameters);

        for row in tape.rows() {
            assert_eq!(
                row.base_volatility, parameters.volatility,
                "step {} drifted from the model's volatility",
                row.step
            );
        }
    }

    /// A GARCH model's volatility varies across the tape and stays aligned with
    /// the spot path, one value per row.
    #[test]
    fn test_garch_volatility_varies_and_stays_aligned() {
        let parameters = parameters(request(60, garch(0.18), 0.18));

        let tape = tape(&parameters);

        assert_eq!(tape.len(), 60);

        let series: Vec<Positive> = tape.rows().iter().map(|row| row.base_volatility).collect();
        let distinct: std::collections::BTreeSet<String> =
            series.iter().map(ToString::to_string).collect();
        assert!(
            distinct.len() > 1,
            "a GARCH tape must not have a constant volatility"
        );

        // Alignment, not just variation: row 0 carries the model's own
        // volatility, which is where upstream starts the series, and the series
        // is not its own mirror image — so a reversed or shifted column fails
        // here rather than passing on variation alone.
        assert_eq!(
            series.first(),
            Some(&parameters.volatility),
            "row 0 must carry the model's starting volatility"
        );
        let reversed: Vec<Positive> = series.iter().rev().copied().collect();
        assert_ne!(
            series, reversed,
            "a symmetric series would hide a reversed column"
        );
    }

    /// The same holds for Heston.
    #[test]
    fn test_heston_volatility_varies_and_stays_aligned() {
        let parameters = parameters(request(60, heston(0.18), 0.18));

        let tape = tape(&parameters);

        assert_eq!(tape.len(), 60);

        let series: Vec<Positive> = tape.rows().iter().map(|row| row.base_volatility).collect();
        let distinct: std::collections::BTreeSet<String> =
            series.iter().map(ToString::to_string).collect();
        assert!(
            distinct.len() > 1,
            "a Heston tape must not have a constant volatility"
        );

        // Alignment, not just variation: row 0 carries the model's own
        // volatility, which is where upstream starts the series, and the series
        // is not its own mirror image — so a reversed or shifted column fails
        // here rather than passing on variation alone.
        assert_eq!(
            series.first(),
            Some(&parameters.volatility),
            "row 0 must carry the model's starting volatility"
        );
        let reversed: Vec<Positive> = series.iter().rev().copied().collect();
        assert_ne!(
            series, reversed,
            "a symmetric series would hide a reversed column"
        );
    }

    /// A stochastic-volatility tape is reproducible in both of its series, not
    /// just the spot path.
    #[test]
    fn test_stochastic_volatility_is_reproducible() {
        let first = tape(&parameters(request(40, garch(0.18), 0.18)));
        let second = tape(&parameters(request(40, garch(0.18), 0.18)));

        assert_eq!(first.rows(), second.rows());
    }

    /// A request whose top-level volatility disagrees with its walk model's is
    /// rejected rather than silently pricing step zero at one number and
    /// walking at another.
    ///
    /// v1 accepts exactly this; removing the ambiguity is part of what #45 is
    /// for.
    #[test]
    fn test_disagreeing_volatilities_are_rejected() {
        let parameters = parameters(request(10, brownian(0.35), 0.35));
        // Build parameters whose model says 0.35 but whose top level says 0.18.
        let mismatched = SimulationParametersV2 {
            volatility: match Positive::new(0.18) {
                Ok(value) => value,
                Err(error) => panic!("0.18 must be a valid Positive: {error}"),
            },
            ..parameters
        };

        match FactorTape::build(&mismatched, &mismatched.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "volatility");
                assert!(reason.contains("exactly one base volatility"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// The agreement is enforced at the request boundary, not only when a tape
    /// is built — so a contradictory request never reaches the domain.
    #[test]
    fn test_disagreeing_volatilities_are_rejected_at_the_boundary() {
        let mut contradictory = request(10, brownian(0.35), 0.35);
        contradictory.volatility = 0.18;

        match SimulationParametersV2::try_from(contradictory) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "volatility");
                assert!(reason.contains("exactly one base volatility"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// Building a tape with a method the parameters do not name is refused.
    ///
    /// `build` takes the method separately so a historical walk can be resolved
    /// first; without this guard that flexibility would let a caller produce a
    /// tape nothing could reproduce from the persisted replay inputs.
    #[test]
    fn test_a_method_the_parameters_do_not_name_is_refused() {
        let parameters = parameters(request(10, brownian(0.18), 0.18));
        let mismatched = match SimulationParametersV2::try_from(request(10, garch(0.18), 0.18)) {
            Ok(other) => other.method,
            Err(error) => panic!("the request must convert: {error}"),
        };

        match FactorTape::build(&parameters, &mismatched) {
            Err(ChainError::Internal(reason)) => {
                assert!(reason.contains("does not match"), "{reason}");
            }
            other => panic!("expected an internal error, got {other:?}"),
        }
    }

    /// A resolved historical method is accepted even though its prices and
    /// symbol differ from the stored ones — resolution is what fills those in.
    #[test]
    fn test_a_resolved_historical_method_is_accepted() {
        let prices: Vec<f64> = (0..30).map(|i| 5000.0 + f64::from(i)).collect();
        let mut historical = request(15, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: Vec::new(),
            symbol: None,
        };
        let parameters = parameters(historical);

        let resolved = SimulationMethod::Historical {
            timeframe: optionstratlib::utils::TimeFrame::Day,
            prices: prices
                .iter()
                .map(|price| match Positive::new(*price) {
                    Ok(value) => value,
                    Err(error) => panic!("the test price must be valid: {error}"),
                })
                .collect(),
            symbol: Some("SPX".to_string()),
        };

        match FactorTape::build(&parameters, &resolved) {
            Ok(tape) => assert_eq!(tape.len(), 15),
            Err(error) => panic!("a resolved historical method must build: {error}"),
        }
    }

    /// A historical series too short for the horizon is a client error naming
    /// the field, not an internal failure.
    #[test]
    fn test_a_short_historical_series_is_a_client_error() {
        let mut historical = request(50, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: vec![5000.0, 5001.0, 5002.0],
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "method.prices");
                assert!(reason.contains("3 supplied for 50 steps"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// A horizon of fewer than three steps has one return at most, and one
    /// return has no dispersion. v1 would price it from the whole embedded
    /// series — data past the horizon — so v2 refuses instead, which issue #63
    /// lists as an accepted answer.
    #[test]
    fn test_a_horizon_too_short_to_estimate_is_refused() {
        let mut historical = request(2, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: volatile_prices(60),
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "method.prices");
                assert!(reason.contains("zero"), "{reason}");
                assert!(reason.contains("prices nothing"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// A series that never moves has no volatility, and upstream refuses to
    /// price a chain at zero. It becomes one 400 naming the series rather than
    /// a 500 from inside the chain builder.
    #[test]
    fn test_a_series_without_dispersion_is_refused() {
        let mut historical = request(4, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: vec![5000.0; 8],
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "method.prices");
                assert!(reason.contains("zero-value options"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// A series too turbulent to price is refused with advice that applies: the
    /// volatility comes from the series, so lowering the request's does nothing.
    #[test]
    fn test_a_series_above_the_priceable_volatility_is_refused() {
        let prices: Vec<f64> = (0..20)
            .map(|index| if index % 2 == 0 { 5000.0 } else { 5500.0 })
            .collect();
        let mut historical = request(10, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "method.prices");
                assert!(reason.contains("above the 1.0 maximum"), "{reason}");
                assert!(reason.contains("the series that has to change"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// The resolved method is separately supplied and passes no boundary
    /// validation, so a zero close reaching it from the database has to be
    /// caught here — a log return would divide by it, and that division panics.
    #[test]
    fn test_a_zero_price_in_the_resolved_series_is_refused() {
        let mut historical = request(4, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: volatile_prices(20),
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        let mut resolved = volatile_series(20);
        match resolved.get_mut(3) {
            Some(price) => *price = Positive::ZERO,
            None => panic!("the fixture must have a fourth price"),
        }
        let resolved = SimulationMethod::Historical {
            timeframe: TimeFrame::Day,
            prices: resolved,
            symbol: Some("SPX".to_string()),
        };

        match FactorTape::build(&parameters, &resolved) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "method.prices");
                assert!(reason.contains("index 3 is zero"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// A historical walk prices itself: the volatility comes from the series,
    /// never from the `volatility` the request happened to carry.
    #[test]
    fn test_historical_ignores_the_requested_volatility() {
        let prices: Vec<f64> = (0..40).map(|i| 5000.0 + f64::from(i)).collect();
        let mut historical = request(20, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        let tape = tape(&parameters);

        assert_eq!(tape.len(), 20);
        // A near-linear ramp has almost no dispersion, so every estimate sits
        // far below the 0.18 the request asked for. The point is not the
        // number: it is that the request's value prices nothing.
        for row in tape.rows() {
            assert_ne!(row.base_volatility, parameters.volatility);
            assert!(
                row.base_volatility < parameters.volatility,
                "a flat series cannot be as volatile as {}, got {} at step {}",
                parameters.volatility,
                row.base_volatility,
                row.step
            );
        }
    }

    /// A series with a turbulent tail must not price its calm opening: the
    /// estimate at each step is the one the prefix alone produces.
    #[test]
    fn test_historical_volatility_has_no_look_ahead() {
        let series = volatile_series(40);
        let full = match expanding_window_volatilities(&series, TimeFrame::Day) {
            Ok(Some(volatilities)) => volatilities,
            other => panic!("the full series must yield estimates, got {other:?}"),
        };

        for cut in 3..=series.len() {
            let prefix = match series.get(..cut) {
                Some(prefix) => prefix,
                None => panic!("the cut must be within the series"),
            };
            let partial = match expanding_window_volatilities(prefix, TimeFrame::Day) {
                Ok(Some(volatilities)) => volatilities,
                other => panic!("the prefix of {cut} must yield estimates, got {other:?}"),
            };

            assert_eq!(partial.len(), cut);
            for (point, volatility) in partial.iter().enumerate() {
                assert_eq!(
                    Some(volatility),
                    full.get(point),
                    "point {point} moved when the series grew to {cut} observations"
                );
            }
        }
    }

    /// Fewer than three prices leave nothing to expand over, so the caller is
    /// told to fall back rather than handed a fabricated estimate.
    #[test]
    fn test_expanding_window_needs_three_prices() {
        let series = volatile_series(4);

        for length in 0..3 {
            let prefix = match series.get(..length) {
                Some(prefix) => prefix,
                None => panic!("the prefix must be within the series"),
            };
            assert!(
                matches!(
                    expanding_window_volatilities(prefix, TimeFrame::Day),
                    Ok(None)
                ),
                "{length} prices cannot yield an expanding window"
            );
        }

        assert!(matches!(
            expanding_window_volatilities(&series, TimeFrame::Day),
            Ok(Some(_))
        ));
    }

    /// The first two points have no window of their own, so they carry the
    /// first computable estimate — the vector stays aligned with the prices and
    /// has no holes.
    #[test]
    fn test_expanding_window_backfills_the_first_two_points() {
        let series = volatile_series(12);

        let volatilities = match expanding_window_volatilities(&series, TimeFrame::Day) {
            Ok(Some(volatilities)) => volatilities,
            other => panic!("the series must yield estimates, got {other:?}"),
        };

        assert_eq!(volatilities.len(), series.len());
        assert_eq!(volatilities.first(), volatilities.get(2));
        assert_eq!(volatilities.get(1), volatilities.get(2));
    }

    /// A constant log return has no dispersion. Upstream reports zero rather
    /// than refusing, and so does this: an answer, not an error or a panic.
    #[test]
    fn test_expanding_window_of_a_constant_return_is_zero() {
        let mut price = Positive::new(5000.0).unwrap_or(Positive::ONE);
        let mut series = Vec::with_capacity(10);
        for _ in 0..10 {
            series.push(price);
            price = price * Positive::new(1.01).unwrap_or(Positive::ONE);
        }

        let volatilities = match expanding_window_volatilities(&series, TimeFrame::Day) {
            Ok(Some(volatilities)) => volatilities,
            other => panic!("a constant-return series must still yield estimates, got {other:?}"),
        };

        assert_eq!(volatilities.len(), series.len());
        for (point, volatility) in volatilities.iter().enumerate() {
            assert!(
                *volatility < Positive::new(1e-12).unwrap_or(Positive::ONE),
                "point {point} of a constant-return series should be flat, got {volatility}"
            );
        }
    }

    /// The estimate moves with the series, which is the whole point: a tape
    /// that reported one number would be the constant this issue removed.
    #[test]
    fn test_historical_tape_volatility_varies_across_steps() {
        let parameters = parameters(volatile_historical_request(30));

        let tape = tape(&parameters);

        let first = match tape.row(0) {
            Some(row) => row.base_volatility,
            None => panic!("the tape must have a first row"),
        };
        assert!(
            tape.rows().iter().any(|row| row.base_volatility != first),
            "every step reported the same volatility, so nothing is being estimated"
        );
    }

    /// Rebuilding after eviction is the same call, so the estimates come back
    /// identical — the tape stays a pure function of the parameters.
    #[test]
    fn test_historical_tape_volatility_is_reproducible() {
        let parameters = parameters(volatile_historical_request(30));

        let first = tape(&parameters);
        let second = tape(&parameters);

        assert_eq!(first.rows(), second.rows());
    }

    /// The acceptance criterion of issue #63: v1 and v2 price a historical step
    /// at the same volatility.
    ///
    /// v1's per-step value is the one its driver hands the chain builder, so
    /// the comparison calls that driver — `walk_steps_par`, the exact function
    /// `generator_optionchain` uses — and records the volatility it passes.
    /// Reading it there rather than off a built chain keeps skew, smile and
    /// quote rounding out of the comparison and leaves the two estimates facing
    /// each other.
    ///
    /// Agreement is numeric, not bit-exact: upstream accumulates the window
    /// with prefix sums and `constant_volatility` centres in two passes. They
    /// are algebraically the same expression, so what is left is `Decimal`
    /// rounding. The largest deviation this series produces is 3.4e-23 on an
    /// annualised volatility; the tolerance below sits five orders above that
    /// and fifteen below anything an option price could notice.
    ///
    /// Step 0 is excluded, and that exclusion is the one real difference: v1
    /// never asks its estimator about step 0 (its driver starts at index 1 and
    /// its first chain is the seeding chain, priced at the request's constant),
    /// while v2 serves step 0 as a snapshot and prices it with the backfilled
    /// estimate. Pricing a served step at a volatility the series contradicts
    /// would be the worse answer.
    #[test]
    fn test_v1_and_v2_agree_on_historical_volatility() {
        /// Absolute, on an annualised volatility.
        const TOLERANCE: Decimal = Decimal::from_parts(1, 0, 0, false, 18);

        let parameters = parameters(volatile_historical_request(30));
        let tape = tape(&parameters);

        let base_volatility = match resolve_base_volatility(&parameters, &parameters.method) {
            Ok(volatility) => volatility,
            Err(error) => panic!("the historical series must yield a volatility: {error}"),
        };
        let initial_chain = match build_initial_chain(&parameters, base_volatility) {
            Ok(chain) => chain,
            Err(error) => panic!("the seeding chain must build: {error}"),
        };
        let walk_params = WalkParams {
            size: parameters.steps,
            init_step: Step {
                x: Xstep::new(
                    Positive::ONE,
                    parameters.time_frame,
                    // Far enough out that the driver's per-step expiry decay
                    // cannot truncate the walk before the horizon ends; a
                    // historical path ignores it either way.
                    ExpirationDate::Days(Positive::new(3650.0).unwrap_or(Positive::ONE)),
                ),
                y: Ystep::new(0, initial_chain.clone()),
            },
            walk_type: parameters.method.clone(),
            walker: Box::new(Walker::new_with_seed(parameters.seed)),
        };

        // The driver builds its steps in parallel, so the volatilities are
        // recorded with the step index the driver itself assigns.
        let observed: Mutex<Vec<(i32, Option<Positive>)>> = Mutex::new(Vec::new());
        let walked = walk_steps_par::<OptionChain, SimulationError, _>(
            &walk_params,
            |_price, volatility, x_step| match observed.lock() {
                Ok(mut guard) => {
                    guard.push((*x_step.index(), volatility));
                    Ok(Some(initial_chain.clone()))
                }
                Err(_) => Err(SimulationError::walk_error("the recorder lock is poisoned")),
            },
        );
        if let Err(error) = walked {
            panic!("the v1 driver must walk the series: {error}");
        }

        let mut v1_volatilities = match observed.into_inner() {
            Ok(volatilities) => volatilities,
            Err(_) => panic!("the recorder lock must not be poisoned"),
        };
        v1_volatilities.sort_by_key(|(index, _)| *index);

        assert_eq!(
            v1_volatilities.len(),
            tape.len() - 1,
            "v1 prices every step but the seeding one"
        );

        for (index, volatility) in &v1_volatilities {
            let step = match usize::try_from(*index) {
                Ok(step) => step,
                Err(error) => panic!("the driver's step index must be non-negative: {error}"),
            };
            let v2_row = match tape.row(step) {
                Some(row) => row,
                None => panic!("the tape must have a row for step {step}"),
            };
            let v1_volatility = match volatility {
                Some(volatility) => *volatility,
                None => panic!("v1 must price historical step {step} with an estimate"),
            };

            let deviation = (v1_volatility.to_dec() - v2_row.base_volatility.to_dec()).abs();
            assert!(
                deviation <= TOLERANCE,
                "step {step} disagrees by {deviation}: v1 {v1_volatility}, v2 {}",
                v2_row.base_volatility
            );
        }
    }

    /// A price series with a calm opening and a turbulent tail, so an expanding
    /// window has something to move over.
    fn volatile_series(length: usize) -> Vec<Positive> {
        volatile_series_from(&volatile_prices(length))
    }

    fn volatile_series_from(prices: &[f64]) -> Vec<Positive> {
        prices
            .iter()
            .map(|price| match Positive::new(*price) {
                Ok(price) => price,
                Err(error) => panic!("the test price must be positive: {error}"),
            })
            .collect()
    }

    fn volatile_prices(length: usize) -> Vec<f64> {
        let mut prices = Vec::with_capacity(length);
        let mut price = 5000.0_f64;
        for index in 0..length {
            prices.push(price);
            // Calm for the first half, then a widening zig-zag: the expanding
            // window has to keep moving instead of settling.
            let shock = if index < length / 2 {
                1.0
            } else {
                20.0 + f64::from(u32::try_from(index).unwrap_or(0))
            };
            price += if index % 2 == 0 { shock } else { -shock };
        }
        prices
    }

    fn volatile_historical_request(steps: usize) -> CreateSimulationRequest {
        let mut historical = request(steps, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: volatile_prices(steps * 2),
            symbol: Some("SPX".to_string()),
        };
        historical
    }

    /// A ratio too large to represent is a rejection, not a panic.
    ///
    /// Both prices are strictly positive and perfectly legal on their own; it
    /// is the jump between them that no `Decimal` can hold. Upstream's
    /// `calculate_log_returns` divides two `Positive`s, which aborts the
    /// process on exactly this, so the estimator computes the ratio itself.
    #[test]
    fn test_an_unrepresentable_price_jump_is_rejected() {
        let mut prices = vec![1e-28_f64; 4];
        prices.push(7e28);
        prices.extend(std::iter::repeat_n(7e28, 8));

        let mut historical = request(4, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, .. }) => assert_eq!(field, "method.prices"),
            other => panic!("an unrepresentable ratio must be a 400, got {other:?}"),
        }
    }

    /// And the same in the other direction, where the ratio underflows to
    /// something whose log is not representable.
    #[test]
    fn test_an_unrepresentable_price_collapse_is_rejected() {
        let mut prices = vec![7e28_f64; 4];
        prices.push(1e-28);
        prices.extend(std::iter::repeat_n(1e-28, 8));

        let mut historical = request(4, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, .. }) => assert_eq!(field, "method.prices"),
            other => panic!("an unrepresentable ratio must be a 400, got {other:?}"),
        }
    }

    /// A series a client could plausibly send still estimates, so the guard
    /// above rejects the unrepresentable rather than the merely volatile.
    ///
    /// The ceiling on a priceable volatility is a separate check with its own
    /// tests; this one only has to stay under it.
    #[test]
    fn test_a_violently_volatile_series_still_estimates() {
        // Two percent daily moves, which annualise to about a third — well
        // inside what a chain can be priced at, and far outside anything the
        // ratio guard should touch.
        let prices: Vec<f64> = (0..40)
            .map(|i| 5000.0 * (1.0 + 0.02 * f64::from(i).sin()))
            .collect();

        let mut historical = request(20, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Ok(tape) => assert_eq!(tape.len(), 20),
            Err(error) => panic!("a two percent daily move is legal, got {error}"),
        }
    }

    /// A historical tape replays the supplied series in order, with no
    /// look-ahead: row `i` is the `i`-th observation, never a later one.
    #[test]
    fn test_historical_replays_in_order_without_look_ahead() {
        let prices: Vec<f64> = (0..30).map(|i| 5000.0 + f64::from(i)).collect();
        let mut historical = request(15, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: prices.clone(),
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        let tape = tape(&parameters);

        for row in tape.rows() {
            let expected = match prices.get(row.step) {
                Some(price) => *price,
                None => panic!("the series must cover step {}", row.step),
            };
            assert_eq!(
                row.spot.to_f64(),
                expected,
                "step {} must replay its own observation",
                row.step
            );
        }
    }

    /// Later observations cannot change an earlier step's base volatility.
    ///
    /// The property the estimator turns on (#63): whatever prices a historical
    /// step must be a function of that step and what came before it. It held
    /// when the answer was a constant and it holds now that it is an estimate,
    /// which is the point — it is the invariant, not the implementation, that
    /// this pins. The narrower claim, that no reduction reads past the horizon,
    /// is the next test's.
    #[test]
    fn test_a_longer_series_leaves_earlier_steps_untouched() {
        // The observation count is a `u32` so the index converts to `f64`
        // losslessly and infallibly — no conversion to swallow, which is what a
        // fallback of zero would have done, quietly flattening the series.
        let build = |steps: usize, observations: u32| {
            let prices: Vec<f64> = (0..observations)
                .map(|i| 5000.0 + (f64::from(i) * 7.0).sin() * 250.0)
                .collect();
            let mut historical = request(steps, brownian(0.18), 0.18);
            historical.method = ApiWalkType::Historical {
                timeframe: ApiTimeFrame::Day,
                prices,
                symbol: Some("SPX".to_string()),
            };
            tape(&parameters(historical))
        };

        let short = build(15, 20);
        let long = build(15, 400);

        for (early, later) in short.rows().iter().zip(long.rows()) {
            assert_eq!(
                early.base_volatility, later.base_volatility,
                "step {} must not depend on observations after it",
                early.step
            );
            assert_eq!(
                early.spot, later.spot,
                "step {} replayed differently",
                early.step
            );
        }
    }

    /// Turbulence past the horizon cannot refuse a request whose own horizon is
    /// calm.
    ///
    /// This is the case the reduction over the walked prefix exists for. The
    /// tail here annualises far above the 1.0 a chain can be priced at, so
    /// reducing the whole embedded series — which is what v1 does for its own
    /// fallback — would 400 the simulation over observations it never reaches.
    /// The calm prefix is priceable, so it builds.
    #[test]
    fn test_turbulence_past_the_horizon_cannot_refuse_a_calm_one() {
        let mut prices: Vec<f64> = (0..10).map(|index| 5000.0 + f64::from(index)).collect();
        prices.extend((0..10).map(|index| if index % 2 == 0 { 5000.0 } else { 5500.0 }));

        let mut historical = request(10, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices: prices.clone(),
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        let tape = tape(&parameters);
        assert_eq!(tape.len(), 10);

        // The guard is only meaningful if the tail really is unpriceable: a
        // whole-series reduction has to be the thing that would have failed.
        let whole_series = volatile_series_from(&prices);
        match historical_constant_volatility(&whole_series, TimeFrame::Day) {
            Ok(volatility) => assert!(
                volatility > Positive::ONE,
                "the fixture's tail must be unpriceable for this test to mean anything, got \
                 {volatility}"
            ),
            Err(error) => panic!("the fixture must reduce: {error}"),
        }
    }

    /// A flat opening is enough to refuse the simulation, because points 0 and 1
    /// carry the first computable estimate and three equal prices make that
    /// estimate zero. The rest of the horizon never gets a say.
    #[test]
    fn test_a_flat_opening_is_refused_even_when_the_rest_moves() {
        let mut prices = vec![5000.0, 5000.0, 5000.0];
        prices.extend((0..10).map(|index| if index % 2 == 0 { 5050.0 } else { 4980.0 }));

        let mut historical = request(8, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "method.prices");
                assert!(reason.contains("zero at step 0"), "{reason}");
            }
            other => panic!("expected a validation error, got {other:?}"),
        }
    }

    /// A historical tape rebuilds identically, so an eviction or a restart is
    /// invisible.
    #[test]
    fn test_historical_rebuild_is_deterministic() {
        let prices: Vec<f64> = (0..30).map(|i| 5000.0 + f64::from(i)).collect();
        let mut historical = request(15, brownian(0.18), 0.18);
        historical.method = ApiWalkType::Historical {
            timeframe: ApiTimeFrame::Day,
            prices,
            symbol: Some("SPX".to_string()),
        };
        let parameters = parameters(historical);

        assert_eq!(tape(&parameters), tape(&parameters));
    }

    // ---- bounds -----------------------------------------------------------

    /// The tape stores rows, not contracts: its memory is `O(steps)`, and the
    /// chain shape reaches neither its size nor its contents.
    ///
    /// The second assertion is the load-bearing one. Only the seeding chain's
    /// `underlying_price` enters the walk, and upstream copies that verbatim
    /// from the price parameters, so a 200-strike ladder and a default one must
    /// produce the same rows for the same seed. If that ever stops holding, the
    /// chain shape has started perturbing the tape.
    #[test]
    fn test_memory_is_o_steps_and_independent_of_chain_size() {
        let mut wide = request(30, brownian(0.18), 0.18);
        wide.chain_size = Some(200);
        let narrow = request(30, brownian(0.18), 0.18);

        let wide_tape = tape(&parameters(wide));
        let narrow_tape = tape(&parameters(narrow));

        assert_eq!(wide_tape.rows(), narrow_tape.rows());
        assert!(
            std::mem::size_of::<FactorRow>() <= 128,
            "a row is a handful of small fields, got {} bytes",
            std::mem::size_of::<FactorRow>()
        );
    }

    /// A volatility above what a chain can be priced at is a 400 at tape build,
    /// not a 500 halfway through the run.
    ///
    /// Upstream refuses to build a chain above 1.0 annualised, so without this
    /// the first snapshot at the offending step would fail with an internal
    /// error, and every later one that also crosses.
    #[test]
    fn test_a_volatility_above_one_is_rejected_when_the_tape_is_built() {
        let mut request = request(30, brownian(1.5), 1.5);
        request.volatility = 1.5;

        let parameters = match SimulationParametersV2::try_from(request) {
            Ok(parameters) => parameters,
            Err(error) => panic!("the request must convert: {error}"),
        };

        match FactorTape::build(&parameters, &parameters.method) {
            Err(ChainError::Validation { field, reason }) => {
                assert_eq!(field, "volatility");
                assert!(
                    reason.contains("1.0"),
                    "the reason must name the cap, got {reason}"
                );
            }
            other => panic!("a 1.5 volatility must be refused, got {other:?}"),
        }
    }

    /// The step cap is enforced before a tape is ever built, at the request
    /// boundary, so no oversized tape can be requested.
    #[test]
    fn test_the_step_cap_is_enforced_at_the_boundary() {
        let oversized = request(usize::MAX, brownian(0.18), 0.18);

        match SimulationParametersV2::try_from(oversized) {
            Err(ChainError::Validation { field, .. }) => assert_eq!(field, "steps"),
            other => panic!("expected the step cap to reject it, got {other:?}"),
        }
    }

    /// A single-step simulation is a valid tape with exactly one row.
    #[test]
    fn test_a_single_step_simulation_builds_one_row() {
        let parameters = parameters(request(1, brownian(0.18), 0.18));

        let tape = tape(&parameters);

        assert_eq!(tape.len(), 1);
        assert_eq!(
            tape.row(0).map(|row| row.spot),
            Some(parameters.initial_price)
        );
    }
}