simulator-api 0.29.0

Wire-protocol types for the Solana simulator backtest WebSocket API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
//! Wire types for the Termina simulator's backtest API.
//!
//! This crate defines the JSON the server and its clients exchange: requests and responses on the
//! session control channel, payloads on the session's RPC endpoint, and the bodies of the HTTP
//! endpoints. It does no I/O.
//!
//! Most users want [`simulator-client`](https://docs.rs/simulator-client) instead. It sends these
//! types for you, reconnects and reattaches, and re-exports this crate as
//! `simulator_client::simulator_api`, so the versions always match. Depend on `simulator-api`
//! directly only to speak the protocol over your own transport.
//!
//! # Message envelope
//!
//! Every message on the session control channel (`wss://<host>/backtest`) is a JSON object with a
//! `method` and, when the variant carries data, `params`:
//!
//! ```json
//! {"method": "continue", "params": {"advanceCount": 10}}
//! {"method": "readyForContinue"}
//! ```
//!
//! - Requests are [`BacktestRequest`] and responses are [`BacktestResponse`]. The `method` is the
//!   variant name in camelCase.
//! - Unless `disconnectTimeoutSecs` is 0, a single session wraps what the running session streams
//!   in a [`SequencedResponse`] (unset counts: it defaults to 30), which adds a top-level sequence
//!   number, `seqId`: `{"seqId": 7, "method": "slotNotification", "params": 1234}`. Keep the last
//!   one you received: you need it to reattach.
//! - Startup `status` updates, `sessionCreated`, `sessionAttached`, `success` and errors sent before
//!   the session runs carry no `seqId`. Parse a [`SequencedResponse`] first and fall back to a bare
//!   [`BacktestResponse`].
//! - Parallel sessions report through `sessionEventV2`
//!   ([`BacktestResponse::SessionEventV2`]), which carries its own per-session `seq_id`.
//!
//! # Session lifecycle
//!
//! 1. Send `createBacktestSession` with [`CreateSessionParams`], or with
//!    [`CreateBacktestSessionRequestV1`] to name the session or split the range across parallel
//!    sessions. While the session starts, the server sends `status` updates.
//! 2. The server replies `sessionCreated` with the `session_id` and the session's RPC endpoint
//!    (`rpc_endpoint`, a path on the server's host: `/backtest/<session_id>`), then
//!    `readyForContinue`.
//! 3. Send `continue` ([`ContinueParams`]) to execute the next `advanceCount` blocks, with any user
//!    transactions and account overrides, or `continueTo` ([`ContinueToParams`]) to pause at a
//!    slot or before a batch. The server streams `status`, `slotNotification`, `paused` and
//!    `discoveryBatch`, then sends `readyForContinue` again. Answer only `readyForContinue`: a
//!    `continueTo` gets `paused` first, and answering both sends two continues.
//! 4. Between steps, read and change state through the session's RPC endpoint.
//! 5. After the last slot the server sends `completed`, with a [`SessionSummary`] when
//!    `sendSummary` was set. Send `closeBacktestSession` to end the session; the server replies
//!    `success`.
//!
//! An `error` response carries a [`BacktestError`]. [`BacktestError::is_terminal`] tells you
//! whether the session is over, and [`BacktestError::is_retryable`] whether sending the request
//! again later can succeed.
//!
//! A parallel create sends `sessionCreated` for each session, then `sessionsCreatedV2` with a
//! `control_session_id` and one `session_ids` entry per session. Drive each session with
//! `continueSessionV1`, `continueToSessionV1` and `closeSessionV1`, which name it by `sessionId`.
//! `closeSessionV1` ends one session and sends no reply. `closeBacktestSession` ends the whole
//! parallel run and closes the connection without a reply.
//!
//! **Reattach.** When the connection drops, the session waits `disconnectTimeoutSecs` for you to
//! come back: 30 seconds when unset (900 for a parallel run), at most
//! [`MAX_DISCONNECT_TIMEOUT_SECS`]. With `0`, the session ends with the connection. To reattach:
//!
//! 1. Open a new session control channel.
//! 2. Send `attachBacktestSession` with the `session_id` and the last sequence number you received
//!    as `last_sequence`. A parallel run sends `attachParallelControlSessionV2` with its
//!    `control_session_id` and `last_sequences`, one per session.
//! 3. The server replies `sessionAttached` (or `parallelSessionAttachedV2`) and replays every
//!    response after those sequence numbers.
//! 4. For a single session, rebuild your subscriptions, then send `resumeAttachedSession`; the
//!    server replies `success`. A parallel run needs no resume.
//!
//! # Wire casing
//!
//! Casing depends on where a field sits. These names are the contract and do not change.
//!
//! | Where | Casing | Examples |
//! |---|---|---|
//! | `method` names and enum values on the session control channel | camelCase | `createBacktestSession`, `readyForContinue`, `startingRuntime` |
//! | Fields declared on a [`BacktestRequest`] or [`BacktestResponse`] variant | snake_case | `session_id`, `last_sequence`, `rpc_endpoint`, `control_session_id`, `last_sequences`, `seq_id` (in `sessionEventV2`) |
//! | Fields of a params struct, such as [`CreateSessionParams`], [`ContinueParams`] or [`ScheduledAction`] | camelCase | `startSlot`, `disconnectTimeoutSecs`, `advanceCount`, `modifyAccountStates`, `sessionId` (in `continueSessionV1`) |
//! | The [`SequencedResponse`] wrapper | camelCase | `seqId` |
//! | [`BacktestError`] | camelCase variant name, snake_case fields | `{"bundleNotFound": {"start_slot": 1, "end_slot": 2}}` |
//! | HTTP request and response bodies and query parameters | snake_case, enum values too | `start_slot`, `bundle_size`, `request_id`, `"in_progress"` |
//!
//! So `sessionCreated` arrives as:
//!
//! ```json
//! {"method": "sessionCreated", "params": {"session_id": "backtest_…", "rpc_endpoint": "…"}}
//! ```
//!
//! # Encoded fields
//!
//! | Field | Encoding |
//! |---|---|
//! | [`CreateSessionParams::actions`], [`ScheduledAction::transactions`], and `slots` in a `beforeSlot` or `afterSlot` [`ActionAnchor`] | One string: base64 (standard, padded) of the zstd-compressed JSON of the whole list. Each list decompresses to at most 256 MiB. `actions` nests: each action in it keeps its own encoded `transactions` and `slots`. |
//! | Each transaction in [`ScheduledAction::transactions`] and [`ContinueParams::transactions`] | base64 of the transaction's standard wire bytes, the bytes `sendTransaction` takes, for a legacy, v0 or v1 transaction. Build it with `simulator_client::encode_transaction`. wincode writes these bytes; bincode does not: it drops a v1 transaction's version marker. |
//! | [`AccountData::data`] | [`EncodedBinary`] of the raw account bytes: `{"data": "<base64>", "encoding": "base64"}` |
//! | [`DiscoveryBatchEvent::transactions`] | [`EncodedBinary`] of a wincode-serialized `VersionedTransaction`. Decode with `simulator_client::decode_transaction`. |
//! | [`ProgramOverride::elf`] | base64 of the program binary |
//! | Addresses, mints and program IDs | base58 strings |
//! | [`AccountModifications`] | A JSON object keyed by base58 address |
//! | [`SessionId`] and [`ControlSessionId`] | `backtest_<uuid>` and `parallel_<uuid>` |
//!
//! # Modules
//!
//! | Module | Contents |
//! |---|---|
//! | crate root | Requests, responses, session parameters, scheduled actions, account overrides, errors and HTTP bodies |
//! | [`venue`] | Venue templates for rerouting directly to a venue |
//! | [`replacement`] | `replacementSubscribe` notifications |
//! | [`route_plan`] | Routes hop by hop, as the router quotes them and as transactions report them |
//! | [`reroute_report`] | Reports built from reroute results |
//! | [`mints`] | The stablecoins and major mints the reroute reports price against |
//! | [`token`] | The SPL token-account layout, for building token account overrides |
//! | [`subscribe_config`] | Options a subscription adds to its config object |
//! | [`session_name`] | Session name rules |
//! | [`usage`] | `GET /usage` bodies |
//! | [`geyser_route`] | How a gRPC client names its session |
//!
//! # Compatibility
//!
//! - If you depend on both crates, use the `simulator-api` version your `simulator-client`
//!   depends on, or reach this crate through `simulator_client::simulator_api`.
//! - A new field is added with a default, so a message without it still parses. Unknown fields
//!   are ignored.
//! - An incompatible change to a message ships as a new versioned variant or type next to the old
//!   one, such as [`CreateBacktestSessionRequestV1`] or `sessionsCreatedV2`.
//! - An unknown `method` or enum value is a parse error. A client older than the server can fail
//!   on a new response or status, so keep the client up to date.
//! - Before 1.0, a minor release can break the Rust API. The changelog lists every break.

#![warn(missing_docs)]

use std::{
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    fmt,
    num::{NonZeroU64, NonZeroUsize},
    str::FromStr,
    sync::Arc,
};

use base64::{
    DecodeError as Base64DecodeError, Engine as _, engine::general_purpose::STANDARD as BASE64,
};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use session_name::{CreateToken, InvalidSessionName, RequestedName};
use solana_account::AccountSharedData;

mod dataset_jobs;
mod datasets;
mod session_id;
mod session_type;
mod slot_range;

pub use dataset_jobs::{
    DatasetJobListResponse, DatasetJobPhase, DatasetJobRequest, DatasetJobSpec,
    DatasetJobStatusResponse, DatasetLocation, PredictTable, Progress,
};
pub use datasets::{
    DatasetContents, DatasetDate, DatasetDeleteRequest, DatasetDeleteResponse, DatasetFile,
    DatasetListQuery, DatasetListResponse, DatasetPartition, DatasetParts, DatasetScope,
    DatasetSummary, DatasetVersion, HeldSlots,
};
pub use reroute_report::SwapMode;
pub use session_id::{ControlSessionId, SessionId};
pub use session_type::SessionType;
pub use slot_range::{InvertedSlotRange, SlotRange};
/// Solana account address used throughout this API; re-exported so callers need not pin a
/// matching `solana-address` version.
pub use solana_address::Address;
/// Why a string is not a valid [`Address`]; carried by this API's parse errors.
pub use solana_address::error::ParseAddressError;
pub use venue::{
    AMOUNT_WIDTH, DerivedAccount, ParseVenueTemplateError, Seed, TakerSlots, TemplateAccount,
    TemplateInstruction, TemplateResolver, VenueTemplate,
};

#[doc(hidden)]
pub mod client_identity;
pub mod geyser_route;
pub mod mints;
pub mod replacement;
pub mod reroute_report;
pub mod route_plan;
pub mod session_name;
pub mod subscribe_config;
pub mod token;
pub mod usage;
pub mod venue;
#[doc(hidden)]
pub mod ws_compression;

/// A request you send on the session control channel.
///
/// Serialized as `{"method": "<variantName>", "params": …}`; a variant without data has no
/// `params`. Fields declared on a variant itself are snake_case on the wire.
///
/// ```
/// use simulator_api::{BacktestRequest, ContinueParams};
///
/// let next = BacktestRequest::Continue(ContinueParams {
///     advance_count: 10,
///     ..ContinueParams::default()
/// });
/// assert_eq!(
///     serde_json::to_string(&next)?,
///     r#"{"method":"continue","params":{"advanceCount":10,"transactions":[],"modifyAccountStates":{}}}"#,
/// );
/// # Ok::<(), serde_json::Error>(())
/// ```
#[allow(
    clippy::large_enum_variant,
    reason = "decoded once per message and consumed by value; boxing the create variant would \
              change every caller's construction for no measurable gain"
)]
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "method", content = "params", rename_all = "camelCase")]
pub enum BacktestRequest {
    /// `createBacktestSession`: start a session, or a parallel run.
    CreateBacktestSession(CreateBacktestSessionRequest),
    /// `continue`: execute the next blocks of a single session.
    Continue(ContinueParams),
    /// `continueTo`: run a single session up to a slot, or to just before a batch in it.
    ContinueTo(ContinueToParams),
    /// `continueSessionV1`: [`Self::Continue`] for one session of a parallel run.
    ContinueSessionV1(ContinueSessionRequestV1),
    /// `continueToSessionV1`: [`Self::ContinueTo`] for one session of a parallel run.
    ContinueToSessionV1(ContinueToSessionRequestV1),
    /// `closeBacktestSession`: end the session; the server replies `success` and closes the
    /// connection. On a parallel run it ends every session and closes the connection without a
    /// reply.
    CloseBacktestSession,
    /// `closeSessionV1`: end one session of a parallel run.
    CloseSessionV1(CloseSessionRequestV1),
    /// `attachBacktestSession`: reattach to a single session after the connection dropped. The
    /// server replies `sessionAttached`, replays what you missed, then waits for
    /// [`Self::ResumeAttachedSession`].
    AttachBacktestSession {
        /// The session to reattach to, from `sessionCreated`.
        session_id: SessionId,
        /// The last sequence number (`seqId`) you received. The server replays every response
        /// after it; `None` replays everything it still holds.
        last_sequence: Option<u64>,
    },
    /// `resumeAttachedSession`: sent after reattaching and rebuilding your subscriptions. The
    /// session stays paused until you send it.
    ResumeAttachedSession,
    /// `attachParallelControlSessionV2`: reattach to a parallel run. The server replies
    /// `parallelSessionAttachedV2` and replays each session's missed events. No resume is needed.
    AttachParallelControlSessionV2 {
        /// The parallel run to reattach to, from `sessionsCreatedV2`.
        control_session_id: ControlSessionId,
        /// The last per-session `seq_id` you received, by session.
        /// The server replays each session's events after it; a session left out replays
        /// everything the server still holds for it.
        #[serde(default)]
        last_sequences: BTreeMap<SessionId, u64>,
    },
}

/// The `params` of `createBacktestSession`, in either version. Untagged: the server tells them
/// apart by shape.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateBacktestSessionRequest {
    /// Adds a session name and parallel sessions to [`CreateSessionParams`].
    V1(CreateBacktestSessionRequestV1),
    /// [`CreateSessionParams`] alone: one unnamed session.
    V0(CreateSessionParams),
}

impl CreateBacktestSessionRequest {
    #[doc(hidden)]
    pub fn try_into_request_options(
        self,
    ) -> Result<CreateBacktestSessionRequestOptions, InvalidSessionName> {
        match self {
            Self::V0(request) => Ok(CreateBacktestSessionRequestOptions {
                request,
                parallel: false,
                name: None,
            }),
            Self::V1(CreateBacktestSessionRequestV1 {
                request,
                parallel,
                name,
                create_token,
            }) => {
                let name = name
                    .map(|name| {
                        name.try_into()
                            .map(|name| RequestedName { name, create_token })
                    })
                    .transpose()?;
                Ok(CreateBacktestSessionRequestOptions {
                    request,
                    parallel,
                    name,
                })
            }
        }
    }

    /// The session parameters and whether the range is split across parallel sessions.
    pub fn into_request_and_parallel(self) -> (CreateSessionParams, bool) {
        match self {
            Self::V0(request) => (request, false),
            Self::V1(CreateBacktestSessionRequestV1 {
                request,
                parallel,
                name: _,
                create_token: _,
            }) => (request, parallel),
        }
    }
}

impl From<CreateSessionParams> for CreateBacktestSessionRequest {
    fn from(value: CreateSessionParams) -> Self {
        Self::V0(value)
    }
}

impl From<CreateBacktestSessionRequestV1> for CreateBacktestSessionRequest {
    fn from(value: CreateBacktestSessionRequestV1) -> Self {
        Self::V1(value)
    }
}

/// The `params` of `createBacktestSession` when you name the session or split it into parallel
/// sessions. The [`CreateSessionParams`] fields sit at the same level as these.
///
/// ```no_run
/// use simulator_api::{
///     BacktestRequest, CreateBacktestSessionRequestV1, CreateSessionParams,
///     session_name::CreateToken,
/// };
///
/// let request = CreateBacktestSessionRequestV1 {
///     request: CreateSessionParams::builder()
///         .start_slot(380_000_000)
///         .end_slot(380_000_099)
///         .send_summary(true)
///         .capacity_wait_timeout_secs(900)
///         .disconnect_timeout_secs(300)
///         .build(),
///     parallel: false,
///     name: Some("sol-usdc-baseline".to_string()),
///     // Keep this request: resending it after a reconnect reclaims the name.
///     create_token: Some(CreateToken::random()),
/// };
/// let message = serde_json::to_string(&BacktestRequest::CreateBacktestSession(request.into()))?;
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateBacktestSessionRequestV1 {
    /// The session parameters, flattened into this object on the wire.
    #[serde(flatten)]
    pub request: CreateSessionParams,
    /// Split the range into one session per available bundle and run them in parallel, as
    /// [`split_range`] splits it. The server replies `sessionsCreatedV2`. Default `false`.
    #[serde(default)]
    pub parallel: bool,
    /// The session's name, or the whole parallel run's when `parallel` is set; the server picks one
    /// when unset. 1 to 100 letters, digits, `-`, `_` or `.`, starting and ending with a letter
    /// or digit. Case-insensitive: it is stored lowercased. Names are never reused, so a taken
    /// one fails with [`BacktestError::SessionNameTaken`]. See
    /// [`SessionName`](session_name::SessionName).
    // Not `SessionName`: an unparseable name would fall through the untagged enum to V0 and be lost.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Wire name `createToken`. Identifies this create request, so resending the same request
    /// after a reconnect reclaims its `name` instead of failing with
    /// [`BacktestError::SessionNameTaken`]. Make one with
    /// [`CreateToken::random`](session_name::CreateToken::random) and reuse it only for
    /// resends of this request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub create_token: Option<CreateToken>,
}

#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct CreateBacktestSessionRequestOptions {
    pub request: CreateSessionParams,
    pub parallel: bool,
    pub name: Option<RequestedName>,
}

/// The `params` of `continueSessionV1`.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinueSessionRequestV1 {
    /// Wire name `sessionId`: the session of the parallel run to continue.
    pub session_id: SessionId,
    #[allow(missing_docs)]
    pub request: ContinueParams,
}

/// The `params` of `continueToSessionV1`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinueToSessionRequestV1 {
    /// Wire name `sessionId`: the session of the parallel run to step.
    pub session_id: SessionId,
    #[allow(missing_docs)]
    pub request: ContinueToParams,
}

/// The `params` of `closeSessionV1`.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloseSessionRequestV1 {
    /// Wire name `sessionId`: the session of the parallel run to end.
    pub session_id: SessionId,
}

/// A filter registered at session creation describing which upcoming batches
/// the session should announce ahead of execution via
/// [`BacktestResponse::DiscoveryBatch`] (and its session-event twins). Each
/// filter describes an event of interest (e.g. a specific program executing);
/// the session "discovers" the batch in which that event will occur and
/// emits a `DiscoveryBatch` so the client can pause immediately before it.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
pub enum DiscoveryFilter {
    /// Discover batches containing a transaction that invokes this program.
    ProgramExecuted(#[serde_as(as = "serde_with::DisplayFromStr")] Address),
    /// Discover batches containing a market maker's write to its pricing state: a transaction
    /// that invokes one of `programs`, moves no token balance and, unless `accounts` is empty,
    /// writes one of `accounts`. Besides price updates this also matches the maker's other
    /// token-free writes, such as configuration.
    OracleUpdate {
        /// The market maker's programs.
        #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
        programs: BTreeSet<Address>,
        /// A write through a lookup table whose addresses did not resolve counts as a write to one
        /// of these, since those accounts are unknown here.
        #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
        #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
        accounts: BTreeSet<Address>,
    },
    /// Discover batches containing a transaction that invokes `program` and writes one of
    /// `accounts`, so an empty set matches nothing. A write through a lookup table whose addresses
    /// did not resolve counts, as for [`Self::OracleUpdate`].
    ProgramWrite {
        /// The program the transaction must invoke.
        #[serde_as(as = "serde_with::DisplayFromStr")]
        program: Address,
        /// Accounts the transaction must write one of.
        #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
        accounts: BTreeSet<Address>,
    },
}

/// Per-transaction facts a [`DiscoveryFilter`] can inspect when deciding
/// whether to match. Callers build this once per transaction and feed it to
/// every registered filter; new variants add fields here rather than growing
/// the [`DiscoveryFilter::matches`] signature.
#[doc(hidden)]
pub struct TxMatchContext {
    /// Programs invoked by the transaction (top-level + CPI observed in logs).
    pub invoked_programs: HashSet<Address>,
    /// Whether any token account's balance changed.
    pub moves_tokens: bool,
    /// Accounts the transaction may write, by the batcher's writability rule: its static keys and
    /// the lookup-table addresses resolved for it.
    pub written_accounts: Vec<Address>,
    /// Whether it writes through a lookup table whose addresses did not resolve, so
    /// `written_accounts` can't name them.
    pub writes_via_unresolved_lookup: bool,
}

impl DiscoveryFilter {
    /// Return `true` when this filter is satisfied by the transaction
    /// described by `ctx`.
    #[doc(hidden)]
    pub fn matches(&self, ctx: &TxMatchContext) -> bool {
        match self {
            Self::ProgramExecuted(target) => ctx.invoked_programs.contains(target),
            Self::OracleUpdate { programs, accounts } => {
                !ctx.moves_tokens
                    && ctx
                        .invoked_programs
                        .iter()
                        .any(|program| programs.contains(program))
                    && (accounts.is_empty() || writes_one_of(ctx, accounts))
            }
            Self::ProgramWrite { program, accounts } => {
                ctx.invoked_programs.contains(program) && writes_one_of(ctx, accounts)
            }
        }
    }
}

fn writes_one_of(ctx: &TxMatchContext, accounts: &BTreeSet<Address>) -> bool {
    !accounts.is_empty()
        && (ctx.writes_via_unresolved_lookup
            || ctx
                .written_accounts
                .iter()
                .any(|account| accounts.contains(account)))
}

/// Deserializes from a non-empty list of base58 addresses.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NonEmptyAccounts(BTreeSet<Address>);

impl NonEmptyAccounts {
    /// The accounts, in address order.
    pub fn iter(&self) -> impl Iterator<Item = &Address> {
        self.0.iter()
    }
}

impl Serialize for NonEmptyAccounts {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serde_with::As::<BTreeSet<serde_with::DisplayFromStr>>::serialize(&self.0, serializer)
    }
}

impl<'de> Deserialize<'de> for NonEmptyAccounts {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let accounts: BTreeSet<Address> =
            serde_with::As::<BTreeSet<serde_with::DisplayFromStr>>::deserialize(deserializer)?;
        Self::try_from(accounts).map_err(serde::de::Error::custom)
    }
}

/// A [`NonEmptyAccounts`] built from no accounts.
#[derive(Debug, thiserror::Error)]
#[error("no accounts listed")]
pub struct EmptyAccounts;

impl TryFrom<BTreeSet<Address>> for NonEmptyAccounts {
    type Error = EmptyAccounts;

    fn try_from(accounts: BTreeSet<Address>) -> Result<Self, Self::Error> {
        if accounts.is_empty() {
            Err(EmptyAccounts)
        } else {
            Ok(Self(accounts))
        }
    }
}

/// The two mints a swap trades, without a direction: a maker quotes a pair both ways, so
/// `(a, b)` and `(b, a)` are the same pair. Normalized on construction and on deserialization,
/// which is what makes the set lookup direction-agnostic. On the wire, an array of two base58
/// mints.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "[String; 2]", into = "[String; 2]")]
pub struct MintPair([Address; 2]);

impl MintPair {
    /// The pair of `one` and `other`, in either order.
    pub fn new(one: Address, other: Address) -> Self {
        Self(if one <= other {
            [one, other]
        } else {
            [other, one]
        })
    }

    /// The two mints, lower address first.
    pub fn mints(&self) -> (Address, Address) {
        (self.0[0], self.0[1])
    }
}

/// A [`MintPair`] mint that is not a valid base58 address.
#[derive(Debug, thiserror::Error)]
#[error("invalid mint {mint} in pair")]
pub struct ParseMintPairError {
    mint: String,
    source: ParseAddressError,
}

impl TryFrom<[String; 2]> for MintPair {
    type Error = ParseMintPairError;

    fn try_from([one, other]: [String; 2]) -> Result<Self, Self::Error> {
        fn parse(mint: String) -> Result<Address, ParseMintPairError> {
            Address::from_str(&mint).map_err(|source| ParseMintPairError { mint, source })
        }
        Ok(Self::new(parse(one)?, parse(other)?))
    }
}

impl From<MintPair> for [String; 2] {
    fn from(pair: MintPair) -> Self {
        let (one, other) = pair.mints();
        [one.to_string(), other.to_string()]
    }
}

/// Restricts which detected swaps are rerouted. A transaction is rerouted when at least one
/// of its swaps trades a listed pair; the rest replay unchanged, counted as `swaps_filtered`.
/// A filter with no pairs is rejected: omit the filter to reroute every pair.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RerouteFilter {
    /// A swap matches when the mints it trades are one of these pairs, either direction.
    #[serde(default)]
    pub pairs: BTreeSet<MintPair>,
}

impl RerouteFilter {
    /// An empty filter admits nothing, which creation-time validation rejects: omit the filter
    /// to admit everything.
    pub fn is_empty(&self) -> bool {
        self.pairs.is_empty()
    }

    /// Whether a swap from `input` to `output` trades a listed pair, in either direction.
    pub fn matches_mints(&self, input: &Address, output: &Address) -> bool {
        self.pairs.contains(&MintPair::new(*input, *output))
    }

    /// Whether any listed pair trades `mint`. An atomic arbitrage trades one mint with itself, so
    /// it is admitted by the book naming that mint rather than by a pair it can never match.
    pub fn mentions_mint(&self, mint: &Address) -> bool {
        self.pairs.iter().any(|pair| {
            let (one, other) = pair.mints();
            one == *mint || other == *mint
        })
    }
}

/// How an action's transactions run. Only meaningful for an action that carries
/// transactions: one that carries none is a schedule entry for `account_overrides`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ActionKind {
    /// Runs against session state without committing. Each transaction's writes are
    /// visible to the next one in the same action and to nothing else, so the replay is
    /// unaffected.
    #[default]
    Simulate,
    /// Executes and commits to the session ledger. The writes are visible to every later
    /// slot, including the historical transactions that follow — a deliberate change to
    /// the replayed world, not a simulation of one. Rejected under `replay_account_state`,
    /// where the recording restamps account state and the commit would be lost.
    Send,
}

/// Where a [`ScheduledAction`] fires.
///
/// Tagged by `at`: `{"at": "afterEverySlot", "everyNSlots": 10}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "at", rename_all = "camelCase")]
pub enum ActionAnchor {
    /// At the start of each slot, before its transactions execute and before
    /// reroute quoting. Fires the entry for the current slot, if any.
    BeforeSlot {
        /// The slots the action fires at. With transactions, one per transaction: transaction
        /// `i` fires at `slots[i]`. Encoded on the wire as base64 of the zstd-compressed JSON
        /// list.
        #[serde(default, with = "compressed")]
        slots: Vec<u64>,
    },
    /// At the end of each slot, after its transactions execute but before it
    /// finalizes. Fires the entry for the current slot, if any.
    AfterSlot {
        /// As for [`Self::BeforeSlot`].
        #[serde(default, with = "compressed")]
        slots: Vec<u64>,
    },
    /// Where `beforeSlot` fires, at every slot that is a multiple of
    /// `every_n_slots`. The whole sequence fires at each, so a sequence repeated
    /// across a range is sent once rather than once per slot. A slot that
    /// carried no block fires nothing.
    #[serde(rename_all = "camelCase")]
    BeforeEverySlot {
        /// Wire name `everyNSlots`. Default 1: every slot.
        #[serde(default = "every_slot")]
        every_n_slots: NonZeroU64,
    },
    /// Where `afterSlot` fires, at every slot that is a multiple of
    /// `every_n_slots`. The whole sequence fires at each. A slot that carried no
    /// block fires nothing.
    #[serde(rename_all = "camelCase")]
    AfterEverySlot {
        /// Wire name `everyNSlots`. Default 1: every slot.
        #[serde(default = "every_slot")]
        every_n_slots: NonZeroU64,
    },
    /// Fires entry `i` of `transactions` alone before `batches[i]`.
    BeforeBatch {
        /// Parallel to `transactions`.
        #[serde(default, with = "compressed")]
        batches: Vec<BatchPosition>,
    },
    /// Before each batch matching `filter` executes. The whole sequence fires at
    /// each matching batch.
    BeforeMatch {
        /// Which batches to fire before.
        filter: DiscoveryFilter,
    },
    /// After each batch matching `filter` commits. The whole sequence fires at
    /// each matching batch.
    AfterMatch {
        /// Which batches to fire after.
        filter: DiscoveryFilter,
    },
    /// After each batch that changed one of `accounts`, decided from the state the batch left
    /// rather than from the accounts its transactions lock. The whole sequence fires at each such
    /// batch. Only under `replayAccountState`, whose recording holds the accounts each batch
    /// changed.
    AfterChange {
        /// The accounts whose change fires the sequence.
        accounts: NonEmptyAccounts,
    },
}

const fn every_slot() -> NonZeroU64 {
    NonZeroU64::MIN
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
/// A batch of a block, by its slot and its place among the block's batches.
pub struct BatchPosition {
    /// The block's slot.
    pub slot: u64,
    /// Which of the block's batches.
    pub batch_index: u32,
}

/// Upper bound on a decompressed transactions blob, guarding the server against
/// a decompression bomb in client input. A per-slot override schedule runs about
/// 2.8 KiB a slot, so this clears a 50k-slot range with room to spare.
const MAX_ACTION_TRANSACTIONS_BYTES: u64 = 256 * 1024 * 1024;
const PROGRAM_OWNERS: [Address; 4] = [
    solana_sdk_ids::bpf_loader_upgradeable::ID,
    solana_sdk_ids::bpf_loader::ID,
    solana_sdk_ids::bpf_loader_deprecated::ID,
    solana_sdk_ids::loader_v4::ID,
];

/// serde adapter that stores any value as a base64-encoded, zstd-compressed JSON
/// blob on the wire, so transaction bytes never travel raw. Used via
/// `#[serde(with = "compressed")]` on [`ScheduledAction`]'s `transactions` field
/// and [`ActionAnchor`]'s `slots` field.
mod compressed {
    use std::io::Read;

    use base64::Engine as _;
    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};

    use super::{BASE64, MAX_ACTION_TRANSACTIONS_BYTES};

    /// zstd compression level; `0` selects zstd's default (level 3).
    const COMPRESSION_LEVEL: i32 = 0;

    pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Serialize,
        S: Serializer,
    {
        let json = serde_json::to_vec(value).map_err(serde::ser::Error::custom)?;
        let compressed = zstd::stream::encode_all(json.as_slice(), COMPRESSION_LEVEL)
            .map_err(serde::ser::Error::custom)?;
        serializer.serialize_str(&BASE64.encode(compressed))
    }

    pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
    where
        T: DeserializeOwned,
        D: Deserializer<'de>,
    {
        let blob = String::deserialize(deserializer)?;
        let compressed = BASE64
            .decode(blob.as_bytes())
            .map_err(serde::de::Error::custom)?;
        let json = decode_capped(&compressed, MAX_ACTION_TRANSACTIONS_BYTES)
            .map_err(serde::de::Error::custom)?;
        serde_json::from_slice(&json).map_err(serde::de::Error::custom)
    }

    /// Refuses a blob over `cap` rather than truncating it: reading to the cap alone leaves
    /// malformed JSON, and an untagged enum reports that as no variant matching at all.
    fn decode_capped(compressed: &[u8], cap: u64) -> std::io::Result<Vec<u8>> {
        let mut json = Vec::new();
        zstd::stream::read::Decoder::new(compressed)
            .and_then(|d| Read::take(d, cap + 1).read_to_end(&mut json))?;
        match json.len() as u64 > cap {
            true => Err(std::io::Error::other(format!(
                "decompressed blob is over the {cap} byte ceiling"
            ))),
            false => Ok(json),
        }
    }

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

        #[test]
        fn a_blob_over_the_ceiling_names_it_instead_of_truncating() {
            let compressed = zstd::stream::encode_all([b'a'; 1024].as_slice(), 0).unwrap();
            let error = decode_capped(&compressed, 64).unwrap_err();
            assert!(error.to_string().contains("64 byte ceiling"), "{error}");
        }

        #[test]
        fn a_blob_at_the_ceiling_is_kept_whole() {
            let compressed = zstd::stream::encode_all([b'a'; 64].as_slice(), 0).unwrap();
            assert_eq!(decode_capped(&compressed, 64).unwrap().len(), 64);
        }
    }
}

/// A sequence of transactions the server runs automatically during a backtest,
/// with results streamed over the `actionSubscribe` subscription.
///
/// Each transaction runs as given:
///
/// - Its signatures are not verified.
/// - Its recent blockhash is not checked, so `Hash::default()` works, unless it uses a durable
///   nonce.
/// - Nothing rejects a duplicate: the same transaction can run again, in this action or another.
/// - Its fee payer pays the fee, so it needs lamports. Fund it with `account_overrides` or an
///   earlier action.
///
/// Pass actions in [`CreateSessionParams::actions`]. These two fund a wallet at the first
/// slot, then simulate a transaction after every tenth slot and return the wallet's state:
///
/// ```no_run
/// use std::{collections::BTreeMap, num::NonZeroU64};
///
/// use simulator_api::{
///     AccountData, AccountModifications, ActionAnchor, ActionKind, Address, CreateSessionParams,
///     ScheduledAction,
/// };
///
/// /// `encoded_tx` comes from `simulator_client::encode_transaction`.
/// fn params(
///     wallet: Address,
///     encoded_tx: String,
/// ) -> Result<CreateSessionParams, std::num::TryFromIntError> {
///     let fund = ScheduledAction {
///         anchor: ActionAnchor::BeforeSlot { slots: vec![380_000_000] },
///         kind: ActionKind::Simulate,
///         transactions: Vec::new(),
///         // 10 SOL, in lamports.
///         account_overrides: AccountModifications::from(BTreeMap::from([(
///             wallet,
///             AccountData::system_account(10_000_000_000),
///         )])),
///         feeds_reroute: false,
///         return_accounts: Vec::new(),
///         label: Some("fund".to_string()),
///         resolve: None,
///         within: None,
///     };
///     let probe = ScheduledAction {
///         anchor: ActionAnchor::AfterEverySlot { every_n_slots: NonZeroU64::try_from(10_u64)? },
///         kind: ActionKind::Simulate,
///         transactions: vec![encoded_tx],
///         account_overrides: AccountModifications::default(),
///         feeds_reroute: false,
///         return_accounts: vec![wallet],
///         label: Some("probe".to_string()),
///         resolve: None,
///         within: None,
///     };
///     Ok(CreateSessionParams::builder()
///         .start_slot(380_000_000)
///         .end_slot(380_000_099)
///         .actions(vec![fund, probe])
///         .build())
/// }
/// ```
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledAction {
    /// Where the action fires.
    pub anchor: ActionAnchor,
    /// Ignored when `transactions` is empty — that action is a schedule entry, not a run.
    #[serde(default)]
    pub kind: ActionKind,
    /// Base64-encoded transactions, carried over the wire as a base64-encoded,
    /// zstd-compressed blob. For a slot anchor (`beforeSlot`/`afterSlot`),
    /// entry `i` fires at `slots[i]` — the two lists must be the same length,
    /// and repeating a slot runs its entries there in order as one sequence.
    /// For match anchors the whole list fires, in order, at each matching
    /// batch, and for every-slot anchors at each slot the cadence names. For
    /// `simulate`, each transaction's writes are visible to the next
    /// without committing to the session ledger. Empty under `feeds_reroute`
    /// makes the action declarative: `account_overrides` is then the whole payload.
    /// Encode each with `simulator_client::encode_transaction`.
    #[serde(default, with = "compressed")]
    pub transactions: Vec<String>,
    /// Account state overrides seeding the first transaction's simulation, per
    /// `simulateTransaction` `modifyAccountStates` semantics. Invalid for
    /// `kind: send`. Without transactions they are themselves the contribution to
    /// the session's override schedule, `feeds_reroute` or not.
    #[serde(default)]
    pub account_overrides: AccountModifications,
    /// Feed the account state this action ends with to the session's override schedule, where it
    /// applies from the anchored slot to reroute candidates, later scheduled actions and account
    /// reads by address, per account until a later action names the same one. Requires a
    /// `beforeSlot` anchor.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub feeds_reroute: bool,
    /// Accounts whose post-execution state to return, following
    /// `simulateTransaction` semantics; reflects cumulative state after the
    /// final transaction.
    #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
    #[serde(default)]
    pub return_accounts: Vec<Address>,
    /// Optional client tag echoed back on each `actionSubscribe` result to correlate it to this action.
    #[serde(default)]
    pub label: Option<String>,
    /// Rewrites the action's transactions from live state each time it fires. What each variant
    /// needs of them is checked only when the session starts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolve: Option<TxResolver>,
    /// Fires only at the slots of its anchor that fall within this range. Not valid on an action
    /// that contributes to the override schedule, whose `beforeSlot` slots already bound it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub within: Option<SlotRange>,
}

impl ScheduledAction {
    /// Whether the action's resulting state has to be simulated before it can be
    /// published — a slot's overrides are then unknown until the action runs.
    pub fn is_computed_override(&self) -> bool {
        self.feeds_reroute && !self.transactions.is_empty()
    }

    /// Whether firing the action asks the session's metis router.
    pub fn asks_router(&self) -> bool {
        matches!(self.resolve, Some(TxResolver::Requote { .. }))
    }

    fn validate_resolve(&self) -> Result<(), TxResolverError> {
        let Some(resolver) = &self.resolve else {
            return Ok(());
        };
        match self.kind {
            ActionKind::Send => return Err(TxResolverError::Send),
            ActionKind::Simulate => {}
        }
        match resolver {
            TxResolver::LiquidityArrays { .. } if self.transactions.len() != 1 => {
                return Err(TxResolverError::TransactionCount {
                    got: self.transactions.len(),
                });
            }
            TxResolver::QuoteStamp | TxResolver::Requote { .. } if self.transactions.is_empty() => {
                return Err(TxResolverError::NoTransactions);
            }
            TxResolver::LiquidityArrays { .. }
            | TxResolver::QuoteStamp
            | TxResolver::Requote { .. } => {}
        }
        if self.feeds_reroute {
            return Err(TxResolverError::FeedsReroute);
        }
        Ok(())
    }
}

/// Checks each action's [`ScheduledAction::resolve`] against the rest of the action, as the
/// server does when the session starts.
pub fn validate_resolvers(actions: &[ScheduledAction]) -> Result<(), ActionResolveError> {
    actions
        .iter()
        .enumerate()
        .try_for_each(|(action, scheduled)| {
            scheduled
                .validate_resolve()
                .map_err(|source| ActionResolveError { action, source })
        })
}

/// Opens a transaction outcome's `err` when the action's [`TxResolver`] failed, so nothing was
/// simulated; the outcome's `unresolved` flag is what marks one.
pub const RESOLVE_FAILURE_PREFIX: &str = "resolve: ";

/// How a [`ScheduledAction`] rewrites its transactions from live state each time it fires.
/// Only valid for `kind: simulate` and without `feeds_reroute`.
///
/// Tagged by `type`; fields are camelCase: `{"type": "liquidityArrays", "pool": "…",
/// "inputMint": "…", "arrayKeyIndices": [3, 4]}`.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
#[allow(missing_docs)]
pub enum TxResolver {
    /// Points a single-pool swap at the liquidity arrays (CLMM tick arrays) it reads at the pool's
    /// price when the action fires, instead of the ones it was built with. The action's one
    /// transaction must be v0 with no address lookup tables, and every array key index must name
    /// a static key that is neither a signer nor an invoked program.
    LiquidityArrays {
        /// The pool the swap trades against.
        #[serde_as(as = "serde_with::DisplayFromStr")]
        pool: Address,
        /// Must be one of the pool's two mints.
        #[serde_as(as = "serde_with::DisplayFromStr")]
        input_mint: Address,
        /// Indices into the transaction's static account keys holding the swap's liquidity
        /// arrays, in the order the swap reads them.
        array_key_indices: ArrayKeyIndices,
    },
    /// Re-stamps each transaction's one-step Jupiter route through a venue that prices a stale
    /// quote short (Scorch, Flux) as quoted at the slot the action fires. The transaction must
    /// carry such a route. Unlike `liquidityArrays`, a slot anchor may repeat the transaction
    /// once per slot.
    QuoteStamp,
    /// Replaces each transaction's one-step Jupiter route with the one the session's metis router
    /// quotes for these terms, for a venue whose quote stamp only its own router can issue
    /// (HumidiFi). The route is quoted ahead of the slots it fires at and reused only while its
    /// stamp is fresh, and the router's accounts must be the ones the transaction already names.
    /// Needs the metis sidecar, which the session then starts.
    Requote {
        /// The venue's program, the route's only one.
        #[serde_as(as = "serde_with::DisplayFromStr")]
        dex: Address,
        #[serde_as(as = "serde_with::DisplayFromStr")]
        input_mint: Address,
        #[serde_as(as = "serde_with::DisplayFromStr")]
        output_mint: Address,
        /// Exact-in, in input-mint base units.
        amount: u64,
        slippage_bps: u16,
    },
}

/// One or more distinct indices into a transaction's static account keys. On the wire, a JSON
/// array of numbers; build one with `ArrayKeyIndices::try_from(vec![3, 4])`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "Vec<u8>", into = "Vec<u8>")]
pub struct ArrayKeyIndices {
    first: u8,
    rest: Vec<u8>,
}

impl ArrayKeyIndices {
    /// The indices, in order.
    pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
        std::iter::once(self.first).chain(self.rest.iter().copied())
    }

    #[allow(missing_docs)]
    pub fn count(&self) -> NonZeroUsize {
        NonZeroUsize::MIN.saturating_add(self.rest.len())
    }
}

/// Why a list is not valid [`ArrayKeyIndices`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ArrayKeyIndicesError {
    #[error("no arrayKeyIndices")]
    Empty,
    #[error("arrayKeyIndex {index} repeated")]
    Duplicate { index: u8 },
}

impl TryFrom<Vec<u8>> for ArrayKeyIndices {
    type Error = ArrayKeyIndicesError;

    fn try_from(indices: Vec<u8>) -> Result<Self, Self::Error> {
        let Some((&first, rest)) = indices.split_first() else {
            return Err(ArrayKeyIndicesError::Empty);
        };
        let mut seen = [false; 256];
        match indices
            .iter()
            .find(|&&index| std::mem::replace(&mut seen[usize::from(index)], true))
        {
            Some(&index) => Err(ArrayKeyIndicesError::Duplicate { index }),
            None => Ok(Self {
                first,
                rest: rest.to_vec(),
            }),
        }
    }
}

impl From<ArrayKeyIndices> for Vec<u8> {
    fn from(indices: ArrayKeyIndices) -> Self {
        std::iter::once(indices.first).chain(indices.rest).collect()
    }
}

/// Why a [`ScheduledAction::resolve`] does not fit its action.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TxResolverError {
    /// The action has `kind: send`; resolvers only rewrite simulations.
    #[error("resolve is not valid for kind: send")]
    Send,
    /// A `liquidityArrays` action carries other than exactly one transaction.
    #[error("resolve rewrites exactly one transaction, and the action carries {got}")]
    TransactionCount {
        /// How many transactions the action carries.
        got: usize,
    },
    /// A `quoteStamp` action carries no transactions.
    #[error("resolve needs a transaction to rewrite")]
    NoTransactions,
    /// The action also sets `feedsReroute`.
    #[error("resolve cannot be combined with feedsReroute")]
    FeedsReroute,
}

/// A [`TxResolverError`] and the action it is in.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("action {action}: {source}")]
pub struct ActionResolveError {
    /// The action's index in [`CreateSessionParams::actions`].
    pub action: usize,
    /// What is wrong with it.
    #[source]
    pub source: TxResolverError,
}

/// Most pools, `markets` and `candidates` together, one [`DiagnosticProbeParams`] can name.
pub const MAX_DIAGNOSTIC_MARKETS: usize = 64;
/// Most `usdValues` one [`DiagnosticProbeParams`] can name.
pub const MAX_DIAGNOSTIC_USD_VALUES: usize = 16;
/// Most pairs one [`DiagnosticMarketPairs`] can name.
pub const MAX_DIAGNOSTIC_MARKET_PAIRS: usize = 16;

/// Probe markets through the router's `/diagnostic` endpoint as the session runs, and stream
/// the results over `diagnosticSubscribe`.
///
/// A probe reports what the router would have priced against the state it has seen, not what the
/// venue would have filled onchain. Each firing makes [`Self::fires`] round trips to the router while
/// the replay waits. Checked by [`Self::validate`] when the session is created.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticProbeParams {
    /// When to probe: `afterSlot` or `afterEverySlot` only.
    pub anchor: ActionAnchor,
    /// Market (pool) addresses to probe, no repeats; with `candidates`, 1 to
    /// [`MAX_DIAGNOSTIC_MARKETS`] in all.
    #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
    pub markets: Vec<Address>,
    /// Wire name `usdValues`: trade sizes in whole US dollars, 1 to
    /// [`MAX_DIAGNOSTIC_USD_VALUES`] of them, none 0. Each market is probed at each size.
    pub usd_values: Vec<u32>,
    /// Tag echoed back on each `diagnosticSubscribe` result.
    #[serde(default)]
    pub label: Option<String>,
    /// Markets probed only for these pairs, both ways, each input sized from a `/quote` of its
    /// mint at the slot, or by metis from `usdValues` if that fails; every other market is
    /// answered for every pair it holds.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pairs: Vec<DiagnosticMarketPairs>,
    /// Pools the router may not hold, each probed from the first fire its account exists at.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<DiagnosticCandidate>,
    /// The pairs a candidate is probed for: those of them it holds. One holding none of them is
    /// never probed.
    #[serde_as(as = "Vec<[serde_with::DisplayFromStr; 2]>")]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidate_pairs: Vec<[Address; 2]>,
}

/// A pool the router may not hold, probed for [`DiagnosticProbeParams::candidate_pairs`].
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticCandidate {
    #[serde_as(as = "serde_with::DisplayFromStr")]
    #[allow(missing_docs)]
    pub market: Address,
    /// The program owning the pool's account; on a mismatch the pool is never probed.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub owner: Address,
    /// A lookup table the pool's swaps use, if any.
    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub address_lookup_table: Option<Address>,
}

/// The mint pairs one probed market is answered for.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticMarketPairs {
    /// A market from [`DiagnosticProbeParams::markets`], named at most once.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub market: Address,
    /// 1 to [`MAX_DIAGNOSTIC_MARKET_PAIRS`] pairs of two different mints, each probed both ways.
    #[serde_as(as = "Vec<[serde_with::DisplayFromStr; 2]>")]
    pub pairs: Vec<[Address; 2]>,
}

/// Why a [`DiagnosticProbeParams`] is rejected at session creation.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum DiagnosticProbeError {
    /// `markets` and `candidates` are both empty.
    #[error("a diagnostic probe names no markets")]
    NoMarkets,
    #[error("a diagnostic probe names no usdValues")]
    NoUsdValues,
    /// `markets` and `candidates` together are longer than [`MAX_DIAGNOSTIC_MARKETS`].
    #[error("a diagnostic probe names {got} markets, over the ceiling of {MAX_DIAGNOSTIC_MARKETS}")]
    TooManyMarkets {
        /// How many pools the probe names.
        got: usize,
    },
    /// `usdValues` is longer than [`MAX_DIAGNOSTIC_USD_VALUES`].
    #[error(
        "a diagnostic probe names {got} usdValues, over the ceiling of {MAX_DIAGNOSTIC_USD_VALUES}"
    )]
    TooManyUsdValues {
        /// How many sizes the probe names.
        got: usize,
    },
    /// `usdValues` contains 0.
    #[error("a diagnostic probe names usdValue 0, which the router reads as no size at all")]
    ZeroUsdValue,
    /// A market appears twice across `markets` and `candidates`.
    #[error("a diagnostic probe names market {market} more than once")]
    DuplicateMarket { market: Address },
    /// `pairs` names a market that is not in `markets`.
    #[error("a diagnostic probe names pairs for market {market}, which it does not probe")]
    PairsOfUnprobedMarket {
        /// The market missing from `markets`.
        market: Address,
    },
    #[error("a diagnostic probe names pairs for market {market} more than once")]
    DuplicatePairsMarket { market: Address },
    /// A market's pair list is empty or longer than [`MAX_DIAGNOSTIC_MARKET_PAIRS`].
    #[error(
        "a diagnostic probe names {got} pairs for market {market}, outside \
         1..={MAX_DIAGNOSTIC_MARKET_PAIRS}"
    )]
    PairCount {
        market: Address,
        /// How many pairs it names.
        got: usize,
    },
    /// A pair names the same mint twice.
    #[error("a diagnostic probe pairs mint {mint} with itself on market {market}")]
    SelfPair { market: Address, mint: Address },
    /// `candidatePairs` is empty or longer than [`MAX_DIAGNOSTIC_MARKET_PAIRS`] while
    /// `candidates` is not.
    #[error(
        "a diagnostic probe names {got} candidate pairs for its candidates, outside \
         1..={MAX_DIAGNOSTIC_MARKET_PAIRS}"
    )]
    CandidatePairCount {
        /// How many candidate pairs it names.
        got: usize,
    },
    /// A candidate pair names the same mint twice.
    #[error("a diagnostic probe pairs mint {mint} with itself for its candidates")]
    CandidateSelfPair {
        /// The repeated mint.
        mint: Address,
    },
    /// The anchor is not `afterSlot` or `afterEverySlot`.
    #[error(
        "a diagnostic probe anchors at {anchor}; probing the router is an await, and only the \
         slot-end hook has a point for one, so only afterSlot and afterEverySlot are supported"
    )]
    UnsupportedAnchor {
        /// The anchor's wire name.
        anchor: &'static str,
    },
}

impl DiagnosticProbeParams {
    /// Round-trips one anchor costs.
    pub fn fires(&self) -> usize {
        self.pools() * self.usd_values.len()
    }

    fn pools(&self) -> usize {
        self.markets.len() + self.candidates.len()
    }

    /// Checks the probe as the server does when the session is created.
    pub fn validate(&self) -> Result<(), DiagnosticProbeError> {
        if self.pools() == 0 {
            return Err(DiagnosticProbeError::NoMarkets);
        }
        if self.usd_values.is_empty() {
            return Err(DiagnosticProbeError::NoUsdValues);
        }
        if self.pools() > MAX_DIAGNOSTIC_MARKETS {
            return Err(DiagnosticProbeError::TooManyMarkets { got: self.pools() });
        }
        if self.usd_values.len() > MAX_DIAGNOSTIC_USD_VALUES {
            return Err(DiagnosticProbeError::TooManyUsdValues {
                got: self.usd_values.len(),
            });
        }
        if self.usd_values.contains(&0) {
            return Err(DiagnosticProbeError::ZeroUsdValue);
        }
        let mut seen = HashSet::with_capacity(self.markets.len());
        if let Some(market) = self.markets.iter().find(|market| !seen.insert(**market)) {
            return Err(DiagnosticProbeError::DuplicateMarket { market: *market });
        }
        let mut paired = HashSet::with_capacity(self.pairs.len());
        for DiagnosticMarketPairs { market, pairs } in &self.pairs {
            let market = *market;
            if !seen.contains(&market) {
                return Err(DiagnosticProbeError::PairsOfUnprobedMarket { market });
            }
            if !paired.insert(market) {
                return Err(DiagnosticProbeError::DuplicatePairsMarket { market });
            }
            match pairs_fault(pairs) {
                Some(PairsFault::Count(got)) => {
                    return Err(DiagnosticProbeError::PairCount { market, got });
                }
                Some(PairsFault::SelfPair(mint)) => {
                    return Err(DiagnosticProbeError::SelfPair { market, mint });
                }
                None => {}
            }
        }
        if let Some(DiagnosticCandidate { market, .. }) = self
            .candidates
            .iter()
            .find(|candidate| !seen.insert(candidate.market))
        {
            return Err(DiagnosticProbeError::DuplicateMarket { market: *market });
        }
        if !self.candidates.is_empty() {
            match pairs_fault(&self.candidate_pairs) {
                Some(PairsFault::Count(got)) => {
                    return Err(DiagnosticProbeError::CandidatePairCount { got });
                }
                Some(PairsFault::SelfPair(mint)) => {
                    return Err(DiagnosticProbeError::CandidateSelfPair { mint });
                }
                None => {}
            }
        }
        match &self.anchor {
            ActionAnchor::AfterSlot { .. } | ActionAnchor::AfterEverySlot { .. } => Ok(()),
            ActionAnchor::BeforeSlot { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
                anchor: "beforeSlot",
            }),
            ActionAnchor::BeforeEverySlot { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
                anchor: "beforeEverySlot",
            }),
            ActionAnchor::BeforeBatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
                anchor: "beforeBatch",
            }),
            ActionAnchor::BeforeMatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
                anchor: "beforeMatch",
            }),
            ActionAnchor::AfterMatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
                anchor: "afterMatch",
            }),
            ActionAnchor::AfterChange { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
                anchor: "afterChange",
            }),
        }
    }
}

enum PairsFault {
    Count(usize),
    SelfPair(Address),
}

fn pairs_fault(pairs: &[[Address; 2]]) -> Option<PairsFault> {
    if !(1..=MAX_DIAGNOSTIC_MARKET_PAIRS).contains(&pairs.len()) {
        return Some(PairsFault::Count(pairs.len()));
    }
    pairs
        .iter()
        .find(|[a, b]| a == b)
        .map(|[mint, _]| PairsFault::SelfPair(*mint))
}

/// One ordered contribution to a slot's override state.
#[derive(Debug, Clone)]
enum OverrideContribution {
    Static(HashMap<Address, AccountSharedData>),
    Pending,
    Resolved(HashMap<Address, AccountSharedData>),
    Failed,
}

#[derive(Debug, Clone, Default)]
struct OverrideScheduleInner {
    entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>>,
    /// Every account some contribution names. The geyser rewrite path asks `active_for` about each
    /// account event it sees, and almost none are overridden; without this the miss walks every
    /// entry up to the slot.
    keys: HashSet<Address>,
}

impl OverrideScheduleInner {
    fn new(entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>>) -> Self {
        let keys = entries
            .values()
            .flatten()
            .filter_map(|(_, contribution)| match contribution {
                OverrideContribution::Static(accounts)
                | OverrideContribution::Resolved(accounts) => Some(accounts.keys().copied()),
                OverrideContribution::Pending | OverrideContribution::Failed => None,
            })
            .flatten()
            .collect();
        Self { entries, keys }
    }
}

/// Slot-keyed account overrides, carried forward per account. Clones share the same runtime
/// resolutions so the session, reroute engine, and geyser pump observe one schedule.
#[doc(hidden)]
#[derive(Debug, Clone, Default)]
pub struct OverrideSchedule {
    inner: Arc<RwLock<OverrideScheduleInner>>,
}

impl From<BTreeMap<u64, HashMap<Address, AccountSharedData>>> for OverrideSchedule {
    fn from(entries: BTreeMap<u64, HashMap<Address, AccountSharedData>>) -> Self {
        Self {
            inner: Arc::new(RwLock::new(OverrideScheduleInner::new(
                entries
                    .into_iter()
                    .map(|(slot, accounts)| {
                        (slot, vec![(0, OverrideContribution::Static(accounts))])
                    })
                    .collect(),
            ))),
        }
    }
}

impl OverrideSchedule {
    pub fn is_empty(&self) -> bool {
        self.inner.read().entries.is_empty()
    }

    /// Slots at which some entry activates, ascending.
    pub fn slots(&self) -> impl Iterator<Item = u64> + '_ {
        self.inner
            .read()
            .entries
            .keys()
            .copied()
            .collect::<Vec<_>>()
            .into_iter()
    }

    /// Everything active at `slot`, resolved per account.
    pub fn active_at(&self, slot: u64) -> HashMap<Address, AccountSharedData> {
        self.inner.read().entries.range(..=slot).fold(
            HashMap::new(),
            |mut active, (_, contributions)| {
                active.extend(fold_contributions(contributions));
                active
            },
        )
    }

    /// The override active for `key` at `slot`, if any.
    pub fn active_for(&self, key: &Address, slot: u64) -> Option<AccountSharedData> {
        let inner = self.inner.read();
        if !inner.keys.contains(key) {
            return None;
        }
        inner
            .entries
            .range(..=slot)
            .rev()
            .find_map(|(_, contributions)| {
                contributions
                    .iter()
                    .rev()
                    .find_map(|(_, contribution)| match contribution {
                        OverrideContribution::Static(accounts)
                        | OverrideContribution::Resolved(accounts) => accounts.get(key).cloned(),
                        OverrideContribution::Pending | OverrideContribution::Failed => None,
                    })
            })
    }

    /// Final values activated in `(after, up_to]`, deduplicated per account.
    pub fn newly_active(
        &self,
        after: Option<u64>,
        up_to: u64,
    ) -> Vec<(Address, AccountSharedData)> {
        let lower = after.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded);
        self.inner
            .read()
            .entries
            .range((lower, std::ops::Bound::Included(up_to)))
            .flat_map(|(_, contributions)| fold_contributions(contributions))
            .collect::<HashMap<_, _>>()
            .into_iter()
            .collect()
    }

    /// Resolve one computed contribution; `None` marks the action failed, contributing no accounts.
    /// Counting failures is the caller's job — it also sees the errors returned here.
    pub fn resolve(
        &self,
        slot: u64,
        action_index: u32,
        accounts: Option<HashMap<Address, AccountSharedData>>,
    ) -> Result<(), String> {
        let mut inner = self.inner.write();
        let OverrideScheduleInner { entries, keys } = &mut *inner;
        let contribution = entries
            .get_mut(&slot)
            .and_then(|contributions| {
                contributions
                    .iter_mut()
                    .find(|(index, _)| *index == action_index)
                    .map(|(_, contribution)| contribution)
            })
            .ok_or_else(|| {
                format!("override action {action_index} has no contribution at slot {slot}")
            })?;
        if !matches!(contribution, OverrideContribution::Pending) {
            return Err(format!(
                "override action {action_index} at slot {slot} is not pending"
            ));
        }
        *contribution = match accounts {
            Some(accounts) => {
                keys.extend(accounts.keys().copied());
                OverrideContribution::Resolved(accounts)
            }
            None => OverrideContribution::Failed,
        };
        Ok(())
    }
}

fn fold_contributions(
    contributions: &[(u32, OverrideContribution)],
) -> HashMap<Address, AccountSharedData> {
    let mut accounts = HashMap::new();
    for (_, contribution) in contributions {
        match contribution {
            OverrideContribution::Static(next) | OverrideContribution::Resolved(next) => {
                accounts.extend(next.iter().map(|(key, account)| (*key, account.clone())));
            }
            OverrideContribution::Pending | OverrideContribution::Failed => {}
        }
    }
    accounts
}

/// Validate and compile the publishing actions into the slot-keyed override schedule every
/// simulation surface consumes — reroute candidates and scheduled-action runs alike. Static
/// contributions are immediately available; computed contributions retain their action order as
/// pending entries until the action scheduler resolves them.
///
/// `feeds_reroute` actions contribute their end-state; a declarative override action (account
/// overrides, no transactions) contributes without the flag, so overrides stay usable in a
/// session that never reroutes.
fn decode_override_actions(actions: &[ScheduledAction]) -> Result<OverrideSchedule, String> {
    let mut entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>> = BTreeMap::new();
    for (action_index, action) in actions.iter().enumerate().filter(|(_, action)| {
        action.feeds_reroute
            || (action.transactions.is_empty() && !action.account_overrides.0.is_empty())
    }) {
        // Without this an action that meant to send would feed the schedule instead, silently.
        if action.kind == ActionKind::Send {
            return Err("account overrides are not valid for kind: send".to_string());
        }
        if action.transactions.is_empty() && action.account_overrides.0.is_empty() {
            return Err(
                "feedsReroute needs something to feed: transactions to simulate, or \
                 accountOverrides"
                    .to_string(),
            );
        }
        let ActionAnchor::BeforeSlot { slots } = &action.anchor else {
            return Err("scheduled account overrides require a beforeSlot anchor".to_string());
        };
        if action.within.is_some() {
            return Err("scheduled account overrides cannot be bounded by within".to_string());
        }
        let accounts = decode_account_modifications(&action.account_overrides)?;
        let contribution = if action.transactions.is_empty() {
            OverrideContribution::Static(accounts)
        } else {
            OverrideContribution::Pending
        };
        // Deduplicated: a slot repeated in one action would push two contributions sharing an
        // action index, and `resolve` only ever finds the first — leaving the second pending.
        for slot in slots.iter().copied().collect::<BTreeSet<_>>() {
            entries
                .entry(slot)
                .or_default()
                .push((action_index as u32, contribution.clone()));
        }
    }
    Ok(OverrideSchedule {
        inner: Arc::new(RwLock::new(OverrideScheduleInner::new(entries))),
    })
}

/// Decode account overrides into engine override form, rejecting
/// executable/program accounts (cached program binaries make program overrides
/// stale).
#[allow(
    deprecated,
    reason = "`PROGRAM_OWNERS` remains the canonical loader-owner list"
)]
#[doc(hidden)]
pub fn decode_account_modifications(
    modifications: &AccountModifications,
) -> Result<HashMap<Address, AccountSharedData>, String> {
    modifications
        .0
        .iter()
        .map(|(address, data)| {
            let account = data
                .to_account()
                .map_err(|error| format!("invalid account data for {address}: {error}"))?;
            if account.executable || PROGRAM_OWNERS.contains(&account.owner) {
                return Err(format!(
                    "overriding executable/program accounts is not supported (account {address})"
                ));
            }
            Ok((*address, AccountSharedData::from(account)))
        })
        .collect()
}

/// Server-side ceiling on [`CreateSessionParams::disconnect_timeout_secs`]:
/// 900 seconds (15 minutes). A larger request is silently clamped to this, so
/// clients must keep their reconnect budget under it to survive a detach.
pub const MAX_DISCONNECT_TIMEOUT_SECS: u16 = 900;

/// A router whose historical swaps a session can reroute. Lowercase on the wire; parsing
/// ignores case and surrounding spaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", try_from = "String")]
pub enum SwapAggregator {
    /// `jupiter`, the default.
    Jupiter,
    /// `okx`.
    Okx,
    /// `titan`.
    Titan,
    /// `dflow`.
    Dflow,
}

impl SwapAggregator {
    /// Every aggregator a session can reroute, in `Ord` order.
    pub const ALL: [Self; 4] = [Self::Jupiter, Self::Okx, Self::Titan, Self::Dflow];

    /// Matches the serialized spelling and the aggregator labels in the per-reroute rows.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Jupiter => "jupiter",
            Self::Okx => "okx",
            Self::Titan => "titan",
            Self::Dflow => "dflow",
        }
    }
}

impl std::fmt::Display for SwapAggregator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a string is not a [`SwapAggregator`] or a [`RerouteAggregators`] list.
#[derive(Debug, thiserror::Error)]
pub enum ParseAggregatorError {
    /// Not one of `jupiter`, `okx`, `titan` or `dflow`; carries the input.
    #[error("unknown swap aggregator {0:?}; expected one of jupiter, okx, titan, dflow")]
    Unknown(String),
    /// A session that admits no aggregator drives the whole reroute apparatus and reroutes nothing.
    #[error("name at least one aggregator (jupiter, okx, titan, dflow)")]
    NoAggregator,
}

impl TryFrom<String> for SwapAggregator {
    type Error = ParseAggregatorError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl std::str::FromStr for SwapAggregator {
    type Err = ParseAggregatorError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "jupiter" => Ok(Self::Jupiter),
            "okx" => Ok(Self::Okx),
            "titan" => Ok(Self::Titan),
            "dflow" => Ok(Self::Dflow),
            _ => Err(ParseAggregatorError::Unknown(s.to_string())),
        }
    }
}

/// The aggregators a session reroutes. Jupiter alone by default: the router builds Jupiter replacements,
/// so other aggregators' order flow is a cross-router counterfactual a session asks for
/// deliberately. On the wire, an array such as `["jupiter", "okx"]`. Also parsed from one
/// comma-separated string (`"jupiter,okx"`) so a flag or an env var carries the set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RerouteAggregators(BTreeSet<SwapAggregator>);

impl Default for RerouteAggregators {
    fn default() -> Self {
        Self([SwapAggregator::Jupiter].into_iter().collect())
    }
}

impl RerouteAggregators {
    /// The set of `aggregators`; repeats collapse.
    pub fn new(aggregators: impl IntoIterator<Item = SwapAggregator>) -> Self {
        Self(aggregators.into_iter().collect())
    }

    /// Admits every aggregator; the default is Jupiter alone.
    pub fn all() -> Self {
        Self::new(SwapAggregator::ALL)
    }

    #[allow(missing_docs)]
    pub fn contains(&self, aggregator: SwapAggregator) -> bool {
        self.0.contains(&aggregator)
    }

    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl std::fmt::Display for RerouteAggregators {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut aggregators = self.0.iter();
        if let Some(first) = aggregators.next() {
            write!(f, "{first}")?;
        }
        aggregators.try_for_each(|aggregator| write!(f, ",{aggregator}"))
    }
}

impl std::str::FromStr for RerouteAggregators {
    type Err = ParseAggregatorError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let aggregators: BTreeSet<SwapAggregator> = s
            .split(',')
            .filter(|aggregator| !aggregator.trim().is_empty())
            .map(str::parse)
            .collect::<Result<_, _>>()?;
        if aggregators.is_empty() {
            return Err(ParseAggregatorError::NoAggregator);
        }
        Ok(Self(aggregators))
    }
}

/// Where a rerouted swap ran in its transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", try_from = "String")]
pub enum SwapScope {
    /// A router instruction of the transaction's own, rerouted in its place.
    TopLevel,
    /// A router another instruction CPI'd, rerouted on its own for a funded stand-in taker.
    Nested,
    /// A venue call no router reading owns, read from the transaction's flows and re-quoted on
    /// its own the same way.
    Venue,
}

impl SwapScope {
    /// Matches the serialized spelling (`top-level` or `nested`).
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::TopLevel => "top-level",
            Self::Nested => "nested",
            Self::Venue => "venue",
        }
    }
}

impl std::fmt::Display for SwapScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a string is not a [`SwapScope`] or a [`RerouteScopes`] list.
#[derive(Debug, thiserror::Error)]
pub enum ParseScopeError {
    /// Not `top-level`, `nested` or `venue`; carries the input.
    #[error("unknown swap scope {0:?}; expected one of top-level, nested, venue")]
    Unknown(String),
    /// A session that admits no scope reroutes nothing.
    #[error("name at least one swap scope (top-level, nested, venue)")]
    NoScope,
}

impl TryFrom<String> for SwapScope {
    type Error = ParseScopeError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl std::str::FromStr for SwapScope {
    type Err = ParseScopeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "top-level" => Ok(Self::TopLevel),
            "nested" => Ok(Self::Nested),
            "venue" => Ok(Self::Venue),
            _ => Err(ParseScopeError::Unknown(s.to_string())),
        }
    }
}

/// Which swaps a session reroutes, by where they ran. Top-level router instructions alone by
/// default. Parsed from one comma-separated string so a flag or an env var carries the set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RerouteScopes(BTreeSet<SwapScope>);

impl Default for RerouteScopes {
    fn default() -> Self {
        Self([SwapScope::TopLevel].into_iter().collect())
    }
}

impl RerouteScopes {
    /// The set of `scopes`; repeats collapse.
    pub fn new(scopes: impl IntoIterator<Item = SwapScope>) -> Self {
        Self(scopes.into_iter().collect())
    }

    #[allow(missing_docs)]
    pub fn contains(&self, scope: SwapScope) -> bool {
        self.0.contains(&scope)
    }

    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Whether this is [`Self::default`] (`top-level` alone).
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

impl std::fmt::Display for RerouteScopes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut scopes = self.0.iter();
        if let Some(first) = scopes.next() {
            write!(f, "{first}")?;
        }
        scopes.try_for_each(|scope| write!(f, ",{scope}"))
    }
}

impl std::str::FromStr for RerouteScopes {
    type Err = ParseScopeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let scopes: BTreeSet<SwapScope> = s
            .split(',')
            .filter(|scope| !scope.trim().is_empty())
            .map(str::parse)
            .collect::<Result<_, _>>()?;
        if scopes.is_empty() {
            return Err(ParseScopeError::NoScope);
        }
        Ok(Self(scopes))
    }
}

/// Rerouting historical swaps through the router: each admitted swap is rerouted and the
/// routed transaction is *simulated* just before the original executes — never
/// committed, so the replay is unaffected. Each simulation reads the state of the batch its
/// original belonged to; reroutes never observe one another.
///
/// Presence is the switch, which makes "a knob but no rerouting" unrepresentable rather than a
/// validation error.
///
/// Silent defaults: an empty object (`"reroute": {}`) reroutes Jupiter's swaps only, every pair,
/// through the router (`requote: true`), with no venue templates, no failed original swaps and no
/// atomic arbitrage.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RerouteParams {
    /// Whose original swaps to reroute. Default: Jupiter's alone. This also limits rerouting
    /// directly to a venue: only swaps from these aggregators reach the templates.
    #[serde(default)]
    pub aggregators: RerouteAggregators,
    /// Where an admitted swap may have run to be rerouted. [`Self::aggregators`] names the
    /// router either way, so admitting Jupiter admits a Jupiter route a bot CPI'd once
    /// [`SwapScope::Nested`] is on.
    #[serde(default, skip_serializing_if = "RerouteScopes::is_default")]
    pub scopes: RerouteScopes,
    /// Restrict rerouting to the mint pairs of interest — a maker's own book. Absent: every
    /// detected swap on an admitted aggregator is rerouted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter: Option<RerouteFilter>,
    /// Also reroute swaps whose historical transaction failed, when the allowlist admits the
    /// failure as one rerouting can answer (a slippage rejection, or a failure after the swap
    /// already ran).
    ///
    /// Off by default. The original swap realised nothing for these, so nothing compares with
    /// it, and they are counted apart: `swaps_detected` and `swaps_rerouted` exclude them, and
    /// every row carries `original_failed`. `l1` in the name means the original (onchain) swap.
    #[serde(default)]
    pub detect_failed_l1_swaps: bool,
    /// Also reroute atomic arbitrage — swaps whose input and output mint are the same. Each cycle
    /// is quoted leg by leg and built back as one circular route. A cycle that can't be split into
    /// legs fails with a `cycle_*` category. Off by default: a transaction holding a cycle is then
    /// left out as filtered.
    #[serde(default)]
    pub circular_arbs: bool,
    /// Reroute detected swaps through the router.
    ///
    /// On by default. Turn it off to reroute only directly to a venue, with
    /// [`Self::venue_templates`]: the session then runs without the router, which a venue the
    /// router cannot route does not need.
    #[serde(default = "RerouteParams::default_requote")]
    pub requote: bool,
    /// Instruction templates to probe against the hops this session detects, alongside the
    /// re-quoting: each hop whose direction and mode a template names is instantiated through
    /// it, funded, simulated and scored against what the historical hop filled. Empty: no
    /// rerouting directly to a venue.
    ///
    /// The templates decide only how a hop is priced. [`Self::aggregators`] still decides which
    /// original swaps reach them, so a session that only reroutes directly to a venue must list
    /// every router whose hops it wants priced.
    ///
    /// `directFill` on the wire.
    #[serde(rename = "directFill", default, skip_serializing_if = "Vec::is_empty")]
    pub venue_templates: Vec<VenueTemplate>,
    /// Pools for the router to consider on top of the markets it already knows. Each must hold
    /// an account at the start of the range: a pool that exists nowhere onchain gets its
    /// accounts from an account override anchored at the first slot. Requires [`Self::requote`].
    #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub extra_markets: BTreeSet<Address>,
    /// Price each swap as late in its quote slot as it could have been, instead of at the slot's
    /// start: after the slot's last transaction, or just before the swap's own batch when it
    /// lands in that slot.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub quote_late_in_slot: bool,
}

/// Hand-written rather than derived: `requote` defaults to ON, and a derived `Default` would
/// give the opposite of what deserializing an empty object gives.
impl Default for RerouteParams {
    fn default() -> Self {
        Self {
            aggregators: RerouteAggregators::default(),
            scopes: RerouteScopes::default(),
            filter: None,
            detect_failed_l1_swaps: false,
            circular_arbs: false,
            requote: Self::default_requote(),
            venue_templates: Vec::new(),
            extra_markets: BTreeSet::new(),
            quote_late_in_slot: false,
        }
    }
}

/// `<base>,<quote>` in base58 — the spelling a CLI flag or env var carries.
impl std::str::FromStr for MintPair {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (base, quote) = s
            .split_once(',')
            .ok_or_else(|| format!("expected two comma-separated mints, got {s:?}"))?;
        Self::try_from([base.trim().to_owned(), quote.trim().to_owned()])
            .map_err(|error| error.to_string())
    }
}

impl std::fmt::Display for MintPair {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (one, other) = self.mints();
        write!(f, "{one},{other}")
    }
}

impl RerouteParams {
    const fn default_requote() -> bool {
        true
    }

    /// Whether this block asks for anything at all — a session with neither re-quoting nor a venue
    /// template has a reroute section that does nothing.
    pub const fn is_noop(&self) -> bool {
        !self.requote && self.venue_templates.is_empty()
    }
}

/// Parameters required to start a new session: the `params` of `createBacktestSession`, or the
/// `request` of a [`CreateBacktestSessionRequestV1`]. Fields are camelCase on the wire.
///
/// Build one with [`CreateSessionParams::builder`]; only `start_slot` and `end_slot` are
/// required. List the ranges you can replay with `GET /available-ranges` ([`AvailableRange`]).
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
#[serde(rename_all = "camelCase")]
pub struct CreateSessionParams {
    /// First slot (inclusive) to replay. A single session must start exactly at an available
    /// range's `bundle_start_slot`. A parallel run may start inside a range; its first session
    /// then starts at that range's `bundle_start_slot`.
    pub start_slot: u64,
    /// Last slot (inclusive) to replay, at most the range's `max_bundle_end_slot`.
    pub end_slot: u64,
    /// Send a [`SessionSummary`] with `completed`. Default `false`: `completed` carries none.
    #[serde(default)]
    #[builder(default)]
    pub send_summary: bool,
    /// Reroute historical swaps. Absent: plain replay.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reroute: Option<RerouteParams>,
    /// Seconds to keep retrying while the server has no capacity for a new session, before
    /// failing the create. Unset or 0: fail at once when the server is busy.
    #[serde(default)]
    pub capacity_wait_timeout_secs: Option<u16>,
    /// Seconds the session waits for you to reattach after the session control channel drops.
    /// Unset: 30 (900 for a parallel run). 0: the session ends with the connection and responses
    /// carry no sequence number; otherwise they are wrapped in a [`SequencedResponse`]. Clamped to
    /// [`MAX_DISCONNECT_TIMEOUT_SECS`] (900 seconds).
    #[serde(default)]
    pub disconnect_timeout_secs: Option<u16>,
    /// Extra compute units to add to each transaction's `SetComputeUnitLimit` budget.
    /// Useful when replaying with an account override whose program uses more CU than
    /// the original, causing otherwise-healthy transactions to run out of budget.
    /// Only applied when a `SetComputeUnitLimit` instruction is already present.
    #[serde(default)]
    pub extra_compute_units: Option<u32>,
    /// Events of interest the session should watch for. When an upcoming
    /// batch matches any filter, the server emits
    /// [`BacktestResponse::DiscoveryBatch`] (and its session-event twins)
    /// ahead of execution so the client can follow up with
    /// [`BacktestRequest::ContinueTo`] to pause before the batch. Empty: no
    /// `discoveryBatch` events.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[builder(default)]
    pub discoveries: Vec<DiscoveryFilter>,
    /// Transactions the server runs automatically during the backtest, with
    /// results streamed over `actionSubscribe`.
    ///
    /// Compressed as a whole rather than per action: a per-slot schedule repeats
    /// near-identical account bytes thousands of times, and that redundancy is
    /// only visible across actions. Compressing each action alone leaves a
    /// 10k-slot schedule near the WebSocket message limit; compressing the
    /// vector takes the same schedule from ~28 MiB to ~1 MiB.
    #[serde(default, with = "compressed", skip_serializing_if = "Vec::is_empty")]
    #[builder(default)]
    pub actions: Vec<ScheduledAction>,
    /// Replay recorded account state for this range instead of executing its transactions,
    /// which is faster. Needs an account-state bundle for the range ([`BundleKind::AccountState`]).
    /// Nothing executes, so sending transactions, `kind: send` actions and transaction lookups
    /// are rejected; simulations still work.
    #[serde(default)]
    #[builder(default)]
    pub replay_account_state: bool,
    /// Markets to probe through the router as the session runs, streamed over
    /// `diagnosticSubscribe`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[builder(default)]
    pub diagnostic_probes: Vec<DiagnosticProbeParams>,
}

/// What account state replay cannot serve, worded once. Client, server and
/// session all reject through here, so a user meets the same explanation
/// wherever the request is stopped.
#[doc(hidden)]
pub mod replay_support {
    use super::{ActionKind, CreateSessionParams};

    /// `getTransaction`/`getSignatureStatuses`: nothing executed, so nothing is found.
    pub const NO_TRANSACTIONS: &str =
        "Create the session without replayAccountState to execute and persist transactions.";

    pub const SEND_TRANSACTION: &str = "Use simulateTransaction to run it against the replayed state, or create the session \
         without replayAccountState.";

    pub const SEND_ACTION: &str = "Use kind: simulate, which runs against the replayed state without committing, post state \
         directly with an action carrying accountOverrides and no transactions, or create the \
         session without replayAccountState.";

    /// States the operation, why replay cannot serve it, then the way forward.
    pub fn unsupported(operation: &str, remedy: &str) -> String {
        format!(
            "{operation} is not supported while account state replay is enabled: replay \
             reconstructs account state from the recorded delta bundle instead of executing \
             transactions, so this session never executes or persists any. {remedy}"
        )
    }

    /// The one rule decidable from the request alone, so it can be caught before
    /// a session — or a runtime to host it — is ever created.
    pub fn send_action_conflict(params: &CreateSessionParams) -> Option<String> {
        (params.replay_account_state
            && params
                .actions
                .iter()
                .any(|action| action.kind == ActionKind::Send))
        .then(|| unsupported("A scheduled action with kind: send", SEND_ACTION))
    }
}

impl CreateSessionParams {
    /// Whether a session needs a router sidecar (reroute quotes through it).
    /// Only re-quoting, or a template re-quoted through the router, needs the router; a session
    /// that only reroutes directly to a venue prices without it.
    #[doc(hidden)]
    pub fn requires_sidecar(&self) -> bool {
        self.reroute.as_ref().is_some_and(|reroute| {
            reroute.requote
                || reroute
                    .venue_templates
                    .iter()
                    .any(|template| template.resolve == Some(TemplateResolver::Requote))
        }) || !self.diagnostic_probes.is_empty()
            || self.actions.iter().any(ScheduledAction::asks_router)
    }

    /// Whether the sidecar has to start the router with `--enable-diagnostic`. A rerouting session
    /// asks for the same endpoint through an operator variable the sidecar inherits; probes are a
    /// session parameter, so they have to ask through the launch spec.
    pub fn requires_diagnostic_endpoint(&self) -> bool {
        !self.diagnostic_probes.is_empty()
    }

    /// Checks every [`Self::diagnostic_probes`] entry, as the server does.
    pub fn validate_diagnostic_probes(&self) -> Result<(), DiagnosticProbeError> {
        self.diagnostic_probes
            .iter()
            .try_for_each(DiagnosticProbeParams::validate)
    }

    /// Checks every action's resolver; see [`validate_resolvers`].
    pub fn validate_action_resolvers(&self) -> Result<(), ActionResolveError> {
        validate_resolvers(&self.actions)
    }

    /// Whether the session should warm its account universe before replaying.
    #[doc(hidden)]
    pub fn warms_account_universe(&self) -> bool {
        self.requires_sidecar()
            || self
                .reroute
                .as_ref()
                .is_some_and(|reroute| !reroute.venue_templates.is_empty())
    }

    /// Whether the session reroutes swaps, that is whether [`Self::reroute`] is set.
    pub fn reroute_order_flow(&self) -> bool {
        self.reroute.is_some()
    }

    /// The Override actions in [`Self::actions`], compiled into the slot-keyed schedule the
    /// reroute layer consumes. Same-slot actions merge account-wise, later wins.
    #[doc(hidden)]
    pub fn override_schedule(&self) -> Result<OverrideSchedule, String> {
        decode_override_actions(&self.actions)
    }

    /// The mint pairs rerouting is restricted to, if the session named any.
    pub fn reroute_filter(&self) -> Option<&RerouteFilter> {
        self.reroute.as_ref()?.filter.as_ref()
    }
}

/// What counts as a "non-benign" divergence for the session fail-fast
/// behaviour.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FailFastDivergenceKind {
    /// Any divergence other than a benign log diff (the full `is_divergent()` set:
    /// log mismatch, error mismatch, balance-diff mismatch).
    #[default]
    AnyNonBenign,
    /// Only divergences on transactions that touch an account currently watched by an
    /// account-diff subscription (subscribed directly, or owned by a subscribed program).
    Tracked,
}

impl FailFastDivergenceKind {
    /// Stable string form used for CLI/env-var serialization. Matches the serde
    /// `kebab-case` representation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AnyNonBenign => "any-non-benign",
            Self::Tracked => "tracked",
        }
    }

    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
    pub fn from_str_opt(value: &str) -> Option<Self> {
        match value {
            "any-non-benign" => Some(Self::AnyNonBenign),
            "tracked" => Some(Self::Tracked),
            _ => None,
        }
    }
}

/// Account state modifications to apply.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct AccountModifications(
    #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, _>")]
    #[serde(default)]
    pub BTreeMap<Address, AccountData>,
);

impl From<BTreeMap<Address, AccountData>> for AccountModifications {
    fn from(value: BTreeMap<Address, AccountData>) -> Self {
        Self(value)
    }
}

impl AccountModifications {
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// The `params` of `continue`: execute the next blocks, after your own transactions and account
/// overrides. Every field has a default, so `{}` advances one block.
///
/// Before the first block, the session runs `transactions` in order and commits them, then
/// writes `modify_account_states`. A failed user transaction does not produce an `error`
/// response.
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinueParams {
    #[serde(default = "ContinueParams::default_advance_count")]
    /// Wire name `advanceCount`: blocks to execute before the session waits again. Default 1.
    /// Counts blocks, not slots: a skipped slot has no block and is not counted.
    pub advance_count: u64,
    #[serde(default)]
    /// User transactions to execute before advancing, each the base64 of a transaction's
    /// standard wire bytes. Encode each with `simulator_client::encode_transaction`. Signatures
    /// and the recent blockhash are not checked, as for a [`ScheduledAction`]. Rejected
    /// in a session created with `replay_account_state`.
    pub transactions: Vec<String>,
    #[serde(default)]
    /// Wire name `modifyAccountStates`: account overrides, written after the user transactions
    /// and before the first block.
    pub modify_account_states: AccountModifications,
}

impl Default for ContinueParams {
    fn default() -> Self {
        Self {
            advance_count: Self::default_advance_count(),
            transactions: Vec::new(),
            modify_account_states: AccountModifications(BTreeMap::new()),
        }
    }
}

impl ContinueParams {
    /// The `advance_count` an absent field means: 1.
    pub fn default_advance_count() -> u64 {
        1
    }
}

/// Payload emitted when a session halts at a caller-specified point.
/// `batch_index` is `None` for block-boundary pauses and `Some(n)` when the
/// session stopped *before* batch `n` within `slot` (no transaction from
/// batch `n` has been applied). While paused, RPC reads against the session
/// observe partial state up through batch `n - 1`. A `readyForContinue` always follows: answer
/// that, not this.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PausedEvent {
    #[allow(missing_docs)]
    pub slot: u64,
    /// Wire name `batchIndex`, absent at a block boundary: the batch the session paused
    /// before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch_index: Option<u32>,
}

/// Payload emitted when the session has *discovered* an upcoming batch that
/// matches one or more registered [`DiscoveryFilter`]s from session creation
/// (for example, a batch containing a transaction that invokes a program of
/// interest). The `(slot, batch_index)` pair can be fed directly to
/// [`BacktestRequest::ContinueTo`] to pause immediately before the batch
/// executes. After each `Continue` / `ContinueTo`, the session emits the
/// next `DiscoveryBatchEvent` ahead of the next matching batch, enabling a
/// reactive "pause on every discovery" driver loop.
///
/// ```no_run
/// use simulator_api::{BacktestRequest, BacktestResponse, ContinueToParams};
///
/// /// On a discovery, inspect the matching transactions and pause just before their batch.
/// fn on_response(
///     response: &BacktestResponse,
/// ) -> Result<Option<BacktestRequest>, Box<dyn std::error::Error>> {
///     let BacktestResponse::DiscoveryBatch(event) = response else {
///         return Ok(None);
///     };
///     for (encoded, index) in event.transactions.iter().zip(&event.transaction_indices) {
///         // Raw wincode bytes; `simulator_client::decode_transaction(encoded)` parses them.
///         let bytes = encoded.decode()?;
///         println!("slot {} transaction {index}: {} bytes", event.slot, bytes.len());
///     }
///     Ok(Some(BacktestRequest::ContinueTo(ContinueToParams {
///         slot: event.slot,
///         batch_index: Some(event.batch_index),
///     })))
/// }
/// ```
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DiscoveryBatchEvent {
    /// The slot the matching batch is in.
    pub slot: u64,
    /// Wire name `batchIndex`: the matching batch's index within `slot`.
    pub batch_index: u32,
    /// Filters that matched this batch (always non-empty).
    pub matched: Vec<DiscoveryFilter>,
    /// Encoded transactions in this batch that triggered the match. Decode each
    /// with `simulator_client::decode_transaction` (base64 wincode of `VersionedTransaction`).
    pub transactions: Vec<EncodedBinary>,
    /// Each of `transactions`' index in its slot's block, the index Solana reports for it. Empty
    /// from a session that predates it.
    #[serde(default)]
    pub transaction_indices: Vec<u32>,
}

/// The `params` of `continueTo`: execute up to a point, then pause there.
///
/// The session executes through `slot`, or with `batch_index`, up to just before that batch of
/// it. It then sends `paused` ([`PausedEvent`]) and `readyForContinue`; answer only the
/// `readyForContinue`.
///
/// - `slot` must be after the last executed slot. Otherwise the server sends an
///   [`BacktestError::InvalidRequest`] error and the session stays where it is.
/// - `slot` must have a block. A skipped slot has none, and the session does not stop at it: it
///   runs on to the end of the range.
/// - To run transactions just before slot `n`, pause at `n - 1` and send them with the next
///   `continue`, or schedule a `beforeSlot` [`ScheduledAction`] of kind [`ActionKind::Send`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinueToParams {
    /// The slot to pause in, or at the end of when `batch_index` is `None`.
    pub slot: u64,
    /// Batch within the target slot at which to pause, **exclusive** — the
    /// session halts immediately *before* batch `n` executes, so no
    /// transaction in that batch has been applied yet. `None` runs the
    /// whole slot, pausing at the block boundary. While paused, RPC reads
    /// observe partial state up through batch `n - 1`.
    #[serde(default)]
    pub batch_index: Option<u32>,
}

/// Supported binary encodings for account/transaction payloads.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum BinaryEncoding {
    /// `base64`: standard alphabet, padded.
    Base64,
}

impl BinaryEncoding {
    #[allow(missing_docs)]
    pub fn encode(self, bytes: &[u8]) -> String {
        match self {
            Self::Base64 => BASE64.encode(bytes),
        }
    }

    #[allow(missing_docs)]
    pub fn decode(self, data: &str) -> Result<Vec<u8>, Base64DecodeError> {
        match self {
            Self::Base64 => BASE64.decode(data),
        }
    }
}

/// A blob paired with the encoding needed to decode it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EncodedBinary {
    /// Encoded payload.
    pub data: String,
    /// Encoding scheme used for the payload.
    pub encoding: BinaryEncoding,
}

impl EncodedBinary {
    /// Wraps already-encoded `data`.
    pub fn new(data: String, encoding: BinaryEncoding) -> Self {
        Self { data, encoding }
    }

    #[allow(missing_docs)]
    pub fn from_bytes(bytes: &[u8], encoding: BinaryEncoding) -> Self {
        Self {
            data: encoding.encode(bytes),
            encoding,
        }
    }

    #[allow(missing_docs)]
    pub fn decode(&self) -> Result<Vec<u8>, Base64DecodeError> {
        self.encoding.decode(&self.data)
    }
}

/// An account's full state, used as an account override.
///
/// On the wire: `{"data": {"data": "<base64>", "encoding": "base64"}, "executable": false,
/// "lamports": 1000000, "owner": "<base58>", "space": 0}`.
///
/// - The override replaces the whole account. To change a token balance, build the token
///   account's bytes with [`token`].
/// - `rent_epoch` is not carried; the session sets it to 0.
/// - Scheduled-action, depth and `simulateTransaction` overrides reject an executable account or
///   one owned by a program loader: a program cannot be overridden this way.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountData {
    /// Account data bytes and encoding.
    pub data: EncodedBinary,
    /// Whether the account is executable.
    pub executable: bool,
    /// Balance in lamports (1 SOL = 1,000,000,000 lamports).
    pub lamports: u64,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    /// The owning program, base58.
    pub owner: Address,
    /// The data length in bytes. Set it to the decoded length of `data`: the account's size
    /// comes from `data`, not from this field.
    pub space: u64,
}

impl AccountData {
    /// The account these fields describe, with `rent_epoch` 0. Fails if `data` does not
    /// decode.
    pub fn to_account(&self) -> Result<solana_account::Account, Base64DecodeError> {
        Ok(solana_account::Account {
            data: self.data.decode()?,
            lamports: self.lamports,
            owner: self.owner,
            executable: self.executable,
            rent_epoch: 0,
        })
    }

    /// A system-owned account with no data holding `lamports`. At `0` the account does not exist.
    pub fn system_account(lamports: u64) -> Self {
        Self {
            data: EncodedBinary::new(String::new(), BinaryEncoding::Base64),
            executable: false,
            lamports,
            owner: solana_sdk_ids::system_program::ID,
            space: 0,
        }
    }
}

/// The wire form of `account`: base64 data, `space = data.len()`. The inverse of
/// [`AccountData::to_account`]; `rent_epoch` is dropped because the wire does not carry it.
impl From<&solana_account::Account> for AccountData {
    fn from(account: &solana_account::Account) -> Self {
        Self {
            data: EncodedBinary::from_bytes(&account.data, BinaryEncoding::Base64),
            executable: account.executable,
            lamports: account.lamports,
            owner: account.owner,
            space: account.data.len() as u64,
        }
    }
}

/// A response the server sends on the session control channel.
///
/// Serialized as `{"method": "<variantName>", "params": …}`; a variant without data has no
/// `params`. Fields declared on a variant itself are snake_case on the wire. Once a session runs,
/// its responses arrive wrapped in a [`SequencedResponse`] unless `disconnectTimeoutSecs` is 0.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "method", content = "params", rename_all = "camelCase")]
#[allow(missing_docs)]
pub enum BacktestResponse {
    /// `sessionCreated`: the session exists. For a parallel run, sent once per session.
    SessionCreated {
        /// The session's ID; keep it to reattach.
        session_id: SessionId,
        /// The session's RPC endpoint: a path on the server's host, `/backtest/<session_id>`.
        /// Prefix it with `https://<host>`.
        rpc_endpoint: String,
        /// The server's ID for the machine running the session. Quote it when reporting a
        /// problem.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        task_id: Option<String>,
        /// The session's name, or the parallel run's for a session in one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        session_name: Option<String>,
    },
    /// `sessionAttached`: the reply to [`BacktestRequest::AttachBacktestSession`], with the
    /// same fields as [`Self::SessionCreated`]. The missed responses follow.
    SessionAttached {
        /// As in [`Self::SessionCreated`].
        session_id: SessionId,
        /// As in [`Self::SessionCreated`].
        rpc_endpoint: String,
        /// As in [`Self::SessionCreated`].
        #[serde(default, skip_serializing_if = "Option::is_none")]
        task_id: Option<String>,
        /// As in [`Self::SessionCreated`].
        #[serde(default, skip_serializing_if = "Option::is_none")]
        session_name: Option<String>,
    },
    /// `sessionsCreatedV2`: every session of a parallel run exists. The lists are parallel:
    /// entry `i` of each describes the same session.
    SessionsCreatedV2 {
        /// The parallel run's ID; keep it to reattach.
        control_session_id: ControlSessionId,
        /// The parallel run's name.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        control_session_name: Option<String>,
        /// One per session.
        session_ids: Vec<SessionId>,
        /// As `task_id` in [`Self::SessionCreated`], per session.
        #[serde(default)]
        task_ids: Vec<Option<String>>,
        /// Per-session start/end slots, parallel to `session_ids`. The
        /// server's split is authoritative (a mid-bundle request anchors to the
        /// covering bundle), so the client binds each session to its range
        /// from here rather than re-deriving the split locally.
        #[serde(default)]
        start_slots: Vec<u64>,
        /// Each session's last slot, parallel to `session_ids`.
        #[serde(default)]
        end_slots: Vec<u64>,
    },
    /// `parallelSessionAttachedV2`: the reply to
    /// [`BacktestRequest::AttachParallelControlSessionV2`]. Each session's missed events follow.
    ParallelSessionAttachedV2 {
        /// The parallel run reattached to.
        control_session_id: ControlSessionId,
        session_ids: Vec<SessionId>,
        /// As in [`Self::SessionsCreatedV2`].
        #[serde(default)]
        task_ids: Vec<Option<String>>,
    },
    /// `readyForContinue`: the session is waiting for your next `continue` or `continueTo`.
    /// Read and change state through the session's RPC endpoint now.
    ReadyForContinue,
    /// `slotNotification`: the slot that just executed, as a bare number in `params`.
    SlotNotification(u64),
    /// `paused`: the session stopped where a `continueTo` asked.
    Paused(PausedEvent),
    /// `discoveryBatch`: an upcoming batch matches a [`CreateSessionParams::discoveries`]
    /// filter.
    DiscoveryBatch(DiscoveryBatchEvent),
    /// `error`: something failed. Check [`BacktestError::is_terminal`] to see whether the
    /// session is over.
    Error(BacktestError),
    /// `success`: acknowledges a request with nothing else to return, such as a single session's
    /// `closeBacktestSession` or `resumeAttachedSession`. A parallel run's close requests get no
    /// `success`.
    Success,
    /// `completed`: the session replayed its last slot. Terminal.
    Completed {
        /// Session summary with transaction statistics.
        /// `None` unless the session was created with `send_summary`.
        #[serde(skip_serializing_if = "Option::is_none")]
        summary: Option<SessionSummary>,
    },
    /// `status`: a progress update, while the session starts and during each `continue`.
    Status { status: BacktestStatus },
    /// `sessionEventV2`: an event from one session of a parallel run.
    SessionEventV2 {
        session_id: SessionId,
        /// The session's own sequence number for this event. Keep the last one per session to
        /// reattach.
        seq_id: u64,
        event: SessionEventKind,
    },
}

impl BacktestResponse {
    #[allow(missing_docs)]
    pub fn is_completed(&self) -> bool {
        matches!(self, BacktestResponse::Completed { .. })
    }

    /// Whether the session is over: `completed`, or an `error` whose
    /// [`BacktestError::is_terminal`] is true.
    pub fn is_terminal(&self) -> bool {
        match self {
            BacktestResponse::Completed { .. } => true,
            BacktestResponse::Error(e) => e.is_terminal(),
            _ => false,
        }
    }
}

impl From<BacktestStatus> for BacktestResponse {
    fn from(status: BacktestStatus) -> Self {
        Self::Status { status }
    }
}

impl From<String> for BacktestResponse {
    fn from(message: String) -> Self {
        BacktestError::Internal { error: message }.into()
    }
}

impl From<&str> for BacktestResponse {
    fn from(message: &str) -> Self {
        BacktestError::Internal {
            error: message.to_string(),
        }
        .into()
    }
}

/// What happened in one session of a parallel run: the `event` of `sessionEventV2`. Each
/// variant means what the [`BacktestResponse`] variant of the same name means, for that session
/// alone.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "method", content = "params", rename_all = "camelCase")]
#[allow(missing_docs)]
pub enum SessionEventKind {
    /// As [`BacktestResponse::ReadyForContinue`].
    ReadyForContinue,
    /// As [`BacktestResponse::SlotNotification`].
    SlotNotification(u64),
    /// As [`BacktestResponse::Paused`].
    Paused(PausedEvent),
    /// As [`BacktestResponse::DiscoveryBatch`].
    DiscoveryBatch(DiscoveryBatchEvent),
    /// As [`BacktestResponse::Error`].
    Error(BacktestError),
    /// As [`BacktestResponse::Success`].
    Success,
    /// As [`BacktestResponse::Completed`]: this session is done; the others may still run.
    Completed {
        /// As in [`BacktestResponse::Completed`].
        #[serde(skip_serializing_if = "Option::is_none")]
        summary: Option<SessionSummary>,
    },
    /// As [`BacktestResponse::Status`].
    Status { status: BacktestStatus },
}

impl SessionEventKind {
    /// Whether this session is over; see [`BacktestResponse::is_terminal`].
    pub fn is_terminal(&self) -> bool {
        match self {
            Self::Completed { .. } => true,
            Self::Error(e) => e.is_terminal(),
            _ => false,
        }
    }
}

/// Wire format wrapper for responses sent over the session control channel.
/// Sessions whose `disconnect_timeout_secs` is not 0 (unset defaults to 30) use this to track
/// client position.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SequencedResponse {
    /// Wire name `seqId`: the sequence number, increasing with each response. Keep the last one
    /// you received; reattaching replays everything after it.
    pub seq_id: u64,
    /// The response, flattened beside `seqId`.
    #[serde(flatten)]
    pub response: BacktestResponse,
}

/// Progress reported in a `status` response, as a camelCase string such as
/// `"startingRuntime"`. Informational: you need not act on any of them.
///
/// A `continue` reports, in order: `decodedTransactions` and `executedUserTransactions` (only
/// when it carries user transactions), `appliedAccountModifications`,
/// `readyToExecuteUserTransactions`, then `executingBlockTransactions` and
/// `executedBlockTransactions` for each block.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BacktestStatus {
    /// Runtime startup is in progress. Sent when the create is accepted, then about every 10
    /// seconds until the session is ready.
    StartingRuntime,
    /// The `continue`'s user transactions decoded.
    DecodedTransactions,
    /// The `continue`'s account overrides are written.
    AppliedAccountModifications,
    /// The `continue`'s inputs are applied; blocks run next.
    ReadyToExecuteUserTransactions,
    /// The `continue`'s user transactions ran.
    ExecutedUserTransactions,
    /// A block started executing.
    ExecutingBlockTransactions,
    /// A block finished executing.
    ExecutedBlockTransactions,
    /// Not sent by the current server.
    ProgramAccountsLoaded,
}

impl std::fmt::Display for BacktestStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::StartingRuntime => "starting runtime",
            Self::DecodedTransactions => "decoded transactions",
            Self::AppliedAccountModifications => "applied account modifications",
            Self::ReadyToExecuteUserTransactions => "ready to execute user transactions",
            Self::ExecutedUserTransactions => "executed user transactions",
            Self::ExecutingBlockTransactions => "executing block transactions",
            Self::ExecutedBlockTransactions => "executed block transactions",
            Self::ProgramAccountsLoaded => "program accounts loaded",
        };
        f.write_str(s)
    }
}

/// Summary of a session run with `reroute_order_flow`: how many detected swaps made it from
/// rerouting through simulation to a non-reverting execution, and — for a session carrying a
/// [`VenueTemplate`] list — how many hops each template priced. Per-swap
/// economics and latency land in the reroute tables, published to `dataset_uri` when set.
///
/// Fields are camelCase on the wire (`swapsDetected`), except the `venue_*` fields, which keep
/// their `directFill*` names (`directFillMatched`). Counts are of swaps unless a field says
/// otherwise; `*_bps_total` fields are sums in basis points (1 bps = 0.01%).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RerouteStatsReport {
    /// Reroutable swaps detected in the replayed range, across the admitted aggregators.
    #[serde(default)]
    pub swaps_detected: u64,
    /// Detected swaps excluded before quoting — an unadmitted aggregator, an atomic arbitrage, a
    /// mint pair the filter does not name. Without it the gap between `swaps_detected` and
    /// `swaps_rerouted` reads as routing failures.
    #[serde(default)]
    pub swaps_filtered: u64,
    /// Swaps rerouted through the router and queued for simulation.
    #[serde(default)]
    pub swaps_rerouted: u64,
    /// Swaps whose routed transaction was simulated.
    #[serde(default)]
    pub swaps_simulated: u64,
    /// Simulated swaps whose routed transaction executed without reverting.
    #[serde(default)]
    pub swaps_succeeded: u64,
    /// Detected swaps the router could not route; nothing was simulated for them.
    #[serde(default)]
    pub requote_failures: u64,
    /// Computed override actions that failed and therefore contributed no state.
    #[serde(default)]
    pub override_setup_failures: u64,
    /// Blocks replayed unchanged because the router client was unavailable.
    #[serde(default)]
    pub metis_unavailable_blocks: u64,
    /// Quote attempts that could not be made because the router client was unavailable, summed
    /// over every swap left queued by each such block. Each one is retried on the next block,
    /// so this counts retries forced rather than swaps lost.
    #[serde(default)]
    pub quote_attempts_unavailable: u64,
    /// Hops a template matched, summed over [`Self::venue_template_reports`]. A hop two templates
    /// match counts twice. Zero when no template was configured.
    #[serde(rename = "directFillMatched", default)]
    pub venue_matched: u64,
    /// Probes by outcome, summed over the templates — `filled`, `reverted_*`, `unattributed`
    /// (ran clean, but the seeded account was gone or unreadable), `unsimulatable` (could not be
    /// compiled or run), `unresolved_*` (the template could not be brought up to the pass). Every
    /// matched hop lands in exactly one bucket.
    #[serde(rename = "directFillOutcomes", default)]
    pub venue_outcomes: BTreeMap<String, u64>,
    /// Probes scored against the hop they replace, summed over the templates.
    #[serde(rename = "directFillScored", default)]
    pub venue_scored: u64,
    /// Sum of each scored probe's change against its historical fill in basis points, over
    /// `venue_scored` — divide by that count for the mean. Positive always means the
    /// template beat the hop, whichever amount the mode fixed.
    #[serde(rename = "directFillBpsTotal", default)]
    pub venue_bps_total: i64,
    /// The same four counters per template, keyed by label. A template that never matched is
    /// present with zeros.
    #[serde(rename = "directFillTemplates", default)]
    pub venue_template_reports: BTreeMap<String, VenueTemplateReport>,
    /// Original swaps scored against their own historical fill at quote time.
    #[serde(default)]
    pub originals_scored: u64,
    /// Sum of `(quote time fill - historical fill) / historical fill` in basis points over
    /// `originals_scored` swaps — divide by that count for the mean.
    #[serde(default)]
    pub originals_bps_total: i64,
    /// Originals replayed at the position their replacements were priced at.
    #[serde(default)]
    pub originals_replayed: u64,
    /// `s3://` URI the reroute tables are published to at session end; `None` when they aren't.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dataset_uri: Option<String>,
}

/// How long a session's published reroute tables stay in its owner's datasets.
pub const REROUTE_DATASET_RETENTION_DAYS: u32 = 30;

/// One template's share of the venue probes; the flat `venue_*` counters on
/// [`RerouteStatsReport`] are the sums of these.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VenueTemplateReport {
    /// Hops this template matched; see [`RerouteStatsReport::venue_matched`].
    pub matched: u64,
    /// This template's probes by outcome; see [`RerouteStatsReport::venue_outcomes`].
    pub outcomes: BTreeMap<String, u64>,
    /// This template's probes scored against the hop they replace.
    pub scored: u64,
    /// Wire name `bpsTotal`: the sum of this template's scored changes in basis points; divide
    /// by `scored` for the mean. Positive means the template beat the hop.
    pub bps_total: i64,
}

/// Summary of transaction execution statistics for a completed session: how the replayed
/// transactions compare with what happened onchain. Sent with `completed` when the session was
/// created with `send_summary`. Fields are camelCase on the wire (`correctSimulation`).
///
/// - [`Self::total_transactions`] does not count `unsanitizable`.
/// - [`Self::has_deviations`] ignores `log_diff`, since log differences are usually benign.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionSummary {
    /// Number of simulations where simulator outcome matched onchain outcome
    /// (`true_success + true_failure`).
    pub correct_simulation: usize,
    /// Number of simulations where simulator outcome did not match onchain outcome
    /// (`false_success + false_failure`).
    pub incorrect_simulation: usize,
    /// Number of transactions that had execution errors in simulation.
    pub execution_errors: usize,
    /// Number of transactions with different balance diffs.
    pub balance_diff: usize,
    /// Number of transactions with different log diffs.
    pub log_diff: usize,
    /// Transactions skipped because they could not be sanitized (malformed message or
    /// unresolvable address lookup table).
    #[serde(default)]
    pub unsanitizable: usize,
    /// Aggregate reroute metrics, populated only for reroute-order-flow sessions. Boxed to
    /// keep `SessionSummary` small in the many response enums that carry it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reroute_stats: Option<Box<RerouteStatsReport>>,
}

impl SessionSummary {
    /// Returns true if there were any execution deviations (errors or mismatched results):
    /// `incorrect_simulation`, `execution_errors` or `balance_diff` above 0. `log_diff` does not
    /// count.
    pub fn has_deviations(&self) -> bool {
        self.incorrect_simulation > 0 || self.execution_errors > 0 || self.balance_diff > 0
    }

    /// Total number of transactions processed: the sum of every count except
    /// `unsanitizable`.
    pub fn total_transactions(&self) -> usize {
        self.correct_simulation
            + self.incorrect_simulation
            + self.execution_errors
            + self.balance_diff
            + self.log_diff
    }

    /// Renders the compact "N incorrect simulations, N execution errors, ..." deviation list
    /// shared by console reporters. `balance_label` / `log_label` let each caller keep its own
    /// historical wording for the trailing two counts (e.g. "balance diffs" vs
    /// "different balances").
    pub fn deviation_details(&self, balance_label: &str, log_label: &str) -> String {
        format!(
            "{} incorrect simulations, {} execution errors, {} {balance_label}, {} {log_label}",
            self.incorrect_simulation, self.execution_errors, self.balance_diff, self.log_diff,
        )
    }
}

impl std::fmt::Display for SessionSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let total = self.total_transactions();
        write!(
            f,
            "Session summary: {total} transactions\n\
             \x20  - {} correct simulation\n\
             \x20  - {} incorrect simulation\n\
             \x20  - {} execution errors\n\
             \x20  - {} unsanitizable\n\
             \x20  - {} balance diffs\n\
             \x20  - {} log diffs",
            self.correct_simulation,
            self.incorrect_simulation,
            self.execution_errors,
            self.unsanitizable,
            self.balance_diff,
            self.log_diff,
        )
    }
}

/// Error variants surfaced to backtest RPC clients: the `params` of an `error` response.
///
/// On the wire, a camelCase variant name with snake_case fields:
/// `{"method": "error", "params": {"bundleNotFound": {"start_slot": 1, "end_slot": 2}}}`. A
/// variant without fields is a bare string: `{"method": "error", "params": "noMoreBlocks"}`.
///
/// [`Self::is_terminal`] says whether a running session is over. An error that answers a create
/// or an attach ends that request whatever it says: no session was created or attached.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(missing_docs)]
pub enum BacktestError {
    /// A user transaction in a `continue` is not valid base64. Not terminal: none of that
    /// `continue` ran, so fix the transaction and send it again.
    InvalidTransactionEncoding {
        /// Its position in [`ContinueParams::transactions`].
        index: usize,
        error: String,
    },
    /// A user transaction in a `continue` is valid base64 but not a transaction's wire bytes.
    /// Not terminal: none of that `continue` ran. Encode with
    /// `simulator_client::encode_transaction`.
    InvalidTransactionFormat {
        /// Its position in [`ContinueParams::transactions`].
        index: usize,
        error: String,
    },
    /// An account override's `data` does not decode. Not terminal: the `continue`'s user
    /// transactions ran, but no override was written and no block executed.
    InvalidAccountEncoding {
        /// The account, base58.
        address: String,
        /// The encoding `data` claimed.
        encoding: BinaryEncoding,
        error: String,
    },
    /// Not sent by the current server.
    InvalidAccountOwner {
        /// The account, base58.
        address: String,
        error: String,
    },
    /// Not sent by the current server.
    InvalidAccountPubkey {
        /// The account, base58.
        address: String,
        error: String,
    },
    /// The session has no block left to execute. Terminal.
    NoMoreBlocks,
    /// The server has no bundle for the range. Terminal: pick a range from
    /// `GET /available-ranges`, or build one with `POST /build-bundle`.
    BundleNotFound {
        start_slot: u64,
        end_slot: u64,
    },
    /// The session could not start a slot. Terminal: report it with the session's `task_id`.
    AdvanceSlotFailed {
        slot: u64,
        error: String,
    },
    /// The session could not finish a slot. Terminal: report it with the session's `task_id`.
    FinalizeSlotFailed {
        slot: u64,
        error: String,
    },
    /// The request is malformed, not allowed in the session's current state, or asks for
    /// something the server cannot serve, such as a range that is not available. Not terminal
    /// for a running session; `error` says what to change.
    InvalidRequest {
        /// What is wrong, and usually how to fix it.
        error: String,
    },
    /// The server failed. Terminal: retry later, and report it if it persists.
    Internal {
        error: String,
    },
    /// Not sent by the current server.
    InvalidBlockhashFormat {
        slot: u64,
        error: String,
    },
    /// Not sent by the current server.
    InitializingSysvarsFailed {
        slot: u64,
        error: String,
    },
    /// The server could not load historical data the session needs, such as its starting state
    /// or an account. Not terminal by [`Self::is_terminal`], but during a create it fails the
    /// create: retry later.
    ClerkError {
        error: String,
    },
    /// An operation inside the session failed, such as reading an account. Not terminal: the
    /// session keeps running, and `simulator-client` only logs these.
    SimulationError {
        error: String,
    },
    /// The session named by an attach, `continueSessionV1`, `continueToSessionV1` or
    /// `closeSessionV1` does not exist or has ended. Not terminal.
    SessionNotFound {
        /// The ID you sent.
        session_id: String,
    },
    /// You tried to attach to a session created with a different API key. Not terminal: attach
    /// with the key that created it.
    SessionOwnerMismatch,
    /// The session is moving to another server, or another attach raced this one. Not terminal:
    /// retry the attach after a short backoff; a managed session does this for you. Also sent
    /// when attaching a session of a parallel run on its own: attach the parallel run with
    /// `attachParallelControlSessionV2` instead.
    SessionOwnershipBusy {
        /// Why the attach was refused.
        reason: String,
    },
    /// The requested range contains no produced blocks (every slot in it was
    /// skipped onchain), so there is nothing to execute. A user error: the
    /// session cannot start and the range must be adjusted. Terminal.
    // Appended last: the manager<->runtime hop is postcard, where variant
    // order is wire-significant across version skew.
    NoProducedBlocksInRange {
        start_slot: u64,
        end_slot: u64,
    },
    /// Names are never reused, even after their session ends. Choose another name, or resend
    /// the original request with its `create_token` to reclaim this one.
    SessionNameTaken {
        /// The name you asked for.
        session_name: String,
    },
    ProgramdataNotDeployed {
        address: String,
    },
}

impl BacktestError {
    /// Whether a fresh session given the same request would refuse it too.
    pub fn is_refusal(&self) -> bool {
        match self {
            BacktestError::NoProducedBlocksInRange { .. }
            | BacktestError::ProgramdataNotDeployed { .. } => true,
            BacktestError::InvalidTransactionEncoding { .. }
            | BacktestError::InvalidTransactionFormat { .. }
            | BacktestError::InvalidAccountEncoding { .. }
            | BacktestError::InvalidAccountOwner { .. }
            | BacktestError::InvalidAccountPubkey { .. }
            | BacktestError::NoMoreBlocks
            | BacktestError::BundleNotFound { .. }
            | BacktestError::AdvanceSlotFailed { .. }
            | BacktestError::FinalizeSlotFailed { .. }
            | BacktestError::InvalidRequest { .. }
            | BacktestError::Internal { .. }
            | BacktestError::InvalidBlockhashFormat { .. }
            | BacktestError::InitializingSysvarsFailed { .. }
            | BacktestError::ClerkError { .. }
            | BacktestError::SimulationError { .. }
            | BacktestError::SessionNotFound { .. }
            | BacktestError::SessionOwnerMismatch
            | BacktestError::SessionOwnershipBusy { .. }
            | BacktestError::SessionNameTaken { .. } => false,
        }
    }

    /// Errors the backtest cannot recover from mid-session — the single source
    /// of truth for terminal-error classification, shared by the response/event
    /// wrappers and the managed client.
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            BacktestError::NoMoreBlocks
                | BacktestError::BundleNotFound { .. }
                | BacktestError::AdvanceSlotFailed { .. }
                | BacktestError::FinalizeSlotFailed { .. }
                | BacktestError::Internal { .. }
                | BacktestError::NoProducedBlocksInRange { .. }
                | BacktestError::ProgramdataNotDeployed { .. }
        )
    }

    /// Whether the same request may succeed if you send it again later, unchanged.
    ///
    /// True for a server-side failure ([`Self::Internal`], which is also how a create reports
    /// insufficient capacity, and [`Self::ClerkError`]) and for [`Self::SessionOwnershipBusy`].
    /// Every other error names something to change first. A retryable error can still be
    /// terminal: then retry with a new session.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            BacktestError::Internal { .. }
                | BacktestError::ClerkError { .. }
                | BacktestError::SessionOwnershipBusy { .. }
        )
    }
}

/// One contiguous range of slots you can replay: an entry of `GET /available-ranges`.
///
/// A single session must start at `bundle_start_slot` and end at or before
/// `max_bundle_end_slot`. Times are RFC 3339 UTC strings, such as `"2026-01-01T00:00:01Z"`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AvailableRange {
    /// The first slot of the range; a session's `start_slot`.
    pub bundle_start_slot: u64,
    /// When `bundle_start_slot` was produced, if known.
    pub bundle_start_slot_utc: Option<String>,
    /// The last slot a session starting here can reach.
    pub max_bundle_end_slot: Option<u64>,
    /// When `max_bundle_end_slot` was produced, if known.
    pub max_bundle_end_slot_utc: Option<String>,
    /// The range's length in slots, both ends included.
    pub max_bundle_size: Option<u64>,
    /// What the range can be used for. `None` from a server that predates the
    /// field, where every listed range is [`BundleKind::Blocks`].
    #[serde(default)]
    pub kind: Option<BundleKind>,
    /// Who the range is available to. `None` from a server that predates the
    /// field.
    #[serde(default)]
    pub scope: Option<RangeScope>,
}

/// Who a listed range is available to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RangeScope {
    /// Available to every caller.
    Global,
    /// Built for the calling API key, and listed only for that key.
    User,
}

impl RangeScope {
    /// Stable string form matching the serde `snake_case` wire representation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Global => "global",
            Self::User => "user",
        }
    }
}

/// What a bundle build produces.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BundleKind {
    /// The block bundle a session replays transactions from.
    #[default]
    Blocks,
    /// An account-state bundle covering exactly the requested range, which
    /// later sessions replay instead of executing transactions. Builds the
    /// block bundle it needs first.
    AccountState,
}

/// Why a replayed range has to begin where a recording does. Shared so the
/// splitter's refusal and the service's single-session refusal cannot drift
/// apart.
pub const REPLAY_RANGE_ADVICE: &str = "replayed state is resolved by the recording that begins \
     where the request does, so request a range that begins where one was recorded and ends \
     within it";

impl BundleKind {
    /// What a caller is short of, named for a coverage error.
    fn coverage_noun(self) -> &'static str {
        match self {
            Self::Blocks => "bundle range",
            Self::AccountState => "account-state bundle",
        }
    }

    /// [`Self::coverage_noun`] pluralised, for a message about several.
    fn coverage_nouns(self) -> &'static str {
        match self {
            Self::Blocks => "bundle ranges",
            Self::AccountState => "account-state bundles",
        }
    }

    /// Stable string form matching the serde `snake_case` wire representation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Blocks => "blocks",
            Self::AccountState => "account_state",
        }
    }

    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
    pub fn from_str_opt(value: &str) -> Option<Self> {
        match value {
            "blocks" => Some(Self::Blocks),
            "account_state" => Some(Self::AccountState),
            _ => None,
        }
    }
}

/// Spelled for the reader, not the wire: `blocks` shows as `transactions`.
/// Use [`BundleKind::as_str`] where the wire spelling is required.
impl fmt::Display for BundleKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let label = match self {
            Self::Blocks => "transactions",
            Self::AccountState => "account_state",
        };
        f.pad(label)
    }
}

/// Which user-triggered job a stored request belongs to.
///
/// One request table serves them all, and they carry different fields beside the range they share,
/// so a reader has to know which shape it holds.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobKind {
    /// A bundle build: `POST /build-bundle`.
    #[default]
    BundleBuild,
    /// A venue-depth dataset job: `POST /generate-depth`.
    Depth,
    EstimatedFills,
    Predict,
}

impl JobKind {
    /// The wire and storage spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::BundleBuild => "bundle_build",
            Self::Depth => "depth",
            Self::EstimatedFills => "estimated_fills",
            Self::Predict => "predict",
        }
    }

    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
    pub fn from_str_opt(value: &str) -> Option<Self> {
        match value {
            "bundle_build" => Some(Self::BundleBuild),
            "depth" => Some(Self::Depth),
            "estimated_fills" => Some(Self::EstimatedFills),
            "predict" => Some(Self::Predict),
            _ => None,
        }
    }
}

/// Which side of a venue a depth job measures.
///
/// The two sources publish separate datasets over the same range, so this picks the dataset as
/// much as the measurement.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
pub enum DepthSource {
    /// What the venues' own onchain liquidity would have filled.
    #[default]
    Onchain,
    /// What the router would have quoted.
    Router,
}

impl DepthSource {
    /// Stable string form matching the serde wire representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Onchain => "onchain",
            Self::Router => "router",
        }
    }

    /// Inverse of [`Self::as_str`]; returns `None` for an unrecognized value.
    pub fn from_str_opt(value: &str) -> Option<Self> {
        match value {
            "onchain" => Some(Self::Onchain),
            "router" => Some(Self::Router),
            _ => None,
        }
    }

    /// A frozen identity for hashing, deliberately divorced from [`Self::as_str`].
    ///
    /// Job IDs are derived from it, so renaming what callers see must never move them, or a
    /// resubmit of the same measurement would trigger a second job they pay for again.
    #[doc(hidden)]
    pub const fn discriminant(self) -> u8 {
        match self {
            Self::Onchain => 0,
            Self::Router => 1,
        }
    }
}

impl fmt::Display for DepthSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// How often a depth job samples its source; each publishes its own dataset under the source.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
pub enum DepthGranularity {
    /// On a fixed one-slot grid (default).
    #[default]
    Slot,
    /// After each batch where the venue's program or an oracle update wrote an account a probe
    /// reads (`onchain` only).
    Oracle,
}

impl DepthGranularity {
    /// Stable string form matching the serde wire representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Slot => "slot",
            Self::Oracle => "oracle",
        }
    }

    /// Whether this is [`Self::Slot`], the default.
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }

    /// Frozen for job ID hashing, as [`DepthSource::discriminant`] is.
    #[doc(hidden)]
    pub const fn discriminant(self) -> u8 {
        match self {
            Self::Slot => 0,
            Self::Oracle => 1,
        }
    }
}

impl fmt::Display for DepthGranularity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A depth dataset: a source at a granularity it can be measured at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
pub enum DepthKind {
    /// On-chain depth sampled every slot.
    OnchainSlot,
    /// On-chain depth sampled at oracle updates.
    OnchainOracle,
    /// Router depth sampled every slot.
    RouterSlot,
}

impl DepthKind {
    /// The source measured.
    pub const fn source(self) -> DepthSource {
        match self {
            Self::OnchainSlot | Self::OnchainOracle => DepthSource::Onchain,
            Self::RouterSlot => DepthSource::Router,
        }
    }

    /// When the source is sampled.
    pub const fn granularity(self) -> DepthGranularity {
        match self {
            Self::OnchainSlot | Self::RouterSlot => DepthGranularity::Slot,
            Self::OnchainOracle => DepthGranularity::Oracle,
        }
    }
}

/// A source asked for at a granularity it cannot be measured at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the {0} source cannot be measured at {1} granularity")]
pub struct UnmeasuredDepth(pub DepthSource, pub DepthGranularity);

impl TryFrom<(DepthSource, DepthGranularity)> for DepthKind {
    type Error = UnmeasuredDepth;

    fn try_from(
        (source, granularity): (DepthSource, DepthGranularity),
    ) -> Result<Self, Self::Error> {
        match (source, granularity) {
            (DepthSource::Onchain, DepthGranularity::Slot) => Ok(Self::OnchainSlot),
            (DepthSource::Onchain, DepthGranularity::Oracle) => Ok(Self::OnchainOracle),
            (DepthSource::Router, DepthGranularity::Slot) => Ok(Self::RouterSlot),
            (DepthSource::Router, DepthGranularity::Oracle) => {
                Err(UnmeasuredDepth(source, granularity))
            }
        }
    }
}

/// The key prefix a depth job's dataset publishes under, e.g. `depth/onchain/slot`.
pub const fn depth_dataset_prefix(
    source: DepthSource,
    granularity: DepthGranularity,
) -> &'static str {
    match (source, granularity) {
        (DepthSource::Onchain, DepthGranularity::Slot) => "depth/onchain/slot",
        (DepthSource::Onchain, DepthGranularity::Oracle) => "depth/onchain/oracle",
        (DepthSource::Router, DepthGranularity::Slot) => "depth/router/slot",
        (DepthSource::Router, DepthGranularity::Oracle) => "depth/router/oracle",
    }
}

/// Where `dataset` measured under the modifications with `digest` publishes: under `modified/`,
/// never in `dataset` itself.
pub fn modified_dataset_root(dataset: &str, digest: &str) -> String {
    format!("{MODIFIED_PREFIX}/{dataset}/{digest}")
}

/// The directory under which datasets measured under modifications publish.
pub const MODIFIED_PREFIX: &str = "modified";

/// What a depth request will sample, per source. Response body of `GET /generate-depth/coverage`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthCoverageResponse {
    /// One entry per [`DepthSource`].
    pub sources: Vec<DepthSourceCoverage>,
}

/// What one [`DepthSource`] samples.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthSourceCoverage {
    /// Which side of the venue this one measures.
    pub source: DepthSource,
    /// Bumping this in the universe re-samples every reachable range, so it also
    /// partitions the published dataset.
    pub revision: u16,
    /// Market ids, as the dataset's `market` partition spells them.
    pub markets: Vec<String>,
    /// Venue labels, as the dataset's `venue` partition spells them.
    pub venues: Vec<String>,
    /// How many sizes each direction is sampled at.
    pub size_rungs: usize,
    /// Ranges this caller has already published under the current revision.
    ///
    /// Sending the same request again (same source, granularity, range, markets and overrides)
    /// returns the same job ID and its status, without running or charging it again. A failed job
    /// runs again, also without a new charge. A request that differs in any of these, such as an
    /// overlapping range, is a new job.
    pub completed_ranges: Vec<SlotRange>,
}

/// Server-side ceiling on [`DepthSelection::program_overrides`].
pub const MAX_PROGRAM_OVERRIDES: usize = 8;
/// Server-side ceiling on [`DepthSelection::account_overrides`].
pub const MAX_ACCOUNT_OVERRIDES: usize = 64;
/// Ceiling on a request's ELFs together.
pub const MAX_TOTAL_ELF_BYTES: usize = 8 * 1024 * 1024;
/// Ceiling on a session JSON-RPC request's body; fits [`MAX_TOTAL_ELF_BYTES`] base64-encoded.
pub const MAX_RPC_REQUEST_BODY_BYTES: u32 = 16 * 1024 * 1024;
/// Ceiling on a request's decoded account data together. The set repeats on every probe action
/// inside one CreateSession message.
pub const MAX_ACCOUNT_OVERRIDE_BYTES: usize = 128 * 1024;

/// Request body of `POST /generate-depth`.
///
/// Sessions start and stop at snapshot boundaries, so the captured range can extend beyond
/// `start_slot`/`end_slot`; [`DepthStatusResponse::capture`] reports the range actually captured.
/// A range with no bundles first waits for them to build.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DepthRequest {
    /// First slot requested, inclusive; the capture may start earlier. Each row is filed
    /// under the UTC date its slot falls on.
    pub start_slot: u64,
    /// Last slot requested, inclusive; the capture may end later.
    pub end_slot: u64,
    /// What to measure over the range; sent beside the slots.
    #[serde(flatten)]
    pub selection: DepthSelection,
}

/// What a depth job measures over its slot range.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DepthSelection {
    /// Which side of the venue to measure. The two sources publish separate
    /// datasets over the same range.
    #[serde(default)]
    pub source: DepthSource,
    /// How often to sample. Default `slot`; `oracle` needs the `onchain` source.
    #[serde(default, skip_serializing_if = "DepthGranularity::is_default")]
    pub granularity: DepthGranularity,
    /// Market ids to sample. Empty samples every market in the source's universe.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub markets: Vec<String>,
    /// Programs the probes run in place of the deployed ones. `onchain` only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub program_overrides: Vec<ProgramOverride>,
    /// Accounts every probe sees in place of the recorded ones, across the whole range.
    /// `onchain` only.
    #[serde(default, skip_serializing_if = "AccountModifications::is_empty")]
    pub account_overrides: AccountModifications,
}

/// A program the probes run in place of the deployed one: `program_id` names a deployed
/// upgradeable (loader-v3) program, whose code becomes `elf`.
#[serde_with::serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProgramOverride {
    /// The deployed program to replace, base58.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub program_id: Address,
    /// The program binary (ELF) to run instead, base64 on the wire.
    #[serde_as(as = "serde_with::base64::Base64")]
    pub elf: Vec<u8>,
}

/// Response body of `POST /generate-depth` and `GET /generate-depth/{request_id}`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct DepthStatusResponse {
    /// The job ID; poll `GET /generate-depth/{request_id}` with it.
    pub request_id: String,
    pub start_slot: u64,
    pub end_slot: u64,
    pub source: DepthSource,
    /// How often it samples. Absent means `slot`.
    #[serde(default, skip_serializing_if = "DepthGranularity::is_default")]
    pub granularity: DepthGranularity,
    pub status: BundleBuildStatus,
    /// First and last slot the capture covers: the requested range snapped outward. Absent for
    /// a request an older server accepted, and from a server that predates it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture: Option<SlotRange>,
    /// Names the modifications the dataset is measured under, and its
    /// `modified/depth/onchain/slot/<digest>` path. Absent for an unmodified request, and from a
    /// server that predates it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modification_digest: Option<String>,
}

/// The modifications a depth dataset was measured under, stored with each ELF inline as
/// `modifications.json` beside its parts. Its JSON is canonical — each account re-encoded with
/// `space` its data's length — so its blake3 is the dataset's digest.
#[doc(hidden)]
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DepthModifications {
    #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, serde_with::base64::Base64>")]
    pub programs: BTreeMap<Address, Vec<u8>>,
    pub accounts: AccountModifications,
}

/// Request body of `POST /build-bundle`.
///
/// Construct via `..Default::default()` so a new field stays source-compatible.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BundleBuildRequest {
    /// First slot to build, inclusive.
    pub start_slot: u64,
    /// Last slot to build, inclusive.
    pub end_slot: u64,
    /// Slots per bundle, above 0. Absent: the whole range is one bundle. A session replays one
    /// bundle, so smaller bundles allow more parallel sessions.
    #[serde(default)]
    pub bundle_size: Option<u64>,
    /// Optional repeat key; a resubmit dedupes the quota charge. The same key
    /// under a different `kind` is a distinct request.
    #[serde(default)]
    pub idempotency_key: Option<String>,
    /// Absent on the wire means [`BundleKind::Blocks`].
    #[serde(default)]
    pub kind: BundleKind,
}

/// Where a bundle build or depth job is. snake_case on the wire: `"in_progress"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BundleBuildStatus {
    /// The bundle was built and is ready to use.
    Completed,
    /// The build failed and will not produce a bundle.
    Failed,
    /// The build has not finished yet; poll the status endpoint again later.
    InProgress,
    /// The outcome of the build could not be determined; do not assume success
    /// or failure.
    NeedsInvestigation,
}

impl BundleBuildStatus {
    /// Stable string form matching the serde `snake_case` wire representation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::InProgress => "in_progress",
            Self::NeedsInvestigation => "needs_investigation",
        }
    }
}

/// Response of the server's bundle-build endpoints.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct BundleBuildStatusResponse {
    /// The job ID; poll `GET /build-bundle/{request_id}` with it.
    pub request_id: String,
    pub start_slot: u64,
    pub end_slot: u64,
    /// Slots per bundle, as requested.
    pub bundle_size: Option<u64>,
    pub status: BundleBuildStatus,
    /// When the job was created (unix ms) — lets clients show a live ETA
    /// countdown by computing elapsed since this.
    pub created_at_unix_ms: u64,
    /// Absent on records predating the field, which are all `blocks`.
    #[serde(default)]
    pub kind: BundleKind,
    /// Server-side estimate of the seconds left on an in-progress build.
    /// `None` on a build that isn't running or if inputs can't be resolved.
    #[serde(default)]
    pub eta_secs: Option<u64>,
}

/// A bundle the caller owns and can use now. Ordered by slot range, then kind.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct CompletedBundle {
    pub start_slot: u64,
    pub end_slot: u64,
    pub kind: BundleKind,
    /// When the bundle became available (unix ms), where known.
    #[serde(default)]
    pub completed_at_unix_ms: Option<i64>,
    /// The bundle's size in bytes, where known.
    #[serde(default)]
    pub size_bytes: Option<i64>,
}

/// Query of `DELETE /bundles`: the bundle to delete, by kind and exact range.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BundleDeleteRequest {
    #[allow(missing_docs)]
    pub start_slot: u64,
    #[allow(missing_docs)]
    pub end_slot: u64,
    /// Absent means [`BundleKind::Blocks`].
    #[serde(default)]
    pub kind: BundleKind,
}

/// What `DELETE /bundles` removed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct BundleDeleteResponse {
    pub start_slot: u64,
    pub end_slot: u64,
    pub kind: BundleKind,
}

/// Response of `GET /build-bundle`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BundleBuildListResponse {
    /// The caller's own builds, newest first. A build belongs to the endpoint
    /// running it, so this covers only builds requested here.
    pub builds: Vec<BundleBuildStatusResponse>,
    /// The caller's own bundles, ascending by range, wherever they were built.
    /// Not a view of `builds`: one build can produce several bundles, and a
    /// bundle outlives the record of the build that made it. `None` when the
    /// listing was unavailable, as opposed to `Some([])` for owning nothing.
    #[serde(default)]
    pub bundles: Option<Vec<CompletedBundle>>,
}

/// Response of the server's `/snapshot-slot` endpoint. The chosen source and
/// import state are internal, so only the resolved slot is exposed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotSlotResponse {
    /// The most recent slot the server has a snapshot for.
    pub snapshot_slot: u64,
}

/// Response of `POST /datasets/credentials`: temporary, read-only credentials
/// plus a path, so a caller doesn't need to reconstruct the S3 layout.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct DatasetCredentialsResponse {
    pub access_key_id: String,
    pub secret_access_key: String,
    pub session_token: String,
    /// When the credentials stop working; request new ones after it.
    pub expiration: Option<chrono::DateTime<chrono::Utc>>,
    /// The shared datasets, as an `s3://` URI.
    pub s3_uri: String,
    /// Where this key's own jobs publish, when its name can be a prefix segment.
    /// `None` leaves the caller the shared datasets only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_s3_uri: Option<String>,
    pub region: Option<String>,
}

/// Split a user-requested `[start_slot, end_slot]` range across the available
/// bundle ranges, returning a list of contiguous, non-overlapping `(start, end)`
/// pairs — one per bundle that the server can serve as its own session.
///
/// Each emitted `start` is a real `bundle_start_slot` and each `end` is within
/// the `max_bundle_end_slot` of a bundle that begins *exactly* at that start
/// (the server requires `start_slot == bundle_start_slot` and caps `end_slot` at
/// that bundle's `max_bundle_end_slot`). Among all such gap-free splits we pick
/// the one with the most sub-ranges, i.e. the highest parallelism: a fine-grained
/// (e.g. 10k) bundle grid yields one session per fine bundle instead of
/// collapsing onto a coarser series that overlaps the same slots — even when the
/// coarse and fine bundles share a start slot. A coarser bundle is only ridden
/// where no finer grid continues the walk, which still lets us serve a request
/// the coarse data covers even across a hole in the fine grid.
///
/// `kind` picks which bundles the split rides; the walk itself is the same for
/// either, since a recording is read slot by slot exactly as a block bundle is.
/// An unlabelled range, from a server predating [`AvailableRange::kind`],
/// counts as [`BundleKind::Blocks`].
///
/// Returns an error if the requested start cannot anchor, or if no gap-free
/// split reaches `requested_end`.
pub fn split_range(
    ranges: &[AvailableRange],
    requested: SlotRange,
    kind: BundleKind,
) -> Result<Vec<(u64, u64)>, String> {
    split_range_preferring(ranges, requested, kind, Prefer::Most)
}

/// [`split_range`], choosing the gap-free split with the fewest sub-ranges
/// instead of the most. Anchors, validates and errors exactly like it: an
/// uncovered range names the first slot no bundle reaches.
pub fn split_range_fewest(
    ranges: &[AvailableRange],
    requested: SlotRange,
    kind: BundleKind,
) -> Result<Vec<(u64, u64)>, String> {
    split_range_preferring(ranges, requested, kind, Prefer::Fewest)
}

/// Which gap-free split [`split_range_preferring`] keeps when several reach the end.
#[derive(Clone, Copy)]
enum Prefer {
    Most,
    Fewest,
}

/// The walk behind [`split_range`] and [`split_range_fewest`], keeping the split
/// with the sub-range count `prefer` names.
fn split_range_preferring(
    ranges: &[AvailableRange],
    requested: SlotRange,
    kind: BundleKind,
    prefer: Prefer,
) -> Result<Vec<(u64, u64)>, String> {
    let (requested_start, requested_end) = (requested.start(), requested.end());

    // Every advertised end per bundle start. A start can carry several ends — a
    // 50k snapshot bundle and the 10k bundle built on the same snapshot share a
    // start slot but reach different ends — so we keep them all and let the walk
    // pick among them.
    // A one-slot bundle (`end == start`) counts: a series whose last split
    // begins on the requested end records exactly one slot.
    let ends_by_start = ranges
        .iter()
        .filter(|r| r.kind.unwrap_or_default() == kind)
        .filter_map(|r| {
            r.max_bundle_end_slot
                .filter(|&end| end >= r.bundle_start_slot)
                .map(|end| (r.bundle_start_slot, end))
        })
        .fold(
            BTreeMap::<u64, BTreeSet<u64>>::new(),
            |mut ends_by_start, (start, end)| {
                ends_by_start.entry(start).or_default().insert(end);
                ends_by_start
            },
        );

    // Anchor a request that lands mid-bundle to the covering bundle's start —
    // the latest bundle beginning at or before `requested_start` that still
    // covers it. The server's `select_parallel_requests` shares this fn and
    // anchors the same way, so the client must too or it would falsely reject a
    // start that isn't itself a bundle boundary. An exact bundle-start request
    // anchors to itself. (Single sessions instead require an exact bundle start
    // for every kind: `evaluate_requested_range`.)
    let Some((&anchor_start, _)) = ends_by_start.range(..=requested_start).rfind(|(_, ends)| {
        ends.iter()
            .next_back()
            .is_some_and(|&end| end >= requested_start)
    }) else {
        return Err(format!(
            "start_slot {requested_start} is not covered by any available {}",
            kind.coverage_noun()
        ));
    };

    // Walk the bundle starts from `requested_end` backwards, recording for each
    // start the gap-free split `prefer` picks. A sub-range ends within one of its
    // start's bundles and the next sub-range must begin on the very next slot.
    let mut best_from: BTreeMap<u64, Vec<(u64, u64)>> = BTreeMap::new();
    for (&start, ends) in ends_by_start.range(anchor_start..=requested_end).rev() {
        let mut best: Option<Vec<(u64, u64)>> = None;
        for &end in ends {
            let candidate = if end >= requested_end {
                Some(vec![(start, requested_end)])
            } else {
                best_from.get(&(end + 1)).map(|rest| {
                    std::iter::once((start, end))
                        .chain(rest.iter().copied())
                        .collect()
                })
            };
            if let Some(candidate) = candidate
                && best.as_ref().is_none_or(|b| match prefer {
                    Prefer::Most => candidate.len() > b.len(),
                    Prefer::Fewest => candidate.len() < b.len(),
                })
            {
                best = Some(candidate);
            }
        }
        if let Some(best) = best {
            best_from.insert(start, best);
        }
    }

    best_from.remove(&anchor_start).ok_or_else(|| {
        // Point at the first uncovered slot when the bundles leave a hole; fall
        // back to a generic message when the range is covered but cannot be
        // tiled to bundle boundaries.
        let mut covered_to = anchor_start.saturating_sub(1);
        for (&start, ends) in ends_by_start.range(anchor_start..=requested_end) {
            if start > covered_to.saturating_add(1) {
                break;
            }
            if let Some(&end) = ends.iter().next_back() {
                covered_to = covered_to.max(end);
            }
        }
        if covered_to < requested_end {
            format!("gap in coverage at slot {}", covered_to + 1)
        } else {
            format!(
                "no gap-free split of [{requested_start}, {requested_end}] aligns with the available {}",
                kind.coverage_nouns()
            )
        }
    })
}

impl From<BacktestError> for BacktestResponse {
    fn from(error: BacktestError) -> Self {
        Self::Error(error)
    }
}

impl std::error::Error for BacktestError {}

impl fmt::Display for BacktestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BacktestError::InvalidTransactionEncoding { index, error } => {
                write!(f, "invalid transaction encoding at index {index}: {error}")
            }
            BacktestError::InvalidTransactionFormat { index, error } => {
                write!(f, "invalid transaction format at index {index}: {error}")
            }
            BacktestError::InvalidAccountEncoding {
                address,
                encoding,
                error,
            } => write!(
                f,
                "invalid encoding for account {address} ({encoding:?}): {error}"
            ),
            BacktestError::InvalidAccountOwner { address, error } => {
                write!(f, "invalid owner for account {address}: {error}")
            }
            BacktestError::InvalidAccountPubkey { address, error } => {
                write!(f, "invalid account pubkey {address}: {error}")
            }
            BacktestError::NoMoreBlocks => write!(f, "no more blocks available"),
            BacktestError::BundleNotFound {
                start_slot,
                end_slot,
            } => write!(
                f,
                "block bundle not found for start_slot={start_slot}, end_slot={end_slot}"
            ),
            BacktestError::AdvanceSlotFailed { slot, error } => {
                write!(f, "failed to advance to slot {slot}: {error}")
            }
            BacktestError::FinalizeSlotFailed { slot, error } => {
                write!(f, "failed to finalize slot {slot}: {error}")
            }
            BacktestError::InvalidRequest { error } => write!(f, "invalid request: {error}"),
            BacktestError::Internal { error } => write!(f, "internal error: {error}"),
            BacktestError::InvalidBlockhashFormat { slot, error } => {
                write!(f, "invalid blockhash at slot {slot}: {error}")
            }
            BacktestError::InitializingSysvarsFailed { slot, error } => {
                write!(f, "failed to initialize sysvars at slot {slot}: {error}")
            }
            BacktestError::ClerkError { error } => write!(f, "clerk error: {error}"),
            BacktestError::SimulationError { error } => {
                write!(f, "simulation error: {error}")
            }
            BacktestError::SessionNotFound { session_id } => {
                write!(f, "session not found: {session_id}")
            }
            BacktestError::SessionOwnerMismatch => {
                write!(f, "session owner mismatch")
            }
            BacktestError::SessionOwnershipBusy { reason } => {
                write!(f, "session ownership busy: {reason}")
            }
            BacktestError::NoProducedBlocksInRange {
                start_slot,
                end_slot,
            } => write!(
                f,
                "no produced blocks in requested range {start_slot}..={end_slot}; \
                 slot(s) may be skipped onchain"
            ),
            BacktestError::ProgramdataNotDeployed { address } => write!(
                f,
                "{address} is not a deployed upgradeable program's programdata, so its \
                 replacement would never run"
            ),
            BacktestError::SessionNameTaken { session_name } => {
                write!(f, "session name '{session_name}' is already in use")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use solana_account::ReadableAccount;

    use super::*;

    #[rstest]
    #[case::onchain_slot(
        DepthSource::Onchain,
        DepthGranularity::Slot,
        Some(DepthKind::OnchainSlot)
    )]
    #[case::onchain_oracle(
        DepthSource::Onchain,
        DepthGranularity::Oracle,
        Some(DepthKind::OnchainOracle)
    )]
    #[case::router_slot(
        DepthSource::Router,
        DepthGranularity::Slot,
        Some(DepthKind::RouterSlot)
    )]
    #[case::router_oracle(DepthSource::Router, DepthGranularity::Oracle, None)]
    fn only_a_source_at_a_granularity_it_measures_names_a_depth_kind(
        #[case] source: DepthSource,
        #[case] granularity: DepthGranularity,
        #[case] kind: Option<DepthKind>,
    ) {
        let named = DepthKind::try_from((source, granularity));
        assert_eq!(named.ok(), kind);
        if let Some(kind) = kind {
            assert_eq!((kind.source(), kind.granularity()), (source, granularity));
        }
    }

    /// Request ids are derived from these, so they are a wire contract: reordering the variants
    /// or renumbering them would silently re-issue every caller's measurement as a second run.
    #[test]
    fn a_sources_discriminant_is_frozen_independently_of_its_label() {
        assert_eq!(DepthSource::Onchain.discriminant(), 0);
        assert_eq!(DepthSource::Router.discriminant(), 1);
    }

    /// `as_str`, `from_str_opt` and serde are three tables over the same two names; one of them
    /// drifting would change what a stored row or a request body means.
    #[test]
    fn a_source_spells_itself_the_same_way_three_times() {
        for source in [DepthSource::Onchain, DepthSource::Router] {
            assert_eq!(
                serde_json::to_value(source).expect("a source serialises"),
                serde_json::json!(source.as_str())
            );
            assert_eq!(DepthSource::from_str_opt(source.as_str()), Some(source));
        }
    }

    /// The crate doc's casing table is the contract raw clients code against.
    #[rstest]
    #[case::continue_params(r#"{"method": "continue", "params": {"advanceCount": 10}}"#)]
    #[case::attach(
        r#"{"method": "attachBacktestSession", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "last_sequence": 7}}"#
    )]
    #[case::attach_parallel(
        r#"{"method": "attachParallelControlSessionV2", "params": {"control_session_id": "parallel_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "last_sequences": {"backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b": 7}}}"#
    )]
    #[case::continue_v1(
        r#"{"method": "continueSessionV1", "params": {"sessionId": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "request": {"advanceCount": 1}}}"#
    )]
    #[case::resume(r#"{"method": "resumeAttachedSession"}"#)]
    fn a_documented_request_parses(#[case] wire: &str) {
        serde_json::from_str::<BacktestRequest>(wire).expect("documented request parses");
    }

    /// The crate doc's casing table is the contract raw clients code against.
    #[rstest]
    #[case::session_created(
        r#"{"method": "sessionCreated", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "rpc_endpoint": "https://host/backtest/backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b"}}"#
    )]
    #[case::sequenced(r#"{"seqId": 7, "method": "slotNotification", "params": 1234}"#)]
    #[case::ready(r#"{"method": "readyForContinue"}"#)]
    #[case::error(
        r#"{"method": "error", "params": {"bundleNotFound": {"start_slot": 1, "end_slot": 2}}}"#
    )]
    #[case::session_event(
        r#"{"method": "sessionEventV2", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "seq_id": 3, "event": {"method": "readyForContinue"}}}"#
    )]
    fn a_documented_response_round_trips(#[case] wire: &str) {
        let expected: serde_json::Value = serde_json::from_str(wire).expect("valid JSON");
        let actual = match expected.get("seqId") {
            Some(_) => serde_json::to_value(
                serde_json::from_str::<SequencedResponse>(wire)
                    .expect("documented response parses"),
            ),
            None => serde_json::to_value(
                serde_json::from_str::<BacktestResponse>(wire).expect("documented response parses"),
            ),
        }
        .expect("response serialises");
        assert_eq!(actual, expected);
    }

    #[rstest]
    #[case::empty(solana_account::Account { lamports: 1, rent_epoch: 7, ..Default::default() })]
    #[case::executable_with_data(solana_account::Account {
        lamports: 2,
        data: vec![1, 2, 3],
        owner: Address::from([9; 32]),
        executable: true,
        rent_epoch: u64::MAX,
    })]
    fn an_account_survives_the_wire_round_trip_apart_from_its_rent_epoch(
        #[case] account: solana_account::Account,
    ) {
        let wire = AccountData::from(&account);

        assert_eq!(wire.space, account.data.len() as u64);
        assert_eq!(wire.data.encoding, BinaryEncoding::Base64);
        assert_eq!(
            wire.to_account().expect("base64 decodes"),
            solana_account::Account {
                rent_epoch: 0,
                ..account
            }
        );
    }

    #[rstest]
    #[case::nonexistent(0)]
    #[case::funded(1_000_000)]
    fn system_account_is_an_empty_system_owned_account(#[case] lamports: u64) {
        assert_eq!(
            AccountData::system_account(lamports)
                .to_account()
                .expect("base64 decodes"),
            solana_account::Account {
                lamports,
                ..Default::default()
            }
        );
    }

    fn address(byte: u8) -> Address {
        Address::from([byte; 32])
    }

    #[rstest]
    #[case::one("jupiter", Some(&[SwapAggregator::Jupiter][..]))]
    #[case::several("jupiter,okx", Some(&[SwapAggregator::Jupiter, SwapAggregator::Okx][..]))]
    #[case::spaced_and_uppercased(" Jupiter , OKX ", Some(&[SwapAggregator::Jupiter, SwapAggregator::Okx][..]))]
    #[case::repeats_collapse("okx,okx", Some(&[SwapAggregator::Okx][..]))]
    #[case::trailing_separator("okx,", Some(&[SwapAggregator::Okx][..]))]
    #[case::unknown("jupiter,bogus", None)]
    #[case::empty("", None)]
    #[case::separators_only(",,", None)]
    fn reroute_aggregators_parse_the_shapes_a_flag_carries(
        #[case] input: &str,
        #[case] expected: Option<&[SwapAggregator]>,
    ) {
        assert_eq!(
            input.parse::<RerouteAggregators>().ok(),
            expected.map(|aggregators| RerouteAggregators::new(aggregators.iter().copied()))
        );
    }

    /// `Display` renders `--reroute-aggregators`' default, so clap re-parses whatever it prints.
    #[test]
    fn reroute_aggregators_round_trip_through_their_rendering() {
        let aggregators = RerouteAggregators::new([SwapAggregator::Dflow, SwapAggregator::Jupiter]);

        assert_eq!(aggregators.to_string(), "jupiter,dflow");
        assert_eq!(
            aggregators
                .to_string()
                .parse::<RerouteAggregators>()
                .unwrap(),
            aggregators
        );
        assert_eq!(RerouteAggregators::default().to_string(), "jupiter");
    }

    #[test]
    fn all_lists_every_aggregator_once_in_order() {
        // Exhaustive: a new variant stops this compiling, a prompt to add it to `ALL`.
        let _tripwire = |aggregator: SwapAggregator| match aggregator {
            SwapAggregator::Jupiter
            | SwapAggregator::Okx
            | SwapAggregator::Titan
            | SwapAggregator::Dflow => (),
        };

        // Strictly increasing: sorted with no repeats.
        assert!(SwapAggregator::ALL.is_sorted_by(|a, b| a < b));
    }

    #[test]
    fn all_aggregators_render_and_parse_back() {
        let all = RerouteAggregators::all();

        assert_eq!(all.to_string(), "jupiter,okx,titan,dflow");
        assert_eq!(all.to_string().parse::<RerouteAggregators>().unwrap(), all);
    }

    /// The API deserializes aggregators through the same parser the flag uses, so a spelling one
    /// entry point accepts is not a hard error at the other.
    #[test]
    fn aggregators_deserialize_through_the_same_parser_the_flag_uses() {
        let params: CreateSessionParams = serde_json::from_value(
            serde_json::json!({"startSlot": 1, "endSlot": 2, "reroute": {"aggregators": ["Jupiter", "OKX"]}}),
        )
        .expect("decode");

        assert_eq!(
            params.reroute.expect("rerouting requested").aggregators,
            RerouteAggregators::new([SwapAggregator::Jupiter, SwapAggregator::Okx])
        );
    }

    /// A request that names no knob gets the narrow defaults, not the every-aggregator behaviour a
    /// client written before this change expected — the switch these defaults are here to make.
    #[test]
    fn params_without_the_new_reroute_fields_decode_to_the_narrow_defaults() {
        let params: CreateSessionParams = serde_json::from_value(
            serde_json::json!({"startSlot": 1, "endSlot": 2, "reroute": {}}),
        )
        .expect("decode");

        let reroute = params.reroute.expect("rerouting requested");
        assert_eq!(reroute.aggregators, RerouteAggregators::default());
        assert!(reroute.aggregators.contains(SwapAggregator::Jupiter));
        assert!(!reroute.aggregators.contains(SwapAggregator::Okx));
        assert!(!reroute.circular_arbs);
        assert!(!reroute.detect_failed_l1_swaps);
        assert_eq!(reroute.scopes, RerouteScopes::default());
    }

    #[rstest]
    #[case::top_level("top-level", Some(&[SwapScope::TopLevel][..]))]
    #[case::both(" Nested , top-level ", Some(&[SwapScope::TopLevel, SwapScope::Nested][..]))]
    #[case::all(
        "venue,nested,top-level",
        Some(&[SwapScope::TopLevel, SwapScope::Nested, SwapScope::Venue][..])
    )]
    #[case::unknown("nested,bogus", None)]
    #[case::empty(",", None)]
    fn reroute_scopes_parse_the_shapes_a_flag_carries(
        #[case] input: &str,
        #[case] expected: Option<&[SwapScope]>,
    ) {
        assert_eq!(
            input.parse::<RerouteScopes>().ok(),
            expected.map(|scopes| RerouteScopes::new(scopes.iter().copied()))
        );
    }

    /// `Display` renders `--reroute-scopes`' default, so clap re-parses whatever it prints, and the
    /// default stays off the wire so a request written before scopes encodes as it did.
    #[test]
    fn reroute_scopes_round_trip_and_keep_the_default_off_the_wire() {
        let scopes = RerouteScopes::new([SwapScope::Nested, SwapScope::TopLevel]);

        assert_eq!(scopes.to_string(), "top-level,nested");
        assert_eq!(scopes.to_string().parse::<RerouteScopes>().unwrap(), scopes);
        assert_eq!(
            serde_json::to_value(RerouteParams::default()).unwrap()["scopes"],
            serde_json::Value::Null
        );
        assert_eq!(
            serde_json::to_value(RerouteParams {
                scopes,
                ..RerouteParams::default()
            })
            .unwrap()["scopes"],
            serde_json::json!(["top-level", "nested"])
        );
    }

    /// Presence is the switch: a replay that will never quote must not reserve a metis sidecar.
    #[test]
    fn a_request_without_reroute_reserves_no_sidecar() {
        let params: CreateSessionParams =
            serde_json::from_value(serde_json::json!({"startSlot": 1, "endSlot": 2}))
                .expect("decode");

        assert!(!params.requires_sidecar());
    }

    /// A per-slot override schedule is the largest thing a client sends. Each
    /// action alone is incompressible enough to sit near the websocket message
    /// limit; the redundancy lives *across* actions, so the whole vector has to
    /// travel as one blob. Pins both the round trip and that size property.
    #[test]
    fn a_per_slot_action_schedule_compresses_across_actions() {
        let slots = 2_000u64;
        let actions = (0..slots)
            .map(|slot| ScheduledAction {
                anchor: ActionAnchor::AfterSlot { slots: vec![slot] },
                kind: ActionKind::Simulate,
                feeds_reroute: false,
                transactions: Vec::new(),
                account_overrides: AccountModifications(BTreeMap::from([(
                    address(7),
                    AccountData {
                        // Realistic pool account: 2 KiB that barely moves slot to slot.
                        data: EncodedBinary::new(
                            BASE64.encode(
                                [&slot.to_le_bytes()[..], &[0xAB; 2040][..]]
                                    .concat()
                                    .as_slice(),
                            ),
                            BinaryEncoding::Base64,
                        ),
                        executable: false,
                        lamports: 15_144_966,
                        owner: address(9),
                        space: 2048,
                    },
                )])),
                return_accounts: Vec::new(),
                label: None,
                resolve: None,
                within: None,
            })
            .collect::<Vec<_>>();
        let params = CreateSessionParams::builder()
            .start_slot(1)
            .end_slot(slots)
            .actions(actions.clone())
            .build();

        let encoded = serde_json::to_string(&params).expect("serialize");
        let raw = serde_json::to_string(&actions).expect("serialize raw actions");
        assert!(
            encoded.len() * 8 < raw.len(),
            "expected the schedule to compress well; got {} bytes from {} raw",
            encoded.len(),
            raw.len()
        );

        let decoded: CreateSessionParams = serde_json::from_str(&encoded).expect("round trip");
        assert_eq!(
            serde_json::to_string(&decoded.actions).expect("serialize decoded"),
            raw
        );
    }

    /// Absent actions stay absent on the wire, so a session without a schedule
    /// is unchanged by the compression.
    #[test]
    fn an_empty_action_list_is_omitted_entirely() {
        let params = CreateSessionParams::builder()
            .start_slot(1)
            .end_slot(2)
            .build();
        let json = serde_json::to_value(&params).expect("serialize");
        assert!(json.get("actions").is_none(), "{json}");
        let decoded: CreateSessionParams = serde_json::from_value(json).expect("round trip");
        assert!(decoded.actions.is_empty());
    }

    /// The conflict is `send` *and* replay: neither alone is a problem, and simulate runs
    /// fine under replay because it never commits.
    #[test]
    fn send_actions_conflict_with_replay_only_together() {
        let params = |replay, kind| {
            CreateSessionParams::builder()
                .start_slot(1)
                .end_slot(2)
                .replay_account_state(replay)
                .actions(vec![ScheduledAction {
                    anchor: ActionAnchor::BeforeSlot { slots: vec![1] },
                    kind,
                    feeds_reroute: false,
                    transactions: vec!["dGVzdA==".to_string()],
                    account_overrides: Default::default(),
                    return_accounts: Default::default(),
                    label: None,
                    resolve: None,
                    within: None,
                }])
                .build()
        };
        assert!(replay_support::send_action_conflict(&params(false, ActionKind::Send)).is_none());
        assert!(
            replay_support::send_action_conflict(&params(true, ActionKind::Simulate)).is_none()
        );
        let mut publishing = params(true, ActionKind::Simulate);
        publishing.actions[0].feeds_reroute = true;
        assert!(replay_support::send_action_conflict(&publishing).is_none());

        let conflict = replay_support::send_action_conflict(&params(true, ActionKind::Send))
            .expect("send under replay conflicts");
        assert!(conflict.contains("kind: send"), "{conflict}");
        assert!(conflict.contains(replay_support::SEND_ACTION), "{conflict}");
    }

    fn override_entry(owner: Address, executable: bool) -> AccountData {
        AccountData {
            data: EncodedBinary::from_bytes(&[1, 2, 3], BinaryEncoding::Base64),
            executable,
            lamports: 1,
            owner,
            space: 3,
        }
    }

    fn before() -> ActionAnchor {
        ActionAnchor::BeforeSlot { slots: vec![1] }
    }

    fn valid() -> ScheduledAction {
        override_action(before(), address(3), override_entry(address(4), false))
    }

    fn override_action(
        anchor: ActionAnchor,
        account: Address,
        data: AccountData,
    ) -> ScheduledAction {
        ScheduledAction {
            anchor,
            kind: ActionKind::default(),
            transactions: Vec::new(),
            account_overrides: AccountModifications(BTreeMap::from([(account, data)])),
            return_accounts: Vec::new(),
            label: None,
            feeds_reroute: true,
            resolve: None,
            within: None,
        }
    }

    #[test]
    fn override_action_round_trips() {
        let key = address(1);
        let entry = override_entry(address(2), false);
        let action = override_action(
            ActionAnchor::BeforeSlot { slots: vec![5, 9] },
            key,
            entry.clone(),
        );
        let json = serde_json::to_value(&action).unwrap();
        assert!(
            json["anchor"]["slots"].is_string(),
            "slots travel as a compressed blob: {json}"
        );
        let back: ScheduledAction = serde_json::from_value(json).unwrap();
        assert_eq!(back.anchor, ActionAnchor::BeforeSlot { slots: vec![5, 9] });
        assert!(back.feeds_reroute);
        assert!(!back.is_computed_override(), "no transactions to simulate");
        let survived = &back.account_overrides.0[&key];
        assert_eq!(survived.lamports, entry.lamports);
        assert_eq!(survived.data.data, entry.data.data);
    }

    #[rstest]
    #[case::unbounded(None)]
    #[case::bounded(Some(SlotRange::new_unchecked(5, 9)))]
    fn a_slot_bound_round_trips_and_stays_off_the_wire_when_absent(
        #[case] within: Option<SlotRange>,
    ) {
        let action = ScheduledAction {
            within,
            ..resolved_action()
        };
        let json = serde_json::to_value(&action).unwrap();
        assert_eq!(json.get("within").is_some(), within.is_some(), "{json}");
        let back: ScheduledAction = serde_json::from_value(json).unwrap();
        assert_eq!(back.within, within);
    }

    #[test]
    fn a_before_batch_anchor_round_trips_its_batches_compressed() {
        let anchor = ActionAnchor::BeforeBatch {
            batches: vec![
                BatchPosition {
                    slot: 5,
                    batch_index: 2,
                },
                BatchPosition {
                    slot: 5,
                    batch_index: 2,
                },
            ],
        };

        let json = serde_json::to_value(&anchor).unwrap();

        assert_eq!(json["at"], "beforeBatch");
        assert!(json["batches"].is_string(), "{json}");
        assert_eq!(
            serde_json::from_value::<ActionAnchor>(json).unwrap(),
            anchor
        );
    }

    #[test]
    fn an_every_slot_anchor_round_trips_and_defaults_to_every_slot() {
        let anchor = ActionAnchor::AfterEverySlot {
            every_n_slots: NonZeroU64::new(10).unwrap(),
        };
        let json = serde_json::to_value(&anchor).unwrap();
        assert_eq!(
            json,
            serde_json::json!({ "at": "afterEverySlot", "everyNSlots": 10 })
        );
        assert_eq!(
            serde_json::from_value::<ActionAnchor>(json).unwrap(),
            anchor
        );

        assert_eq!(
            serde_json::from_value::<ActionAnchor>(serde_json::json!({ "at": "beforeEverySlot" }))
                .unwrap(),
            ActionAnchor::BeforeEverySlot {
                every_n_slots: NonZeroU64::MIN
            }
        );
        assert!(
            serde_json::from_value::<ActionAnchor>(
                serde_json::json!({ "at": "beforeEverySlot", "everyNSlots": 0 })
            )
            .is_err(),
            "a zero cadence names no slot"
        );
    }

    fn context(
        invoked: &[u8],
        moves_tokens: bool,
        written: &[u8],
        writes_via_unresolved_lookup: bool,
    ) -> TxMatchContext {
        TxMatchContext {
            invoked_programs: invoked.iter().copied().map(address).collect(),
            moves_tokens,
            written_accounts: written.iter().copied().map(address).collect(),
            writes_via_unresolved_lookup,
        }
    }

    /// The venue lists programs 1 and 2, and a scoped filter names account 10.
    #[rstest]
    #[case::update(&[], context(&[1], false, &[11], false), true)]
    #[case::moves_tokens(&[], context(&[1], true, &[11], false), false)]
    #[case::second_program_of_the_set(&[], context(&[2], false, &[11], false), true)]
    #[case::other_program(&[], context(&[3], false, &[11], false), false)]
    #[case::write_to_the_scope(&[10], context(&[1], false, &[11, 10], false), true)]
    #[case::write_elsewhere(&[10], context(&[1], false, &[11], false), false)]
    #[case::unresolved_write_through_a_lookup_table(&[10], context(&[1], false, &[11], true), true)]
    fn an_oracle_update_is_a_token_free_write_by_a_listed_program(
        #[case] accounts: &[u8],
        #[case] ctx: TxMatchContext,
        #[case] expected: bool,
    ) {
        let filter = DiscoveryFilter::OracleUpdate {
            programs: BTreeSet::from([address(1), address(2)]),
            accounts: accounts.iter().copied().map(address).collect(),
        };
        assert_eq!(filter.matches(&ctx), expected);
    }

    #[rstest]
    #[case::write_to_the_scope(&[10], context(&[1], true, &[11, 10], false), true)]
    #[case::another_market_s_write(&[10], context(&[1], false, &[11], false), false)]
    #[case::unresolved_write_through_a_lookup_table(&[10], context(&[1], false, &[11], true), true)]
    #[case::program_did_not_run(&[10], context(&[2], false, &[10], false), false)]
    #[case::empty_scope(&[], context(&[1], false, &[10], true), false)]
    fn a_program_write_is_a_call_to_the_program_writing_its_scope(
        #[case] accounts: &[u8],
        #[case] ctx: TxMatchContext,
        #[case] expected: bool,
    ) {
        let filter = DiscoveryFilter::ProgramWrite {
            program: address(1),
            accounts: accounts.iter().copied().map(address).collect(),
        };
        assert_eq!(filter.matches(&ctx), expected);
    }

    #[rstest]
    #[case::unscoped(
        &[],
        serde_json::json!({ "kind": "oracleUpdate", "value": { "programs": [address(1).to_string()] } })
    )]
    #[case::scoped(
        &[2],
        serde_json::json!({
            "kind": "oracleUpdate",
            "value": { "programs": [address(1).to_string()], "accounts": [address(2).to_string()] }
        })
    )]
    fn an_oracle_update_filter_round_trips_as_kind_and_value(
        #[case] accounts: &[u8],
        #[case] expected: serde_json::Value,
    ) {
        let filter = DiscoveryFilter::OracleUpdate {
            programs: BTreeSet::from([address(1)]),
            accounts: accounts.iter().copied().map(address).collect(),
        };
        let json = serde_json::to_value(&filter).unwrap();

        assert_eq!(json, expected);
        assert_eq!(
            serde_json::from_value::<DiscoveryFilter>(json).unwrap(),
            filter
        );
    }

    #[test]
    fn an_after_change_anchor_round_trips_with_its_accounts() {
        let anchor = ActionAnchor::AfterChange {
            accounts: BTreeSet::from([address(1), address(2)]).try_into().unwrap(),
        };
        let json = serde_json::to_value(&anchor).unwrap();

        assert_eq!(
            json,
            serde_json::json!({
                "at": "afterChange",
                "accounts": [address(1).to_string(), address(2).to_string()]
            })
        );
        assert_eq!(
            serde_json::from_value::<ActionAnchor>(json).unwrap(),
            anchor
        );
    }

    #[rstest]
    #[case::empty(serde_json::json!([]))]
    #[case::not_an_address(serde_json::json!(["not-an-address"]))]
    fn an_after_change_anchor_rejects_an_unusable_account_list(
        #[case] accounts: serde_json::Value,
    ) {
        let json = serde_json::json!({ "at": "afterChange", "accounts": accounts });
        assert!(serde_json::from_value::<ActionAnchor>(json).is_err());
    }

    /// A venue's vaults are token accounts, so pricing one against different inventory means
    /// overriding them. They were rejected outright on the grounds that prepare-stage reads would
    /// desync from simulation — but prepare's only use for them is clerk cache warming, and every
    /// simulation applies the schedule on top of whatever that warmed.
    #[test]
    fn a_token_account_override_is_accepted() {
        let action = override_action(
            before(),
            address(3),
            override_entry(spl_token_interface::ID, false),
        );
        let schedule = decode_override_actions(&[action]).expect("token overrides decode");
        assert!(!schedule.active_at(1).is_empty());
    }

    #[rstest]
    #[case::executable(override_action(before(), address(3), override_entry(address(10), true)))]
    #[case::program_owned(override_action(
        before(),
        address(3),
        override_entry(PROGRAM_OWNERS[0], false),
    ))]
    #[case::after_slot_anchor(override_action(
        ActionAnchor::AfterSlot { slots: vec![1] },
        address(3),
        override_entry(address(4), false),
    ))]
    #[case::every_slot_anchor(override_action(
        ActionAnchor::BeforeEverySlot { every_n_slots: NonZeroU64::MIN },
        address(3),
        override_entry(address(4), false),
    ))]
    #[case::nothing_to_post(ScheduledAction {
        account_overrides: AccountModifications::default(),
        ..valid()
    })]
    // Otherwise an action that meant to send would silently post overrides instead.
    #[case::send(ScheduledAction {
        kind: ActionKind::Send,
        ..valid()
    })]
    #[case::bounded(ScheduledAction {
        within: Some(SlotRange::new_unchecked(0, 9)),
        ..valid()
    })]
    #[allow(deprecated, reason = "exercise the loader-owner rejection path")]
    fn override_actions_reject_invalid_accounts_and_shapes(#[case] action: ScheduledAction) {
        assert!(decode_override_actions(&[action]).is_err());
    }

    fn liquidity_arrays(array_key_indices: Vec<u8>) -> TxResolver {
        TxResolver::LiquidityArrays {
            pool: address(1),
            input_mint: address(2),
            array_key_indices: array_key_indices.try_into().unwrap(),
        }
    }

    fn resolved_action() -> ScheduledAction {
        ScheduledAction {
            anchor: ActionAnchor::AfterSlot { slots: vec![5] },
            kind: ActionKind::Simulate,
            transactions: vec!["dGVzdA==".to_string()],
            account_overrides: AccountModifications::default(),
            feeds_reroute: false,
            return_accounts: Vec::new(),
            label: None,
            resolve: Some(liquidity_arrays(vec![6, 7, 8])),
            within: None,
        }
    }

    fn requote() -> TxResolver {
        TxResolver::Requote {
            dex: address(1),
            input_mint: address(2),
            output_mint: address(3),
            amount: 1_000_000_000,
            slippage_bps: 9900,
        }
    }

    fn validate_session_resolvers(actions: Vec<ScheduledAction>) -> Result<(), ActionResolveError> {
        CreateSessionParams::builder()
            .start_slot(1)
            .end_slot(10)
            .actions(actions)
            .build()
            .validate_action_resolvers()
    }

    #[test]
    fn a_liquidity_arrays_resolver_serializes_as_a_type_tagged_camel_case_object() {
        let resolver = liquidity_arrays(vec![6, 7, 8]);
        let json = serde_json::to_value(&resolver).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "type": "liquidityArrays",
                "pool": address(1).to_string(),
                "inputMint": address(2).to_string(),
                "arrayKeyIndices": [6, 7, 8],
            })
        );
        assert_eq!(
            serde_json::from_value::<TxResolver>(json).unwrap(),
            resolver
        );
    }

    #[test]
    fn a_quote_stamp_resolver_serializes_as_its_type_tag_alone() {
        let json = serde_json::to_value(TxResolver::QuoteStamp).unwrap();
        assert_eq!(json, serde_json::json!({ "type": "quoteStamp" }));
        assert_eq!(
            serde_json::from_value::<TxResolver>(json).unwrap(),
            TxResolver::QuoteStamp
        );
    }

    #[test]
    fn a_requote_resolver_round_trips_its_terms() {
        let resolver = requote();
        let json = serde_json::to_value(&resolver).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "type": "requote",
                "dex": address(1).to_string(),
                "inputMint": address(2).to_string(),
                "outputMint": address(3).to_string(),
                "amount": 1_000_000_000_u64,
                "slippageBps": 9900,
            })
        );
        assert_eq!(
            serde_json::from_value::<TxResolver>(json).unwrap(),
            resolver
        );
    }

    #[test]
    fn only_an_action_that_requotes_needs_the_sidecar() {
        let params = |resolve| {
            CreateSessionParams::builder()
                .start_slot(1)
                .end_slot(10)
                .actions(vec![ScheduledAction {
                    resolve,
                    ..resolved_action()
                }])
                .build()
        };
        assert!(params(Some(requote())).requires_sidecar());
        assert!(!params(Some(TxResolver::QuoteStamp)).requires_sidecar());
    }

    #[test]
    fn an_action_without_a_resolver_omits_the_key_and_reads_back_as_none() {
        let action = ScheduledAction {
            resolve: None,
            ..resolved_action()
        };
        let json = serde_json::to_value(&action).unwrap();
        assert!(json.get("resolve").is_none(), "{json}");
        let back: ScheduledAction = serde_json::from_value(json).unwrap();
        assert_eq!(back.resolve, None);
    }

    #[test]
    fn a_well_formed_resolver_and_an_unresolved_action_pass_validation() {
        let unresolved = ScheduledAction {
            resolve: None,
            kind: ActionKind::Send,
            ..resolved_action()
        };
        assert_eq!(
            validate_session_resolvers(vec![unresolved, resolved_action()]),
            Ok(())
        );
    }

    #[test]
    fn a_quote_stamp_may_rewrite_a_transaction_repeated_per_slot() {
        let stamped = ScheduledAction {
            anchor: ActionAnchor::BeforeSlot { slots: vec![5, 6] },
            transactions: vec!["dGVzdA==".to_string(); 2],
            resolve: Some(TxResolver::QuoteStamp),
            ..resolved_action()
        };
        assert_eq!(validate_session_resolvers(vec![stamped]), Ok(()));
    }

    #[rstest]
    #[case::send(
        ScheduledAction { kind: ActionKind::Send, ..resolved_action() },
        TxResolverError::Send,
    )]
    #[case::no_transactions(
        ScheduledAction { transactions: Vec::new(), ..resolved_action() },
        TxResolverError::TransactionCount { got: 0 },
    )]
    #[case::two_transactions(
        ScheduledAction { transactions: vec!["dGVzdA==".to_string(); 2], ..resolved_action() },
        TxResolverError::TransactionCount { got: 2 },
    )]
    #[case::feeds_reroute(
        ScheduledAction { feeds_reroute: true, ..resolved_action() },
        TxResolverError::FeedsReroute,
    )]
    #[case::quote_stamp_without_transactions(
        ScheduledAction { transactions: Vec::new(), resolve: Some(TxResolver::QuoteStamp), ..resolved_action() },
        TxResolverError::NoTransactions,
    )]
    #[case::requote_without_transactions(
        ScheduledAction { transactions: Vec::new(), resolve: Some(requote()), ..resolved_action() },
        TxResolverError::NoTransactions,
    )]
    #[case::requote_feeding_reroute(
        ScheduledAction { feeds_reroute: true, resolve: Some(requote()), ..resolved_action() },
        TxResolverError::FeedsReroute,
    )]
    fn a_resolver_on_an_action_it_cannot_rewrite_is_rejected_at_its_index(
        #[case] action: ScheduledAction,
        #[case] expected: TxResolverError,
    ) {
        assert_eq!(
            validate_session_resolvers(vec![resolved_action(), action]),
            Err(ActionResolveError {
                action: 1,
                source: expected,
            })
        );
    }

    #[rstest]
    #[case::empty(Vec::new(), ArrayKeyIndicesError::Empty)]
    #[case::duplicate(vec![6, 7, 6], ArrayKeyIndicesError::Duplicate { index: 6 })]
    fn array_key_indices_refuse_an_empty_or_repeating_list(
        #[case] indices: Vec<u8>,
        #[case] expected: ArrayKeyIndicesError,
    ) {
        assert_eq!(ArrayKeyIndices::try_from(indices), Err(expected));
    }

    #[test]
    fn a_resolver_with_unusable_array_key_indices_fails_to_deserialize() {
        let json = serde_json::json!({
            "type": "liquidityArrays",
            "pool": address(1).to_string(),
            "inputMint": address(2).to_string(),
            "arrayKeyIndices": [6, 7, 6],
        });
        assert!(serde_json::from_value::<TxResolver>(json).is_err());
    }

    fn diagnostic_probe() -> DiagnosticProbeParams {
        DiagnosticProbeParams {
            anchor: ActionAnchor::AfterEverySlot {
                every_n_slots: NonZeroU64::MIN,
            },
            markets: vec![address(1), address(2)],
            usd_values: vec![100, 25_000],
            label: Some("depth-0".to_owned()),
            pairs: Vec::new(),
            candidates: Vec::new(),
            candidate_pairs: Vec::new(),
        }
    }

    fn with_candidate(market: u8, pairs: Vec<[Address; 2]>) -> DiagnosticProbeParams {
        DiagnosticProbeParams {
            candidates: vec![DiagnosticCandidate {
                market: address(market),
                owner: address(20),
                address_lookup_table: None,
            }],
            candidate_pairs: pairs,
            ..diagnostic_probe()
        }
    }

    fn paired(market: u8, pairs: Vec<[Address; 2]>) -> DiagnosticProbeParams {
        DiagnosticProbeParams {
            pairs: vec![DiagnosticMarketPairs {
                market: address(market),
                pairs,
            }],
            ..diagnostic_probe()
        }
    }

    #[rstest]
    #[case::no_markets(DiagnosticProbeParams { markets: Vec::new(), ..diagnostic_probe() })]
    #[case::no_usd_values(DiagnosticProbeParams { usd_values: Vec::new(), ..diagnostic_probe() })]
    #[case::too_many_markets(DiagnosticProbeParams {
        markets: (0..=MAX_DIAGNOSTIC_MARKETS as u8).map(address).collect(),
        ..diagnostic_probe()
    })]
    #[case::too_many_usd_values(DiagnosticProbeParams {
        usd_values: (1..=MAX_DIAGNOSTIC_USD_VALUES as u32 + 1).collect(),
        ..diagnostic_probe()
    })]
    #[case::zero_usd_value(DiagnosticProbeParams { usd_values: vec![0, 100], ..diagnostic_probe() })]
    #[case::duplicate_market(DiagnosticProbeParams {
        markets: vec![address(1), address(1)],
        ..diagnostic_probe()
    })]
    #[case::before_slot(DiagnosticProbeParams {
        anchor: ActionAnchor::BeforeSlot { slots: vec![1] },
        ..diagnostic_probe()
    })]
    #[case::before_every_slot(DiagnosticProbeParams {
        anchor: ActionAnchor::BeforeEverySlot { every_n_slots: NonZeroU64::MIN },
        ..diagnostic_probe()
    })]
    #[case::pairs_of_an_unprobed_market(paired(3, vec![[address(7), address(8)]]))]
    #[case::no_pairs(paired(1, Vec::new()))]
    #[case::too_many_pairs(paired(
        1,
        (0..=MAX_DIAGNOSTIC_MARKET_PAIRS as u8)
            .map(|mint| [address(7), address(mint + 8)])
            .collect(),
    ))]
    #[case::self_pair(paired(1, vec![[address(7), address(7)]]))]
    #[case::market_paired_twice(DiagnosticProbeParams {
        pairs: [
            paired(1, vec![[address(7), address(8)]]).pairs,
            paired(1, vec![[address(7), address(9)]]).pairs,
        ]
        .concat(),
        ..diagnostic_probe()
    })]
    #[case::candidate_repeating_a_market(with_candidate(1, vec![[address(7), address(8)]]))]
    #[case::candidate_without_pairs(with_candidate(3, Vec::new()))]
    #[case::candidate_self_pair(with_candidate(3, vec![[address(7), address(7)]]))]
    #[case::markets_and_candidates_over_the_ceiling(DiagnosticProbeParams {
        markets: (0..MAX_DIAGNOSTIC_MARKETS as u8).map(address).collect(),
        ..with_candidate(200, vec![[address(7), address(8)]])
    })]
    fn diagnostic_probes_reject_invalid_shapes(#[case] probe: DiagnosticProbeParams) {
        assert!(probe.validate().is_err());
    }

    #[rstest]
    #[case::without_pairs(diagnostic_probe(), serde_json::json!({
        "anchor": diagnostic_probe().anchor,
        "markets": [address(1).to_string(), address(2).to_string()],
        "usdValues": [100, 25_000],
        "label": "depth-0",
    }))]
    #[case::with_pairs(paired(1, vec![[address(7), address(8)]]), serde_json::json!({
        "anchor": diagnostic_probe().anchor,
        "markets": [address(1).to_string(), address(2).to_string()],
        "usdValues": [100, 25_000],
        "label": "depth-0",
        "pairs": [{
            "market": address(1).to_string(),
            "pairs": [[address(7).to_string(), address(8).to_string()]],
        }],
    }))]
    #[case::with_candidates(with_candidate(3, vec![[address(7), address(8)]]), serde_json::json!({
        "anchor": diagnostic_probe().anchor,
        "markets": [address(1).to_string(), address(2).to_string()],
        "usdValues": [100, 25_000],
        "label": "depth-0",
        "candidates": [{
            "market": address(3).to_string(),
            "owner": address(20).to_string(),
        }],
        "candidatePairs": [[address(7).to_string(), address(8).to_string()]],
    }))]
    fn a_diagnostic_probe_round_trips_its_wire_json(
        #[case] probe: DiagnosticProbeParams,
        #[case] wire: serde_json::Value,
    ) {
        assert_eq!(serde_json::to_value(&probe).unwrap(), wire);
        assert_eq!(
            serde_json::from_value::<DiagnosticProbeParams>(wire).unwrap(),
            probe
        );
    }

    #[rstest]
    #[case::markets_only(diagnostic_probe())]
    #[case::paired(paired(1, vec![[address(7), address(8)]]))]
    #[case::candidates_only(DiagnosticProbeParams {
        markets: Vec::new(),
        ..with_candidate(3, vec![[address(7), address(8)]])
    })]
    #[case::after_slot(DiagnosticProbeParams {
        anchor: ActionAnchor::AfterSlot { slots: vec![1, 2] },
        ..diagnostic_probe()
    })]
    fn diagnostic_probes_accept_valid_shapes(#[case] probe: DiagnosticProbeParams) {
        assert!(probe.validate().is_ok());
    }

    /// The shapes the rejections above are variations of.
    #[test]
    fn override_actions_accept_a_static_and_a_computed_shape() {
        assert!(decode_override_actions(&[valid()]).is_ok());
        // Transactions make the contribution computed rather than static — still valid,
        // just not resolvable until the action runs.
        assert!(
            decode_override_actions(&[ScheduledAction {
                transactions: vec!["dGVzdA==".to_string()],
                ..valid()
            }])
            .is_ok()
        );
    }

    #[test]
    fn override_actions_merge_account_wise_later_wins() {
        let entry = |lamports| AccountData {
            lamports,
            ..override_entry(address(9), false)
        };
        let slot_action = |slots, account, lamports| {
            override_action(ActionAnchor::BeforeSlot { slots }, account, entry(lamports))
        };
        let actions = [
            slot_action(vec![5, 7], address(1), 1),
            slot_action(vec![5], address(2), 2),
            slot_action(vec![5], address(1), 3),
            ScheduledAction {
                anchor: ActionAnchor::AfterSlot { slots: vec![5] },
                kind: ActionKind::Simulate,
                feeds_reroute: false,
                transactions: vec!["dGVzdA==".to_string()],
                account_overrides: AccountModifications::default(),
                return_accounts: Vec::new(),
                label: None,
                resolve: None,
                within: None,
            },
        ];
        let schedule = decode_override_actions(&actions).unwrap();
        assert_eq!(schedule.slots().collect::<Vec<_>>(), vec![5, 7]);
        let lamports_at = |key, slot| {
            schedule
                .active_for(&key, slot)
                .map(|account| account.lamports())
        };
        assert_eq!(lamports_at(address(1), 5), Some(3));
        assert_eq!(lamports_at(address(2), 5), Some(2));
        assert_eq!(lamports_at(address(1), 7), Some(1));
    }

    #[test]
    fn computed_override_resolution_preserves_action_order_and_failure() {
        let key = address(1);
        let static_action = |lamports| {
            override_action(
                ActionAnchor::BeforeSlot { slots: vec![5] },
                key,
                AccountData {
                    lamports,
                    ..override_entry(address(9), false)
                },
            )
        };
        let computed_action = || ScheduledAction {
            transactions: vec!["dGVzdA==".to_string()],
            ..static_action(2)
        };

        let computed_last =
            decode_override_actions(&[static_action(1), computed_action()]).unwrap();
        computed_last
            .resolve(5, 1, Some(HashMap::from([(key, shared_account(2))])))
            .unwrap();
        assert_eq!(
            computed_last.active_for(&key, 5).map(|a| a.lamports()),
            Some(2)
        );

        let static_last = decode_override_actions(&[computed_action(), static_action(3)]).unwrap();
        static_last
            .resolve(5, 0, Some(HashMap::from([(key, shared_account(2))])))
            .unwrap();
        assert_eq!(
            static_last.active_for(&key, 5).map(|a| a.lamports()),
            Some(3)
        );

        let failed = decode_override_actions(&[static_action(1), computed_action()]).unwrap();
        failed.resolve(5, 1, None).unwrap();
        assert_eq!(failed.active_for(&key, 5).map(|a| a.lamports()), Some(1));
        assert!(failed.resolve(5, 1, None).is_err(), "resolving twice");
    }

    fn shared_account(lamports: u64) -> AccountSharedData {
        AccountSharedData::from(solana_account::Account {
            lamports,
            data: vec![1],
            owner: address(9),
            executable: false,
            rent_epoch: 0,
        })
    }

    fn carry_forward_schedule() -> (Address, Address, OverrideSchedule) {
        let (a, b) = (address(1), address(2));
        let schedule = OverrideSchedule::from(BTreeMap::from([
            (10, HashMap::from([(a, shared_account(1))])),
            (
                20,
                HashMap::from([(a, shared_account(2)), (b, shared_account(9))]),
            ),
        ]));
        (a, b, schedule)
    }

    #[test]
    fn override_schedule_resolves_carry_forward_per_account() {
        let (a, b, schedule) = carry_forward_schedule();

        assert!(schedule.active_for(&a, 9).is_none());
        let cases = [
            (9, None, None),
            (10, Some(1), None),
            (15, Some(1), None),
            (20, Some(2), Some(9)),
            (u64::MAX, Some(2), Some(9)),
        ];
        for (slot, want_a, want_b) in cases {
            assert_eq!(
                schedule
                    .active_for(&a, slot)
                    .map(|account| account.lamports()),
                want_a,
                "active_for a at {slot}"
            );
            let active = schedule.active_at(slot);
            assert_eq!(
                active.get(&a).map(ReadableAccount::lamports),
                want_a,
                "active_at a at {slot}"
            );
            assert_eq!(
                active.get(&b).map(ReadableAccount::lamports),
                want_b,
                "active_at b at {slot}"
            );
        }
    }

    #[test]
    fn newly_active_yields_final_values_in_window() {
        let (a, b, schedule) = carry_forward_schedule();

        let newly: HashMap<_, _> = schedule.newly_active(Some(10), 20).into_iter().collect();
        assert_eq!(newly.len(), 2);
        assert_eq!(newly[&a].lamports(), 2);
        assert_eq!(newly[&b].lamports(), 9);
        let spanning: HashMap<_, _> = schedule.newly_active(None, 20).into_iter().collect();
        assert_eq!(spanning[&a].lamports(), 2, "later slot wins");
        assert_eq!(schedule.newly_active(None, 15).len(), 1);
    }

    #[test]
    fn reroute_filter_round_trips_camel_case() {
        let filter = RerouteFilter {
            pairs: BTreeSet::from([MintPair::new(address(1), address(2))]),
        };
        let json = serde_json::to_value(&filter).unwrap();
        assert!(
            json["pairs"][0][0].is_string() && json["pairs"][0][1].is_string(),
            "a pair serializes as two base58 strings: {json}"
        );
        let back: RerouteFilter = serde_json::from_value(json).unwrap();
        assert_eq!(back, filter);
    }

    /// The set lookup is only direction-agnostic because construction normalizes, and
    /// values arriving over the wire have to be normalized on that path too.
    #[test]
    fn mint_pairs_are_normalized_however_they_are_built() {
        let (one, other) = (address(1), address(2));
        assert_eq!(MintPair::new(one, other), MintPair::new(other, one));

        let reversed: MintPair =
            serde_json::from_value(serde_json::json!([other.to_string(), one.to_string()]))
                .unwrap();
        assert_eq!(reversed, MintPair::new(one, other));
    }

    #[test]
    fn fail_fast_divergence_kind_str_round_trips() {
        for kind in [
            FailFastDivergenceKind::AnyNonBenign,
            FailFastDivergenceKind::Tracked,
        ] {
            assert_eq!(
                FailFastDivergenceKind::from_str_opt(kind.as_str()),
                Some(kind)
            );
        }
        assert_eq!(FailFastDivergenceKind::from_str_opt("nonsense"), None);
        assert_eq!(
            FailFastDivergenceKind::default(),
            FailFastDivergenceKind::AnyNonBenign
        );
    }

    #[test]
    fn bundle_not_found_is_terminal_and_descriptive() {
        let error = BacktestError::BundleNotFound {
            start_slot: 100,
            end_slot: 600,
        };

        assert!(error.is_terminal());
        assert_eq!(
            error.to_string(),
            "block bundle not found for start_slot=100, end_slot=600"
        );
    }

    #[test]
    fn no_produced_blocks_is_terminal_and_descriptive() {
        let error = BacktestError::NoProducedBlocksInRange {
            start_slot: 100,
            end_slot: 100,
        };

        assert!(error.is_terminal());
        // placement-e2e matches this phrase to classify the failure as
        // transient; keep it stable.
        assert_eq!(
            error.to_string(),
            "no produced blocks in requested range 100..=100; slot(s) may be skipped onchain"
        );
    }

    #[test]
    fn session_name_taken_is_not_terminal_and_names_the_session() {
        let error = BacktestError::SessionNameTaken {
            session_name: "my-run".to_string(),
        };

        assert!(!error.is_terminal());
        assert_eq!(error.to_string(), "session name 'my-run' is already in use");
    }

    #[rstest]
    #[case::no_produced_blocks(BacktestError::NoProducedBlocksInRange { start_slot: 1, end_slot: 2 }, true)]
    #[case::programdata_not_deployed(BacktestError::ProgramdataNotDeployed { address: "x".into() }, true)]
    #[case::bundle_not_found(BacktestError::BundleNotFound { start_slot: 1, end_slot: 2 }, false)]
    #[case::internal(BacktestError::Internal { error: "x".into() }, false)]
    fn refusals_are_the_terminal_errors_a_fresh_session_meets_again(
        #[case] error: BacktestError,
        #[case] refusal: bool,
    ) {
        assert!(error.is_terminal());
        assert_eq!(error.is_refusal(), refusal);
    }

    fn create_request(
        body: serde_json::Value,
    ) -> Result<CreateBacktestSessionRequestOptions, InvalidSessionName> {
        serde_json::from_value::<CreateBacktestSessionRequest>(body)
            .expect("decode create request")
            .try_into_request_options()
    }

    #[test]
    fn create_requests_from_older_clients_decode_without_a_name() {
        let v0 = create_request(serde_json::json!({"startSlot": 1, "endSlot": 2})).expect("v0");
        assert!(!v0.parallel);
        assert_eq!(v0.name, None);

        let v1 =
            create_request(serde_json::json!({"startSlot": 1, "endSlot": 2, "parallel": true}))
                .expect("v1");
        assert!(v1.parallel);
        assert_eq!(v1.name, None);
    }

    #[test]
    fn named_create_request_without_parallel_keeps_its_name() {
        let options = create_request(serde_json::json!({
            "startSlot": 1,
            "endSlot": 2,
            "name": "my-run",
            "createToken": "token-1",
        }))
        .expect("valid name");

        assert!(!options.parallel);
        assert_eq!(options.request.end_slot, 2);
        let requested = options.name.expect("name");
        assert_eq!(requested.name.as_str(), "my-run");
        assert_eq!(
            requested.create_token.as_ref().map(CreateToken::as_str),
            Some("token-1")
        );
    }

    #[test]
    fn create_request_with_an_invalid_name_is_rejected() {
        let error = create_request(serde_json::json!({
            "startSlot": 1,
            "endSlot": 2,
            "name": "my run",
        }))
        .expect_err("invalid name");
        assert!(error.to_string().contains("'my run'"), "{error}");
    }

    #[test]
    fn create_requests_without_a_name_serialize_as_before() {
        let params = CreateSessionParams::builder()
            .start_slot(1)
            .end_slot(2)
            .build();
        let params_json = serde_json::to_value(&params).expect("encode params");

        let v0 = serde_json::to_value(CreateBacktestSessionRequest::from(params.clone()))
            .expect("encode v0");
        assert_eq!(v0, params_json);

        let v1 = serde_json::to_value(CreateBacktestSessionRequest::from(
            CreateBacktestSessionRequestV1 {
                request: params,
                parallel: true,
                name: None,
                create_token: None,
            },
        ))
        .expect("encode v1");
        let mut expected = params_json;
        expected["parallel"] = true.into();
        assert_eq!(v1, expected);
    }

    #[test]
    fn session_responses_omit_an_absent_name_and_decode_without_one() {
        let created = BacktestResponse::SessionCreated {
            session_id: SessionId::new(),
            rpc_endpoint: "/backtest/s".to_string(),
            task_id: None,
            session_name: None,
        };
        let json = serde_json::to_string(&created).expect("encode");
        assert!(!json.contains("session_name"), "{json}");
        let decoded: BacktestResponse = serde_json::from_str(&json).expect("decode");
        assert!(matches!(
            decoded,
            BacktestResponse::SessionCreated {
                session_name: None,
                ..
            }
        ));

        let parallel = BacktestResponse::SessionsCreatedV2 {
            control_session_id: ControlSessionId::new(),
            control_session_name: None,
            session_ids: Vec::new(),
            task_ids: Vec::new(),
            start_slots: Vec::new(),
            end_slots: Vec::new(),
        };
        let json = serde_json::to_string(&parallel).expect("encode");
        assert!(!json.contains("control_session_name"), "{json}");
        let decoded: BacktestResponse = serde_json::from_str(&json).expect("decode");
        assert!(matches!(
            decoded,
            BacktestResponse::SessionsCreatedV2 {
                control_session_name: None,
                ..
            }
        ));
    }

    #[test]
    fn bundle_build_request_optional_fields_default_to_none() {
        let req: BundleBuildRequest =
            serde_json::from_str(r#"{"start_slot":1,"end_slot":2}"#).expect("parse");
        assert_eq!((req.start_slot, req.end_slot), (1, 2));
        assert_eq!(req.bundle_size, None);
        assert_eq!(req.idempotency_key, None);
    }

    #[test]
    fn bundle_build_request_parses_optional_fields() {
        let req: BundleBuildRequest = serde_json::from_str(
            r#"{"start_slot":1,"end_slot":2,"bundle_size":500,"idempotency_key":"abc"}"#,
        )
        .expect("parse");
        assert_eq!(req.bundle_size, Some(500));
        assert_eq!(req.idempotency_key.as_deref(), Some("abc"));
    }

    #[test]
    fn bundle_build_status_serde_round_trips_with_snake_case() {
        let cases = [
            (BundleBuildStatus::Completed, "\"completed\""),
            (BundleBuildStatus::Failed, "\"failed\""),
            (BundleBuildStatus::InProgress, "\"in_progress\""),
            (
                BundleBuildStatus::NeedsInvestigation,
                "\"needs_investigation\"",
            ),
        ];
        for (status, expected) in cases {
            assert_eq!(serde_json::to_string(&status).unwrap(), expected);
            assert_eq!(
                serde_json::from_str::<BundleBuildStatus>(expected).unwrap(),
                status
            );
            assert_eq!(status.as_str(), expected.trim_matches('"'));
        }
        assert!(serde_json::from_str::<BundleBuildStatus>("\"queued\"").is_err());
    }

    #[test]
    fn bundle_build_request_without_kind_deserializes_as_blocks() {
        // An old client's payload must keep meaning a plain block build.
        let request: BundleBuildRequest =
            serde_json::from_str(r#"{"start_slot":100,"end_slot":200}"#).unwrap();
        assert_eq!(request.kind, BundleKind::Blocks);
    }

    #[test]
    fn bundle_kind_round_trips_over_serde_and_as_str() {
        for kind in [BundleKind::Blocks, BundleKind::AccountState] {
            let json = serde_json::to_string(&kind).unwrap();
            assert_eq!(json, format!("\"{}\"", kind.as_str()));
            assert_eq!(serde_json::from_str::<BundleKind>(&json).unwrap(), kind);
            // The store round-trips through `as_str`, not serde, so the two
            // maps have to agree for a stored kind to read back.
            assert_eq!(BundleKind::from_str_opt(kind.as_str()), Some(kind));
        }
        assert!(serde_json::from_str::<BundleKind>("\"accountState\"").is_err());
        assert_eq!(BundleKind::from_str_opt("accountState"), None);
    }

    #[test]
    fn bundle_build_request_carries_kind_through_serde() {
        let request = BundleBuildRequest {
            start_slot: 100,
            end_slot: 200,
            kind: BundleKind::AccountState,
            ..Default::default()
        };
        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains(r#""kind":"account_state""#), "{json}");
        let parsed: BundleBuildRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.kind, BundleKind::AccountState);
    }

    #[test]
    fn bundle_build_status_response_serializes_request_and_status() {
        let response = BundleBuildStatusResponse {
            request_id: "r".to_string(),
            start_slot: 100,
            end_slot: 200,
            bundle_size: Some(50),
            status: BundleBuildStatus::InProgress,
            created_at_unix_ms: 0,
            kind: BundleKind::Blocks,
            eta_secs: Some(600),
        };
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["request_id"].as_str(), Some("r"));
        assert_eq!(json["start_slot"].as_u64(), Some(100));
        assert_eq!(json["bundle_size"].as_u64(), Some(50));
        assert_eq!(json["status"].as_str(), Some("in_progress"));
        assert_eq!(json["created_at_unix_ms"].as_u64(), Some(0));
        assert_eq!(json["eta_secs"].as_u64(), Some(600));
    }

    #[test]
    fn an_empty_bundles_list_is_distinct_from_an_absent_one() {
        // A server that predates the section sends no `bundles` at all.
        let absent: BundleBuildListResponse = serde_json::from_str(r#"{"builds":[]}"#).unwrap();
        let empty: BundleBuildListResponse =
            serde_json::from_str(r#"{"builds":[],"bundles":[]}"#).unwrap();
        assert_eq!(absent.bundles, None);
        assert_eq!(empty.bundles, Some(Vec::new()));
    }

    #[test]
    fn completed_bundle_round_trips() {
        let bundle = CompletedBundle {
            start_slot: 100,
            end_slot: 200,
            kind: BundleKind::AccountState,
            completed_at_unix_ms: Some(1_700_000_000_000),
            size_bytes: Some(4_096),
        };
        let json = serde_json::to_string(&bundle).unwrap();
        assert!(json.contains(r#""kind":"account_state""#), "{json}");
        assert_eq!(
            serde_json::from_str::<CompletedBundle>(&json).unwrap(),
            bundle
        );

        let sparse = r#"{"start_slot":1,"end_slot":2,"kind":"blocks"}"#;
        let parsed: CompletedBundle = serde_json::from_str(sparse).unwrap();
        assert_eq!(parsed.completed_at_unix_ms, None);
        assert_eq!(parsed.size_bytes, None);
    }

    #[test]
    fn available_range_reads_a_server_that_predates_kind_and_scope() {
        // Deploys are not atomic: a new client must not fail on the old shape.
        let json = r#"{
            "bundle_start_slot": 100,
            "bundle_start_slot_utc": null,
            "max_bundle_end_slot": 200,
            "max_bundle_end_slot_utc": null,
            "max_bundle_size": 101
        }"#;
        let parsed: AvailableRange = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.bundle_start_slot, 100);
        assert_eq!(parsed.kind, None);
        assert_eq!(parsed.scope, None);
    }

    #[test]
    fn available_range_ignores_fields_it_does_not_know() {
        // The other direction: an old client against a newer server.
        let json = r#"{"bundle_start_slot": 1, "some_future_field": "x"}"#;
        assert_eq!(
            serde_json::from_str::<AvailableRange>(json)
                .unwrap()
                .bundle_start_slot,
            1
        );
    }

    #[test]
    fn available_range_labels_round_trip() {
        let range = AvailableRange {
            bundle_start_slot: 100,
            max_bundle_end_slot: Some(200),
            kind: Some(BundleKind::AccountState),
            scope: Some(RangeScope::User),
            ..Default::default()
        };
        let json = serde_json::to_string(&range).unwrap();
        assert!(json.contains(r#""kind":"account_state""#), "{json}");
        assert!(json.contains(r#""scope":"user""#), "{json}");
        let parsed: AvailableRange = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.kind, Some(BundleKind::AccountState));
        assert_eq!(parsed.scope, Some(RangeScope::User));
    }

    /// Deploys are not atomic: a new client reads an old server's status.
    #[rstest]
    #[case::from_a_server_predating_it(None, None)]
    #[case::snapped_outward(Some(SlotRange::new_unchecked(90, 210)), None)]
    #[case::modified(Some(SlotRange::new_unchecked(90, 210)), Some("ab"))]
    fn a_depth_status_carries_its_optional_fields_only_when_it_has_them(
        #[case] capture: Option<SlotRange>,
        #[case] digest: Option<&str>,
    ) {
        let mut wire = serde_json::json!({
            "request_id": "r",
            "start_slot": 100,
            "end_slot": 200,
            "source": "onchain",
            "status": "in_progress",
        });
        if let Some(capture) = capture {
            wire["capture"] = serde_json::json!({"start": capture.start(), "end": capture.end()});
        }
        if let Some(digest) = digest {
            wire["modification_digest"] = digest.into();
        }
        let status: DepthStatusResponse =
            serde_json::from_value(wire.clone()).expect("deserialize");
        assert_eq!(status.capture, capture);
        assert_eq!(status.modification_digest.as_deref(), digest);
        assert_eq!(serde_json::to_value(&status).expect("serialize"), wire);
    }

    /// An unmodified request reaches an older server as it does today, its empty modifications
    /// off the wire. Program ids and owners are base58 while an ELF is base64.
    #[rstest]
    #[case::unmodified(
        serde_json::json!({"start_slot": 100, "end_slot": 199, "source": "onchain"})
    )]
    #[case::at_oracle_updates(serde_json::json!({
        "start_slot": 100,
        "end_slot": 199,
        "source": "onchain",
        "granularity": "oracle",
    }))]
    #[case::modified(serde_json::json!({
        "start_slot": 100,
        "end_slot": 199,
        "source": "onchain",
        "program_overrides": [{"program_id": address(7).to_string(), "elf": "f0VMRg=="}],
        "account_overrides": {
            address(8).to_string(): {
                "data": {"data": "AQID", "encoding": "base64"},
                "executable": false,
                "lamports": 1,
                "owner": address(9).to_string(),
                "space": 3,
            },
        },
    }))]
    fn a_depth_request_keeps_its_wire_shape(#[case] wire: serde_json::Value) {
        let req: DepthRequest = serde_json::from_value(wire.clone()).expect("deserialize");
        assert_eq!(serde_json::to_value(&req).expect("serialize"), wire);
    }

    /// The manager hashes these bytes into the dataset's digest and the tool parses them back:
    /// both fields always present, in this order, each ELF keyed by its program id.
    #[rstest]
    #[case::accounts_only(BTreeMap::new(), r#"{"programs":{},"accounts":{}}"#.to_owned())]
    #[case::one_program(
        BTreeMap::from([(address(7), b"\x7fELF".to_vec())]),
        format!(r#"{{"programs":{{"{}":"f0VMRg=="}},"accounts":{{}}}}"#, address(7))
    )]
    fn a_depth_modifications_manifest_keeps_its_pinned_shape(
        #[case] programs: BTreeMap<Address, Vec<u8>>,
        #[case] expected: String,
    ) {
        let modifications = DepthModifications {
            programs,
            accounts: AccountModifications::default(),
        };
        assert_eq!(
            serde_json::to_string(&modifications).expect("serialize"),
            expected
        );
    }

    fn range(start: u64, end: u64) -> AvailableRange {
        AvailableRange {
            bundle_start_slot: start,
            max_bundle_end_slot: Some(end),
            ..Default::default()
        }
    }

    /// Each case lists the available bundles, the requested `[start, end]`, and
    /// the expected split — `Some(_)` for an accepted plan, `None` when the range
    /// is unservable and `split_range` must error.
    #[rstest::rstest]
    #[case::single(vec![range(100, 300)], 100, 300, Some(vec![(100, 300)]))]
    #[case::multi(
        vec![range(100, 200), range(201, 300), range(301, 400)],
        100, 300, Some(vec![(100, 200), (201, 300)])
    )]
    // Smaller bundles nested inside a larger one don't bridge the gap, but the
    // range is still coverable by riding the coarse series.
    #[case::nested(
        vec![range(100, 500), range(110, 150), range(150, 190), range(501, 900)],
        100, 900, Some(vec![(100, 500), (501, 900)])
    )]
    // A fine grid (1k bundles standing in for the 10k grid) overlapped by a
    // coarser, differently-aligned series: ride the fine grid, never landing on
    // the coarse bundle's drifted start.
    #[case::prefers_finer_grid(
        vec![range(1_000, 1_999), range(1_500, 3_400), range(2_000, 2_999), range(3_000, 3_999)],
        1_000, 3_999, Some(vec![(1_000, 1_999), (2_000, 2_999), (3_000, 3_999)])
    )]
    // A 50k snapshot bundle and the 10k bundles built on it share start 100: ride
    // the 10k grid instead of the coarse end, which would strand the cursor on a
    // slot no bundle starts at.
    #[case::shared_start_prefers_finer(
        vec![range(100, 150), range(100, 120), range(121, 140), range(141, 160)],
        100, 160, Some(vec![(100, 120), (121, 140), (141, 160)])
    )]
    // A coarse bundle (100, 200) overlaps a finer pair covering the same span:
    // split_range maximises parallelism, riding the fine pair (two sessions)
    // rather than merging onto the coarse max end (one session).
    #[case::coarse_overlap_prefers_finer_pair(
        vec![range(100, 200), range(100, 150), range(151, 160)],
        100, 160, Some(vec![(100, 150), (151, 160)])
    )]
    // The fine grid has a hole (nothing starts at 141), but a coarse bundle
    // sharing the start spans it: serve the request off the coarse bundle rather
    // than reporting an unsupported range.
    #[case::falls_back_to_coarse(
        vec![range(100, 160), range(100, 120), range(121, 140)],
        100, 160, Some(vec![(100, 160)])
    )]
    // The last bundle overshoots the requested end and is clamped.
    #[case::clamps_final_bundle(vec![range(100, 199), range(200, 999)], 100, 450, Some(vec![(100, 199), (200, 450)]))]
    // A request landing mid-bundle anchors to the covering bundle's start
    // (matching the server) instead of erroring as "not covered".
    #[case::anchors_mid_bundle(vec![range(150, 350)], 200, 300, Some(vec![(150, 300)]))]
    #[case::anchors_then_continues(
        vec![range(150, 350), range(351, 600)],
        200, 600, Some(vec![(150, 350), (351, 600)])
    )]
    #[case::start_inside_bundle_anchors(vec![range(200, 400)], 300, 400, Some(vec![(200, 400)]))]
    // Errors: a start before any bundle's coverage has no covering bundle...
    #[case::start_before_first_bundle(vec![range(200, 400)], 100, 400, None)]
    // ...the end must be reachable...
    #[case::end_not_covered(vec![range(100, 200)], 100, 300, None)]
    #[case::gap_in_coverage(vec![range(100, 200), range(210, 300)], 100, 300, None)]
    // Per-API-key isolation: a user's finer bundles and a coarse GLOBAL bundle
    // sharing a start are fed as SEPARATE entries (never merged on snapshot_slot,
    // which would keep only the max end). split_range set-unions the ends and
    // rides the finer user grid — a regression guard against re-merging.
    #[case::user_and_global_ranges_not_collapsed(
        vec![range(100, 200), range(100, 150), range(151, 200)],
        100, 200, Some(vec![(100, 150), (151, 200)])
    )]
    fn split_range_cases(
        #[case] ranges: Vec<AvailableRange>,
        #[case] start: u64,
        #[case] end: u64,
        #[case] expected: Option<Vec<(u64, u64)>>,
    ) {
        match expected {
            Some(expected) => assert_eq!(
                split_range(
                    &ranges,
                    SlotRange::new_unchecked(start, end),
                    BundleKind::Blocks
                )
                .unwrap(),
                expected
            ),
            None => assert!(
                split_range(
                    &ranges,
                    SlotRange::new_unchecked(start, end),
                    BundleKind::Blocks
                )
                .is_err()
            ),
        }
    }

    /// Rides the coarsest series that still reaches the end.
    #[rstest]
    #[case::rides_a_coarse_bundle_over_a_finer_pair(
        vec![range(100, 200), range(100, 150), range(151, 160)],
        100, 160, vec![(100, 160)]
    )]
    #[case::never_strands_the_walk(
        vec![range(100, 150), range(100, 120), range(121, 140), range(141, 160)],
        100, 160, vec![(100, 120), (121, 140), (141, 160)]
    )]
    fn split_range_fewest_cases(
        #[case] ranges: Vec<AvailableRange>,
        #[case] start: u64,
        #[case] end: u64,
        #[case] expected: Vec<(u64, u64)>,
    ) {
        assert_eq!(
            split_range_fewest(
                &ranges,
                SlotRange::new_unchecked(start, end),
                BundleKind::Blocks
            ),
            Ok(expected)
        );
    }

    fn account_state_range(start: u64, end: u64) -> AvailableRange {
        AvailableRange {
            kind: Some(BundleKind::AccountState),
            ..range(start, end)
        }
    }

    #[test]
    fn a_replay_split_rides_the_recordings_not_a_finer_block_grid() {
        // The finer block grid wins on piece count, which is precisely what would
        // hand a replay run sub-ranges nothing ever recorded.
        let ranges = vec![
            range(100, 149),
            range(150, 199),
            account_state_range(100, 199),
        ];
        let requested = SlotRange::new_unchecked(100, 199);

        assert_eq!(
            split_range(&ranges, requested, BundleKind::Blocks).unwrap(),
            [(100, 149), (150, 199)]
        );
        assert_eq!(
            split_range(&ranges, requested, BundleKind::AccountState).unwrap(),
            [(100, 199)]
        );
    }

    #[test]
    fn a_replay_split_tiles_consecutive_recordings() {
        let ranges = vec![account_state_range(100, 199), account_state_range(200, 299)];
        assert_eq!(
            split_range(
                &ranges,
                SlotRange::new_unchecked(100, 299),
                BundleKind::AccountState
            )
            .unwrap(),
            [(100, 199), (200, 299)]
        );
    }

    #[test]
    fn a_replay_split_ends_short_of_a_recording() {
        // A recording is read slot by slot, so a session stops wherever asked
        // inside it — the same as a block session does inside its bundle.
        let requested = SlotRange::new_unchecked(100, 150);
        assert_eq!(
            split_range(&[range(100, 199)], requested, BundleKind::Blocks).unwrap(),
            [(100, 150)]
        );
        assert_eq!(
            split_range(
                &[account_state_range(100, 199)],
                requested,
                BundleKind::AccountState
            )
            .unwrap(),
            [(100, 150)]
        );
    }

    #[test]
    fn a_replay_split_ends_short_of_its_last_recording() {
        // Only the last sub-range may stop mid-recording; the ones before it
        // still have to hand over on the very next slot.
        let ranges = vec![account_state_range(100, 199), account_state_range(200, 299)];
        assert_eq!(
            split_range(
                &ranges,
                SlotRange::new_unchecked(100, 250),
                BundleKind::AccountState
            )
            .unwrap(),
            [(100, 199), (200, 250)]
        );
    }

    #[test]
    fn a_replay_split_tiles_a_one_slot_recording() {
        // A series whose last split begins on the requested end records exactly
        // one slot.
        let ranges = vec![account_state_range(100, 249), account_state_range(250, 250)];
        assert_eq!(
            split_range(
                &ranges,
                SlotRange::new_unchecked(100, 250),
                BundleKind::AccountState
            )
            .unwrap(),
            [(100, 249), (250, 250)]
        );
    }

    #[test]
    fn a_replay_split_anchors_a_mid_recording_start() {
        // A mid-bundle start anchors to the bundle covering it, whichever kind
        // the walk rides — the two differ in the bundles they read, not in the
        // ranges they admit.
        let requested = SlotRange::new_unchecked(150, 199);
        assert_eq!(
            split_range(&[range(100, 199)], requested, BundleKind::Blocks).unwrap(),
            [(100, 199)]
        );
        assert_eq!(
            split_range(
                &[account_state_range(100, 199)],
                requested,
                BundleKind::AccountState
            )
            .unwrap(),
            [(100, 199)]
        );
    }

    #[test]
    fn a_replay_split_refuses_a_start_no_recording_covers() {
        let error = split_range(
            &[account_state_range(200, 299)],
            SlotRange::new_unchecked(100, 299),
            BundleKind::AccountState,
        )
        .expect_err("no recording covers 100");
        assert!(
            error.contains("is not covered by any available account-state bundle"),
            "{error}"
        );
    }

    #[test]
    fn a_replay_split_ignores_block_ranges() {
        let error = split_range(
            &[range(100, 199)],
            SlotRange::new_unchecked(100, 199),
            BundleKind::AccountState,
        )
        .expect_err("owns no recordings");
        assert!(error.contains("account-state bundle"), "{error}");
    }

    #[test]
    fn blocks_mode_admits_ranges_from_a_server_that_predates_kind() {
        // A server predating the field omits it, and those ranges must still
        // split exactly as they did before the kind was consulted.
        let unlabelled = range(100, 199);
        assert_eq!(unlabelled.kind, None);
        assert_eq!(
            split_range(
                &[unlabelled],
                SlotRange::new_unchecked(100, 150),
                BundleKind::Blocks
            )
            .unwrap(),
            [(100, 150)]
        );
    }

    /// Servable end per bundle start, as `split_range` sees it — every advertised
    /// end at or past its start, keyed by start.
    fn ends_by_start(ranges: &[AvailableRange]) -> BTreeMap<u64, BTreeSet<u64>> {
        let mut ends: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
        for r in ranges {
            if let Some(end) = r.max_bundle_end_slot
                && end >= r.bundle_start_slot
            {
                ends.entry(r.bundle_start_slot).or_default().insert(end);
            }
        }
        ends
    }

    /// Independent spec for the optimum: the sub-range count of every gap-free
    /// split of `[cursor, end]`, found by exhaustively trying every advertised end
    /// at each cursor. Empty when no split aligns with the bundle starts.
    fn split_lengths(
        ends: &BTreeMap<u64, BTreeSet<u64>>,
        cursor: u64,
        end: u64,
    ) -> BTreeSet<usize> {
        ends.get(&cursor)
            .into_iter()
            .flatten()
            .flat_map(|&bundle_end| {
                if bundle_end >= end {
                    BTreeSet::from([1])
                } else {
                    split_lengths(ends, bundle_end + 1, end)
                        .into_iter()
                        .map(|rest| rest + 1)
                        .collect()
                }
            })
            .collect()
    }

    /// Structure-independent check that a split is one the server can serve: it
    /// tiles `[start, end]` gap-free, every start is a real bundle start, and
    /// every end is within that start's largest advertised end.
    fn is_valid_split(
        split: &[(u64, u64)],
        ends: &BTreeMap<u64, BTreeSet<u64>>,
        start: u64,
        end: u64,
    ) -> bool {
        split.first().is_some_and(|&(s, _)| s == start)
            && split.last().is_some_and(|&(_, e)| e == end)
            && split.windows(2).all(|w| w[1].0 == w[0].1 + 1)
            && split.iter().all(|&(s, e)| {
                e >= s
                    && ends
                        .get(&s)
                        .and_then(|bundle_ends| bundle_ends.iter().next_back())
                        .is_some_and(|&max_end| e <= max_end)
            })
    }

    type SplitFn = fn(&[AvailableRange], SlotRange, BundleKind) -> Result<Vec<(u64, u64)>, String>;
    type OptimumFn = fn(&BTreeSet<usize>) -> Option<&usize>;

    /// Property test: across many randomized bundle layouts, each walk must return
    /// a *valid* split with its *optimal* number of sub-ranges (the most for
    /// `split_range`, the fewest for `split_range_fewest`) whenever one exists, and
    /// error exactly when none does. Deterministic (fixed LCG seed) so a failure is
    /// reproducible.
    #[rstest]
    #[case::most(split_range as SplitFn, BTreeSet::last as OptimumFn)]
    #[case::fewest(split_range_fewest as SplitFn, BTreeSet::first as OptimumFn)]
    fn split_range_matches_reference(#[case] walk: SplitFn, #[case] optimum: OptimumFn) {
        let mut seed: u64 = 0x9E3779B97F4A7C15;
        let mut next = || {
            seed = seed
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            seed >> 33
        };

        for _ in 0..50_000 {
            // A small slot universe makes shared starts, overlaps, nesting, and
            // gaps all common.
            let ranges: Vec<AvailableRange> = (0..next() % 6)
                .map(|_| {
                    let start = next() % 12;
                    range(start, start + next() % 6) // len 0 => filtered out
                })
                .collect();
            let start = next() % 12;
            let end = start + next() % 6; // sometimes start == end, sometimes unservable

            let got = walk(
                &ranges,
                SlotRange::new_unchecked(start, end),
                BundleKind::Blocks,
            );
            let ends = ends_by_start(&ranges);
            // split_range anchors a mid-bundle start to the covering bundle's
            // start, so the reference must walk from the same anchor.
            let anchor = ends
                .range(..=start)
                .rfind(|(_, e)| e.iter().next_back().is_some_and(|&x| x >= start))
                .map(|(&s, _)| s);
            let reference = anchor.and_then(|a| optimum(&split_lengths(&ends, a, end)).copied());

            let layout: Vec<_> = ranges
                .iter()
                .map(|r| (r.bundle_start_slot, r.max_bundle_end_slot))
                .collect();
            match (&got, reference) {
                (Ok(split), Some(best)) => {
                    assert!(
                        is_valid_split(split, &ends, anchor.unwrap(), end),
                        "invalid split {split:?} for {layout:?} [{start},{end}]"
                    );
                    assert_eq!(
                        split.len(),
                        best,
                        "suboptimal split {split:?} vs {best} sub-ranges for {layout:?} [{start},{end}]"
                    );
                }
                (Err(_), None) => {}
                _ => panic!(
                    "disagreement: walk={got:?}, reference={reference:?} sub-ranges for {layout:?} [{start},{end}]"
                ),
            }
        }
    }

    #[test]
    fn a_reroute_without_templates_omits_venue() {
        let json = serde_json::to_value(RerouteParams::default()).expect("serialize");
        assert!(json.get("directFill").is_none(), "{json}");
    }

    #[test]
    fn venue_fields_keep_their_venue_wire_names() {
        let reroute = RerouteParams {
            venue_templates: vec![template("t")],
            ..Default::default()
        };
        let json = serde_json::to_value(&reroute).expect("serialize");
        assert_eq!(json["directFill"][0]["label"], "t", "{json}");

        let json = serde_json::to_value(RerouteStatsReport::default()).expect("serialize");
        for key in [
            "directFillMatched",
            "directFillOutcomes",
            "directFillScored",
            "directFillBpsTotal",
            "directFillTemplates",
        ] {
            assert!(json.get(key).is_some(), "{key} missing from {json}");
        }
    }

    #[test]
    fn extra_markets_cross_the_wire_as_base58() {
        let json = serde_json::to_value(RerouteParams::default()).expect("serialize");
        assert!(json.get("extraMarkets").is_none(), "{json}");

        let reroute = RerouteParams {
            extra_markets: BTreeSet::from([address(7)]),
            ..Default::default()
        };
        let json = serde_json::to_value(&reroute).expect("serialize");
        assert_eq!(
            json["extraMarkets"],
            serde_json::json!([address(7).to_string()])
        );
        assert_eq!(
            serde_json::from_value::<RerouteParams>(json).expect("deserialize"),
            reroute
        );

        serde_json::from_value::<RerouteParams>(serde_json::json!({
            "extraMarkets": ["not-an-address"]
        }))
        .expect_err("an invalid address is rejected");
    }

    /// A valid template, spelled out rather than parsed: the wire twins are their own test.
    fn template(label: &str) -> VenueTemplate {
        let placeholder = Address::default();
        VenueTemplate {
            label: label.to_owned(),
            mode: SwapMode::ExactIn,
            input_mint: mints::SOL,
            output_mint: mints::USDC,
            instruction: TemplateInstruction {
                program_id: address(7),
                accounts: vec![
                    TemplateAccount {
                        address: placeholder,
                        writable: true,
                        signer: true,
                    },
                    TemplateAccount {
                        address: placeholder,
                        writable: true,
                        signer: false,
                    },
                    TemplateAccount {
                        address: placeholder,
                        writable: true,
                        signer: false,
                    },
                    TemplateAccount {
                        address: address(8),
                        writable: false,
                        signer: false,
                    },
                ],
                data: vec![0; 16],
            },
            amount_offset: 2,
            taker: TakerSlots {
                user: vec![0],
                input_token_account: vec![1],
                output_token_account: vec![2],
                derived: Vec::new(),
            },
            resolve: None,
        }
    }

    /// Presence of templates is the switch, exactly as `requote` is.
    #[rstest]
    #[case::requote_alone(true, 0, false)]
    #[case::templates_alone(false, 1, false)]
    #[case::both(true, 2, false)]
    #[case::neither(false, 0, true)]
    fn a_reroute_is_a_noop_only_with_nothing_to_ask(
        #[case] requote: bool,
        #[case] templates: usize,
        #[case] noop: bool,
    ) {
        let reroute = RerouteParams {
            requote,
            venue_templates: (0..templates).map(|i| template(&format!("t{i}"))).collect(),
            ..Default::default()
        };
        assert_eq!(reroute.is_noop(), noop);
    }

    /// A template-only run warms the universe its probes trade through, sidecar or not.
    #[rstest]
    #[case::templates_without_requote(false, 1, true)]
    #[case::requote_without_templates(true, 0, true)]
    #[case::nothing(false, 0, false)]
    fn the_account_universe_warms_for_templates_as_for_requoting(
        #[case] requote: bool,
        #[case] templates: usize,
        #[case] warms: bool,
    ) {
        let params = CreateSessionParams::builder()
            .start_slot(1)
            .end_slot(2)
            .reroute(RerouteParams {
                requote,
                venue_templates: (0..templates).map(|i| template(&format!("t{i}"))).collect(),
                ..Default::default()
            })
            .build();
        assert_eq!(params.warms_account_universe(), warms);
    }

    #[rstest]
    #[case::a_requoted_template_without_requote(false, Some(TemplateResolver::Requote), true)]
    #[case::an_array_template_without_requote(
        false,
        Some(TemplateResolver::LiquidityArrays),
        false
    )]
    #[case::a_fixed_template_without_requote(false, None, false)]
    #[case::requote(true, None, true)]
    fn only_requoting_or_a_requoted_template_needs_the_sidecar(
        #[case] requote: bool,
        #[case] resolve: Option<TemplateResolver>,
        #[case] needs: bool,
    ) {
        let params = CreateSessionParams::builder()
            .start_slot(1)
            .end_slot(2)
            .reroute(RerouteParams {
                requote,
                venue_templates: vec![VenueTemplate {
                    resolve,
                    ..template("t")
                }],
                ..Default::default()
            })
            .build();
        assert_eq!(params.requires_sidecar(), needs);
    }

    /// A busy create arrives as `Internal`; a bad request must never look retryable.
    #[rstest]
    #[case::capacity(BacktestError::Internal { error: "unable to start session: insufficient capacity".into() }, true)]
    #[case::clerk(BacktestError::ClerkError { error: "timeout".into() }, true)]
    #[case::ownership_busy(BacktestError::SessionOwnershipBusy { reason: "draining".into() }, true)]
    #[case::invalid_request(BacktestError::InvalidRequest { error: "bad range".into() }, false)]
    #[case::bundle_not_found(BacktestError::BundleNotFound { start_slot: 1, end_slot: 2 }, false)]
    #[case::name_taken(BacktestError::SessionNameTaken { session_name: "a".into() }, false)]
    #[case::no_more_blocks(BacktestError::NoMoreBlocks, false)]
    fn only_server_side_failures_are_retryable(
        #[case] error: BacktestError,
        #[case] retryable: bool,
    ) {
        assert_eq!(error.is_retryable(), retryable);
    }
}