sim-cli 0.23.0

CLI tool for running and comparing Solana simulator backtests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
use std::{
    collections::{BTreeMap, HashMap},
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use clap::Parser;
use console::style;
use eyre::{Context, Result};
use indicatif::{MultiProgress, ProgressBar};
use sim_cli::{
    ApiKeyArg,
    args::SimRangeArgs,
    engine::{
        self, DrivableSession, ModificationsProvider, Outcome, SessionFailure, SessionObserver,
        SlotRange, format_slot,
    },
    signals::{Interrupted, spawn_ctrlc_cursor_fix},
};
use simulator_api::{
    AccountModifications, CreateBacktestSessionRequest, REROUTE_DATASET_RETENTION_DAYS,
    RerouteAggregators, RerouteScopes, VenueTemplate, VenueTemplateReport,
    session_name::SessionName,
};
use simulator_client::{
    AvailableRange, BacktestClient, BacktestClientError, BundleKind, CreateSession,
    backtest_ws_url,
    managed::{
        ManagedBacktestSession, ManagedEvent, ManagedParallelSession, ManagedSessionError,
        ParallelSubSession, ReconnectCoordinator, StartSessionParams, SubscriptionDiagnostics,
    },
    modify_program_via_rpc, split_range,
};
use solana_address::Address;
use solana_client::nonblocking::rpc_client::RpcClient;
use tokio_util::sync::CancellationToken;
use tracing::info;

use crate::{
    output::{
        OutputEvent, RunDiagnostics, SessionCompletedRecord, SessionStartedRecord,
        SimulationMetadata, SimulationSummary,
    },
    subscription::{RecordsStore, on_account_diff_notification, on_transaction_notification},
};

const MAX_PARALLEL_SESSIONS: usize = 50;
const CREATION_TIMEOUT_SECS: u16 = 900;
/// How long the server holds a session's runtime after the control connection
/// drops, giving the managed session time to reconnect and resume. Applied to
/// both the single-session and parallel creates so the reconnect window matches.
const DISCONNECT_TIMEOUT_SECS: u16 = 180;
const ESTIMATED_MS_PER_BLOCK: u64 = 250;

/// `(program_id, elf_bytes)` pairs preloaded from disk before sessions start.
/// Read once and shared across parallel sessions to keep the file-descriptor
/// count bounded — opening the .so per-session blew through the per-process
/// fd limit when many sessions ran concurrently.
type PreloadedPrograms = Vec<(String, Vec<u8>)>;

/// Shared infrastructure threaded into every session — built once in `run()`
/// and cloned (cheaply) into each parallel session task.
#[derive(Clone)]
struct SessionInfra {
    preloaded_programs: Arc<PreloadedPrograms>,
    account_overrides: Arc<AccountModifications>,
}

impl ModificationsProvider for SessionInfra {
    fn is_empty(&self) -> bool {
        self.preloaded_programs.is_empty() && self.account_overrides.0.is_empty()
    }

    async fn build(
        &self,
        rpc: &RpcClient,
    ) -> Result<BTreeMap<Address, simulator_api::AccountData>> {
        let mut mods = self.account_overrides.0.clone();
        for (id, elf) in self.preloaded_programs.iter() {
            let m = modify_program_via_rpc(rpc, id, elf)
                .await
                .map_err(|e| eyre::eyre!("building program injection for {id}: {e}"))?;
            mods.extend(m);
        }
        Ok(mods)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum SubscriptionType {
    /// Same as `transaction`, which already includes logs. Hidden; kept so
    /// existing scripts keep working.
    #[value(hide = true)]
    Logs,
    /// Transaction records plus, for each account a transaction changes, its
    /// state before and after.
    AccountDiff,
    /// One record per transaction, with its logs and balance changes.
    Transaction,
}

#[derive(Clone)]
struct OutputSink {
    /// Per-tx records used for the trailing `summary` totals and (in
    /// account-diff mode) for matching each diff back to its tx's
    /// balance/token data. See [`RecordsStore`] for retention behavior.
    records: RecordsStore,
    /// Shared with every session's subscription managers so one run's counters
    /// aggregate across sub-sessions.
    client_diagnostics: Arc<SubscriptionDiagnostics>,
    /// Primary output channel — every event (metadata / session_started /
    /// tx / diff / summary) flows through here to the NDJSON writer task.
    output_tx: tokio::sync::mpsc::UnboundedSender<OutputEvent>,
}

impl SessionObserver for OutputSink {
    fn on_data_event(&self, event: ManagedEvent) {
        match event {
            ManagedEvent::Transaction(notification) => {
                on_transaction_notification(&self.records, &self.output_tx, *notification)
            }
            ManagedEvent::AccountDiff(notification) => {
                on_account_diff_notification(&self.records, &self.output_tx, notification)
            }
            // Other variants are handled inline in the engine's match arms.
            _ => {}
        }
    }
}

/// What a router, or your own venue, would have filled a detected swap at, priced at the
/// swap's pricing point, next to what the original swap actually did.
///
/// Grouped because none of these mean anything alone: `order_flow` gates the subsystem, and the
/// rest only shape what it asks. Every flag carries an explicit `id` and `long`, so the surface
/// is identical to when these sat loose in [`RunArgs`] — shortening a field cannot rename a flag.
#[derive(clap::Args, Debug, Clone)]
pub struct RerouteArgs {
    /// Reroute historical aggregator swaps and compare each new fill with the original swap.
    ///
    /// Each original swap is priced at its pricing point, `quote_lag_blocks` blocks before the
    /// block it executed in. `router`: the router quotes at the pricing point, and the new
    /// transaction is simulated just before the original swap, in its block. `venue`: each probe is
    /// simulated at the pricing point. Both modes also replay the original swap at the pricing
    /// point. Every simulation is discarded, so the replay is unchanged.
    ///
    /// The bare flag means `router`; `router,venue` runs both. When the run ends, the results are
    /// saved as a SQLite file kept for 30 days: the run prints its URI, and `sim datasets
    /// credentials` gives read access. With `--parallel`, each session prints its own results and
    /// saves its own file.
    #[arg(
        id = "reroute_order_flow",
        long = "reroute-order-flow",
        env = "SIMULATOR_REROUTE_ORDER_FLOW",
        value_name = "MODE",
        value_enum,
        value_delimiter = ',',
        num_args = 0..=1,
        default_missing_value = "router",
        requires_if("venue", "venue_templates")
    )]
    pub order_flow: Vec<RerouteMode>,

    /// Also reroute swaps whose original transaction failed on slippage or after the swap ran.
    /// They are reported separately from the other reroute results. Ignored without
    /// `--reroute-order-flow`. `l1` in the flag's name means the original swap.
    #[arg(
        id = "detect_failed_l1_swaps",
        value_name = "BOOL",
        long = "detect-failed-l1-swaps",
        env = "SIMULATOR_DETECT_FAILED_L1_SWAPS",
        action = clap::ArgAction::Set,
        default_value_t = false
    )]
    pub detect_failed_l1_swaps: bool,

    /// Aggregators whose historical swaps to reroute, comma-separated: `jupiter`, `okx`, `titan`,
    /// `dflow`. Both modes take only these swaps, so a run that reroutes directly to a venue must
    /// name every aggregator whose swaps it wants priced. Rerouting through the router always
    /// builds a Jupiter route, so naming another aggregator compares its swaps with Jupiter.
    /// Ignored without `--reroute-order-flow`.
    #[arg(
        id = "reroute_aggregators",
        value_name = "REROUTE_AGGREGATORS",
        long = "reroute-aggregators",
        env = "SIMULATOR_REROUTE_AGGREGATORS",
        default_value_t = RerouteAggregators::default()
    )]
    pub aggregators: RerouteAggregators,

    /// Where a swap may have run to be re-quoted, comma-separated: `top-level` (a router
    /// instruction of the transaction's own), `nested` (a router another instruction CPI'd,
    /// re-quoted on its own for a funded stand-in taker) and `venue` (a venue call no router
    /// reading owns, re-quoted the same way). Read only under `--reroute-order-flow`.
    #[arg(
        id = "reroute_scopes",
        value_name = "REROUTE_SCOPES",
        long = "reroute-scopes",
        env = "SIMULATOR_REROUTE_SCOPES",
        default_value_t = RerouteScopes::default()
    )]
    pub scopes: RerouteScopes,

    /// Also reroute atomic arbitrage (same input and output mint): the router quotes each arb leg
    /// by leg and builds it back as one circular route. An arb that can't be split into legs fails
    /// with a `cycle_*` category. Off by default: most arbs are built by searchers, so a router
    /// reroute rarely reflects how they were constructed.
    #[arg(
        id = "reroute_circular_arbs",
        long = "reroute-circular-arbs",
        env = "SIMULATOR_REROUTE_CIRCULAR_ARBS",
        requires = "reroute_order_flow"
    )]
    pub circular_arbs: bool,

    /// Extra pools for the router to consider, comma-separated. Each must exist at
    /// `--start-slot`, onchain or in `--account-overrides`. Needs `--reroute-order-flow router`.
    #[arg(
        id = "reroute_extra_markets",
        long = "reroute-extra-markets",
        env = "SIMULATOR_REROUTE_EXTRA_MARKETS",
        value_name = "POOL",
        value_delimiter = ',',
        requires = "reroute_order_flow"
    )]
    pub extra_markets: Vec<Address>,

    #[command(flatten)]
    pub venue: VenueArgs,
}

/// What `--reroute-order-flow` prices detected swaps against.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum RerouteMode {
    /// Reroute each swap through the router; the new route is simulated and
    /// discarded, and the original transaction stays in place.
    Router,
    /// Price each swap directly on a venue, using `--venue-templates`; each
    /// probe is simulated and discarded, and the original transaction stays in
    /// place.
    Venue,
}

impl RerouteArgs {
    fn enabled(&self) -> bool {
        !self.order_flow.is_empty()
    }

    fn selects(&self, mode: RerouteMode) -> bool {
        self.order_flow.contains(&mode)
    }
}

/// The template list `--venue-templates` reads. A newtype rather than the `Vec` itself: clap
/// derive treats a `Vec` field as a repeatable argument, and a file parser returning the whole
/// list panics at parse time.
#[derive(Debug, Clone)]
pub struct VenueTemplatesFile(Vec<VenueTemplate>);

/// The venue instructions `--reroute-order-flow venue` prices detected hops through, one venue
/// probe per (hop, template) match.
#[derive(clap::Args, Debug, Clone)]
pub struct VenueArgs {
    /// JSON file of venue templates, each the instruction that prices a swap directly on your
    /// venue. Needs `--reroute-order-flow venue`. Format:
    /// `https://docs.termina.technology/documentation/cli/file-formats#venue-templates`
    #[arg(
        id = "venue_templates",
        long = "venue-templates",
        value_name = "FILE",
        env = "SIMULATOR_VENUE_TEMPLATES",
        value_parser = venue_templates_from_file,
        requires = "reroute_order_flow"
    )]
    pub templates: Option<VenueTemplatesFile>,
}

const RUN_EXAMPLES: &str = "\
Examples:
  # Baseline run: record a program's transactions over a slot range
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> --program-id <PROGRAM_ID>

  # Override a program with a new program binary and collect its transactions
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
    --program-id <PROGRAM_ID> --program-so ./target/deploy/program.so

  # Split a longer range across parallel sessions
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> --parallel \\
    --program-id <PROGRAM_ID>

  # Replace account states from a file before the range runs
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
    --program-id <PROGRAM_ID> --account-overrides ./accounts.json

  # Reroute aggregator swaps through the router
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
    --program-id <PROGRAM_ID> --reroute-order-flow

  # Reroute swaps directly to your own venue
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
    --program-id <PROGRAM_ID> --reroute-order-flow venue \\
    --venue-templates ./templates.json

  # Replay recorded account state (see `sim bundle build --account-state`)
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
    --program-id <PROGRAM_ID> --replay-account-state

  # In CI: fail if any simulated outcome differs from the onchain outcome
  sim run --start-slot <START_SLOT> --end-slot <END_SLOT> \\
    --program-id <PROGRAM_ID> --fail-on-diff

Take <START_SLOT> and <END_SLOT> from `sim ranges`.";

#[derive(Parser, Debug, Clone)]
#[command(after_help = RUN_EXAMPLES)]
pub struct RunArgs {
    #[command(flatten)]
    pub api_key: ApiKeyArg,

    #[command(flatten)]
    pub range: SimRangeArgs,

    /// Split the range across up to 50 concurrent sessions. The output still
    /// goes to one file.
    #[arg(long, env = "SIMULATOR_PARALLEL", default_value_t = false)]
    pub parallel: bool,

    /// Name for this run, unique across your runs; generated when unset.
    #[arg(long)]
    pub name: Option<SessionName>,

    /// Exit with status 1 if any simulated transaction differs from its onchain
    /// outcome: a different success or failure, an execution error, or a
    /// different balance change. To compare two runs instead, use
    /// `sim compare --fail-on-diff`.
    #[arg(long, env = "SIMULATOR_FAIL_ON_DIFF", default_value_t = false)]
    pub fail_on_diff: bool,

    /// Program whose transactions to record (repeatable). Without one, the run
    /// records no transactions.
    #[arg(long, env = "SIMULATOR_PROGRAM_ID")]
    pub program_id: Vec<Address>,

    /// Program binary (.so) that replaces a `--program-id` for the run.
    /// Repeat it in the same order as `--program-id`.
    #[arg(long, env = "SIMULATOR_PROGRAM_SO")]
    pub program_so: Vec<PathBuf>,

    /// JSON file of account states, keyed by address, that replace the onchain ones at
    /// `--start-slot`. Programs are refused; replace one with `--program-so`. Format:
    /// `https://docs.termina.technology/documentation/cli/file-formats#account-overrides`
    #[arg(
        long,
        env = "SIMULATOR_ACCOUNT_OVERRIDES",
        value_name = "FILE",
        value_parser = account_overrides_from_file
    )]
    pub account_overrides: Option<AccountModifications>,

    /// File to write the run's output to, as newline-delimited JSON. Defaults to
    /// `<start_slot>_<end_slot>_baseline.ndjson`, or `_override.ndjson` when `--program-so` or
    /// `--account-overrides` is set.
    #[arg(long, env = "SIMULATOR_OUTPUT_FILE")]
    pub output_file: Option<PathBuf>,

    /// Extra compute units to add to each transaction's compute unit limit.
    /// Only transactions that set a limit (a `SetComputeUnitLimit`
    /// instruction) get them.
    #[arg(long, env = "SIMULATOR_EXTRA_COMPUTE_UNITS")]
    pub extra_compute_units: Option<u32>,

    /// What to record for each `--program-id` transaction. Defaults to
    /// `transaction`.
    #[arg(long, env = "SIMULATOR_SUBSCRIPTION", requires = "program_id")]
    pub subscription: Option<SubscriptionType>,

    /// Show logs instead of a progress bar. `RUST_LOG` sets the log level (default `info`).
    #[arg(long, default_value_t = false)]
    pub verbose: bool,

    /// Print how the run would be split into sessions and an estimated
    /// duration, then exit without running.
    #[arg(long, env = "SIMULATOR_PLAN", default_value_t = false)]
    pub plan: bool,

    #[command(flatten)]
    pub reroute: RerouteArgs,

    /// Replay account state recorded with `sim bundle build --account-state`
    /// instead of executing the range's transactions.
    ///
    /// Start at an account-state bundle's `Start Slot`, and end at or before
    /// its `End Slot`. With `--parallel`, the range is split across your
    /// account-state bundles (build several with `--bundle-size`). List them
    /// with `sim ranges --kind account-state`. A run that changes execution,
    /// such as `--extra-compute-units`, is rejected.
    #[arg(
        long,
        env = "SIMULATOR_REPLAY_ACCOUNT_STATE",
        default_value_t = false,
        conflicts_with = "extra_compute_units"
    )]
    pub replay_account_state: bool,
}

/// The template list, read from the JSON array `--venue-templates` names.
fn venue_templates_from_file(path: &str) -> Result<VenueTemplatesFile, String> {
    let raw = std::fs::read_to_string(path).map_err(|error| format!("reading {path}: {error}"))?;
    simulator_client::recipes::parse_templates(path, &raw).map(VenueTemplatesFile)
}

fn account_overrides_from_file(path: &str) -> Result<AccountModifications, String> {
    let raw = std::fs::read_to_string(path).map_err(|error| format!("reading {path}: {error}"))?;
    let overrides: AccountModifications =
        serde_json::from_str(&raw).map_err(|error| format!("parsing {path}: {error}"))?;
    if overrides.0.is_empty() {
        return Err(format!("{path}: names no accounts"));
    }
    simulator_api::decode_account_modifications(&overrides)
        .map_err(|error| format!("{path}: {error}"))?;
    Ok(overrides)
}

impl VenueArgs {
    fn templates(&self) -> Vec<VenueTemplate> {
        self.templates
            .as_ref()
            .map(|file| file.0.clone())
            .unwrap_or_default()
    }
}

impl RunArgs {
    /// Start slot, required by `run` and validated in [`validate_args`].
    fn start_slot(&self) -> u64 {
        self.range
            .bounds
            .start_slot
            .expect("range bounds validated in validate_args")
    }

    /// The requested range, rejecting an inverted one.
    fn slot_range(&self) -> Result<SlotRange> {
        SlotRange::new(self.start_slot(), self.end_slot()).map_err(Into::into)
    }

    /// End slot, required by `run` and validated in [`validate_args`].
    fn end_slot(&self) -> u64 {
        self.range
            .bounds
            .end_slot
            .expect("range bounds validated in validate_args")
    }

    /// Rerouting reads `--account-overrides` from this override, which holds each account at the
    /// file's state from the first slot on; executed transactions never read it and get the file
    /// through the first `Continue` instead.
    fn with_account_overrides(&self, create: CreateSession) -> CreateSession {
        match &self.account_overrides {
            Some(overrides) if self.reroute.enabled() => {
                let start_slot = create.start_slot;
                create.add_override(start_slot, overrides.clone())
            }
            _ => create,
        }
    }

    fn create_request(&self, range: SlotRange) -> Result<CreateBacktestSessionRequest> {
        let create = CreateSession::builder()
            .start_slot(range.start())
            .end_slot(range.end())
            .parallel(self.parallel)
            .maybe_name(self.name.clone())
            .send_summary(self.fail_on_diff || self.reroute.enabled())
            .reroute_order_flow(self.reroute.enabled())
            .detect_failed_l1_swaps(self.reroute.detect_failed_l1_swaps)
            .reroute_aggregators(self.reroute.aggregators.clone())
            .reroute_scopes(self.reroute.scopes.clone())
            .reroute_circular_arbs(self.reroute.circular_arbs)
            .reroute_requote(self.reroute.selects(RerouteMode::Router))
            .reroute_venue_templates(self.reroute.venue.templates())
            .reroute_extra_markets(self.reroute.extra_markets.iter().copied().collect())
            .replay_account_state(self.replay_account_state)
            .disconnect_timeout_secs(DISCONNECT_TIMEOUT_SECS)
            .capacity_wait_timeout_secs(CREATION_TIMEOUT_SECS)
            .maybe_extra_compute_units(self.extra_compute_units)
            .build();
        self.with_account_overrides(create)
            .into_request()
            .wrap_err("building create request")
    }
}

fn validate_args(args: &RunArgs) -> Result<()> {
    args.range.bounds.require()?;
    if !args.program_so.is_empty() {
        eyre::ensure!(
            args.program_so.len() == args.program_id.len(),
            "--program-so count ({}) must match --program-id count ({})",
            args.program_so.len(),
            args.program_id.len(),
        );
    }
    eyre::ensure!(
        args.reroute.venue.templates.is_none() || args.reroute.selects(RerouteMode::Venue),
        "--venue-templates is only read under --reroute-order-flow venue",
    );
    eyre::ensure!(
        args.reroute.extra_markets.is_empty() || args.reroute.selects(RerouteMode::Router),
        "--reroute-extra-markets is only read under --reroute-order-flow router",
    );
    Ok(())
}

/// The ranges a run tiles, and the kind of bundle they are: a replay run tiles
/// the account-state bundles it will read back, anything else the block bundles.
async fn split_inputs(
    client: &BacktestClient,
    replay_account_state: bool,
) -> Result<(Vec<AvailableRange>, BundleKind)> {
    let (ranges, kind) = if replay_account_state {
        (
            client.available_ranges_with_account_state().await,
            BundleKind::AccountState,
        )
    } else {
        (client.available_ranges().await, BundleKind::Blocks)
    };
    let ranges = ranges.map_err(|e| match e {
        BacktestClientError::HttpStatus { status, .. }
            if matches!(
                status,
                reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN
            ) =>
        {
            api_key_rejected(status)
        }
        e => eyre::eyre!("failed to fetch available ranges: {e}"),
    })?;
    Ok((ranges, kind))
}

async fn generate_plan(client: &BacktestClient, args: &RunArgs) -> Result<()> {
    let (ranges, mode) = split_inputs(client, args.replay_account_state).await?;

    let sub_ranges = split_range(&ranges, args.slot_range()?, mode)
        .map_err(|e| eyre::eyre!("cannot split range: {e}"))?;

    if sub_ranges.len() > MAX_PARALLEL_SESSIONS {
        eyre::bail!(
            "unable to generate plan: requires {} sessions but max is {MAX_PARALLEL_SESSIONS}",
            sub_ranges.len(),
        );
    }
    for window in sub_ranges.windows(2) {
        let (_, end) = window[0];
        let (next_start, _) = window[1];
        if end + 1 != next_start {
            eyre::bail!(
                "unable to generate plan: gap in data between slots {} and {}",
                format_slot(end),
                format_slot(next_start),
            );
        }
    }

    let max_slots = sub_ranges
        .iter()
        .map(|(start, end)| end.saturating_sub(*start) + 1)
        .max()
        .unwrap_or(0);
    let estimated_ms = max_slots * ESTIMATED_MS_PER_BLOCK;
    let estimated = if estimated_ms < 60 * 60 * 1000 {
        format!("~{}m", estimated_ms / 60_000)
    } else {
        format!("~{:.1}h", estimated_ms as f64 / 3_600_000.0)
    };

    println!(
        "\n{} {estimated} runtime · {} session(s)\n{} [{} → {}] · {} slots",
        style(">").cyan(),
        sub_ranges.len(),
        style(">").cyan(),
        format_slot(args.start_slot()),
        format_slot(args.end_slot()),
        format_slot(args.end_slot() - args.start_slot() + 1),
    );
    println!();
    println!(
        "{:<5} {:<20} {:<20} {:<15}",
        "#", "Start Slot", "End Slot", "Slots"
    );
    println!("{}", "-".repeat(62));
    for (i, (start, end)) in sub_ranges.iter().enumerate() {
        let slots = end.saturating_sub(*start) + 1;
        println!(
            "{:<5} {:<20} {:<20} {:<15}",
            i + 1,
            format_slot(*start),
            format_slot(*end),
            format_slot(slots),
        );
    }

    Ok(())
}

fn resolve_output_file(args: &RunArgs) -> PathBuf {
    args.output_file.clone().unwrap_or_else(|| {
        let suffix = if !args.program_so.is_empty() || args.account_overrides.is_some() {
            "override"
        } else {
            "baseline"
        };
        PathBuf::from(format!(
            "{}_{}_{}.ndjson",
            args.start_slot(),
            args.end_slot(),
            suffix
        ))
    })
}

/// Emit the `metadata` envelope first on the channel, ahead of any session output.
fn setup_output(
    output_file: &Path,
    args: &RunArgs,
) -> Result<(OutputSink, tokio::task::JoinHandle<Result<()>>)> {
    let output_writer = open_output_writer(output_file)?;
    let (output_tx, output_rx) = tokio::sync::mpsc::unbounded_channel::<OutputEvent>();
    let output_writer_handle =
        spawn_output_writer(output_file.to_path_buf(), output_writer, output_rx);

    let metadata = SimulationMetadata {
        start_slot: args.start_slot(),
        end_slot: args.end_slot(),
        program_ids: args.program_id.clone(),
        program_so: args
            .program_so
            .iter()
            .map(|p| p.display().to_string())
            .collect(),
        ran_at_unix_secs: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        // Session IDs aren't known yet — they appear on the trailing `summary`
        // line once sessions have been created.
        session_ids: Vec::new(),
    };
    let _ = output_tx.send(OutputEvent::Metadata(metadata));

    let output = OutputSink {
        records: RecordsStore::new(),
        client_diagnostics: Arc::new(SubscriptionDiagnostics::default()),
        output_tx,
    };
    Ok((output, output_writer_handle))
}

fn build_infra(args: &RunArgs) -> Result<SessionInfra> {
    let preloaded_programs: Arc<PreloadedPrograms> = Arc::new(
        args.program_id
            .iter()
            .zip(&args.program_so)
            .map(|(id, path)| {
                let elf = std::fs::read(path)
                    .with_context(|| format!("failed to read {}", path.display()))?;
                Ok((id.to_string(), elf))
            })
            .collect::<Result<_>>()?,
    );

    Ok(SessionInfra {
        preloaded_programs,
        account_overrides: Arc::new(args.account_overrides.clone().unwrap_or_default()),
    })
}

pub async fn run(args: RunArgs, url: String, cancellation: CancellationToken) -> Result<()> {
    validate_args(&args)?;

    let base_url = backtest_ws_url(&url);
    let client = sim_cli::client::new(&base_url, &args.api_key.get());

    if args.plan {
        return generate_plan(&client, &args).await;
    }

    let output_file = resolve_output_file(&args);
    let (output, output_writer_handle) = setup_output(&output_file, &args)?;
    let session_ids: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let has_deviations = Arc::new(AtomicBool::new(false));
    let infra = build_infra(&args)?;

    let args = Arc::new(args);

    spawn_ctrlc_cursor_fix();

    // Sub-ranges that did not complete, collected across the run so the tail can
    // render one de-duplicated summary rather than aborting on the first failure.
    let mut session_failures: Vec<SessionFailure> = Vec::new();
    let mut session_count = 1;

    let range = args.slot_range()?;
    let session_name = if args.parallel {
        let progress = MultiProgress::new();

        // Compute the split locally so each sub-session gets a determinate
        // `[start, end]` bar; the server uses the same shared `split_range`, so
        // the ranges match.
        let (ranges, split_mode) = split_inputs(&client, args.replay_account_state).await?;

        let sub_ranges = split_range(&ranges, range, split_mode)
            .map_err(|e| eyre::eyre!("cannot split range: {e}"))?;

        session_count = sub_ranges.len();
        info!("splitting into {session_count} parallel session(s)");
        let _ = progress.println(format!(
            "{} Splitting into {session_count} parallel session(s)",
            style(">").cyan(),
        ));

        // One display bar per sub-range, keyed by start slot. Each sub-session
        // binds to its bar by the server-authoritative range it reports, so this
        // local split only seeds the bars (a mismatch falls back to a fresh bar).
        let mut bars_by_start: HashMap<u64, ProgressBar> = HashMap::new();
        for &(start, end) in &sub_ranges {
            let bar = if args.verbose {
                ProgressBar::hidden()
            } else {
                let bar = ProgressBar::new(end.saturating_sub(start) + 1);
                bar.set_style(engine::spinner_style(start, end));
                let bar = progress.add(bar);
                bar.enable_steady_tick(Duration::from_millis(100));
                bar
            };
            bars_by_start.insert(start, bar);
        }

        let create = args.create_request(range)?;

        let parallel = match ManagedParallelSession::start_with_params(
            StartSessionParams::builder()
                .url(base_url.clone())
                .api_key(args.api_key.get())
                .create(create)
                .parent_cancel(cancellation.clone())
                .subscription_diagnostics(output.client_diagnostics.clone())
                .build(),
        )
        .await
        {
            Ok(p) => Some(p),
            Err(ManagedSessionError::Cancelled) => None,
            Err(ManagedSessionError::ApiKeyRejected(status)) => {
                return Err(api_key_rejected(status));
            }
            Err(e @ ManagedSessionError::Create(_)) => return Err(e.into()),
            Err(e) => {
                return Err(eyre::Report::new(e).wrap_err("parallel session create failed"));
            }
        };

        if let Some(parallel) = parallel {
            let run_name = parallel.control_session_name().map(str::to_owned);
            if let Some(name) = &run_name {
                progress.suspend(|| print_session_name(name));
            }
            let bars_by_start = Arc::new(bars_by_start);
            let drive = {
                let args = args.clone();
                let output = output.clone();
                let session_ids = session_ids.clone();
                let infra = infra.clone();
                let bars = bars_by_start.clone();
                let has_deviations = has_deviations.clone();
                move |session: ParallelSubSession| {
                    let args = args.clone();
                    let output = output.clone();
                    let session_ids = session_ids.clone();
                    let infra = infra.clone();
                    let bars = bars.clone();
                    let has_deviations = has_deviations.clone();
                    async move {
                        drive_parallel_sub(
                            session,
                            &args,
                            &bars,
                            &output,
                            &session_ids,
                            &infra,
                            &has_deviations,
                        )
                        .await
                    }
                }
            };
            session_failures =
                engine::run_parallel_sessions(parallel, bars_by_start, None, &cancellation, drive)
                    .await;
            run_name
        } else {
            for bar in bars_by_start.values() {
                if !bar.is_finished() {
                    bar.abandon_with_message("cancelled");
                }
            }
            None
        }
    } else {
        let bar = if args.verbose {
            ProgressBar::hidden()
        } else {
            let bar = ProgressBar::new(range.end().saturating_sub(range.start()) + 1);
            bar.set_style(engine::spinner_style(range.start(), range.end()));
            bar.set_message("starting session...");
            bar.enable_steady_tick(Duration::from_millis(100));
            bar
        };

        drive_single(
            base_url,
            args.api_key.get(),
            &args,
            &bar,
            range,
            &output,
            &session_ids,
            &infra,
            &cancellation,
            None,
            &has_deviations,
        )
        .await
        .inspect_err(|e| bar.abandon_with_message(format!("failed: {e:#}")))?
    };

    if cancellation.is_cancelled() {
        // Still close the writer cleanly so partial output is flushed to disk.
        let OutputSink { output_tx, .. } = output;
        drop(output_tx);
        let _ = output_writer_handle.await;
        return Err(Interrupted.into());
    }

    let OutputSink {
        records,
        client_diagnostics,
        output_tx,
    } = output;

    let session_ids = session_ids.lock().unwrap().clone();
    let total = records.total();
    let successes = records.successes();
    let summary = SimulationSummary {
        total_transactions: total,
        successes,
        failures: total.saturating_sub(successes),
        session_name,
        session_ids,
        diagnostics: Some(RunDiagnostics {
            received: records.received(),
            dedup_swallowed: records.dedup_swallowed(),
            malformed_dropped: records.malformed_dropped(),
            reconnects: client_diagnostics.reconnects(),
        }),
    };

    let _ = output_tx.send(OutputEvent::Summary(summary.clone()));
    drop(output_tx);
    output_writer_handle
        .await
        .context("output writer task panicked")?
        .context("output writer failed")?;

    render_outcome(
        &session_failures,
        session_count,
        &summary,
        &output_file,
        args.replay_account_state,
    )?;

    // A completed run that produced diffs is still a failure under
    // `--fail-on-diff`, even though every session finished cleanly.
    if args.fail_on_diff && has_deviations.load(Ordering::SeqCst) {
        return Err(eyre::eyre!(
            "--fail-on-diff: simulation produced diffs against the onchain outcome"
        ));
    }

    Ok(())
}

/// Render the run tail. Runs after the output writer flushed, so the printed
/// file path points at a complete file.
fn render_outcome(
    session_failures: &[SessionFailure],
    session_count: usize,
    summary: &SimulationSummary,
    output_file: &Path,
    state_only_replay: bool,
) -> Result<()> {
    if !session_failures.is_empty() {
        // De-duplicate by failure reason: identical errors across many
        // sub-ranges collapse to one line listing the affected slot ranges,
        // instead of one noisy stanza per session.
        let mut by_reason: BTreeMap<&str, Vec<(u64, u64)>> = BTreeMap::new();
        for failure in session_failures {
            by_reason
                .entry(failure.reason.as_str())
                .or_default()
                .extend(failure.range);
        }

        println!(
            "\n{} {} of {} session(s) did not complete",
            style("✖").red(),
            session_failures.len(),
            session_count,
        );
        for (reason, ranges) in &mut by_reason {
            ranges.sort_unstable();
            let slots = if ranges.is_empty() {
                String::new()
            } else {
                let list = ranges
                    .iter()
                    .map(|(s, e)| format!("{s}–{e}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!(" {}", style(format!("[slots {list}]")).dim())
            };
            println!("  {}{}", style(reason).yellow(), slots);
        }
        println!(
            "\n  Captured {} transaction(s) from the sessions that finished",
            summary.total_transactions,
        );
        println!("  Output file  : {}", output_file.display());

        // Phrased as a summary so the wrapping red mark in `main.rs` reads as a
        // total, not another per-sub-range failure line (which looked like a
        // second failure when only one sub-range failed).
        return Err(eyre::eyre!(
            "summary: {} of {} parallel sessions failed",
            session_failures.len(),
            session_count,
        ));
    }

    // State-only account-delta replay verifies no transactions (it applies
    // recorded post-states), so zero transactions is the expected, successful
    // outcome rather than a "no matching transactions" failure.
    if summary.total_transactions == 0 && !state_only_replay {
        println!(
            "\n{} Simulation finished with no transactions",
            style("⚠").yellow()
        );
        println!("  Output file  : {}", output_file.display());
        return Err(eyre::eyre!(
            "no matching transactions found in the requested slot range"
        ));
    }

    println!("\n{} Simulation complete", style("✔").green());
    println!("  Transactions : {}", summary.total_transactions);
    println!("  Successes    : {}", summary.successes);
    println!("  Failures     : {}", summary.failures);
    println!("  Output file  : {}", output_file.display());

    Ok(())
}

/// Push the session id and emit the opening `session_started` output row.
fn record_session_started<S: DrivableSession>(
    session: &S,
    range: SlotRange,
    output: &OutputSink,
    session_ids: &Arc<Mutex<Vec<String>>>,
) {
    let info = session.session_info();
    session_ids
        .lock()
        .unwrap()
        .push(info.session_id.to_string());
    info!(
        session_id = %info.session_id,
        session_name = ?info.session_name,
        task_id = ?info.task_id,
        start = range.start(),
        end = range.end(),
        "session created"
    );
    let _ = output
        .output_tx
        .send(OutputEvent::SessionStarted(SessionStartedRecord {
            session_id: info.session_id.to_string(),
            session_name: info.session_name.clone(),
            task_id: info.task_id.clone(),
            start_slot: range.start(),
            end_slot: range.end(),
        }));
}

/// Subscribe (if a program filter is set) and drive a created session to
/// completion. Reconnect, keepalive, and Up-gating on `send_continue` are
/// handled by the wrapper; this just maps events to progress and output rows.
#[allow(clippy::too_many_arguments)]
async fn subscribe_and_drive<S: DrivableSession>(
    mut session: S,
    args: &RunArgs,
    pb: &ProgressBar,
    range: SlotRange,
    advance_count: u64,
    output: &OutputSink,
    infra: &SessionInfra,
    has_deviations: &AtomicBool,
) -> Result<Outcome> {
    // Stay in spinner style until the server signals `ReadyForContinue`.
    pb.set_message("waiting for runtime");

    // AccountDiff mode runs two subscriptions in parallel: transactionSubscribe
    // (for tx records used to enrich diffs) plus accountDiffSubscribe. All
    // other modes get just transactionSubscribe.
    if !args.program_id.is_empty() {
        session.subscribe_transactions(args.program_id.clone());
        if matches!(args.subscription, Some(SubscriptionType::AccountDiff)) {
            session.subscribe_account_diffs(args.program_id.clone());
        }
    }

    let outcome =
        engine::run_session_loop(&mut session, pb, range, advance_count, infra, output).await;
    let session_id = session.session_info().session_id;
    session.shutdown().await;

    let Ok(Outcome::Completed {
        summary: Some(summary),
        ..
    }) = &outcome
    else {
        return outcome;
    };

    let _ = output
        .output_tx
        .send(OutputEvent::SessionCompleted(SessionCompletedRecord {
            session_id,
            start_slot: range.start(),
            end_slot: range.end(),
            summary: summary.clone(),
        }));

    if summary.has_deviations() {
        pb.println(format!(
            "{} Diffs detected: {}",
            style("✖").red(),
            summary.deviation_details("balance diffs", "log diffs"),
        ));
        has_deviations.store(true, Ordering::SeqCst);
    }

    if let Some(stats) = summary.reroute_stats.as_deref() {
        pb.println(format!(
            "{} Reroute: {} detected → {} rerouted → {} simulated → {} succeeded | {} filtered | {} reroute-fail",
            style("↻").cyan(),
            stats.swaps_detected,
            stats.swaps_rerouted,
            stats.swaps_simulated,
            stats.swaps_succeeded,
            stats.swaps_filtered,
            stats.requote_failures,
        ));
        if !stats.venue_template_reports.is_empty() {
            for (label, template) in &stats.venue_template_reports {
                pb.println(venue_line(label, template));
            }
            pb.println(venue_line(
                "total",
                &VenueTemplateReport {
                    matched: stats.venue_matched,
                    outcomes: stats.venue_outcomes.clone(),
                    scored: stats.venue_scored,
                    bps_total: stats.venue_bps_total,
                },
            ));
        }
        if let Some(uri) = &stats.dataset_uri {
            pb.println(format!(
                "{} Reroute tables: {uri} (published once the session shuts down, kept \
                 {REROUTE_DATASET_RETENTION_DAYS} days)",
                style("↻").cyan(),
            ));
        }
    }

    outcome
}

/// One summary line of the venue census, for a template or the total: matches, the outcome
/// breakdown, and the mean change against L1 in bps (`—` while nothing is scored). Same shape as
/// the session's `log_venue_stats` line, so the two reconcile.
fn venue_line(label: &str, report: &VenueTemplateReport) -> String {
    let VenueTemplateReport {
        matched,
        outcomes,
        scored,
        bps_total,
    } = report;
    let outcomes = match outcomes.is_empty() {
        true => "(none)".to_owned(),
        false => outcomes
            .iter()
            .map(|(outcome, n)| format!("{outcome} {n}"))
            .collect::<Vec<_>>()
            .join(", "),
    };
    let mean_bps = match *scored {
        0 => "—".to_owned(),
        scored => format!("{:+.1}", *bps_total as f64 / scored as f64),
    };
    format!(
        "{} Venue probe: {label}: {matched} matched → {outcomes} | {scored} scored, {mean_bps} bps",
        style("◆").magenta()
    )
}

fn print_session_name(name: &str) {
    eprintln!("{} Session name: {}", style(">").cyan(), style(name).bold());
}

/// Names the setting to fix: the client error deliberately doesn't, since it
/// can't know where the key came from.
fn api_key_rejected(status: reqwest::StatusCode) -> eyre::Report {
    eyre::eyre!(
        "the server rejected the API key (HTTP {status}); check SIMULATOR_API_KEY or --api-key"
    )
}

/// Create and drive a single client-side session to completion.
#[allow(clippy::too_many_arguments)]
async fn drive_single(
    base_url: String,
    api_key: String,
    args: &RunArgs,
    pb: &ProgressBar,
    range: SlotRange,
    output: &OutputSink,
    session_ids: &Arc<Mutex<Vec<String>>>,
    infra: &SessionInfra,
    parent_cancel: &CancellationToken,
    reconnect_coordinator: Option<Arc<ReconnectCoordinator>>,
    has_deviations: &AtomicBool,
) -> Result<Option<String>> {
    let advance_count = args.range.advance_count(range.start(), range.end());

    let create = args.create_request(range)?;

    let session = match ManagedBacktestSession::start_with_params(
        StartSessionParams::builder()
            .url(base_url)
            .api_key(api_key)
            .create(create)
            .parent_cancel(parent_cancel.clone())
            .subscription_diagnostics(output.client_diagnostics.clone())
            .build(),
        reconnect_coordinator,
    )
    .await
    {
        Ok(s) => s,
        Err(ManagedSessionError::Cancelled) => {
            pb.abandon_with_message("cancelled");
            return Ok(None);
        }
        Err(ManagedSessionError::ApiKeyRejected(status)) => return Err(api_key_rejected(status)),
        Err(e @ ManagedSessionError::Create(_)) => return Err(e.into()),
        Err(e) => return Err(eyre::Report::new(e).wrap_err("session create failed")),
    };

    let session_name = session.session_info().session_name.clone();
    if let Some(name) = &session_name {
        pb.suspend(|| print_session_name(name));
    }
    record_session_started(&session, range, output, session_ids);
    let outcome = subscribe_and_drive(
        session,
        args,
        pb,
        range,
        advance_count,
        output,
        infra,
        has_deviations,
    )
    .await;
    engine::finish_bar(pb, outcome).map(|()| session_name)
}

/// Drive one sub-session of a parallel run.
/// Its range comes from its grant, so bind to its pre-created bar by the range start.
#[allow(clippy::too_many_arguments)]
async fn drive_parallel_sub(
    session: ParallelSubSession,
    args: &RunArgs,
    bars: &HashMap<u64, ProgressBar>,
    output: &OutputSink,
    session_ids: &Arc<Mutex<Vec<String>>>,
    infra: &SessionInfra,
    has_deviations: &AtomicBool,
) -> std::result::Result<(), SessionFailure> {
    let range = session.range();
    let (start, end) = (range.start(), range.end());
    let pb = bars
        .get(&start)
        .cloned()
        .unwrap_or_else(ProgressBar::hidden);
    let advance_count = args.range.advance_count(start, end);

    record_session_started(&session, range, output, session_ids);

    let outcome = subscribe_and_drive(
        session,
        args,
        &pb,
        range,
        advance_count,
        output,
        infra,
        has_deviations,
    )
    .await;
    engine::finish_bar(&pb, outcome).map_err(|e| SessionFailure {
        range: Some((start, end)),
        reason: format!("{e:#}"),
    })
}

fn open_output_writer(path: &std::path::Path) -> Result<std::fs::File> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
        && !parent.exists()
    {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("could not create output directory '{}'", parent.display()))?;
    }
    std::fs::File::create(path).with_context(|| format!("could not create '{}'", path.display()))
}

fn spawn_output_writer(
    path: PathBuf,
    file: std::fs::File,
    mut rx: tokio::sync::mpsc::UnboundedReceiver<OutputEvent>,
) -> tokio::task::JoinHandle<Result<()>> {
    tokio::spawn(async move {
        use std::io::Write;
        let write_err = || format!("could not write to '{}'", path.display());
        let mut writer = std::io::BufWriter::new(file);

        while let Some(event) = rx.recv().await {
            serde_json::to_writer(&mut writer, &event).with_context(write_err)?;
            writer.write_all(b"\n").with_context(write_err)?;
            while let Ok(event) = rx.try_recv() {
                serde_json::to_writer(&mut writer, &event).with_context(write_err)?;
                writer.write_all(b"\n").with_context(write_err)?;
            }
            writer.flush().with_context(write_err)?;
        }

        writer
            .flush()
            .with_context(|| format!("could not finalize '{}'", path.display()))?;
        Ok(())
    })
}

#[cfg(test)]
mod cli_tests {
    use clap::{CommandFactory, error::ErrorKind};
    use rstest::rstest;

    use super::{CreateSession, RerouteMode, SlotRange};

    /// `clap` validates argument wiring — `requires`, `conflicts_with`, group membership — only
    /// when the command is built, so a flag renamed without its references dies at the first
    /// `--help` rather than at compile time. This is the assertion that turns that into a test
    /// failure: `direct_fill_venue` once required itself, and two flags required an id left over
    /// from a rename, which made every `sim run` invocation panic.
    #[test]
    fn the_argument_wiring_names_arguments_that_exist() {
        crate::Cli::command().debug_assert();
    }

    fn parse(extra: &[&str]) -> Result<crate::Cli, clap::Error> {
        use clap::Parser;

        let dir = tempfile::tempdir().expect("a temp dir");
        let file = template_file(dir.path(), &[TEMPLATE]);
        let overrides = overrides_file(dir.path(), &overrides_json(TOKEN_PROGRAM, false, "AAAA"));
        let extra: Vec<String> = extra
            .iter()
            .map(|arg| match *arg {
                "<FILE>" => file.clone(),
                "<OVERRIDES>" => overrides.clone(),
                arg => arg.to_owned(),
            })
            .collect();

        let base = [
            "sim",
            "run",
            "--api-key",
            "k",
            "--start-slot",
            "1",
            "--end-slot",
            "2",
        ];
        crate::Cli::try_parse_from(
            base.iter()
                .map(|arg| (*arg).to_owned())
                .chain(extra)
                .collect::<Vec<_>>(),
        )
    }

    fn run_args(extra: &[&str]) -> super::RunArgs {
        let cli = parse(extra).expect("the flags parse");
        let crate::Command::Run { args, .. } = cli.command else {
            panic!("the run subcommand");
        };
        *args
    }

    /// Pairings the parser owns, so nothing downstream has to re-derive them. Each was a
    /// hand-written check in `validate_args` first; clap states them where the flags are declared
    /// and rejects before a session is built, naming the flag that would have to appear.
    #[rstest]
    #[case::venue_without_templates(
        &["--reroute-order-flow", "venue"],
        ErrorKind::MissingRequiredArgument, "--venue-templates")]
    #[case::venue_alongside_router_without_templates(
        &["--reroute-order-flow", "router,venue"],
        ErrorKind::MissingRequiredArgument, "--venue-templates")]
    #[case::templates_without_the_feature(
        &["--venue-templates", "<FILE>"],
        ErrorKind::MissingRequiredArgument, "--reroute-order-flow")]
    #[case::an_unknown_mode(
        &["--reroute-order-flow", "requote"],
        ErrorKind::InvalidValue, "router")]
    #[case::extra_markets_without_the_feature(
        &["--reroute-extra-markets", POOL],
        ErrorKind::MissingRequiredArgument, "--reroute-order-flow")]
    #[case::a_pool_that_is_not_an_address(
        &["--reroute-order-flow", "--reroute-extra-markets", "not-a-pool"],
        ErrorKind::ValueValidation, "--reroute-extra-markets")]
    #[case::a_name_with_a_space(
        &["--name", "My Run"],
        ErrorKind::ValueValidation, "invalid session name 'My Run'")]
    fn the_parser_rejects(#[case] extra: &[&str], #[case] kind: ErrorKind, #[case] names: &str) {
        let Err(error) = parse(extra) else {
            panic!("expected a rejection");
        };
        assert_eq!(error.kind(), kind);
        assert!(error.to_string().contains(names), "{error}");
    }

    /// Clap cannot say "requires an argument to have a value", so templates next to a
    /// router-only run parse and are refused by `validate_args` instead.
    #[test]
    fn templates_without_the_venue_mode_are_refused() {
        let args = run_args(&[
            "--reroute-order-flow",
            "router",
            "--venue-templates",
            "<FILE>",
        ]);
        let error = super::validate_args(&args).expect_err("templates nothing reads");
        assert!(error.to_string().contains("--venue-templates"), "{error}");
    }

    #[test]
    fn extra_markets_outside_router_mode_are_refused() {
        let error = super::validate_args(&run_args(&[
            "--reroute-order-flow",
            "venue",
            "--venue-templates",
            "<FILE>",
            "--reroute-extra-markets",
            POOL,
        ]))
        .expect_err("refused");
        let error = error.to_string();
        assert!(
            error.contains("--reroute-extra-markets")
                && error.contains("--reroute-order-flow router"),
            "{error}"
        );
    }

    #[rstest]
    #[case::the_bare_flag(&["--reroute-order-flow"], &[RerouteMode::Router])]
    #[case::router(&["--reroute-order-flow", "router"], &[RerouteMode::Router])]
    #[case::venue(
        &["--reroute-order-flow", "venue", "--venue-templates", "<FILE>"],
        &[RerouteMode::Venue])]
    #[case::both(
        &["--reroute-order-flow", "router,venue", "--venue-templates", "<FILE>"],
        &[RerouteMode::Router, RerouteMode::Venue])]
    #[case::a_run_that_never_mentions_reroute(&[], &[])]
    #[case::router_with_extra_markets_and_overrides(
        &["--reroute-order-flow", "--reroute-extra-markets", POOL, "--account-overrides",
          "<OVERRIDES>"],
        &[RerouteMode::Router])]
    #[case::venue_with_overrides(
        &["--reroute-order-flow", "venue", "--venue-templates", "<FILE>", "--account-overrides",
          "<OVERRIDES>"],
        &[RerouteMode::Venue])]
    #[case::overrides_without_rerouting(&["--account-overrides", "<OVERRIDES>"], &[])]
    #[case::parallel_with_extra_markets_and_overrides(
        &["--reroute-order-flow", "--parallel", "--reroute-extra-markets", POOL,
          "--account-overrides", "<OVERRIDES>"],
        &[RerouteMode::Router])]
    fn the_parser_accepts(#[case] extra: &[&str], #[case] modes: &[RerouteMode]) {
        let args = run_args(extra);
        super::validate_args(&args).expect("a complete reroute request");
        assert_eq!(args.reroute.order_flow, modes);
    }

    /// Grouping these into [`RerouteArgs`] and [`VenueArgs`] is an internal move: the fields
    /// dropped their `reroute_` prefixes, so only the explicit `id` and `long` keep the flags
    /// callable — and `requires` referring to them resolvable.
    #[test]
    fn the_grouped_flags_reach_their_fields() {
        let args = run_args(&[
            "--reroute-order-flow",
            "venue",
            "--detect-failed-l1-swaps",
            "true",
            "--reroute-aggregators",
            "titan",
            "--reroute-scopes",
            "nested",
            "--reroute-circular-arbs",
            "--reroute-extra-markets",
            &format!("{POOL},{OVERRIDDEN}"),
            "--venue-templates",
            "<FILE>",
        ]);
        assert!(args.reroute.enabled());
        assert!(!args.reroute.selects(RerouteMode::Router));
        assert!(args.reroute.detect_failed_l1_swaps);
        assert!(args.reroute.circular_arbs);
        assert_eq!(args.reroute.scopes.to_string(), "nested");
        assert_eq!(
            args.reroute
                .extra_markets
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>(),
            [POOL, OVERRIDDEN]
        );
        let templates = args.reroute.venue.templates();
        assert_eq!(templates.len(), 1);
        assert_eq!(templates[0].label, "t");
        assert_eq!(templates[0].mode, simulator_api::SwapMode::ExactIn);
    }

    const TEMPLATE: &str = r#"{
      "label": "t",
      "mode": "ExactIn",
      "inputMint": "So11111111111111111111111111111111111111112",
      "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
      "instruction": {
        "programId": "11111111111111111111111111111111",
        "accounts": [
          {"address": "11111111111111111111111111111111", "writable": true, "signer": true},
          {"address": "11111111111111111111111111111111", "writable": true},
          {"address": "11111111111111111111111111111111", "writable": true}
        ],
        "data": {"data": "AAAAAAAAAAA=", "encoding": "base64"}
      },
      "amountOffset": 0,
      "taker": {"user": [0], "inputTokenAccount": 1, "outputTokenAccount": 2}
    }"#;

    const POOL: &str = "So11111111111111111111111111111111111111112";
    const OVERRIDDEN: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
    const TOKEN_PROGRAM: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";

    fn overrides_json(owner: &str, executable: bool, data: &str) -> String {
        format!(
            r#"{{"{OVERRIDDEN}": {{"data": ["{data}", "base64"], "executable": {executable},
              "lamports": 1461600, "owner": "{owner}", "rentEpoch": 0, "space": 3}}}}"#
        )
    }

    fn overrides_file(dir: &std::path::Path, contents: &str) -> String {
        let path = dir.join("overrides.json");
        std::fs::write(&path, contents).expect("writing the file");
        path.to_string_lossy().into_owned()
    }

    /// Writes `templates` as the array `--venue-templates` reads and returns the path.
    fn template_file(dir: &std::path::Path, templates: &[&str]) -> String {
        let path = dir.join("venue.json");
        std::fs::write(&path, format!("[{}]", templates.join(","))).expect("writing the file");
        path.to_string_lossy().into_owned()
    }

    #[test]
    fn an_object_shaped_spec_is_refused_naming_the_file() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("old-spec.json");
        std::fs::write(&path, r#"{"aggregator":"router-a","venue":"venue-a"}"#)
            .expect("writing the spec file");
        let path = path.to_string_lossy().into_owned();
        let error =
            super::venue_templates_from_file(&path).expect_err("an object is not a template list");
        assert!(
            error.contains(&path) && error.contains("expected a sequence"),
            "{error}"
        );
    }

    #[rstest]
    #[case::duplicate_labels(&[TEMPLATE, TEMPLATE], "appears more than once")]
    #[case::no_templates(&[], "names no templates")]
    fn a_template_list_is_screened_before_a_session_is_built(
        #[case] templates: &[&str],
        #[case] reason: &str,
    ) {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = template_file(dir.path(), templates);
        let error = super::venue_templates_from_file(&path).expect_err("screened");
        assert!(error.contains(&path) && error.contains(reason), "{error}");
    }

    #[rstest]
    #[case::no_accounts("{}", "names no accounts")]
    #[case::not_a_map("[]", "parsing")]
    #[case::executable(&overrides_json(TOKEN_PROGRAM, true, "AAAA"), "executable/program")]
    #[case::program_owned(
        &overrides_json("BPFLoaderUpgradeab1e11111111111111111111111", false, "AAAA"),
        "executable/program")]
    #[case::data_that_is_not_base64(
        &overrides_json(TOKEN_PROGRAM, false, "!!"),
        "invalid account data")]
    fn account_overrides_are_screened_before_a_session_is_built(
        #[case] contents: &str,
        #[case] reason: &str,
    ) {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = overrides_file(dir.path(), contents);
        let error = super::account_overrides_from_file(&path).expect_err("screened");
        assert!(error.contains(&path) && error.contains(reason), "{error}");
    }

    #[rstest]
    #[case::single(&[])]
    #[case::parallel(&["--parallel"])]
    fn the_create_request_carries_the_name(#[case] extra: &[&str]) {
        let range = SlotRange::new(7, 9).expect("a range");
        let options = run_args(&[&["--name", "My-Run"], extra].concat())
            .create_request(range)
            .expect("a create request")
            .try_into_request_options()
            .expect("a valid name");
        let name = options.name.map(|requested| requested.name.to_string());
        assert_eq!(name.as_deref(), Some("my-run"));
        assert_eq!(options.parallel, extra.contains(&"--parallel"));
    }

    #[test]
    fn the_override_file_is_scheduled_at_the_first_slot_for_rerouting() {
        let actions = |extra: &[&str]| {
            let create = CreateSession::builder().start_slot(7).end_slot(9).build();
            run_args(extra).with_account_overrides(create).actions
        };
        let [action] = actions(&["--reroute-order-flow", "--account-overrides", "<OVERRIDES>"])
            .try_into()
            .expect("one scheduled action");
        assert!(
            matches!(&action.anchor, simulator_api::ActionAnchor::BeforeSlot { slots } if slots == &[7]),
            "{:?}",
            action.anchor
        );
        assert_eq!(
            action
                .account_overrides
                .0
                .keys()
                .map(ToString::to_string)
                .collect::<Vec<_>>(),
            [OVERRIDDEN]
        );
        assert!(actions(&["--reroute-order-flow"]).is_empty());
        assert!(actions(&["--account-overrides", "<OVERRIDES>"]).is_empty());
    }

    #[test]
    fn the_override_file_is_written_with_the_first_continue() {
        use super::{ModificationsProvider, RpcClient};

        let infra = |extra: &[&str]| super::build_infra(&run_args(extra)).expect("the infra");
        assert!(infra(&[]).is_empty());

        let with_overrides = infra(&["--account-overrides", "<OVERRIDES>"]);
        assert!(!with_overrides.is_empty());
        let runtime = tokio::runtime::Runtime::new().expect("a runtime");
        let modifications = runtime
            .block_on(with_overrides.build(&RpcClient::new("http://unused".to_string())))
            .expect("the modifications");
        assert_eq!(
            modifications
                .keys()
                .map(ToString::to_string)
                .collect::<Vec<_>>(),
            [OVERRIDDEN]
        );
    }

    #[rstest]
    #[case::never_matched(0, &[], 0, 0, "0 matched → (none) | 0 scored, — bps")]
    #[case::scored(3, &[("filled", 2), ("reverted_slippage", 1)], 2, 25, "3 matched → filled 2, reverted_slippage 1 | 2 scored, +12.5 bps")]
    fn a_venue_line_renders_matches_outcomes_and_mean_bps(
        #[case] matched: u64,
        #[case] outcomes: &[(&str, u64)],
        #[case] scored: u64,
        #[case] bps_total: i64,
        #[case] expected: &str,
    ) {
        let report = simulator_api::VenueTemplateReport {
            matched,
            outcomes: outcomes
                .iter()
                .map(|(k, n)| ((*k).to_owned(), *n))
                .collect(),
            scored,
            bps_total,
        };
        let line = console::strip_ansi_codes(&super::venue_line("t", &report)).into_owned();
        assert_eq!(line, format!("◆ Venue probe: t: {expected}"));
    }
}