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
//! Lazy rolling multi-expiration snapshots.
//!
//! A **snapshot** is the whole simulated market at one step: one clock, one
//! spot, one base volatility, and the ordered set of option chains that are
//! alive at that instant. It is assembled from two inputs that already exist —
//! a row of the [factor tape](crate::domain::factors) and the
//! [planner](crate::domain::expiry)'s active expirations — and it is built
//! **on demand**, never stored for every step.
//!
//! # Why lazily
//!
//! v1 materialises the whole chain tape up front, which costs
//! `O(steps × strikes)` and stops when its single expiry reaches zero. A
//! rolling simulation multiplies that by the number of live expirations and
//! runs for years, so materialising it is not an option: the reference
//! configuration alone is fifteen chains a step. Building from a factor row
//! keeps the resident cost at `O(steps)` small rows plus a bounded cache of
//! recently-served snapshots.
//!
//! # What this module does not do
//!
//! It does not price anything. Every chain comes from upstream
//! `OptionChain::build_chain`, through the one wiring point the factor tape
//! already uses, so premiums, Greeks, spreads, skew and smile are optionstratlib's
//! and there is no second implementation to drift. It also does not use
//! `generator_optionseries`: that ages expirations and drops them, but never
//! replenishes them, and its `OptionSeries::build_series` path does not
//! preserve the requested strike interval.
//!
//! # The one subtle decision
//!
//! Chains are built with `ExpirationDate::Days(fractional_dte)`, computed here
//! from the same `(simulated_at, expires_at)` pair the planner used — never
//! with `ExpirationDate::DateTime`. Upstream's `DateTime` variant computes the
//! remaining time against `Utc::now()` directly, which would make every premium
//! depend on when the request happened to arrive. Passing `Days` keeps chain
//! building a pure function of the tape and the planner, which is what the
//! replay guarantee rests on.
//!
//! # The one value upstream stamps from the host clock
//!
//! `OptionChain::build_chain` writes a `YYYY-MM-DD` `expiration_date` string
//! derived from `Utc::now()`, and the field is private with no setter, so it
//! cannot be normalised here. Nothing priced depends on it — `get_days()` and
//! `get_years()` read the `Days` value directly — and the authoritative
//! expiration is the absolute `expires_at` the planner produced, which is what
//! [`ExpiryChain`] carries and what #47 must put on the wire. The consequence
//! to keep in mind is narrow but real: two builds of the same snapshot either
//! side of UTC midnight carry different stamps, so the raw upstream chain must
//! not be serialised verbatim into a response.

use crate::domain::expiry::{ActiveExpiry, RollingPlanner};
use crate::domain::factors::{FactorRow, FactorTape, build_chain};
use crate::infrastructure::{DEFAULT_MAX_CACHED_SNAPSHOT_CONTRACTS, DEFAULT_MAX_CACHED_SNAPSHOTS};
use crate::session::SimulationParametersV2;
use crate::utils::ChainError;
use chrono::{DateTime, Utc};
use optionstratlib::ExpirationDate;
use optionstratlib::chains::chain::OptionChain;
use positive::Positive;
use std::collections::HashMap;
use std::time::Instant;
use tracing::{debug, instrument};
use uuid::Uuid;

/// One live expiration at one step: when it expires, how far away that is,
/// which rules asked for it, and its priced chain.
///
/// `PartialEq` is hand-written rather than derived, because upstream's
/// `OptionChain: PartialEq` compares only the expiration string and the symbol
/// — not the strikes, the premiums or the underlying price. Deriving here would
/// give every reproducibility test a comparison that passes with completely
/// different chains.
#[derive(Debug, Clone)]
pub(crate) struct ExpiryChain {
    /// The absolute expiration instant, in UTC.
    pub(crate) expires_at: DateTime<Utc>,
    /// Fractional days remaining, from the same `(simulated_at, expires_at)`
    /// pair the planner used. Always strictly positive: an expired chain is
    /// never emitted.
    pub(crate) days_to_expiration: Positive,
    /// The ids of every rule this expiration satisfies, sorted. A date claimed
    /// by both a weekly and a monthly rule appears **once**, with both labels —
    /// it is priced once, not twice.
    pub(crate) labels: Vec<String>,
    /// The priced chain, built entirely by upstream.
    pub(crate) chain: OptionChain,
}

impl PartialEq for ExpiryChain {
    /// Compares what the simulation produced, contract by contract.
    ///
    /// The chain's `expiration_date` string is deliberately excluded: upstream
    /// stamps it from the host calendar via `Utc::now()`, so including it would
    /// make two otherwise identical snapshots differ across UTC midnight. Every
    /// value that reaches a client — the strikes, the premiums, the Greeks and
    /// the underlying price — is compared.
    fn eq(&self, other: &Self) -> bool {
        self.expires_at == other.expires_at
            && self.days_to_expiration == other.days_to_expiration
            && self.labels == other.labels
            && self.chain.underlying_price == other.chain.underlying_price
            && self.chain.symbol == other.chain.symbol
            && self.chain.options == other.chain.options
    }
}

/// The whole simulated market at one step.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SeriesSnapshot {
    /// The 0-based step this snapshot describes.
    pub(crate) step: usize,
    /// The simulated instant, from the factor row.
    pub(crate) simulated_at: DateTime<Utc>,
    /// The underlying price shared by every chain in the snapshot.
    pub(crate) spot: Positive,
    /// The base implied volatility shared by every chain, before skew and
    /// smile shape it per strike.
    pub(crate) base_volatility: Positive,
    /// The live chains, ordered by `expires_at` ascending.
    pub(crate) chains: Vec<ExpiryChain>,
}

impl SeriesSnapshot {
    /// The chain expiring at `expires_at`, if the snapshot carries one.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "the by-expiration lookup the tests use; the DTO layer walks \
                      `chains` in order instead"
        )
    )]
    pub(crate) fn chain_at(&self, expires_at: DateTime<Utc>) -> Option<&ExpiryChain> {
        self.chains
            .iter()
            .find(|chain| chain.expires_at == expires_at)
    }

    /// Every chain a given rule contributed to.
    ///
    /// A rule's count is satisfied by the chains carrying its label, which is
    /// not the same as the number of chains: coincident expirations are shared.
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "the per-rule view the inventory tests assert on; nothing served \
                      needs it, because a chain carries its own labels"
        )
    )]
    pub(crate) fn chains_for(&self, rule_id: &str) -> impl Iterator<Item = &ExpiryChain> {
        self.chains
            .iter()
            .filter(move |chain| chain.labels.iter().any(|label| label == rule_id))
    }
}

/// How many contracts a snapshot holds.
///
/// The unit the cache budgets in: one priced option per strike per live
/// expiration, which is what makes a snapshot heavy.
#[must_use]
fn snapshot_contracts(snapshot: &SeriesSnapshot) -> usize {
    snapshot
        .chains
        .iter()
        .map(|chain| chain.chain.options.len())
        .sum()
}

/// Builds snapshots for one simulation.
///
/// Borrows its inputs, so a caller that keeps the parameters and the tape in a
/// session can build a snapshot per request without cloning either.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SeriesBuilder<'a> {
    parameters: &'a SimulationParametersV2,
    tape: &'a FactorTape,
}

impl<'a> SeriesBuilder<'a> {
    /// Creates a builder over a simulation's parameters and its factor tape.
    ///
    /// Validates the parameters, for the same reason [`FactorTape::build`]
    /// does: `SimulationParametersV2` is public with public fields, so a caller
    /// can assemble one that never passed a validating constructor. The
    /// schedule cannot be invalid — its fields are private and `Deserialize`
    /// routes through the constructor — but `chain_size` is a bare `Option`
    /// whose cap lives only in `validate`, and it drives how many contracts
    /// every snapshot prices. Once per builder, not once per step.
    ///
    /// # Errors
    ///
    /// Returns [`ChainError::Validation`] when the parameters are invalid.
    pub(crate) fn new(
        parameters: &'a SimulationParametersV2,
        tape: &'a FactorTape,
    ) -> Result<Self, ChainError> {
        parameters.validate()?;
        Ok(Self { parameters, tape })
    }

    /// Builds the snapshot at `step`.
    ///
    /// Pure: the same `(parameters, tape, step)` always produces the same
    /// snapshot, because the factor row is fixed, the planner is deterministic,
    /// and the chains are built from the two of them with no randomness and no
    /// clock read that reaches a priced value — see the module docs for the one
    /// stamp upstream writes from the host calendar.
    ///
    /// # Errors
    ///
    /// Returns [`ChainError::NotFound`] when `step` is past the end of the
    /// tape, [`ChainError::Validation`] when the schedule cannot be projected
    /// at that instant, and [`ChainError::Internal`] when a fractional
    /// days-to-expiration is not representable or upstream cannot build a
    /// chain.
    #[instrument(skip(self), level = "debug")]
    pub(crate) fn snapshot(&self, step: usize) -> Result<SeriesSnapshot, ChainError> {
        let row = self.tape.row(step).ok_or_else(|| {
            ChainError::NotFound(format!(
                "step {step} is past the end of a {}-step simulation",
                self.tape.len()
            ))
        })?;

        let planner = RollingPlanner::new(&self.parameters.schedule);
        let active = planner.active_at(row.simulated_at)?;

        let mut chains = Vec::with_capacity(active.len());
        for expiry in &active {
            chains.push(self.build_expiry_chain(row, expiry)?);
        }

        debug!(
            step,
            chains = chains.len(),
            "Built a rolling multi-expiration snapshot"
        );

        Ok(SeriesSnapshot {
            step: row.step,
            simulated_at: row.simulated_at,
            spot: row.spot,
            base_volatility: row.base_volatility,
            // The planner already returns its expirations chronologically and
            // deduplicated, so the snapshot inherits both properties.
            chains,
        })
    }

    /// Prices one expiration at one factor row.
    fn build_expiry_chain(
        &self,
        row: &FactorRow,
        expiry: &ActiveExpiry,
    ) -> Result<ExpiryChain, ChainError> {
        let days = expiry.days_to_expiration(row.simulated_at)?;
        let days_to_expiration = Positive::new_decimal(days).map_err(|e| {
            ChainError::Internal(format!(
                "days to expiration {days} for {} is not a valid Positive: {e}",
                expiry.expires_at
            ))
        })?;

        // `Days`, not `DateTime`: see the module docs. This is the value that
        // makes a premium a function of the simulated clock rather than of when
        // the request arrived.
        let chain = build_chain(
            self.parameters,
            row.spot,
            row.base_volatility,
            ExpirationDate::Days(days_to_expiration),
        )?;

        Ok(ExpiryChain {
            expires_at: expiry.expires_at,
            days_to_expiration,
            labels: expiry.labels.clone(),
            chain,
        })
    }
}

/// One cached snapshot together with the last time it was served.
struct CacheEntry {
    snapshot: SeriesSnapshot,
    last_access: Instant,
    /// The entry's weight, measured once on insert.
    ///
    /// Kept rather than recomputed because eviction consults it on every
    /// iteration: recomputing would walk every strike of every remaining entry
    /// per victim, under the manager's lock, at a budget measured in millions.
    contracts: usize,
}

/// A bounded, least-recently-accessed cache of built snapshots.
///
/// Snapshots are expensive to build and cheap to reproduce, so the cache is a
/// pure latency optimisation: evicting an entry can never change what a client
/// sees, only how long it waits. That is what lets the bound be small and the
/// eviction policy simple.
///
/// Keyed by `(simulation, step)` so one simulation's working set cannot evict
/// another's wholesale, and so #48 can drop every entry belonging to a
/// simulation that has gone away.
pub(crate) struct SnapshotCache {
    entries: HashMap<(Uuid, usize), CacheEntry>,
    capacity: usize,
    contract_budget: usize,
    /// The sum of every entry's weight, maintained on insert and removal.
    resident_contracts: usize,
}

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

impl SnapshotCache {
    /// Creates a cache bounded by the documented default.
    ///
    /// The bound is configuration, not a constant of the domain: the service
    /// passes the operator's values through [`SnapshotCache::with_bounds`].
    /// This constructor exists for tests and for a caller with nothing to say
    /// about it.
    #[must_use]
    pub(crate) fn new() -> Self {
        Self::with_bounds(
            DEFAULT_MAX_CACHED_SNAPSHOTS,
            DEFAULT_MAX_CACHED_SNAPSHOT_CONTRACTS,
        )
    }

    /// Creates a cache bounded by both entries and contracts.
    ///
    /// Two bounds, because one entry is not one unit of memory: a snapshot
    /// holds every strike of every live expiration, so 256 of them is a few
    /// hundred contracts in the reference configuration and millions in a large
    /// one. The entry bound keeps the map small; the contract budget is what
    /// actually bounds the memory. Both floor at one — a cache that can hold
    /// nothing makes every insert a no-op and every get a miss, which is a
    /// misconfiguration rather than an intent.
    #[must_use]
    pub(crate) fn with_bounds(capacity: usize, contract_budget: usize) -> Self {
        Self {
            entries: HashMap::new(),
            capacity: capacity.max(1),
            contract_budget: contract_budget.max(1),
            resident_contracts: 0,
        }
    }

    /// The number of contracts currently held across every cached snapshot.
    ///
    /// Maintained incrementally, so this is O(1) — eviction consults it per
    /// victim and recomputing would walk every strike of every entry under the
    /// manager's lock.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "the budget is enforced internally; this reports it"
        )
    )]
    pub(crate) fn contracts(&self) -> usize {
        self.resident_contracts
    }

    /// The number of snapshots currently held.
    #[must_use]
    pub(crate) fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the cache holds nothing.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "clippy's len_without_is_empty requires this alongside `len`"
        )
    )]
    pub(crate) fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The bound this cache enforces.
    #[must_use]
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "the configured bound, asserted by the tests that pin the \
                      zero-capacity floor"
        )
    )]
    pub(crate) fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns the cached snapshot for `(simulation, step)`, refreshing its
    /// recency so an actively-walked simulation survives the bound.
    pub(crate) fn get(&mut self, simulation: Uuid, step: usize) -> Option<&SeriesSnapshot> {
        let entry = self.entries.get_mut(&(simulation, step))?;
        entry.last_access = Instant::now();
        Some(&entry.snapshot)
    }

    /// Inserts a snapshot, evicting the least recently accessed entries first.
    ///
    /// Eviction runs down to `capacity - 1` *before* the insert, so the key
    /// being inserted can never be its own victim and the cache never exceeds
    /// its bound afterwards.
    pub(crate) fn insert(&mut self, simulation: Uuid, snapshot: SeriesSnapshot) {
        let key = (simulation, snapshot.step);
        self.remove_entry(&key);

        let incoming = snapshot_contracts(&snapshot);

        // A snapshot heavier than the whole budget is **not** cached. Admitting
        // it would put the cache over the bound its own documentation states,
        // and evicting everything to make room for something that still does
        // not fit is the worst of both. The step stays servable — it is rebuilt
        // on demand, which is what every cache miss does — and the operator's
        // two knobs are what decide whether this can happen at all: the
        // per-snapshot cap bounds one snapshot, this bounds the resident set.
        if incoming > self.contract_budget {
            debug!(
                step = snapshot.step,
                contracts = incoming,
                budget = self.contract_budget,
                "The snapshot is larger than the cache budget; serving it without caching"
            );
            return;
        }

        // `capacity` is raised to at least one in the constructor, so `- 1`
        // cannot underflow. No saturating arithmetic: the rules forbid it, and
        // here it would hide a constructor that stopped enforcing the floor.
        debug_assert!(
            self.capacity >= 1,
            "capacity is floored at one on construction"
        );
        self.evict_to(self.capacity - 1);

        // Make room for this snapshot's own weight before inserting it, so the
        // cache never exceeds its budget afterwards. The subtraction cannot
        // underflow: the branch above returned for anything larger.
        self.evict_to_contracts(self.contract_budget - incoming);

        self.resident_contracts = self.resident_contracts.saturating_add(incoming);
        self.entries.insert(
            key,
            CacheEntry {
                snapshot,
                last_access: Instant::now(),
                contracts: incoming,
            },
        );
    }

    /// Removes one entry and takes its weight off the running total.
    ///
    /// Every removal goes through here, so `resident_contracts` cannot drift
    /// from what the map holds.
    fn remove_entry(&mut self, key: &(Uuid, usize)) {
        if let Some(entry) = self.entries.remove(key) {
            self.resident_contracts = self.resident_contracts.saturating_sub(entry.contracts);
        }
    }

    /// Drops every entry belonging to `simulation`, returning how many went.
    ///
    /// This is what a deleted, completed or expired simulation triggers, so a
    /// heavyweight snapshot cannot outlive the session it belongs to. #48 wires
    /// it to the store's cleanup.
    pub(crate) fn evict_simulation(&mut self, simulation: Uuid) -> usize {
        let victims: Vec<(Uuid, usize)> = self
            .entries
            .keys()
            .filter(|(id, _)| *id == simulation)
            .copied()
            .collect();

        for key in &victims {
            self.remove_entry(key);
        }
        victims.len()
    }

    /// Evicts least-recently-accessed entries until the cache holds at most
    /// `max` contracts.
    ///
    /// Shares the victim rule with [`SnapshotCache::evict_to`], so which entry
    /// goes is the same question either bound asks.
    fn evict_to_contracts(&mut self, max: usize) {
        while self.resident_contracts > max {
            match self.least_recently_used() {
                Some(key) => self.remove_entry(&key),
                None => break,
            }
        }
    }

    /// The key of the least recently accessed entry, or `None` when empty.
    fn least_recently_used(&self) -> Option<(Uuid, usize)> {
        self.entries
            .iter()
            // The key breaks an `Instant` tie, so eviction does not depend on
            // the map's randomised iteration order. Nothing served depends on
            // which entry goes — a rebuild is identical — but a deterministic
            // victim keeps the cache's behaviour reproducible under test.
            .min_by_key(|(key, entry)| (entry.last_access, **key))
            .map(|(key, _)| *key)
    }

    /// Evicts least-recently-accessed entries until at most `max` remain.
    fn evict_to(&mut self, max: usize) {
        while self.entries.len() > max {
            match self.least_recently_used() {
                Some(key) => self.remove_entry(&key),
                None => break,
            }
        }
    }
}

#[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};

    /// ADR 0001 §14's reference configuration: one rolling 0DTE, three
    /// Monday/Wednesday/Friday weeklies, twelve last-Friday monthlies, all at
    /// 17:00 New York.
    fn reference_schedules() -> Vec<ExpiryRule> {
        vec![
            rule("zero_dte", ExpiryRuleKind::Daily, 1),
            rule(
                "weeklies",
                ExpiryRuleKind::weekly([Weekday::Mon, Weekday::Wed, Weekday::Fri]),
                3,
            ),
            rule(
                "monthlies",
                ExpiryRuleKind::Monthly {
                    weekday: Weekday::Fri,
                },
                12,
            ),
        ]
    }

    /// Twelve last-Friday monthlies, the rule the isolation test watches.
    pub(super) fn monthly_rule() -> ExpiryRule {
        rule(
            "monthlies",
            ExpiryRuleKind::Monthly {
                weekday: Weekday::Fri,
            },
            12,
        )
    }

    /// One rolling 0DTE — the nearest expiration, so it is priced first.
    pub(super) fn zero_dte_rule() -> ExpiryRule {
        rule("zero_dte", ExpiryRuleKind::Daily, 1)
    }

    /// The reference configuration with a chosen schedule, for tests in sibling
    /// modules.
    pub(super) fn parameters_with_rules(schedules: Vec<ExpiryRule>) -> SimulationParametersV2 {
        parameters(request(2, schedules))
    }

    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 request(steps: usize, schedules: Vec<ExpiryRule>) -> 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,
            initial_price: 5000.0,
            volatility: 0.18,
            risk_free_rate: 0.04,
            dividend_yield: 0.0,
            method: ApiWalkType::Brownian {
                dt: 1.0 / 252.0,
                drift: 0.0,
                volatility: 0.18,
            },
            time_frame: ApiTimeFrame::Day,
            // A narrow ladder keeps sixteen chains a step affordable in tests.
            chain_size: Some(3),
            strike_interval: Some(25.0),
            skew_slope: None,
            smile_curve: None,
            spread: Some(0.02),
            seed: Some(42),
        }
    }

    /// The reference configuration, for tests in sibling modules.
    pub(super) fn test_parameters() -> SimulationParametersV2 {
        parameters(request(2, reference_schedules()))
    }

    /// The reference configuration's factor tape, for tests in sibling modules.
    pub(super) fn test_tape(parameters: &SimulationParametersV2) -> FactorTape {
        tape(parameters)
    }

    /// The reference configuration under a different seed.
    pub(super) fn test_parameters_with_seed(seed: u64) -> SimulationParametersV2 {
        let mut request = request(2, reference_schedules());
        request.seed = Some(seed);
        parameters(request)
    }

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

    /// Builds a [`SeriesBuilder`], panicking on a validation the tests never
    /// intend to trip. The production path returns the error instead.
    pub(super) fn builder<'a>(
        parameters: &'a SimulationParametersV2,
        tape: &'a FactorTape,
    ) -> SeriesBuilder<'a> {
        match SeriesBuilder::new(parameters, tape) {
            Ok(builder) => builder,
            Err(error) => panic!("the reference parameters must validate: {error}"),
        }
    }

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

    fn snapshot(
        parameters: &SimulationParametersV2,
        tape: &FactorTape,
        step: usize,
    ) -> SeriesSnapshot {
        match builder(parameters, tape).snapshot(step) {
            Ok(snapshot) => snapshot,
            Err(error) => panic!("the snapshot at step {step} must build: {error}"),
        }
    }

    /// The mid price of the at-the-money call, which is what the premium
    /// assertions compare.
    fn atm_call_mid(chain: &ExpiryChain) -> Positive {
        let atm = match chain.chain.atm_option_data() {
            Ok(data) => data,
            Err(error) => panic!("the chain must have an ATM strike: {error}"),
        };
        match atm.call_middle {
            Some(mid) => mid,
            None => panic!("the ATM call must have a mid price"),
        }
    }

    // ---- inventory --------------------------------------------------------

    /// The reference configuration yields every rule's slots at every step,
    /// with coincident expirations shared rather than duplicated.
    #[test]
    fn test_reference_configuration_satisfies_every_rule_at_every_step() {
        let parameters = parameters(request(12, reference_schedules()));
        let tape = tape(&parameters);

        for step in 0..tape.len() {
            let snapshot = snapshot(&parameters, &tape, step);

            for (rule_id, expected) in [("zero_dte", 1), ("weeklies", 3), ("monthlies", 12)] {
                assert_eq!(
                    snapshot.chains_for(rule_id).count(),
                    expected,
                    "step {step} lost inventory for {rule_id}"
                );
            }
            // Sixteen rule slots, but the shared dates collapse, so a snapshot
            // never carries more chains than slots and usually fewer.
            // A bound, not a dedup check: sixteen is the fixed sum of the rule
            // slots and the planner only ever collapses shared dates, so this
            // catches a snapshot that grew chains from nowhere. The collapse
            // itself is asserted at step zero below, where the coincidence is
            // known.
            assert!(
                snapshot.chains.len() <= 16,
                "step {step} priced {} chains, more than the sixteen rule slots",
                snapshot.chains.len()
            );
        }
    }

    /// At step zero the reference configuration collapses to fifteen chains:
    /// Monday's 0DTE and the first weekly are the same physical expiration,
    /// priced once and carrying both labels.
    #[test]
    fn test_coincident_expirations_are_priced_once_with_both_labels() {
        let parameters = parameters(request(1, reference_schedules()));
        let tape = tape(&parameters);

        let snapshot = snapshot(&parameters, &tape, 0);

        assert_eq!(snapshot.chains.len(), 15);
        let first = match snapshot.chains.first() {
            Some(chain) => chain,
            None => panic!("the snapshot must carry chains"),
        };
        assert_eq!(
            first.labels,
            vec!["weeklies".to_string(), "zero_dte".to_string()]
        );
    }

    /// Chains are ordered by expiration and never repeat an instant.
    #[test]
    fn test_chains_are_chronological_and_unique() {
        let parameters = parameters(request(3, reference_schedules()));
        let tape = tape(&parameters);

        let snapshot = snapshot(&parameters, &tape, 0);

        assert!(!snapshot.chains.is_empty());
        for pair in snapshot.chains.windows(2) {
            assert!(
                pair[0].expires_at < pair[1].expires_at,
                "chains must be strictly increasing in expiration"
            );
        }
    }

    /// Every chain shares the step's spot and base volatility but has its own
    /// expiration and fractional days-to-expiration.
    #[test]
    fn test_chains_share_the_step_state_and_differ_in_expiration() {
        let parameters = parameters(request(5, reference_schedules()));
        let tape = tape(&parameters);

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

        assert_eq!(snapshot.spot, row.spot);
        assert_eq!(snapshot.base_volatility, row.base_volatility);
        assert_eq!(snapshot.simulated_at, row.simulated_at);

        let mut seen: Vec<DateTime<Utc>> = Vec::new();
        for chain in &snapshot.chains {
            assert!(chain.days_to_expiration > Positive::ZERO);
            assert!(!seen.contains(&chain.expires_at));
            seen.push(chain.expires_at);
        }
    }

    /// No chain is ever emitted at or past its expiration.
    #[test]
    fn test_an_expired_chain_is_never_emitted() {
        let parameters = parameters(request(20, reference_schedules()));
        let tape = tape(&parameters);

        for step in 0..tape.len() {
            let snapshot = snapshot(&parameters, &tape, step);
            for chain in &snapshot.chains {
                assert!(
                    chain.expires_at > snapshot.simulated_at,
                    "step {step} emitted an expired chain"
                );
            }
        }
    }

    /// Crossing the 0DTE's cutoff replaces it in the same snapshot, so there is
    /// no step with a missing rolling expiration.
    #[test]
    fn test_crossing_the_cutoff_replaces_the_expiry_without_a_gap() {
        // 17:00 New York is 22:00 UTC in January; a 12-hour step crosses it.
        let mut crossing = request(4, vec![rule("zero_dte", ExpiryRuleKind::Daily, 1)]);
        crossing.step_interval_seconds = Some(43_200);
        let parameters = parameters(crossing);
        let tape = tape(&parameters);

        let mut expirations = Vec::new();
        for step in 0..tape.len() {
            let snapshot = snapshot(&parameters, &tape, step);
            assert_eq!(
                snapshot.chains.len(),
                1,
                "step {step} must always carry exactly one 0DTE"
            );
            match snapshot.chains.first() {
                Some(chain) => expirations.push(chain.expires_at),
                None => panic!("step {step} lost its rolling expiration"),
            }
        }

        // The inventory rolled at least once across the horizon.
        let distinct: std::collections::BTreeSet<DateTime<Utc>> =
            expirations.iter().copied().collect();
        assert!(
            distinct.len() > 1,
            "the 0DTE must roll at least once over two simulated days"
        );
    }

    /// A multi-month horizon completes every step despite repeated rolls.
    #[test]
    fn test_a_long_horizon_builds_every_step() {
        let parameters = parameters(request(90, reference_schedules()));
        let tape = tape(&parameters);

        // Sampled rather than exhaustive: ninety full reference snapshots is
        // fifteen chains each, and the property under test is that no step
        // fails, not that every one is inspected.
        for step in [0, 1, 29, 45, 60, 89] {
            let snapshot = snapshot(&parameters, &tape, step);
            assert_eq!(snapshot.chains_for("monthlies").count(), 12);
            assert_eq!(snapshot.chains_for("weeklies").count(), 3);
        }
    }

    /// A step past the end of the tape is a typed error, not a panic.
    #[test]
    fn test_a_step_past_the_tape_is_not_found() {
        let parameters = parameters(request(3, reference_schedules()));
        let tape = tape(&parameters);

        match builder(&parameters, &tape).snapshot(3) {
            Err(ChainError::NotFound(message)) => assert!(message.contains("past the end")),
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    // ---- pricing behaviour ------------------------------------------------

    /// A higher base volatility raises the representative ATM premium, all else
    /// equal.
    #[test]
    fn test_higher_base_volatility_raises_the_atm_premium() {
        let low = parameters(request(1, vec![rule("zero_dte", ExpiryRuleKind::Daily, 1)]));

        let mut high_request = request(1, vec![rule("zero_dte", ExpiryRuleKind::Daily, 1)]);
        high_request.volatility = 0.40;
        high_request.method = ApiWalkType::Brownian {
            dt: 1.0 / 252.0,
            drift: 0.0,
            volatility: 0.40,
        };
        let high = parameters(high_request);

        let low_tape = tape(&low);
        let high_tape = tape(&high);
        let low_snapshot = snapshot(&low, &low_tape, 0);
        let high_snapshot = snapshot(&high, &high_tape, 0);

        let low_chain = match low_snapshot.chains.first() {
            Some(chain) => chain,
            None => panic!("the snapshot must carry a chain"),
        };
        let high_chain = match high_snapshot.chains.first() {
            Some(chain) => chain,
            None => panic!("the snapshot must carry a chain"),
        };
        assert_eq!(
            low_chain.expires_at, high_chain.expires_at,
            "the comparison is only meaningful at the same expiration"
        );
        assert!(
            atm_call_mid(high_chain) > atm_call_mid(low_chain),
            "a higher base volatility must raise the ATM premium"
        );
    }

    /// A nearer expiration carries less extrinsic value than a farther one at
    /// the same step.
    #[test]
    fn test_a_nearer_expiration_carries_less_extrinsic_value() {
        let parameters = parameters(request(1, reference_schedules()));
        let tape = tape(&parameters);

        let snapshot = snapshot(&parameters, &tape, 0);
        let nearest = match snapshot.chains.first() {
            Some(chain) => chain,
            None => panic!("the snapshot must carry chains"),
        };
        let farthest = match snapshot.chains.last() {
            Some(chain) => chain,
            None => panic!("the snapshot must carry chains"),
        };

        assert!(nearest.days_to_expiration < farthest.days_to_expiration);
        assert!(
            atm_call_mid(nearest) < atm_call_mid(farthest),
            "the nearer expiration must carry less extrinsic value"
        );
    }

    /// Per-strike implied volatility is shaped by skew and smile rather than
    /// copying the base.
    #[test]
    fn test_skew_and_smile_shape_the_per_strike_volatility() {
        let mut shaped = request(1, vec![rule("zero_dte", ExpiryRuleKind::Daily, 1)]);
        shaped.chain_size = Some(9);
        shaped.skew_slope = Some(-0.3);
        shaped.smile_curve = Some(0.5);
        let parameters = parameters(shaped);
        let tape = tape(&parameters);

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

        let volatilities: Vec<Positive> = chain
            .chain
            .iter()
            .map(|data| data.implied_volatility)
            .collect();
        assert!(
            volatilities.len() > 2,
            "the ladder must expose per-strike volatilities"
        );
        let distinct: std::collections::BTreeSet<String> =
            volatilities.iter().map(ToString::to_string).collect();
        assert!(
            distinct.len() > 1,
            "skew and smile must vary the volatility across strikes"
        );
    }

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

    /// The same step rebuilds to an identical snapshot, which is what makes
    /// cache eviction unobservable.
    #[test]
    fn test_rebuilding_a_step_yields_an_identical_snapshot() {
        let parameters = parameters(request(4, reference_schedules()));
        let tape = tape(&parameters);
        let builder = builder(&parameters, &tape);

        match (builder.snapshot(2), builder.snapshot(2)) {
            (Ok(first), Ok(second)) => assert_eq!(first, second),
            (first, second) => panic!("both builds must succeed: {first:?} {second:?}"),
        }
    }

    /// Two simulations with the same seed produce identical snapshot tapes,
    /// compared over every field a client can see — timestamps, expirations,
    /// labels, spot, base volatility, and the chains themselves.
    #[test]
    fn test_same_seed_produces_an_identical_snapshot_tape() {
        let first_parameters = parameters(request(6, reference_schedules()));
        let second_parameters = parameters(request(6, reference_schedules()));
        let first_tape = tape(&first_parameters);
        let second_tape = tape(&second_parameters);

        for step in 0..first_tape.len() {
            assert_eq!(
                snapshot(&first_parameters, &first_tape, step),
                snapshot(&second_parameters, &second_tape, step),
                "step {step} diverged under the same seed"
            );
        }
    }

    /// A different seed produces a different snapshot tape.
    #[test]
    fn test_a_different_seed_produces_a_different_snapshot_tape() {
        let baseline = parameters(request(6, reference_schedules()));
        let mut other_request = request(6, reference_schedules());
        other_request.seed = Some(43);
        let other = parameters(other_request);

        let baseline_tape = tape(&baseline);
        let other_tape = tape(&other);

        let baseline_last = snapshot(&baseline, &baseline_tape, 5);
        let other_last = snapshot(&other, &other_tape, 5);

        assert_ne!(baseline_last, other_last);
        // The expirations are schedule-driven and therefore shared; the market
        // state is what diverges.
        let baseline_expiries: Vec<DateTime<Utc>> =
            baseline_last.chains.iter().map(|c| c.expires_at).collect();
        let other_expiries: Vec<DateTime<Utc>> =
            other_last.chains.iter().map(|c| c.expires_at).collect();
        assert_eq!(baseline_expiries, other_expiries);
        assert_ne!(baseline_last.spot, other_last.spot);
    }

    /// Looking a chain up by its expiration finds the one the planner produced.
    #[test]
    fn test_a_chain_can_be_found_by_its_expiration() {
        let parameters = parameters(request(1, reference_schedules()));
        let tape = tape(&parameters);
        let snapshot = snapshot(&parameters, &tape, 0);

        let target = match snapshot.chains.first() {
            Some(chain) => chain.expires_at,
            None => panic!("the snapshot must carry chains"),
        };

        match snapshot.chain_at(target) {
            Some(found) => assert_eq!(found.expires_at, target),
            None => panic!("the chain must be findable by its expiration"),
        }
        assert!(
            snapshot
                .chain_at(target - chrono::Duration::days(3650))
                .is_none()
        );
    }

    // ---- the snapshot cache -----------------------------------------------

    /// A cache bounded by entries alone, for the tests about that bound.
    ///
    /// The contract budget is effectively unlimited here, so each test exercises
    /// exactly the rule it names.
    fn entry_bounded_cache(capacity: usize) -> SnapshotCache {
        SnapshotCache::with_bounds(capacity, usize::MAX)
    }

    fn cached_snapshot(step: usize) -> SeriesSnapshot {
        let simulated_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"),
        };
        SeriesSnapshot {
            step,
            simulated_at,
            spot: Positive::ONE,
            base_volatility: Positive::ONE,
            chains: Vec::new(),
        }
    }

    /// A cached snapshot is returned as stored.
    #[test]
    fn test_the_cache_returns_what_it_stored() {
        let mut cache = entry_bounded_cache(4);
        let simulation = Uuid::new_v4();

        assert!(cache.is_empty());
        cache.insert(simulation, cached_snapshot(0));

        assert_eq!(cache.len(), 1);
        match cache.get(simulation, 0) {
            Some(snapshot) => assert_eq!(snapshot.step, 0),
            None => panic!("the cache must return what it stored"),
        }
        assert!(cache.get(simulation, 1).is_none());
    }

    /// The cache never exceeds its bound, and evicts the least recently
    /// accessed entry first.
    #[test]
    fn test_the_cache_evicts_the_least_recently_accessed_entry() {
        let mut cache = entry_bounded_cache(2);
        let simulation = Uuid::new_v4();

        cache.insert(simulation, cached_snapshot(0));
        cache.insert(simulation, cached_snapshot(1));
        // Touching step 0 makes step 1 the least recently accessed.
        assert!(cache.get(simulation, 0).is_some());
        cache.insert(simulation, cached_snapshot(2));

        assert_eq!(cache.len(), 2, "the cache must respect its bound");
        assert!(
            cache.get(simulation, 0).is_some(),
            "the touched entry stays"
        );
        assert!(cache.get(simulation, 1).is_none(), "the idle entry goes");
        assert!(cache.get(simulation, 2).is_some());
    }

    /// The contract budget evicts before the entry bound would.
    ///
    /// This is the bound that actually protects memory: one entry is a few
    /// hundred contracts in the reference configuration and up to the
    /// per-snapshot cap in a large one, so a cache that holds 256 of anything
    /// says nothing about how much is resident.
    #[test]
    fn test_the_cache_evicts_on_the_contract_budget() {
        // Real snapshots, because the weight is the point: an empty fixture
        // would make the budget trivially satisfiable.
        let parameters = test_parameters();
        let tape = test_tape(&parameters);
        let priced = |step: usize| snapshot(&parameters, &tape, step);

        let first = priced(0);
        let second = priced(1);
        let budget = snapshot_contracts(&first) + snapshot_contracts(&second);
        assert!(budget > 0, "the fixture must price something");

        // Room for exactly these two by weight, and for ten by entry count.
        let mut cache = SnapshotCache::with_bounds(10, budget);
        let simulation = Uuid::new_v4();

        cache.insert(simulation, first);
        cache.insert(simulation, second);
        assert_eq!(cache.len(), 2, "both fit within the budget");

        // The reference tape is two steps long, so the third insert reuses
        // step 0's snapshot under a second simulation id — a distinct key with
        // the same weight, which is all this bound cares about.
        let other = Uuid::new_v4();
        cache.insert(other, priced(0));

        assert!(
            cache.len() < 3,
            "the entry bound of ten cannot be what stopped it"
        );
        assert!(
            cache.contracts() <= budget,
            "the cache holds {} contracts, above its budget of {budget}",
            cache.contracts()
        );
        assert!(cache.get(other, 0).is_some(), "the newest stayed");
    }

    /// A snapshot heavier than the whole budget is not cached, and does not
    /// take the rest of the cache down with it.
    ///
    /// Admitting it would put the cache over the bound its own configuration
    /// states; evicting everything to make room for something that still does
    /// not fit would be worse. The step is served either way — an uncached step
    /// is a rebuild, which is what every miss already is.
    #[test]
    fn test_a_snapshot_larger_than_the_budget_is_not_cached() {
        let parameters = test_parameters();
        let tape = test_tape(&parameters);
        let weight = snapshot_contracts(&snapshot(&parameters, &tape, 0));

        let mut cache = SnapshotCache::with_bounds(10, weight / 2);
        let simulation = Uuid::new_v4();
        let other = Uuid::new_v4();

        cache.insert(other, snapshot(&parameters, &tape, 1));
        let resident = cache.len();

        cache.insert(simulation, snapshot(&parameters, &tape, 0));

        assert!(
            cache.get(simulation, 0).is_none(),
            "an entry that cannot fit the budget must not be admitted"
        );
        assert_eq!(
            cache.len(),
            resident,
            "and it must not evict the entries that do fit"
        );
        assert!(
            cache.contracts() <= weight / 2,
            "the cache holds {} contracts, above its budget",
            cache.contracts()
        );
    }

    /// One simulation's entries do not evict another's wholesale, and a
    /// simulation's entries can be dropped together.
    #[test]
    fn test_a_simulations_entries_can_be_evicted_together() {
        let mut cache = entry_bounded_cache(8);
        let first = Uuid::new_v4();
        let second = Uuid::new_v4();

        cache.insert(first, cached_snapshot(0));
        cache.insert(first, cached_snapshot(1));
        cache.insert(second, cached_snapshot(0));

        assert_eq!(cache.evict_simulation(first), 2);
        assert_eq!(cache.len(), 1);
        assert!(cache.get(first, 0).is_none());
        assert!(cache.get(second, 0).is_some());
        // Evicting a simulation that has nothing cached is not an error.
        assert_eq!(cache.evict_simulation(first), 0);
    }

    /// Re-inserting the same key replaces rather than duplicating.
    #[test]
    fn test_reinserting_a_key_replaces_the_entry() {
        let mut cache = entry_bounded_cache(4);
        let simulation = Uuid::new_v4();

        cache.insert(simulation, cached_snapshot(7));
        cache.insert(simulation, cached_snapshot(7));

        assert_eq!(cache.len(), 1);
    }

    /// A capacity of zero is raised to one rather than making the cache inert.
    #[test]
    fn test_a_zero_capacity_is_raised_to_one() {
        let mut cache = entry_bounded_cache(0);
        let simulation = Uuid::new_v4();

        assert_eq!(cache.capacity(), 1);
        cache.insert(simulation, cached_snapshot(0));
        assert_eq!(cache.len(), 1);
    }

    /// Eviction is unobservable: a rebuilt snapshot equals the evicted one.
    ///
    /// This is what lets the bound be small — the cache is a latency
    /// optimisation, never a source of truth.
    #[test]
    fn test_eviction_is_unobservable() {
        let parameters = parameters(request(3, reference_schedules()));
        let tape = tape(&parameters);
        let simulation = Uuid::new_v4();
        let mut cache = entry_bounded_cache(1);

        let original = snapshot(&parameters, &tape, 1);
        cache.insert(simulation, original.clone());
        // Push it out.
        cache.insert(simulation, snapshot(&parameters, &tape, 2));
        assert!(cache.get(simulation, 1).is_none());

        assert_eq!(snapshot(&parameters, &tape, 1), original);
    }
}

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

    /// Everything about a snapshot that the v2 API surfaces to a client.
    ///
    /// Deliberately explicit rather than `PartialEq` on the whole snapshot: an
    /// `OptionChain` also carries a calendar string upstream stamps from the
    /// host clock (see the module docs), which is not part of the v2 contract
    /// and would make an otherwise-sound comparison fail across midnight.
    ///
    /// What is compared here is exactly what #47 will put on the wire.
    fn surfaced_content(snapshot: &SeriesSnapshot) -> String {
        let mut rendered = format!(
            "step={} at={} spot={} iv={}",
            snapshot.step, snapshot.simulated_at, snapshot.spot, snapshot.base_volatility
        );
        for chain in &snapshot.chains {
            rendered.push_str(&format!(
                "\n  expires={} dte={} labels={:?}",
                chain.expires_at, chain.days_to_expiration, chain.labels
            ));
            for data in chain.chain.iter() {
                rendered.push_str(&format!(
                    "\n    k={} iv={} cb={:?} ca={:?} cm={:?} pb={:?} pa={:?} pm={:?} dc={:?} dp={:?} g={:?}",
                    data.strike_price,
                    data.implied_volatility,
                    data.call_bid,
                    data.call_ask,
                    data.call_middle,
                    data.put_bid,
                    data.put_ask,
                    data.put_middle,
                    data.delta_call,
                    data.delta_put,
                    data.gamma,
                ));
            }
        }
        rendered
    }

    /// Adding an expiration rule does not disturb the chains of the rules that
    /// were already there.
    ///
    /// This is ADR 0001 §8's isolation property, at the level where it could
    /// actually break: chain building draws no randomness, so a client may add,
    /// remove or reorder rules and still compare two runs. The 0DTE rule is
    /// added deliberately — chains are built in chronological order, so it is
    /// built **first**, and anything it consumed would shift every monthly
    /// chain built after it.
    #[test]
    fn test_adding_a_rule_leaves_the_other_chains_untouched() {
        let baseline = parameters_with_rules(vec![monthly_rule()]);
        let extended = parameters_with_rules(vec![monthly_rule(), zero_dte_rule()]);

        let baseline_tape = test_tape(&baseline);
        let extended_tape = test_tape(&extended);

        let baseline_snapshot = match builder(&baseline, &baseline_tape).snapshot(1) {
            Ok(snapshot) => snapshot,
            Err(error) => panic!("the baseline snapshot must build: {error}"),
        };
        let extended_snapshot = match builder(&extended, &extended_tape).snapshot(1) {
            Ok(snapshot) => snapshot,
            Err(error) => panic!("the extended snapshot must build: {error}"),
        };

        assert_eq!(
            baseline_snapshot.spot, extended_snapshot.spot,
            "the price path must not depend on the schedule"
        );

        let monthlies = |snapshot: &SeriesSnapshot| -> Vec<ExpiryChain> {
            snapshot
                .chains
                .iter()
                .filter(|chain| chain.labels.iter().any(|label| label == "monthlies"))
                .cloned()
                .collect()
        };

        let before = monthlies(&baseline_snapshot);
        let after = monthlies(&extended_snapshot);
        assert!(
            !before.is_empty(),
            "the baseline must price a monthly chain"
        );
        assert_eq!(
            before, after,
            "adding a 0DTE rule must not change the monthly chains"
        );
    }

    /// The same seed reproduces every value the v2 surface exposes: timestamps,
    /// expirations, labels, spot, base and per-strike volatility, quotes and
    /// Greeks.
    #[test]
    fn test_same_seed_reproduces_every_surfaced_value() {
        let first = test_parameters();
        let second = test_parameters();
        let first_tape = test_tape(&first);
        let second_tape = test_tape(&second);

        for step in 0..first_tape.len() {
            let left = match builder(&first, &first_tape).snapshot(step) {
                Ok(snapshot) => snapshot,
                Err(error) => panic!("the snapshot must build: {error}"),
            };
            let right = match builder(&second, &second_tape).snapshot(step) {
                Ok(snapshot) => snapshot,
                Err(error) => panic!("the snapshot must build: {error}"),
            };

            assert_eq!(
                surfaced_content(&left),
                surfaced_content(&right),
                "step {step} diverged under the same seed"
            );
        }
    }

    /// Rebuilding a step reproduces every surfaced value, which is what makes
    /// an eviction from the snapshot cache unobservable.
    #[test]
    fn test_rebuilding_reproduces_every_surfaced_value() {
        let parameters = test_parameters();
        let tape = test_tape(&parameters);
        let builder = builder(&parameters, &tape);

        match (builder.snapshot(1), builder.snapshot(1)) {
            (Ok(first), Ok(second)) => {
                assert_eq!(surfaced_content(&first), surfaced_content(&second));
            }
            (first, second) => panic!("both builds must succeed: {first:?} {second:?}"),
        }
    }

    /// A different seed changes the surfaced market state while leaving the
    /// schedule-driven expirations alone.
    #[test]
    fn test_a_different_seed_changes_the_surfaced_market_state() {
        let baseline = test_parameters();
        let other = test_parameters_with_seed(43);
        let baseline_tape = test_tape(&baseline);
        let other_tape = test_tape(&other);

        let left = match builder(&baseline, &baseline_tape).snapshot(1) {
            Ok(snapshot) => snapshot,
            Err(error) => panic!("the snapshot must build: {error}"),
        };
        let right = match builder(&other, &other_tape).snapshot(1) {
            Ok(snapshot) => snapshot,
            Err(error) => panic!("the snapshot must build: {error}"),
        };

        assert_ne!(surfaced_content(&left), surfaced_content(&right));
        let left_expiries: Vec<DateTime<Utc>> = left.chains.iter().map(|c| c.expires_at).collect();
        let right_expiries: Vec<DateTime<Utc>> =
            right.chains.iter().map(|c| c.expires_at).collect();
        assert_eq!(
            left_expiries, right_expiries,
            "expirations come from the schedule, not the seed"
        );
    }
}