optionchain_simulator 0.1.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
use crate::domain::Walker;
use crate::infrastructure::{
    ClickHouseClient, ClickHouseConfig, ClickHouseHistoricalRepository, HistoricalDataRepository,
    calculate_required_duration, select_random_date,
};
use crate::session::{Session, SessionState, SimulationMethod};
use crate::utils::ChainError;
use optionstratlib::utils::{Len, TimeFrame};
use optionstratlib::{
    ExpirationDate,
    chains::{
        OptionChainBuildParams, chain::OptionChain, generator_optionchain,
        utils::OptionDataPriceParams,
    },
    simulation::{
        WalkParams,
        randomwalk::RandomWalk,
        steps::{Step, Xstep, Ystep},
    },
};
use positive::{Positive, pos_or_panic};
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
use std::time::Instant;
use tokio::sync::Mutex;
use tracing::{debug, error, info, instrument, warn};
use uuid::Uuid;

const DEFAULT_CHAIN_SIZE: usize = 30;

const DEFAULT_SKEW_SLOPE: Decimal = dec!(-0.2);
const DEFAULT_SMILE_CURVE: Decimal = dec!(0.4);

/// Default upper bound on the number of random walks held in the simulation cache.
const DEFAULT_MAX_CACHED_WALKS: usize = 1000;

/// Domain-separation salt (ASCII "HISTORY") mixed into the session seed to derive
/// the RNG that selects the historical symbol and start date (issue #12).
///
/// XORing the seed with a fixed salt keeps the historical-selection stream
/// deterministic per seed while decoupling it from the walker's own stream, so the
/// same session seed always loads the same data series without perturbing — or being
/// perturbed by — the walk's stochastic draws.
const HISTORICAL_STREAM_SALT: u64 = 0x0048_4953_544F_5259;

/// Hard bound on the number of random walks the simulation cache may hold
/// (`OCS_MAX_CACHED_WALKS`).
///
/// Read once via [`LazyLock`]; an unset or invalid value (not an integer `>= 1`)
/// falls back to [`DEFAULT_MAX_CACHED_WALKS`] and emits a `tracing::warn!`, so a
/// misconfiguration never aborts startup. The bound is enforced with
/// least-recently-accessed eviction (see [`enforce_capacity`]). This mirrors the
/// parse-once pattern in `api::rest::limits` but lives in the domain layer to keep
/// the dependency flow api -> session -> domain intact.
static MAX_CACHED_WALKS: LazyLock<usize> =
    LazyLock::new(|| match std::env::var("OCS_MAX_CACHED_WALKS").ok() {
        None => DEFAULT_MAX_CACHED_WALKS,
        Some(value) => match value.trim().parse::<usize>() {
            Ok(parsed) if parsed >= 1 => parsed,
            _ => {
                warn!(
                    raw = %value,
                    default = DEFAULT_MAX_CACHED_WALKS,
                    "invalid OCS_MAX_CACHED_WALKS; falling back to default"
                );
                DEFAULT_MAX_CACHED_WALKS
            }
        },
    });

/// One cached random walk together with the last time it was accessed.
///
/// `last_access` drives least-recently-accessed eviction: every cache hit refreshes
/// it so active sessions survive the [`MAX_CACHED_WALKS`] bound while idle ones age out.
///
/// `resolved_method` carries the RESOLVED `SimulationMethod::Historical` (chosen
/// symbol + loaded prices) when this walk's build fetched its series from the
/// database, `None` otherwise. It rides with the entry so EVERY serve — cache miss
/// or cache hit — can write the resolution back into the session it serves. Without
/// it, a read-only peek that builds the walk would discard its session copy, and the
/// following advance (a cache hit) would persist the original UNRESOLVED method.
///
/// The historical eviction pin from the cache-eviction PR is lifted here: with the
/// symbol/date selection drawn from a seed-derived RNG (issue #12), an evicted
/// historical walk rebuilds the identical tape — either from the persisted embedded
/// prices or by replaying the seeded selection — so every entry is evictable again.
struct CacheEntry {
    walk: RandomWalk<Positive, OptionChain>,
    last_access: Instant,
    resolved_method: Option<SimulationMethod>,
}

/// Evicts least-recently-accessed entries until `cache` holds at most `max` entries.
///
/// Pure over the cache map (no I/O, no locking) so it can be unit-tested directly.
/// The insert path calls it with `max = MAX_CACHED_WALKS - 1` BEFORE inserting the
/// new entry, so the id being inserted is absent and can never be the victim, and the
/// cache never exceeds `MAX_CACHED_WALKS` after the insert. An `O(n)` scan per
/// eviction is acceptable at these cache sizes.
///
/// Every entry is a candidate victim, historical walks included: their seeded
/// symbol/date selection (issue #12) makes an evict-and-rebuild reproduce the
/// identical tape, which lifted the earlier pin on historical entries.
fn enforce_capacity(cache: &mut HashMap<Uuid, CacheEntry>, max: usize) {
    while cache.len() > max {
        let victim = cache
            .iter()
            .min_by_key(|(_, entry)| entry.last_access)
            .map(|(id, _)| *id);
        match victim {
            Some(id) => {
                cache.remove(&id);
            }
            None => break,
        }
    }
}

/// Simulator handles the generation of option chains based on simulation parameters.
///
/// It owns a bounded, per-session cache of [`RandomWalk`]s keyed by session id. The
/// cache is evicted on three lifecycle triggers so it never outlives the sessions
/// it serves (issue #9):
/// - DELETE / completion, via [`Simulator::remove_session`] driven by the session
///   manager;
/// - a `Reinitialized` session, which drops and rebuilds its walk in
///   [`Simulator::simulate_next_step`];
/// - the [`MAX_CACHED_WALKS`] LRU bound, enforced by [`enforce_capacity`] on insert.
///
/// Eviction never affects reproducibility: a re-simulate after eviction rebuilds the
/// walk from the same seed, yielding the identical tape.
pub struct Simulator {
    simulation_cache: Arc<Mutex<HashMap<Uuid, CacheEntry>>>,
    database_repo: Option<Arc<dyn HistoricalDataRepository>>,
}

impl Simulator {
    /// Creates a new simulator instance
    pub fn new() -> Self {
        info!("Creating new simulator instance");
        let database_config = ClickHouseConfig::default();
        info!("Connecting to ClickHouse at {}", database_config.host);
        let database_repo = match ClickHouseClient::new(database_config) {
            Ok(client) => {
                let client = Arc::new(client);
                let repo: Arc<dyn HistoricalDataRepository> =
                    Arc::new(ClickHouseHistoricalRepository::new(client));
                Some(repo)
            }
            Err(e) => {
                error!("Failed to connect to ClickHouse: {}", e);
                None
            }
        };

        Self {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo,
        }
    }

    /// Simulates the next step based on the session parameters and returns an OptionChain.
    ///
    /// Documented side effect (issue #12): when the walk's build resolved a
    /// `Historical` source (an empty/insufficient price series triggers a seeded
    /// database fetch), the resolved method — the chosen symbol plus the loaded
    /// prices — is written back into `session.parameters.method` on EVERY serve,
    /// cache hits included (the resolution is stored in the cache entry). This makes
    /// the write-back independent of which call built the walk: a read-only peek may
    /// build it and discard its session copy, and the next advance still receives —
    /// and persists, via the manager's save — the resolved method. Reproducibility
    /// does not depend on this persistence: the seeded selection stream reloads the
    /// identical series on any rebuild.
    #[instrument(skip(self, session), level = "debug")]
    pub async fn simulate_next_step(
        &self,
        session: &mut Session,
    ) -> Result<OptionChain, ChainError> {
        debug!(
            session_id = %session.id,
            current_step = session.current_step,
            "Simulating next step"
        );

        // First check if we need to create a new random walk.
        //
        // Under serve-then-advance the cursor no longer needs a `current_step == 0`
        // trigger: a fresh session is simply not cached yet, so `!contains_key` builds
        // it once. Dropping the `== 0` trigger keeps peek(cursor 0) and the next advance
        // serving the SAME cached walk (they would otherwise rebuild — and, for an
        // unseeded walker, diverge — on every step-0 access).
        //
        // The lock here is held only for these cheap map ops, never across the walk
        // build below. A Reinitialized session's stale walk is evicted so the next
        // build rebuilds it from the (possibly new) seed; `remove` on an absent id is
        // a no-op.
        let need_new_walk;
        {
            let mut cache = self.simulation_cache.lock().await;
            need_new_walk =
                !cache.contains_key(&session.id) || session.state == SessionState::Reinitialized;

            if session.state == SessionState::Reinitialized {
                cache.remove(&session.id);
            }
        }

        // Build the walk OUTSIDE any lock (this awaits ClickHouse). We keep it in an
        // Option so the single critical section below can insert it. Reproducibility is
        // preserved: a seeded rebuild reproduces the identical tape.
        let random_walk_opt = if need_new_walk {
            info!(
                session_id = %session.id,
                "Creating new simulation for session"
            );
            debug!("Reset Random Walk with Session: {}", session);

            Some(self.create_random_walk(session).await?)
        } else {
            None
        };

        // ONE critical section for the cache: on a fresh build, enforce capacity,
        // insert, then range-check and clone the step; on a hit, refresh recency,
        // range-check and clone — all under a single lock. Collapsing insert and step
        // lookup into one lock closes the window in which a concurrent cold insertion
        // could evict this entry between the two, which would otherwise surface as a
        // spurious `Internal` error.
        let step = {
            let mut cache = self.simulation_cache.lock().await;

            let entry = if let Some((random_walk, resolved_method)) = random_walk_opt {
                // Evicting down to `max - 1` before inserting keeps the cache at or
                // below `MAX_CACHED_WALKS` afterwards. `MAX_CACHED_WALKS` is validated
                // `>= 1` at parse time (see its definition), so `max - 1` cannot
                // underflow — no saturating arithmetic (rules forbid it).
                let max = *MAX_CACHED_WALKS;
                debug_assert!(max >= 1, "MAX_CACHED_WALKS is validated >= 1 at parse time");
                enforce_capacity(&mut cache, max - 1);

                // The resolved method rides WITH the entry (not only with this call's
                // session copy) so a later cache hit can re-apply it — see below.
                cache.entry(session.id).or_insert(CacheEntry {
                    walk: random_walk,
                    last_access: Instant::now(),
                    resolved_method,
                })
            } else {
                cache.get_mut(&session.id).ok_or_else(|| {
                    ChainError::Internal(format!(
                        "Failed to get random walk for session {}",
                        session.id
                    ))
                })?
            };

            // Refresh recency so an actively served session survives the LRU bound
            // while idle sessions age out.
            entry.last_access = Instant::now();

            // Apply the resolved Historical source (chosen symbol + loaded prices) to
            // the served session on EVERY serve, hits included. A read-only peek may
            // have built the walk and discarded its session copy; without this, the
            // following advance would hit the cache and persist the original
            // UNRESOLVED method, so a restart or eviction could refetch a different
            // tape. Safe on a hit: any parameter change marks the session
            // `Reinitialized`, which evicts the entry above, so a hit implies the
            // parameters still describe this cached walk. Idempotent once persisted.
            if let Some(resolved) = &entry.resolved_method {
                session.parameters.method = resolved.clone();
            }

            // Check if the current step is within range
            if session.current_step >= entry.walk.len() {
                warn!("Walker reached end of data.");
                return Err(ChainError::SimulatorError(
                    "Walker reached end of data".to_string(),
                ));
            }

            // Clone the step data so we can release the lock
            entry.walk[session.current_step].clone()
        };

        // Process the chain data outside the lock
        let chain = step.y.value().clone();

        debug!(
            session_id = %session.id,
            current_step = session.current_step,
            underlying_price = %chain.underlying_price,
            contracts_count = chain.len(),
            "Retrieved option chain for step"
        );

        Ok(chain)
    }

    /// Fetches historical data for a given symbol and timeframe with a random date
    /// range. If `symbol` is `None`, selects a symbol from the available symbols.
    ///
    /// Both the symbol choice and the start-date choice draw from the caller-supplied
    /// `rng` (issue #12). Passing a seed-derived RNG makes historical selection
    /// reproducible: the same seed loads the same series. Returns the resolved symbol
    /// alongside the prices so the caller can persist the resolution.
    #[instrument(skip(self, rng), level = "debug")]
    pub async fn get_historical_data(
        &self,
        symbol: &Option<String>,
        timeframe: &TimeFrame,
        steps: usize,
        rng: &mut StdRng,
    ) -> Result<(String, Vec<Positive>), ChainError> {
        if let Some(repo) = &self.database_repo {
            let actual_symbol = if let Some(sym) = symbol {
                // Use provided symbol
                sym.clone()
            } else {
                // Get list of available symbols and choose one from the seeded RNG
                let available_symbols = repo
                    .list_available_symbols()
                    .await
                    .map_err(|e| ChainError::ClickHouseError(e.to_string()))?;

                if available_symbols.is_empty() {
                    return Err(ChainError::NotFound(
                        "No symbols available in the database".to_string(),
                    ));
                }

                let random_index = rng.random_range(0..available_symbols.len());
                available_symbols
                    .get(random_index)
                    .ok_or_else(|| ChainError::Internal("symbol index out of range".to_string()))?
                    .clone()
            };

            debug!("Selected symbol: {}", actual_symbol);

            // Get the available date range for the selected symbol
            let (min_date, max_date) = repo
                .get_date_range_for_symbol(&actual_symbol)
                .await
                .map_err(|e| ChainError::ClickHouseError(e.to_string()))?;
            debug!("Available date range: {} - {}", min_date, max_date);

            // Select the start date from the seeded RNG, ensuring enough data for
            // all steps
            let start_date = select_random_date(rng, min_date, max_date, timeframe, steps)?;

            // Calculate end date based on required duration
            let duration = calculate_required_duration(timeframe, steps);
            let end_date = start_date + duration;

            debug!(
                "Fetching data from {} to {} for symbol {}",
                start_date, end_date, actual_symbol
            );

            // Fetch the historical prices
            let prices = repo
                .get_historical_prices(&actual_symbol, timeframe, &start_date, steps)
                .await
                .map_err(|e| ChainError::ClickHouseError(e.to_string()))?;

            // Ensure we have enough data points
            if prices.len() < steps {
                return Err(ChainError::NotEnoughData(format!(
                    "Retrieved {} data points but {} required for symbol {}",
                    prices.len(),
                    steps,
                    actual_symbol
                )));
            }

            // Return the resolved symbol and exactly the number of steps requested
            Ok((actual_symbol, prices.into_iter().take(steps).collect()))
        } else {
            Err(ChainError::SimulatorError(
                "Database not available".to_string(),
            ))
        }
    }

    /// Creates a new RandomWalk for a session.
    ///
    /// Returns the walk together with an `Option<SimulationMethod>` carrying the
    /// RESOLVED method: `Some` only when a `Historical` source was fetched from the
    /// database on this build (resolved symbol + loaded prices + timeframe), so the
    /// caller can persist the resolution; `None` for every other case (a non-historical
    /// method, or a historical method that already carried enough embedded prices).
    #[instrument(skip(self, session), level = "debug")]
    async fn create_random_walk(
        &self,
        session: &Session,
    ) -> Result<(RandomWalk<Positive, OptionChain>, Option<SimulationMethod>), ChainError> {
        let params = &session.parameters;

        // Resolve the simulation method. A Historical source with a missing or
        // insufficient embedded price series triggers a database fetch; the symbol and
        // start date are drawn from a SEEDED, domain-separated RNG so the same session
        // seed always loads the same series (issue #12). The resolved method is
        // returned alongside the walk so the caller can persist it.
        let (method, resolved_method): (SimulationMethod, Option<SimulationMethod>) = match &params
            .method
        {
            SimulationMethod::Historical {
                timeframe,
                prices,
                symbol,
            } => {
                if prices.is_empty() || prices.len() < params.steps {
                    // Derive the historical-selection RNG from the session seed,
                    // domain-separated from the walker's stream by a fixed salt so
                    // seeding the walk never perturbs data selection or vice versa.
                    // A session built without a seed cannot be reproducible here;
                    // fall back to entropy and warn rather than fail.
                    let mut selection_rng = match params.seed {
                        Some(seed) => StdRng::seed_from_u64(seed ^ HISTORICAL_STREAM_SALT),
                        None => {
                            warn!(
                                session_id = %session.id,
                                "historical session has no seed; data selection is not reproducible"
                            );
                            StdRng::from_rng(&mut rand::rng())
                        }
                    };

                    // load historical prices from database using the seeded RNG
                    let (resolved_symbol, loaded_prices) = self
                        .get_historical_data(symbol, timeframe, params.steps, &mut selection_rng)
                        .await?;
                    let resolved = SimulationMethod::Historical {
                        timeframe: *timeframe,
                        prices: loaded_prices,
                        symbol: Some(resolved_symbol),
                    };
                    (resolved.clone(), Some(resolved))
                } else {
                    (params.method.clone(), None)
                }
            }
            _ => (params.method.clone(), None),
        };

        // Extract parameters from session
        let initial_price = params.initial_price;
        let days_to_expiration = params.days_to_expiration;
        let volatility = params.volatility;
        let risk_free_rate = params.risk_free_rate;
        let dividend_yield = params.dividend_yield;
        let symbol = params.symbol.clone();
        let time_frame = params.time_frame;

        // Set default values if not provided
        let chain_size = params.chain_size.unwrap_or(DEFAULT_CHAIN_SIZE);
        let strike_interval = params.strike_interval;
        let skew_slope = params.skew_slope.unwrap_or(DEFAULT_SKEW_SLOPE);
        let smile_curve = params.smile_curve.unwrap_or(DEFAULT_SMILE_CURVE);
        let spread = params.spread.unwrap_or(pos_or_panic!(0.01));

        // Create option data price parameters
        let price_params = OptionDataPriceParams::new(
            Some(Box::new(initial_price)),
            Some(ExpirationDate::Days(days_to_expiration)),
            Some(risk_free_rate),
            Some(dividend_yield),
            Some(symbol.clone()),
        );

        // Create option chain build parameters
        let build_params = OptionChainBuildParams::new(
            symbol.clone(),
            Some(Positive::ONE), // Default volume
            chain_size,
            strike_interval,
            skew_slope,
            smile_curve,
            spread,
            2, // Decimal places
            price_params,
            volatility,
        );

        // Build the initial chain
        let initial_chain = OptionChain::build_chain(&build_params)
            .map_err(|e| ChainError::Internal(format!("Failed to build option chain: {}", e)))?;

        // Create walker for a random walk, seeded when the session requests
        // reproducibility so the same seed always yields the same walk
        let walker = Box::new(match params.seed {
            Some(seed) => Walker::new_with_seed(seed),
            None => Walker::new(),
        });

        // Create step parameters for a random walk
        let walk_params = WalkParams {
            size: params.steps,
            init_step: Step {
                x: Xstep::new(
                    Positive::ONE,
                    time_frame,
                    ExpirationDate::Days(days_to_expiration),
                ),
                y: Ystep::new(0, initial_chain),
            },
            walk_type: method,
            walker,
        };

        // Create the random walk
        let random_walk = RandomWalk::new(
            format!("Session_{}", session.id),
            &walk_params,
            generator_optionchain,
        )
        .map_err(|e| ChainError::Internal(format!("Failed to create random walk: {}", e)))?;

        info!(
            session_id = %session.id,
            steps = random_walk.len(),
            "Created random walk for session"
        );

        Ok((random_walk, resolved_method))
    }

    /// Removes a session's cached random walk, returning whether one was present.
    ///
    /// Driven by the session lifecycle: the manager calls this on DELETE and when an
    /// advance transitions the session to `Completed`, so a deleted or finished
    /// session does not retain its walk (issue #9). Removing an id that is not cached
    /// is a cheap no-op returning `false`.
    ///
    /// Eviction never affects reproducibility: a later re-simulate of a seeded session
    /// rebuilds the identical walk from the same seed.
    #[instrument(skip(self), level = "debug")]
    pub async fn remove_session(&self, id: &Uuid) -> bool {
        let mut cache = self.simulation_cache.lock().await;
        let removed = cache.remove(id).is_some();
        if removed {
            debug!(session_id = %id, "Evicted cached random walk");
        }
        removed
    }

    /// Returns the number of random walks currently held in the simulation cache.
    ///
    /// Read-only; used by the API layer (via the session manager) to publish the
    /// `simulation_cache_size` gauge after operations that grow or shrink the cache.
    pub async fn cache_len(&self) -> usize {
        self.simulation_cache.lock().await.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{SimulationMethod, SimulationParameters};
    use crate::utils::UuidGenerator;
    use async_trait::async_trait;
    use chrono::{DateTime, Utc};
    use mockall::predicate::*;
    use mockall::*;
    use optionstratlib::utils::TimeFrame;
    use positive::{Positive, pos_or_panic};
    use rust_decimal_macros::dec;
    use std::sync::Arc;
    use uuid::Uuid;

    // Mock for HistoricalDataRepository
    mock! {
        pub HistoricalRepository {}

        #[async_trait]
        impl HistoricalDataRepository for HistoricalRepository {
            async fn get_historical_prices(
                &self,
                symbol: &str,
                timeframe: &TimeFrame,
                start_date: &DateTime<Utc>,
                limit: usize,
            ) -> Result<Vec<Positive>, ChainError>;

            async fn list_available_symbols(&self) -> Result<Vec<String>, ChainError>;

            async fn get_date_range_for_symbol(
                &self,
                symbol: &str,
            ) -> Result<(DateTime<Utc>, DateTime<Utc>), ChainError>;
        }
    }

    // Helper function to create a test session
    fn create_test_session(id: Option<Uuid>) -> Session {
        let params = SimulationParameters {
            symbol: "TEST".to_string(),
            steps: 10,
            initial_price: pos_or_panic!(100.0),
            days_to_expiration: pos_or_panic!(30.0),
            volatility: pos_or_panic!(0.2),
            risk_free_rate: dec!(0.0),
            dividend_yield: pos_or_panic!(0.0),
            method: SimulationMethod::GeometricBrownian {
                dt: pos_or_panic!(0.004),
                drift: dec!(0.0),
                volatility: pos_or_panic!(0.2),
            },
            time_frame: TimeFrame::Day,
            chain_size: Some(10),
            strike_interval: Some(pos_or_panic!(5.0)),
            skew_slope: Some(dec!(-0.2)),
            smile_curve: Some(dec!(0.5)),
            spread: Some(pos_or_panic!(0.01)),
            seed: None,
        };

        let namespace = Uuid::parse_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap();
        let uuid_generator = UuidGenerator::new(namespace);

        let mut session = Session::new(params, &uuid_generator);
        // Override the generated ID with the provided one if it exists
        if let Some(id) = id {
            session.id = id;
        }
        session
    }

    // Helper that walks a session through every step and returns the
    // underlying price observed at each snapshot
    async fn collect_tape(simulator: &Simulator, session: &mut Session) -> Vec<Positive> {
        let steps = session.parameters.steps;
        let mut tape = Vec::with_capacity(steps);
        for step in 0..steps {
            session.current_step = step;
            if step > 0 {
                session.state = SessionState::InProgress;
            }
            let chain = simulator
                .simulate_next_step(session)
                .await
                .expect("Simulation step failed");
            tape.push(chain.underlying_price);
        }
        tape
    }

    #[tokio::test]
    async fn test_same_seed_produces_identical_tape() {
        // Complete-tape test: two sessions with identical parameters and the
        // same seed must produce the same sequence of snapshots. Distinct ids keep
        // them as independent cache entries (as real sessions always are).
        let mut session_a = create_test_session(Some(Uuid::new_v4()));
        let mut session_b = create_test_session(Some(Uuid::new_v4()));
        session_a.parameters.seed = Some(20260713);
        session_b.parameters.seed = Some(20260713);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let tape_a = collect_tape(&simulator, &mut session_a).await;
        let tape_b = collect_tape(&simulator, &mut session_b).await;

        assert_eq!(tape_a, tape_b);
    }

    #[tokio::test]
    async fn test_different_seeds_produce_different_tapes() {
        // Distinct ids keep the two walks in independent cache entries so the seeds,
        // not a shared cache slot, drive the difference.
        let mut session_a = create_test_session(Some(Uuid::new_v4()));
        let mut session_b = create_test_session(Some(Uuid::new_v4()));
        session_a.parameters.seed = Some(1);
        session_b.parameters.seed = Some(2);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let tape_a = collect_tape(&simulator, &mut session_a).await;
        let tape_b = collect_tape(&simulator, &mut session_b).await;

        assert_ne!(tape_a, tape_b);
    }

    // JumpDiffusion method with lambda_dt = intensity * dt = 1.0 * 0.004 < 1,
    // so the Bernoulli jump approximation is valid (issue #11).
    fn jump_diffusion_method() -> SimulationMethod {
        SimulationMethod::JumpDiffusion {
            dt: pos_or_panic!(0.004),
            drift: dec!(0.0),
            volatility: pos_or_panic!(0.2),
            intensity: pos_or_panic!(1.0),
            jump_mean: dec!(0.0),
            jump_volatility: pos_or_panic!(0.1),
        }
    }

    #[tokio::test]
    async fn test_jump_diffusion_same_seed_same_tape() {
        // Issue #11: the corrected Bernoulli jump draw stays deterministic —
        // two JumpDiffusion sessions with the same seed produce the identical
        // tape through the full Simulator/generator path. Distinct ids keep
        // them as independent cache entries.
        let mut session_a = create_test_session(Some(Uuid::new_v4()));
        let mut session_b = create_test_session(Some(Uuid::new_v4()));
        session_a.parameters.method = jump_diffusion_method();
        session_b.parameters.method = jump_diffusion_method();
        session_a.parameters.seed = Some(20260713);
        session_b.parameters.seed = Some(20260713);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let tape_a = collect_tape(&simulator, &mut session_a).await;
        let tape_b = collect_tape(&simulator, &mut session_b).await;

        assert_eq!(tape_a, tape_b);
    }

    #[tokio::test]
    async fn test_jump_diffusion_different_seeds_different_tapes() {
        // Distinct seeds must drive distinct JumpDiffusion tapes.
        let mut session_a = create_test_session(Some(Uuid::new_v4()));
        let mut session_b = create_test_session(Some(Uuid::new_v4()));
        session_a.parameters.method = jump_diffusion_method();
        session_b.parameters.method = jump_diffusion_method();
        session_a.parameters.seed = Some(1);
        session_b.parameters.seed = Some(2);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let tape_a = collect_tape(&simulator, &mut session_a).await;
        let tape_b = collect_tape(&simulator, &mut session_b).await;

        assert_ne!(tape_a, tape_b);
    }

    #[tokio::test]
    async fn test_remove_session_evicts_cached_walk() {
        // Issue #9: remove_session drops the cached walk and reports presence.
        let mut session = create_test_session(Some(Uuid::new_v4()));
        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        // Populate the cache via a simulate, then evict.
        simulator
            .simulate_next_step(&mut session)
            .await
            .expect("initial simulate failed");
        assert_eq!(simulator.cache_len().await, 1);

        assert!(simulator.remove_session(&session.id).await);
        assert_eq!(simulator.cache_len().await, 0);

        // Removing again is a no-op reporting absence.
        assert!(!simulator.remove_session(&session.id).await);
    }

    #[tokio::test]
    async fn test_eviction_preserves_seeded_tape() {
        // Issue #9 reproducibility guard: evicting a seeded session's walk and
        // rebuilding it from the same seed yields the identical snapshot.
        let mut session = create_test_session(Some(Uuid::new_v4()));
        session.parameters.seed = Some(20260713);
        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let before = simulator
            .simulate_next_step(&mut session)
            .await
            .expect("first simulate failed");
        assert_eq!(simulator.cache_len().await, 1);

        // Evict, then rebuild from the same seed on the next simulate.
        assert!(simulator.remove_session(&session.id).await);
        assert_eq!(simulator.cache_len().await, 0);

        let after = simulator
            .simulate_next_step(&mut session)
            .await
            .expect("rebuild simulate failed");
        assert_eq!(simulator.cache_len().await, 1);

        // The rebuilt walk reproduces the pre-eviction snapshot exactly.
        assert_eq!(before.underlying_price, after.underlying_price);
    }

    #[tokio::test]
    async fn test_enforce_capacity_evicts_least_recently_accessed() {
        // Bound logic in isolation: with three staggered entries and max 2, the
        // least-recently-accessed entry is the one evicted.
        use std::time::Duration;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };
        let mut small = create_test_session(None);
        small.parameters.steps = 2;

        let id_old = Uuid::new_v4();
        let id_mid = Uuid::new_v4();
        let id_new = Uuid::new_v4();

        let now = Instant::now();
        let mut cache: HashMap<Uuid, CacheEntry> = HashMap::new();
        cache.insert(
            id_old,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(3),
                resolved_method: None,
            },
        );
        cache.insert(
            id_mid,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(2),
                resolved_method: None,
            },
        );
        cache.insert(
            id_new,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(1),
                resolved_method: None,
            },
        );

        enforce_capacity(&mut cache, 2);

        assert_eq!(cache.len(), 2);
        assert!(
            !cache.contains_key(&id_old),
            "least-recently-accessed entry must be evicted"
        );
        assert!(cache.contains_key(&id_mid));
        assert!(cache.contains_key(&id_new));
    }

    #[tokio::test]
    async fn test_enforce_capacity_noop_when_within_bound() {
        // Below/at the bound, enforce_capacity evicts nothing.
        use std::time::Duration;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };
        let mut small = create_test_session(None);
        small.parameters.steps = 2;

        let id_a = Uuid::new_v4();
        let id_b = Uuid::new_v4();
        let now = Instant::now();
        let mut cache: HashMap<Uuid, CacheEntry> = HashMap::new();
        cache.insert(
            id_a,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(2),
                resolved_method: None,
            },
        );
        cache.insert(
            id_b,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(1),
                resolved_method: None,
            },
        );

        enforce_capacity(&mut cache, 5);
        assert_eq!(cache.len(), 2);
    }

    #[tokio::test]
    async fn test_enforce_capacity_evicts_historical_entries_like_any_other() {
        // The historical eviction pin is lifted (issue #12): an entry carrying a
        // resolved Historical method is an ordinary LRU victim, because the seeded
        // selection makes its rebuild reproduce the identical tape. With three
        // staggered entries and max 2, the oldest is evicted even though it is the
        // historical one.
        use std::time::Duration;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };
        let mut small = create_test_session(None);
        small.parameters.steps = 2;

        let id_hist_old = Uuid::new_v4();
        let id_mid = Uuid::new_v4();
        let id_new = Uuid::new_v4();

        let now = Instant::now();
        let mut cache: HashMap<Uuid, CacheEntry> = HashMap::new();
        cache.insert(
            id_hist_old,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(3),
                resolved_method: Some(SimulationMethod::Historical {
                    timeframe: TimeFrame::Day,
                    prices: vec![pos_or_panic!(100.0), pos_or_panic!(101.0)],
                    symbol: Some("SYM0".to_string()),
                }),
            },
        );
        cache.insert(
            id_mid,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(2),
                resolved_method: None,
            },
        );
        cache.insert(
            id_new,
            CacheEntry {
                walk: simulator.create_random_walk(&small).await.unwrap().0,
                last_access: now - Duration::from_secs(1),
                resolved_method: None,
            },
        );

        enforce_capacity(&mut cache, 2);

        assert_eq!(cache.len(), 2);
        assert!(
            !cache.contains_key(&id_hist_old),
            "a least-recently-accessed historical entry is evicted like any other"
        );
        assert!(cache.contains_key(&id_mid));
        assert!(cache.contains_key(&id_new));
    }

    // Helper function to create test historical data
    fn create_test_historical_data(count: usize) -> Vec<Positive> {
        let mut data = Vec::with_capacity(count);
        for i in 0..count {
            data.push(pos_or_panic!(100.0 + i as f64));
        }
        data
    }

    #[tokio::test]
    async fn test_new_simulator_without_db() {
        // Test that a simulator can be created without a database
        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        assert!(simulator.database_repo.is_none());
        assert_eq!(simulator.simulation_cache.lock().await.len(), 0);
    }

    #[tokio::test]
    async fn test_new_simulator_with_mock_db() {
        // Test simulator creation with a mock database
        let mut mock_repo = MockHistoricalRepository::new();
        mock_repo
            .expect_list_available_symbols()
            .returning(|| Ok(vec!["TEST".to_string()]));

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(mock_repo)),
        };

        assert!(simulator.database_repo.is_some());
        let symbols = simulator
            .database_repo
            .as_ref()
            .unwrap()
            .list_available_symbols()
            .await
            .unwrap();
        assert_eq!(symbols, vec!["TEST".to_string()]);
    }

    #[tokio::test]
    async fn test_simulate_next_step_new_session() {
        // Test simulating the next step for a brand new session
        let mut session = create_test_session(None);
        let session_id = session.id;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        // The first call should create a new random walk
        let result = simulator.simulate_next_step(&mut session).await;
        assert!(result.is_ok());

        // Check that the session was added to the cache
        let cache = simulator.simulation_cache.lock().await;
        assert!(cache.contains_key(&session_id));
    }

    #[tokio::test]
    async fn test_simulate_next_step_existing_session() {
        // Test simulating the next step for an existing session
        let mut session = create_test_session(None);
        let session_id = session.id;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        // First call to initialize
        let _ = simulator.simulate_next_step(&mut session).await.unwrap();

        // Update session for next step
        session.current_step = 1;
        session.state = SessionState::InProgress;

        // Second call should use the cached random walk
        let result = simulator.simulate_next_step(&mut session).await;
        assert!(result.is_ok());

        // Check that there's still only one entry in the cache
        let cache = simulator.simulation_cache.lock().await;
        assert_eq!(cache.len(), 1);
        assert!(cache.contains_key(&session_id));
    }

    #[tokio::test]
    async fn test_simulate_next_step_reinitialized_session() {
        // Test simulating with a reinitialized session
        let mut session = create_test_session(None);
        let session_id = session.id;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        // First call to initialize
        let _ = simulator.simulate_next_step(&mut session).await.unwrap();

        // Update session to reinitialized state
        session.state = SessionState::Reinitialized;

        // Next call should create a new random walk
        let result = simulator.simulate_next_step(&mut session).await;
        assert!(result.is_ok());

        // Check that there's still only one entry in the cache (the old one was replaced)
        let cache = simulator.simulation_cache.lock().await;
        assert_eq!(cache.len(), 1);
        assert!(cache.contains_key(&session_id));
    }

    #[tokio::test]
    async fn test_simulate_next_step_out_of_range() {
        // Test simulating a step that's out of range
        let mut session = create_test_session(None);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        // First call to initialize
        let _ = simulator.simulate_next_step(&mut session).await.unwrap();

        // Update session to a step beyond the total
        session.current_step = session.parameters.steps + 1;

        // This should return an error
        let result = simulator.simulate_next_step(&mut session).await;
        assert!(result.is_err());

        match result {
            Err(ChainError::SimulatorError(msg)) => {
                assert_eq!(msg, "Walker reached end of data");
            }
            _ => panic!("Expected SimulatorError"),
        }
    }

    #[tokio::test]
    async fn test_get_historical_data_with_symbol() {
        // Test getting historical data with a specified symbol
        let symbol = Some("TEST".to_string());
        let timeframe = TimeFrame::Day;
        let steps = 5;
        let expected_data = create_test_historical_data(steps);

        let mut mock_repo = MockHistoricalRepository::new();
        mock_repo
            .expect_get_date_range_for_symbol()
            .with(eq("TEST"))
            .returning(|_| Ok((Utc::now() - chrono::Duration::days(30), Utc::now())));

        mock_repo
            .expect_get_historical_prices()
            .returning(move |_, _, _, _| Ok(expected_data.clone()));

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(mock_repo)),
        };

        let mut rng = StdRng::seed_from_u64(1);
        let result = simulator
            .get_historical_data(&symbol, &timeframe, steps, &mut rng)
            .await;
        assert!(result.is_ok());

        let (resolved_symbol, data) = result.unwrap();
        // A supplied symbol is echoed back verbatim as the resolved symbol.
        assert_eq!(resolved_symbol, "TEST");
        assert_eq!(data.len(), steps);
    }

    #[tokio::test]
    async fn test_get_historical_data_without_symbol() {
        // Test getting historical data with no symbol specified (random selection)
        let symbol = None;
        let timeframe = TimeFrame::Day;
        let steps = 5;
        let expected_data = create_test_historical_data(steps);

        let mut mock_repo = MockHistoricalRepository::new();
        mock_repo
            .expect_list_available_symbols()
            .returning(|| Ok(vec!["RANDOM1".to_string(), "RANDOM2".to_string()]));

        mock_repo
            .expect_get_date_range_for_symbol()
            .returning(|_| Ok((Utc::now() - chrono::Duration::days(30), Utc::now())));

        mock_repo
            .expect_get_historical_prices()
            .returning(move |_, _, _, _| Ok(expected_data.clone()));

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(mock_repo)),
        };

        let mut rng = StdRng::seed_from_u64(1);
        let result = simulator
            .get_historical_data(&symbol, &timeframe, steps, &mut rng)
            .await;
        assert!(result.is_ok());

        let (resolved_symbol, data) = result.unwrap();
        // With no symbol supplied, one of the available symbols is chosen via the RNG.
        assert!(resolved_symbol == "RANDOM1" || resolved_symbol == "RANDOM2");
        assert_eq!(data.len(), steps);
    }

    #[tokio::test]
    async fn test_get_historical_data_no_db() {
        // Test getting historical data when no database is available
        let symbol = Some("TEST".to_string());
        let timeframe = TimeFrame::Day;
        let steps = 5;

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let mut rng = StdRng::seed_from_u64(1);
        let result = simulator
            .get_historical_data(&symbol, &timeframe, steps, &mut rng)
            .await;
        assert!(result.is_err());

        match result {
            Err(ChainError::SimulatorError(msg)) => {
                assert_eq!(msg, "Database not available");
            }
            _ => panic!("Expected SimulatorError"),
        }
    }

    #[tokio::test]
    async fn test_get_historical_data_not_enough_data() {
        // Test getting historical data when not enough data is available
        let symbol = Some("TEST".to_string());
        let timeframe = TimeFrame::Day;
        let steps = 10;
        let expected_data = create_test_historical_data(5); // Not enough data

        let mut mock_repo = MockHistoricalRepository::new();
        mock_repo
            .expect_get_date_range_for_symbol()
            .returning(|_| Ok((Utc::now() - chrono::Duration::days(30), Utc::now())));

        mock_repo
            .expect_get_historical_prices()
            .returning(move |_, _, _, _| Ok(expected_data.clone()));

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(mock_repo)),
        };

        let mut rng = StdRng::seed_from_u64(1);
        let result = simulator
            .get_historical_data(&symbol, &timeframe, steps, &mut rng)
            .await;
        assert!(result.is_err());

        match result {
            Err(ChainError::NotEnoughData(_)) => {
                // Expected error
            }
            _ => panic!("Expected NotEnoughData error"),
        }
    }

    #[tokio::test]
    async fn test_create_random_walk() {
        // Test creating a random walk for a session
        let session = create_test_session(None);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: None,
        };

        let result = simulator.create_random_walk(&session).await;
        assert!(result.is_ok());

        let (random_walk, _resolved) = result.unwrap();
        assert_eq!(random_walk.len(), session.parameters.steps);
    }

    #[tokio::test]
    async fn test_create_random_walk_historical() {
        // Test creating a random walk with historical method
        let mut session = create_test_session(None);
        let steps = 5;
        session.parameters.steps = steps;
        session.parameters.method = SimulationMethod::Historical {
            timeframe: TimeFrame::Day,
            prices: vec![], // Empty prices to trigger database fetch
            symbol: Some("TEST".to_string()),
        };

        let expected_data = create_test_historical_data(steps);

        let mut mock_repo = MockHistoricalRepository::new();
        mock_repo
            .expect_get_date_range_for_symbol()
            .returning(|_| Ok((Utc::now() - chrono::Duration::days(30), Utc::now())));

        mock_repo
            .expect_get_historical_prices()
            .returning(move |_, _, _, _| Ok(expected_data.clone()));

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(mock_repo)),
        };

        let result = simulator.create_random_walk(&session).await;
        assert!(result.is_ok());

        let (random_walk, resolved) = result.unwrap();
        assert_eq!(random_walk.len(), steps);

        // A Historical fetch resolves the method: the symbol is now Some and the
        // loaded prices are embedded so the walk is replayable without another fetch.
        match resolved {
            Some(SimulationMethod::Historical { prices, symbol, .. }) => {
                assert_eq!(symbol, Some("TEST".to_string()));
                assert_eq!(prices.len(), steps);
            }
            other => panic!("expected a resolved Historical method, got {other:?}"),
        }
    }

    // A Historical session with an empty embedded price series and no explicit
    // symbol, so both the symbol and the start date must be selected from the
    // seed-derived RNG (issue #12).
    fn historical_session(seed: u64) -> Session {
        let mut session = create_test_session(Some(Uuid::new_v4()));
        session.parameters.steps = 5;
        session.parameters.seed = Some(seed);
        session.parameters.method = SimulationMethod::Historical {
            timeframe: TimeFrame::Day,
            prices: vec![],
            symbol: None,
        };
        session
    }

    // A fully deterministic historical repository: a fixed 8-symbol universe, a fixed
    // (wide) date range, and a price series that is a pure function of the requested
    // symbol and start date. Determinism is what lets the seeded selection be observed
    // as a same-seed/same-tape property end to end.
    fn historical_mock() -> MockHistoricalRepository {
        let mut mock = MockHistoricalRepository::new();
        mock.expect_list_available_symbols()
            .returning(|| Ok((0..8).map(|i| format!("SYM{i}")).collect::<Vec<String>>()));
        mock.expect_get_date_range_for_symbol().returning(|_| {
            // Fixed range (~1157 days) so selection depends only on the seeded RNG.
            let min = DateTime::from_timestamp(1_600_000_000, 0).expect("valid min timestamp");
            let max = DateTime::from_timestamp(1_700_000_000, 0).expect("valid max timestamp");
            Ok((min, max))
        });
        mock.expect_get_historical_prices()
            .returning(|symbol, _tf, start_date, limit| {
                // Deterministic in (symbol, start_date): a different symbol OR a
                // different start date yields a different series, so a divergent
                // selection is observable in the resulting tape.
                let base: u64 = symbol.bytes().map(u64::from).sum();
                let offset = start_date.timestamp().unsigned_abs();
                let seed_val = base.wrapping_add(offset);
                let prices = (0..limit)
                    .map(|i| {
                        let step = seed_val.wrapping_add(i as u64) % 1000;
                        pos_or_panic!(100.0 + step as f64 * 0.1)
                    })
                    .collect();
                Ok(prices)
            });
        mock
    }

    #[tokio::test]
    async fn test_historical_same_seed_identical_selection_and_tape() {
        // Issue #12: two Historical sessions with the same seed must select the SAME
        // symbol and date range and therefore load the identical series, producing the
        // identical tape. Distinct ids keep them as independent cache entries.
        let seed = 20260713;
        let mut session_a = historical_session(seed);
        let mut session_b = historical_session(seed);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(historical_mock())),
        };

        let tape_a = collect_tape(&simulator, &mut session_a).await;
        let tape_b = collect_tape(&simulator, &mut session_b).await;

        assert_eq!(tape_a, tape_b);
        // The seeded selection resolved to the same symbol + embedded prices.
        assert_eq!(session_a.parameters.method, session_b.parameters.method);
    }

    #[tokio::test]
    async fn test_historical_different_seeds_diverge() {
        // Different seeds drive different historical selections (symbol and/or start
        // date), so the tapes differ. With 8 symbols and a ~1157-day range the chance
        // of both seeds picking the identical (symbol, start date) pair is negligible.
        let mut session_a = historical_session(1);
        let mut session_b = historical_session(2);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(historical_mock())),
        };

        let tape_a = collect_tape(&simulator, &mut session_a).await;
        let tape_b = collect_tape(&simulator, &mut session_b).await;

        assert_ne!(tape_a, tape_b);
    }

    #[tokio::test]
    async fn test_historical_resolution_persisted_in_session() {
        // Issue #12: the first simulate on a Historical session writes the resolved
        // source (chosen symbol + loaded prices) back into the session parameters, so
        // the manager's advance can persist it and the tape stays replayable.
        let mut session = historical_session(42);
        assert!(matches!(
            session.parameters.method,
            SimulationMethod::Historical { ref prices, symbol: None, .. } if prices.is_empty()
        ));

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(historical_mock())),
        };

        simulator
            .simulate_next_step(&mut session)
            .await
            .expect("historical simulate failed");

        match &session.parameters.method {
            SimulationMethod::Historical { prices, symbol, .. } => {
                assert!(!prices.is_empty(), "resolved prices must be embedded");
                assert!(symbol.is_some(), "resolved symbol must be recorded");
            }
            other => panic!("expected a resolved Historical method, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_peek_then_advance_applies_resolution_on_cache_hit() {
        // Peek-then-advance persistence regression: a read-only peek builds the walk
        // on ITS session copy, which is then discarded (the peek path never saves).
        // The following advance loads a fresh, still-unresolved copy from the store
        // and hits the cache. The resolution stored in the cache entry must be
        // applied to that copy too, or the advance's save would persist the original
        // unresolved method and a restart or eviction could refetch a different tape.
        let session = historical_session(42);

        let simulator = Simulator {
            simulation_cache: Arc::new(Mutex::new(HashMap::new())),
            database_repo: Some(Arc::new(historical_mock())),
        };

        // GET peek: the walk is built and cached, but the mutated session copy is
        // dropped, exactly as the manager's read-only peek path does.
        let mut peek_copy = session.clone();
        let peeked = simulator
            .simulate_next_step(&mut peek_copy)
            .await
            .expect("peek simulate failed");
        assert_eq!(simulator.cache_len().await, 1);
        drop(peek_copy);

        // POST advance: a fresh copy of the stored (unresolved) session hits the
        // cached walk. The entry's resolution must be applied to this copy as well.
        let mut advance_copy = session.clone();
        assert!(matches!(
            advance_copy.parameters.method,
            SimulationMethod::Historical { ref prices, symbol: None, .. } if prices.is_empty()
        ));
        let advanced = simulator
            .simulate_next_step(&mut advance_copy)
            .await
            .expect("advance simulate failed");

        match &advance_copy.parameters.method {
            SimulationMethod::Historical { prices, symbol, .. } => {
                assert!(
                    !prices.is_empty(),
                    "cache hit must apply the resolved prices to the served session"
                );
                assert!(
                    symbol.is_some(),
                    "cache hit must apply the resolved symbol to the served session"
                );
            }
            other => panic!("expected a resolved Historical method, got {other:?}"),
        }

        // Both serves came from the same cached walk at cursor 0.
        assert_eq!(peeked.underlying_price, advanced.underlying_price);
    }
}