ccxt-base 4.5.84

CCXT – CryptoCurrency eXchange Trading Library (Rust) – untyped engine (runtime, Value, REST/prediction Cores, WS infra)
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
// The OrderRouter suite, living in ccxt-base rather than in the ti-rust test crate.
//
// It is here for one practical reason: ti-rust links the whole generated surface
// (104 typed REST wrappers, 76 WS ones), and building that needs more memory
// than some development machines have — it OOM-kills at link time on a 16 GB
// box, the same way the Go test binary does. The suite exercises nothing but
// `Value` and `OrderRouter`, both of which live in THIS crate, so putting it
// here makes it runnable with `cargo test -p ccxt-base` in about a minute
// without the generated venues.
//
// `run()` is public so `ti-rust --orderRouterTests` drives exactly the same
// checks in CI, alongside the other five ports. One harness, two entry points —
// a second copy is how the two would drift.

// OrderRouter — the sixth port's half of the cross-language contract.
//
// The class is hand-written in six languages; `ts/src/test/base/fixtures/
// orderRouter.json` is what stops them drifting. This file runs that fixture in
// Rust. A case that passes in TypeScript, Python, PHP, C# and Go and fails here
// means THIS port is wrong — that is the whole reason for running the same table
// six times rather than trusting six readings of the same spec.

use std::borrow::Cow;
use crate::order_router::{OrderRouter, MAX_EXECUTED_PLAN_IDS, NO_CAP, TOLERANCE};
use crate::value::{HashMap, Value};

fn fixture() -> Result<Value, String> {
    // From this crate's manifest dir: rust/ccxt-base -> repo root.
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../ts/src/test/base/fixtures/orderRouter.json"
    );
    let raw = std::fs::read_to_string(path)
        .map_err(|e| format!("reading the shared fixture at {path}: {e}"))?;
    let parsed: serde_json::Value =
        serde_json::from_str(&raw).map_err(|e| format!("parsing the shared fixture: {e}"))?;
    Ok(Value::from_json(&parsed))
}

fn router() -> Result<OrderRouter, String> {
    let mut config = HashMap::new();
    config.insert("apiKey".to_string(), Value::Str("test-key".to_string().into()));
    OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())
}

fn section(fixture: &Value, name: &str) -> Result<Value, String> {
    match fixture.as_map().and_then(|m| m.get(name)) {
        Some(found) => Ok(found.clone()),
        None => Err(format!("the shared fixture has no `{name}` section")),
    }
}

fn cases(fixture: &Value, name: &str) -> Result<Vec<Value>, String> {
    match section(fixture, name)? {
        Value::Arr(items) if !items.is_empty() => Ok(items.as_ref().clone()),
        Value::Arr(_) => Err(format!("the fixture's `{name}` section is empty")),
        _ => Err(format!("the fixture's `{name}` section is not an array")),
    }
}

fn named(fixture: &Value, section_name: &str, key: &str) -> Result<Value, String> {
    let holder = section(fixture, section_name)?;
    match holder.as_map().and_then(|m| m.get(key)) {
        Some(found) => Ok(found.clone()),
        None => Err(format!("`{section_name}` has no entry named `{key}`")),
    }
}

fn text(container: &Value, key: &str) -> String {
    match container.as_map().and_then(|m| m.get(key)) {
        Some(Value::Str(s)) => s.to_string(),
        _ => String::new(),
    }
}

fn at<'a>(container: &'a Value, key: &str) -> Option<&'a Value> {
    container.as_map().and_then(|m| m.get(key))
}

/// The same relative comparison the other five ports use: floating point cannot
/// be compared exactly across six languages' arithmetic, and an absolute epsilon
/// is wrong at both ends of the magnitude range a price can take.
fn numbers_match(a: f64, b: f64) -> bool {
    if a == b {
        return true;
    }
    if !a.is_finite() || !b.is_finite() {
        // An infinity only ever matches itself. Without this the relative
        // comparison below reads Infinity <= Infinity as a match, and an
        // infinite value passes against ANY expectation — which is exactly how
        // a number grammar that overflows would slip past the numberCases table.
        return false;
    }
    let mut scale = 1.0f64;
    if a.abs() > scale {
        scale = a.abs();
    }
    if b.abs() > scale {
        scale = b.abs();
    }
    (a - b).abs() <= TOLERANCE * scale
}

fn as_number(value: &Value) -> Option<f64> {
    match value {
        Value::Int(n) => Some(*n as f64),
        Value::Float(n) => Some(*n),
        _ => None,
    }
}

/// Compares an actual structure against the fixture's expectation, in BOTH
/// directions: a missing field and an invented field are both drift.
fn assert_matches(actual: &Value, expected: &Value, whereat: &str) -> Result<(), String> {
    match expected {
        Value::Arr(expected_items) => {
            let actual_items = match actual {
                Value::Arr(items) => items,
                other => return Err(format!("{whereat}: expected an array, got {other:?}")),
            };
            if actual_items.len() != expected_items.len() {
                return Err(format!(
                    "{whereat}: array length — expected {}, got {}",
                    expected_items.len(),
                    actual_items.len()
                ));
            }
            for (i, expected_item) in expected_items.iter().enumerate() {
                assert_matches(&actual_items[i], expected_item, &format!("{whereat}[{i}]"))?;
            }
            Ok(())
        }
        Value::Dict(expected_map) => {
            let actual_map = match actual {
                Value::Dict(map) => map,
                other => return Err(format!("{whereat}: expected an object, got {other:?}")),
            };
            let mut expected_keys: Vec<&String> = expected_map.keys().collect();
            let mut actual_keys: Vec<&String> = actual_map.keys().collect();
            expected_keys.sort();
            actual_keys.sort();
            if expected_keys != actual_keys {
                return Err(format!(
                    "{whereat}: key set — expected {expected_keys:?}, got {actual_keys:?}"
                ));
            }
            for key in expected_keys {
                assert_matches(
                    actual_map.get(key).unwrap_or(&Value::Null),
                    expected_map.get(key).unwrap_or(&Value::Null),
                    &format!("{whereat}.{key}"),
                )?;
            }
            Ok(())
        }
        _ => {
            if let Some(expected_number) = as_number(expected) {
                let actual_number = as_number(actual).ok_or_else(|| {
                    format!("{whereat}: expected the number {expected_number}, got {actual:?}")
                })?;
                if !numbers_match(actual_number, expected_number) {
                    return Err(format!(
                        "{whereat}: expected {expected_number}, got {actual_number}"
                    ));
                }
                return Ok(());
            }
            if actual != expected {
                return Err(format!("{whereat}: expected {expected:?}, got {actual:?}"));
            }
            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// the shared fixture — the cross-language contract
// ---------------------------------------------------------------------------

fn fixture_build_execution_plan(r: &OrderRouter, f: &Value) -> Result<(), String> {
    for test_case in cases(f, "planCases")? {
        let route = named(f, "routes", &text(&test_case, "route"))?;
        let options = at(&test_case, "options").cloned().unwrap_or(Value::Null);
        let plan = r.build_execution_plan(&route, &options).map_err(|e| e.to_string())?;
        let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
        assert_matches(&plan, &expected, &format!("planCase {}", text(&test_case, "id")))?;
    }
    Ok(())
}

fn fixture_plan_is_deterministic(r: &OrderRouter, f: &Value) -> Result<(), String> {
    for test_case in cases(f, "planCases")? {
        let route = named(f, "routes", &text(&test_case, "route"))?;
        let options = at(&test_case, "options").cloned().unwrap_or(Value::Null);
        let before = serde_json::to_string(&route.to_json()).map_err(|e| e.to_string())?;
        let first = r.build_execution_plan(&route, &options).map_err(|e| e.to_string())?;
        let second = r.build_execution_plan(&route, &options).map_err(|e| e.to_string())?;
        let id = text(&test_case, "id");
        assert_matches(&second, &first, &format!("planCase {id} repeated"))?;
        let after = serde_json::to_string(&route.to_json()).map_err(|e| e.to_string())?;
        if before != after {
            return Err(format!("planCase {id}: the route was mutated"));
        }
    }
    Ok(())
}

fn fixture_check_execution_plan_safety(r: &OrderRouter, f: &Value) -> Result<(), String> {
    for test_case in cases(f, "safetyCases")? {
        let route = named(f, "routes", &text(&test_case, "route"))?;
        let markets = named(f, "marketSets", &text(&test_case, "markets"))?;
        let plan_options = at(&test_case, "planOptions").cloned().unwrap_or(Value::Null);
        let options = at(&test_case, "options").cloned().unwrap_or(Value::Null);
        let plan = r.build_execution_plan(&route, &plan_options).map_err(|e| e.to_string())?;
        let violations = r.check_execution_plan_safety(&plan, &markets, &options);
        let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
        assert_matches(
            &Value::List(violations),
            &expected,
            &format!("safetyCase {}", text(&test_case, "id")),
        )?;
    }
    Ok(())
}

fn fixture_reconcile_execution_step(r: &OrderRouter, f: &Value) -> Result<(), String> {
    for test_case in cases(f, "reconcileCases")? {
        // A case names either a route to plan from, or a plan written out in
        // full — the latter is how a plan with field types no builder produces
        // (an int hopIndex on one step and a float on the next) gets covered.
        let plan = if at(&test_case, "plan").is_some() {
            named(f, "plans", &text(&test_case, "plan"))?
        } else {
            let route = named(f, "routes", &text(&test_case, "route"))?;
            let plan_options = at(&test_case, "planOptions").cloned().unwrap_or(Value::Null);
            r.build_execution_plan(&route, &plan_options).map_err(|e| e.to_string())?
        };
        let step_index = r.number_at(&test_case, "stepIndex", 0.0) as i64;
        let realised_out = r.number_at(&test_case, "realisedOut", 0.0);
        let verdict = r
            .reconcile_execution_step(&plan, step_index, realised_out)
            .map_err(|e| e.to_string())?;
        let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
        assert_matches(&verdict, &expected, &format!("reconcileCase {}", text(&test_case, "id")))?;
    }
    Ok(())
}

fn fixture_reconcile_sequence(r: &OrderRouter, f: &Value) -> Result<(), String> {
    // reconcile_execution_step is pure and cannot remember across calls, so a
    // hop's cumulative shortfall lives on the steps themselves — written by
    // apply_resize. That interaction is only visible across a SEQUENCE of calls,
    // which reconcileCases (one call each) cannot express, and it is exactly
    // where the six ports could silently disagree.
    for test_case in cases(f, "reconcileSequenceCases")? {
        let id = text(&test_case, "id");
        let mut steps: Vec<Value> = match at(&test_case, "steps") {
            Some(Value::Arr(items)) => items.as_ref().clone(),
            _ => return Err(format!("reconcileSequenceCase {id}: no steps")),
        };
        let tolerance = r.number_at(&test_case, "reconcileToleranceRatio", 0.0);
        let calls = match at(&test_case, "calls") {
            Some(Value::Arr(items)) => items.as_ref().clone(),
            _ => Vec::new(),
        };
        let expected_scales = match at(&test_case, "expectedScales") {
            Some(Value::Arr(items)) => items.as_ref().clone(),
            _ => Vec::new(),
        };
        for (index, call) in calls.iter().enumerate() {
            // The plan is rebuilt from the working steps on every call, exactly
            // as execute does — PHP copies arrays on assignment, so a plan built
            // once outside this loop would mean six ports running six different
            // tests.
            let mut plan = HashMap::new();
            plan.insert("steps".to_string(), Value::List(steps.clone()));
            plan.insert("reconcileToleranceRatio".to_string(), Value::Float(tolerance));
            let plan = Value::Map(plan);
            let step_index = r.number_at(call, "stepIndex", 0.0) as i64;
            let realised_out = r.number_at(call, "realisedOut", 0.0);
            let reconciliation = r
                .reconcile_execution_step(&plan, step_index, realised_out)
                .map_err(|e| e.to_string())?;
            let scale = r.number_at(&reconciliation, "scale", f64::NAN);
            let expected = as_number(&expected_scales[index]).unwrap_or(f64::NAN);
            if !numbers_match(scale, expected) {
                return Err(format!(
                    "reconcileSequenceCase {id} call {index}: scale — expected {expected}, got {scale}"
                ));
            }
            r.apply_resize(&mut steps, &reconciliation);
        }
        let expected_amounts = match at(&test_case, "expectedAmounts") {
            Some(Value::Arr(items)) => items.as_ref().clone(),
            _ => Vec::new(),
        };
        for (index, step) in steps.iter().enumerate() {
            let amount = r.number_at(step, "amount", f64::NAN);
            let expected = as_number(&expected_amounts[index]).unwrap_or(f64::NAN);
            if !numbers_match(amount, expected) {
                return Err(format!(
                    "reconcileSequenceCase {id} step {index}: amount — expected {expected}, got {amount}"
                ));
            }
        }
    }
    Ok(())
}

fn fixture_build_unwind_plan(r: &OrderRouter, f: &Value) -> Result<(), String> {
    for test_case in cases(f, "unwindCases")? {
        let report = named(f, "reports", &text(&test_case, "report"))?;
        let unwind = r.build_unwind_plan(&report);
        let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
        assert_matches(&unwind, &expected, &format!("unwindCase {}", text(&test_case, "id")))?;
    }
    Ok(())
}

fn fixture_number_at(r: &OrderRouter, f: &Value) -> Result<(), String> {
    // Every port hand-implements JavaScript's parseFloat prefix grammar rather
    // than calling its own parser, because every language's own parser disagrees
    // with the others somewhere. These cases are the contract: a cap read as
    // 1234.5 in one language and 1 in another is a cap that silently disappears,
    // and this table is what stops that shipping green.
    for test_case in cases(f, "numberCases")? {
        let container = at(&test_case, "container").cloned().unwrap_or(Value::Null);
        let key = text(&test_case, "key");
        let default_value = r.number_at(&test_case, "default", 0.0);
        let actual = r.number_at(&container, &key, default_value);
        let expected = at(&test_case, "expected")
            .and_then(as_number)
            .ok_or_else(|| format!("numberCase {}: no expected number", text(&test_case, "id")))?;
        if !numbers_match(actual, expected) {
            return Err(format!(
                "numberCase {}: expected {expected}, got {actual}",
                text(&test_case, "id")
            ));
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// invariants, asserted directly rather than through the fixture
// ---------------------------------------------------------------------------

fn config_with(entries: &[(&str, Value)]) -> Value {
    let mut config = HashMap::new();
    for (key, value) in entries {
        config.insert((*key).to_string(), value.clone());
    }
    Value::Map(config)
}

fn capped_client(cap: f64) -> Result<OrderRouter, String> {
    let config = config_with(&[
        ("apiKey", Value::Str("k".into())),
        ("maxNotionalUsd", Value::Float(cap)),
    ]);
    OrderRouter::new(&config).map_err(|e| e.to_string())
}

fn constructor_guards() -> Result<(), String> {
    // The service dropped API keys in favour of per-IP rate limiting, so an empty
    // key is the normal case and must construct. A key supplied anyway is CARRIED,
    // not ignored: a deployment fronting the router with its own auth still works.
    let keyless = OrderRouter::new(&config_with(&[])).map_err(|e| e.to_string())?;
    if !keyless.api_key().is_empty() {
        return Err("a keyless client holds an empty apiKey".to_string());
    }
    let keyed = OrderRouter::new(&config_with(&[("apiKey", Value::Str("still-works".into()))]))
        .map_err(|e| e.to_string())?;
    if keyed.api_key() != "still-works" {
        return Err("a supplied apiKey is carried, not dropped".to_string());
    }
    // No ceiling. A caller trading thousands is using this correctly, and the
    // class does not get to decide otherwise — the old hard 25 USD limit came
    // from this repository's own live-test safety rule, which is not a rule
    // about anyone's money.
    let large = capped_client(250000.0)?;
    if !numbers_match(large.max_notional_usd(), 250000.0) {
        return Err(format!(
            "a large cap is honoured exactly, not clamped, got {}",
            large.max_notional_usd()
        ));
    }
    let small = capped_client(0.05)?;
    if !numbers_match(small.max_notional_usd(), 0.05) {
        return Err("cents are a legitimate trade size".to_string());
    }
    // The default is NO cap.
    let standard = OrderRouter::new(&config_with(&[("apiKey", Value::Str("k".into()))]))
        .map_err(|e| e.to_string())?;
    if !numbers_match(standard.max_notional_usd(), NO_CAP) || !numbers_match(NO_CAP, 0.0) {
        return Err(format!(
            "the default is NO_CAP, which is 0, got {}",
            standard.max_notional_usd()
        ));
    }
    // 0 is the explicit spelling of "no cap"; a negative value is a typo, and
    // silently ignoring it would leave the caller believing a guardrail is in
    // place.
    if !numbers_match(capped_client(0.0)?.max_notional_usd(), 0.0) {
        return Err("0 is the explicit spelling of no cap".to_string());
    }
    let negative = config_with(&[
        ("apiKey", Value::Str("k".into())),
        ("maxNotionalUsd", Value::Float(-1.0)),
    ]);
    match OrderRouter::new(&negative) {
        Ok(_) => return Err("a negative cap is refused, not ignored".to_string()),
        Err(e) if e.is("BadRequest") => {}
        Err(e) => return Err(format!("a negative cap is a BadRequest, got {e}")),
    }
    // Trailing slashes are stripped so the url is built the same way in six
    // languages.
    let slashed = config_with(&[
        ("apiKey", Value::Str("k".into())),
        ("baseUrl", Value::Str("https://example.test/router///".into())),
    ]);
    let client = OrderRouter::new(&slashed).map_err(|e| e.to_string())?;
    if client.base_url() != "https://example.test/router" {
        return Err(format!("trailing slashes are stripped, got {}", client.base_url()));
    }
    Ok(())
}

/// Every route the invariant checks build gets its own requestId: execute
/// derives the re-execution guard key from it, and refuses a live plan that
/// carries neither a requestId nor an idempotencyKey. A counter, not a random
/// value — the ids stay reproducible.
static TEST_REQUEST_ID_COUNTER: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

fn next_test_request_id() -> Value {
    let next = TEST_REQUEST_ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
    Value::Str(format!("test-req-{next}").into())
}

fn one_leg_route(side: &str, base_code: &str, quote: &str, amount: f64, price: f64) -> Value {
    let mut leg = HashMap::new();
    leg.insert("exchangeId".to_string(), Value::Str("stub".into()));
    leg.insert("amount".to_string(), Value::Float(amount));
    leg.insert("averagePrice".to_string(), Value::Float(price));
    leg.insert("effectivePrice".to_string(), Value::Float(price));
    let mut hop = HashMap::new();
    hop.insert("pair".to_string(), Value::Str(format!("{base_code}/{quote}").into()));
    hop.insert("side".to_string(), Value::Str(side.to_string().into()));
    hop.insert("base".to_string(), Value::Str(base_code.to_string().into()));
    hop.insert("quote".to_string(), Value::Str(quote.to_string().into()));
    hop.insert("legs".to_string(), Value::List(vec![Value::Map(leg)]));
    let mut route = HashMap::new();
    route.insert("requestId".to_string(), next_test_request_id());
    route.insert("from".to_string(), Value::Str(quote.to_string().into()));
    route.insert("to".to_string(), Value::Str(base_code.to_string().into()));
    route.insert("strategy".to_string(), Value::Str("best_single".into()));
    route.insert("exactSide".to_string(), Value::Str("in".into()));
    route.insert("fullyFillable".to_string(), Value::Bool(true));
    route.insert("fillRatio".to_string(), Value::Float(1.0));
    route.insert("hops".to_string(), Value::List(vec![Value::Map(hop)]));
    Value::Map(route)
}

/// USDT -> BTC -> ETH across two hops on the same stub venue, so a report's
/// filledIn/filledOut can be checked against the assets they are supposed to be
/// denominated in.
fn two_hop_route() -> Value {
    let hop = |base_code: &str, quote: &str, side: &str, amount: f64, price: f64| {
        let mut leg = HashMap::new();
        leg.insert("exchangeId".to_string(), Value::Str("stub".into()));
        leg.insert("amount".to_string(), Value::Float(amount));
        leg.insert("averagePrice".to_string(), Value::Float(price));
        leg.insert("effectivePrice".to_string(), Value::Float(price));
        let mut hop = HashMap::new();
        hop.insert("pair".to_string(), Value::Str(format!("{base_code}/{quote}").into()));
        hop.insert("side".to_string(), Value::Str(side.to_string().into()));
        hop.insert("base".to_string(), Value::Str(base_code.to_string().into()));
        hop.insert("quote".to_string(), Value::Str(quote.to_string().into()));
        hop.insert("legs".to_string(), Value::List(vec![Value::Map(leg)]));
        Value::Map(hop)
    };
    let mut route = HashMap::new();
    route.insert("requestId".to_string(), next_test_request_id());
    route.insert("from".to_string(), Value::Str("USDT".into()));
    route.insert("to".to_string(), Value::Str("ETH".into()));
    route.insert("strategy".to_string(), Value::Str("best_single".into()));
    route.insert("exactSide".to_string(), Value::Str("in".into()));
    route.insert("fullyFillable".to_string(), Value::Bool(true));
    route.insert("fillRatio".to_string(), Value::Float(1.0));
    // hop 0 spends 20 USDT for 0.2 BTC; hop 1 sells that 0.2 BTC for 2 ETH
    route.insert("hops".to_string(), Value::List(vec![
        hop("BTC", "USDT", "buy", 0.2, 100.0),
        hop("BTC", "ETH", "sell", 0.2, 10.0),
    ]));
    Value::Map(route)
}

fn a_report_is_summarised_in_the_assets_it_names(r: &OrderRouter) -> Result<(), String> {
    // filledIn is denominated in the route's FROM asset and filledOut in its TO
    // asset, which holds only if each is summed over ONE hop. This port summed
    // inAmount and outAmount across every step, adding USDT to BTC to ETH and
    // reporting the total as one number — meaningless on a multi-hop route, and
    // meaningless in a way that reads like a figure.
    let route = two_hop_route();
    let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    let venue = StubVenue::new("stub");
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let mut options = execute_options(true, "sequential");
    // Both markets, so neither hop is refused for want of one.
    let mut btc_usdt = HashMap::new();
    btc_usdt.insert("symbol".to_string(), Value::Str("BTC/USDT".into()));
    btc_usdt.insert("base".to_string(), Value::Str("BTC".into()));
    btc_usdt.insert("quote".to_string(), Value::Str("USDT".into()));
    let mut btc_eth = HashMap::new();
    btc_eth.insert("symbol".to_string(), Value::Str("BTC/ETH".into()));
    btc_eth.insert("base".to_string(), Value::Str("BTC".into()));
    btc_eth.insert("quote".to_string(), Value::Str("ETH".into()));
    let mut by_symbol = HashMap::new();
    by_symbol.insert("BTC/USDT".to_string(), Value::Map(btc_usdt));
    by_symbol.insert("BTC/ETH".to_string(), Value::Map(btc_eth));
    let mut markets = HashMap::new();
    markets.insert("stub".to_string(), Value::Map(by_symbol));
    OrderRouter::set_key(&mut options, "markets", Value::Map(markets));
    let mut usd_rates = HashMap::new();
    usd_rates.insert("USDT".to_string(), Value::Float(1.0));
    usd_rates.insert("ETH".to_string(), Value::Float(10.0));
    OrderRouter::set_key(&mut options, "usdRates", Value::Map(usd_rates));

    let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if results.len() != 2 {
        return Err(format!("the two-hop route must place two orders, got {results:?}"));
    }
    // hop 0 spends USDT and acquires BTC; hop 1 spends that BTC and produces ETH.
    // filledIn must therefore be hop 0's inAmount alone (USDT) and filledOut hop
    // 1's outAmount alone (ETH). The bug summed both columns over both steps, so
    // filledIn was USDT + BTC and filledOut was BTC + ETH — two currencies added
    // together and reported as one figure.
    let first_in = r.number_at(&results[0], "inAmount", 0.0);
    let second_in = r.number_at(&results[1], "inAmount", 0.0);
    let first_out = r.number_at(&results[0], "outAmount", 0.0);
    let second_out = r.number_at(&results[1], "outAmount", 0.0);
    let filled_in = r.number_at(&report, "filledIn", -1.0);
    let filled_out = r.number_at(&report, "filledOut", -1.0);
    if (filled_in - first_in).abs() > 1e-9 {
        return Err(format!("filledIn is the FIRST hop's spend alone ({first_in} USDT), got {filled_in}"));
    }
    if (filled_out - second_out).abs() > 1e-9 {
        return Err(format!("filledOut is the LAST hop's proceeds alone ({second_out} ETH), got {filled_out}"));
    }
    // Belt and braces: the two hops must actually differ, or the check above
    // would pass on a route where summing happens to give the same answer.
    if second_in <= 0.0 || first_out <= 0.0 {
        return Err("the fixture route must have a real middle asset for this to mean anything".to_string());
    }
    if r.number_at(&report, "ordersPlaced", 0.0) != 2.0 {
        return Err(format!("both placements are counted, got {}", r.number_at(&report, "ordersPlaced", 0.0)));
    }
    // And the companion flags this port dropped entirely: a caller must be able
    // to tell the venue's own figure from this class's fallback.
    for result in &results {
        for flag in ["filledKnown", "averageKnown", "costKnown"] {
            if !r.bool_at(result, flag, false) {
                return Err(format!("{flag} must be reported, and true when the stub answered fully: {result:?}"));
            }
        }
    }
    Ok(())
}

/// A market that actually declares limits, unlike `permissive_stub_markets`.
/// A hand-built plan has to clear these the same way a routed one does.
fn bounded_stub_markets() -> Value {
    let mut limits = HashMap::new();
    limits.insert("amount".to_string(), config_with(&[("min", Value::Float(0.0001)), ("max", Value::Float(0.0))]));
    limits.insert("price".to_string(), config_with(&[("min", Value::Float(1.0)), ("max", Value::Float(1000000.0))]));
    limits.insert("cost".to_string(), config_with(&[("min", Value::Float(10.0)), ("max", Value::Float(0.0))]));
    let mut market = HashMap::new();
    market.insert("symbol".to_string(), Value::Str("BTC/USDT".into()));
    market.insert("base".to_string(), Value::Str("BTC".into()));
    market.insert("quote".to_string(), Value::Str("USDT".into()));
    market.insert("precision".to_string(), config_with(&[("amount", Value::Float(0.0)), ("price", Value::Float(0.0))]));
    market.insert("limits".to_string(), Value::Map(limits));
    let mut venue = HashMap::new();
    venue.insert("BTC/USDT".to_string(), Value::Map(market));
    let mut markets = HashMap::new();
    markets.insert("stub".to_string(), Value::Map(venue));
    Value::Map(markets)
}

fn a_hand_built_plan_with_only_the_required_fields_is_executable(r: &OrderRouter) -> Result<(), String> {
    // The manual documents limitPrice and notionalQuote as OPTIONAL, and its own
    // worked example omits both. Read as 0 they broke the "execute your own
    // plans" path three ways at once: a blocking cost_below_minimum (0 < any
    // minimum cost), a blocking price_out_of_range (0 < minPrice), and — before
    // any strategy branch, so on every strategy — a rounded_to_zero when
    // place_step snapped a price of 0. The documented example could not place a
    // single order.
    let step = config_with(&[
        ("exchangeId", Value::Str("stub".into())),
        ("symbol", Value::Str("BTC/USDT".into())),
        ("side", Value::Str("buy".into())),
        ("amount", Value::Float(1.0)),
        ("base", Value::Str("BTC".into())),
        ("quote", Value::Str("USDT".into())),
        ("hopIndex", Value::Float(0.0)),
        ("expectedPrice", Value::Float(100.0)),
    ]);
    let plan = config_with(&[
        ("requestId", Value::Str("hand-built-0001".into())),
        ("calculatedAt", Value::Float(1700000000000.0)),
        ("steps", Value::List(vec![step])),
    ]);
    let violations = r.check_execution_plan_safety(&plan, &bounded_stub_markets(), &uncapped_options(&[("USDT", 1.0)]));
    let blocking: Vec<String> = violations
        .iter()
        .filter(|v| r.bool_at(v, "blocking", false))
        .map(|v| text(v, "code"))
        .collect();
    if !blocking.is_empty() {
        return Err(format!("the manual's own minimal plan must not be refused: {}", blocking.join(", ")));
    }
    Ok(())
}

fn derived_limit_price_and_notional_follow_amount_and_expected_price(r: &OrderRouter) -> Result<(), String> {
    let step = config_with(&[("amount", Value::Float(2.0)), ("expectedPrice", Value::Float(100.0))]);
    if !numbers_match(r.step_limit_price(&step), 100.0) {
        return Err("no limitPrice falls back to expectedPrice".to_string());
    }
    if !numbers_match(r.step_notional_quote(&step), 200.0) {
        return Err("no notionalQuote is amount * expectedPrice".to_string());
    }
    // An explicit value always wins, including one tighter than the expected price.
    let explicit = config_with(&[
        ("amount", Value::Float(2.0)),
        ("expectedPrice", Value::Float(100.0)),
        ("limitPrice", Value::Float(99.0)),
        ("notionalQuote", Value::Float(1.0)),
    ]);
    if !numbers_match(r.step_limit_price(&explicit), 99.0) {
        return Err("an explicit limitPrice wins".to_string());
    }
    if !numbers_match(r.step_notional_quote(&explicit), 1.0) {
        return Err("an explicit notionalQuote wins".to_string());
    }
    Ok(())
}

fn limit_price_side(r: &OrderRouter) -> Result<(), String> {
    // The limit sits on the side that costs you, and only there.
    let options = config_with(&[("slippageBps", Value::Float(100.0))]);
    let buy = r
        .build_execution_plan(&one_leg_route("buy", "BTC", "USDT", 1.0, 100.0), &options)
        .map_err(|e| e.to_string())?;
    let buy_steps = r.list_at(&buy, "steps");
    let buy_limit = r.number_at(&buy_steps[0], "limitPrice", 0.0);
    if !numbers_match(buy_limit, 101.0) {
        return Err(format!("a buy limit sits ABOVE the expected price, got {buy_limit}"));
    }
    let sell = r
        .build_execution_plan(&one_leg_route("sell", "BTC", "USDT", 1.0, 100.0), &options)
        .map_err(|e| e.to_string())?;
    let sell_steps = r.list_at(&sell, "steps");
    let sell_limit = r.number_at(&sell_steps[0], "limitPrice", 0.0);
    if !numbers_match(sell_limit, 99.0) {
        return Err(format!("a sell limit sits BELOW the expected price, got {sell_limit}"));
    }
    Ok(())
}

fn unwind_buy_is_fundable(r: &OrderRouter, f: &Value) -> Result<(), String> {
    // The residual IS the budget. Sizing the buy at the expected price and then
    // pricing it slippage above that orders more quote than the venue is
    // holding: 44.5 USDT at 0.089 is 500 DOGE, but 500 DOGE at the 0.0892225
    // limit costs 44.61125 — the venue rejects it for insufficient funds, or
    // partially fills and leaves the rest of the stranded money stranded on a
    // halted route.
    let report = named(f, "reports", "haltedCrossVenue")?;
    let unwind = r.build_unwind_plan(&report);
    let steps = r.list_at(&unwind, "steps");
    if steps.len() != 2 {
        return Err(format!("the cross-venue report strands two positions, got {}", steps.len()));
    }
    let buy = &steps[1];
    if text(buy, "side") != "buy" {
        return Err("the mexc leg is the buy".to_string());
    }
    let residual = 44.5f64;
    let spend = r.number_at(buy, "amount", 0.0) * r.number_at(buy, "limitPrice", 0.0);
    if spend > residual + 1e-9 {
        return Err(format!("the buy spends {spend} of a {residual} residual"));
    }
    // And it does not leave the residual pointlessly unspent either.
    if spend < residual - 1e-9 {
        return Err(format!("the buy spends {spend}, short of the {residual} residual"));
    }
    // The notional the safety cap sees must be that same real spend.
    if !numbers_match(r.number_at(buy, "notionalQuote", 0.0), spend) {
        return Err("notionalQuote is priced at the limit the order is placed at".to_string());
    }
    // The sell side is sized on the residual itself — there is no budget to run out of.
    let sell = &steps[0];
    if text(sell, "side") != "sell" {
        return Err("the binance leg is the sell".to_string());
    }
    if !numbers_match(r.number_at(sell, "amount", 0.0), 0.2) {
        return Err("the whole 0.2 SOL residual is sold".to_string());
    }
    if !numbers_match(
        r.number_at(sell, "notionalQuote", 0.0),
        0.2 * r.number_at(sell, "limitPrice", 0.0),
    ) {
        return Err("the sell notional is priced at its limit too".to_string());
    }
    Ok(())
}

fn empty_plan_is_not_safe(r: &OrderRouter) -> Result<(), String> {
    // "Nothing to check" and "checked, all good" are different answers and used
    // to look identical.
    let mut plan = HashMap::new();
    plan.insert("steps".to_string(), Value::List(vec![]));
    let violations = r.check_execution_plan_safety(
        &Value::Map(plan),
        &Value::Map(HashMap::new()),
        &Value::Map(HashMap::new()),
    );
    if violations.len() != 1 {
        return Err(format!("an empty plan yields one finding, got {}", violations.len()));
    }
    if text(&violations[0], "code") != "empty_plan" {
        return Err("an empty plan is flagged empty_plan".to_string());
    }
    Ok(())
}

/// The market set the cap tests check against: it constrains nothing, so the
/// only findings a plan can produce against it are the notional ones.
fn permissive_stub_markets() -> Value {
    let mut market = HashMap::new();
    market.insert("symbol".to_string(), Value::Str("BTC/USDT".into()));
    market.insert("base".to_string(), Value::Str("BTC".into()));
    market.insert("quote".to_string(), Value::Str("USDT".into()));
    let mut venue = HashMap::new();
    venue.insert("BTC/USDT".to_string(), Value::Map(market));
    let mut markets = HashMap::new();
    markets.insert("stub".to_string(), Value::Map(venue));
    Value::Map(markets)
}

/// `{ 'usdRates': { <code>: <rate>, ... } }`, plus whatever else the check
/// options carry.
fn rates(entries: &[(&str, f64)]) -> Value {
    let mut usd_rates = HashMap::new();
    for (code, rate) in entries {
        usd_rates.insert((*code).to_string(), Value::Float(*rate));
    }
    Value::Map(usd_rates)
}

fn capped_options(cap: f64, usd_rates: &[(&str, f64)]) -> Value {
    config_with(&[
        ("usdRates", rates(usd_rates)),
        ("maxNotionalUsd", Value::Float(cap)),
    ])
}

fn uncapped_options(usd_rates: &[(&str, f64)]) -> Value {
    config_with(&[("usdRates", rates(usd_rates))])
}

/// The codes of a plan's findings, in order, so an expectation reads as one
/// line rather than as five index lookups.
fn codes(violations: &[Value]) -> Vec<String> {
    violations.iter().map(|v| text(v, "code")).collect()
}

fn planned(r: &OrderRouter, amount: f64, price: f64, slippage_bps: f64) -> Result<Value, String> {
    let options = config_with(&[("slippageBps", Value::Float(slippage_bps))]);
    r.build_execution_plan(&one_leg_route("buy", "BTC", "USDT", amount, price), &options)
        .map_err(|e| e.to_string())
}

fn a_cap_that_is_set_binds_exactly(r: &OrderRouter) -> Result<(), String> {
    // A cap the caller ASKED FOR is honoured at whatever size they chose, and
    // the slippage is inside the measurement rather than outside it.
    let markets = permissive_stub_markets();
    let capped = capped_options(25.0, &[("USDT", 1.0)]);
    let under = planned(r, 0.24, 100.0, 0.0)?;
    if !codes(&r.check_execution_plan_safety(&under, &markets, &capped)).is_empty() {
        return Err("24 USD passes a 25 USD cap".to_string());
    }
    let at_the_cap = planned(r, 0.25, 100.0, 0.0)?;
    if !codes(&r.check_execution_plan_safety(&at_the_cap, &markets, &capped)).is_empty() {
        return Err("exactly at the cap passes".to_string());
    }
    let over = planned(r, 0.2501, 100.0, 0.0)?;
    if codes(&r.check_execution_plan_safety(&over, &markets, &capped)) != ["notional_exceeds_cap"] {
        return Err("25.01 USD trips a 25 USD cap".to_string());
    }
    let slipped = planned(r, 0.249, 100.0, 100.0)?;
    if codes(&r.check_execution_plan_safety(&slipped, &markets, &capped)) != ["notional_exceeds_cap"]
    {
        return Err("24.90 USD at 1% slippage is 25.15 USD of risk".to_string());
    }
    // A LARGE cap is honoured just as exactly. This is the case the old hard
    // ceiling made unreachable: 2,000 USD of BTC under a 5,000 USD guardrail is
    // a normal trade.
    let large = planned(r, 20.0, 100.0, 0.0)?;
    let generous = capped_options(5000.0, &[("USDT", 1.0)]);
    if !codes(&r.check_execution_plan_safety(&large, &markets, &generous)).is_empty() {
        return Err("2,000 USD under a 5,000 USD cap".to_string());
    }
    let tighter = capped_options(1000.0, &[("USDT", 1.0)]);
    if codes(&r.check_execution_plan_safety(&large, &markets, &tighter)) != ["notional_exceeds_cap"]
    {
        return Err("and the same 2,000 USD trips a 1,000 USD cap".to_string());
    }
    Ok(())
}

fn with_no_cap_no_notional_check_runs(r: &OrderRouter) -> Result<(), String> {
    // The default. This class does not decide how much of your money you may
    // trade — the guardrail is opt-in, so a plan of any size passes untouched,
    // and a caller who never asked for a cap is not made to supply usdRates for
    // it.
    let markets = permissive_stub_markets();
    let large = planned(r, 1000.0, 100.0, 0.0)?;
    let found = codes(&r.check_execution_plan_safety(&large, &markets, &uncapped_options(&[("USDT", 1.0)])));
    if !found.is_empty() {
        return Err(format!("100,000 USD passes when no cap is set, got {found:?}"));
    }
    let bare = codes(&r.check_execution_plan_safety(&large, &markets, &Value::Map(HashMap::new())));
    if !bare.is_empty() {
        return Err(format!("and needs no usdRates at all, got {bare:?}"));
    }
    Ok(())
}

fn usdt_is_not_a_dollar(r: &OrderRouter) -> Result<(), String> {
    // A stablecoin peg is an empirical fact, not a definition. With a cap in
    // force and no rate supplied, a USDT-quoted step cannot be valued and must
    // BLOCK — 0.1 USDT of notional is trivially under the cap, and it is still
    // refused, because the point is that the cap the caller ASKED FOR could not
    // be evaluated.
    let markets = permissive_stub_markets();
    let plan = planned(r, 0.001, 100.0, 25.0)?;
    let violations =
        r.check_execution_plan_safety(&plan, &markets, &capped_options(25.0, &[("USD", 1.0)]));
    let blocked = violations
        .iter()
        .any(|v| text(v, "code") == "notional_unvaluable" && r.bool_at(v, "blocking", false));
    if !blocked {
        return Err("an unvaluable step BLOCKS rather than being skipped".to_string());
    }
    // Unrelated rates do not help.
    let unrelated =
        r.check_execution_plan_safety(&plan, &markets, &capped_options(25.0, &[("ETH", 3000.0)]));
    if codes(&unrelated) != ["notional_unvaluable"] {
        return Err("a rate for another currency does not value this step".to_string());
    }
    // Either side of the market resolves it, and a depegged rate is respected.
    for resolving in [("USDT", 0.4), ("BTC", 100.0)] {
        let resolved =
            r.check_execution_plan_safety(&plan, &markets, &capped_options(25.0, &[resolving]));
        if !codes(&resolved).is_empty() {
            return Err(format!("a rate for {} values the step", resolving.0));
        }
    }
    // And with NO cap set there is nothing to enforce, so the same unvaluable
    // step passes.
    let uncapped = r.check_execution_plan_safety(&plan, &markets, &uncapped_options(&[]));
    if !codes(&uncapped).is_empty() {
        return Err("an unvaluable step passes when no cap is set".to_string());
    }
    Ok(())
}

fn a_per_call_cap_overrides_the_client_one() -> Result<(), String> {
    // The cap is a guardrail the CALLER sets, so the per-call value wins — there
    // is no ceiling re-imposed behind their back. Both directions are asserted
    // because the old implementation clamped one way only, and a guardrail that
    // silently refuses to loosen is as surprising as one that silently refuses
    // to tighten.
    let client = capped_client(100.0)?;
    let markets = permissive_stub_markets();
    // 0.005 BTC at 100000 USDT is 500 USD.
    let plan = planned(&client, 0.005, 100000.0, 0.0)?;
    let against_the_client_cap =
        client.check_execution_plan_safety(&plan, &markets, &uncapped_options(&[("USDT", 1.0)]));
    if codes(&against_the_client_cap) != ["notional_exceeds_cap"] {
        return Err("500 USD trips the client cap of 100".to_string());
    }
    if !numbers_match(client.number_at(&against_the_client_cap[0], "limit", 0.0), 100.0) {
        return Err("the client cap is the limit reported".to_string());
    }
    // Raised for this call.
    let raised =
        client.check_execution_plan_safety(&plan, &markets, &capped_options(1000.0, &[("USDT", 1.0)]));
    if !codes(&raised).is_empty() {
        return Err("a per-call cap of 1000 lets it through".to_string());
    }
    // Lowered for this call.
    let tightened =
        client.check_execution_plan_safety(&plan, &markets, &capped_options(10.0, &[("USDT", 1.0)]));
    if !numbers_match(client.number_at(&tightened[0], "limit", 0.0), 10.0) {
        return Err("a per-call cap of 10 is the limit reported".to_string());
    }
    Ok(())
}

fn refuses_incoherent_routes(r: &OrderRouter) -> Result<(), String> {
    // build_execution_plan used to copy from, to, pair and side straight out of
    // the server's JSON, so a compromised — or simply buggy — router response
    // could steer real orders into any real market and every check would pass
    // it. The client now checks the answer against its OWN record of the
    // question.
    let mut route = one_leg_route("buy", "BTC", "USDT", 0.1, 100.0);
    OrderRouter::set_key(&mut route, "clientRequestedFrom", Value::Str("USDT".into()));
    OrderRouter::set_key(&mut route, "clientRequestedTo", Value::Str("ETH".into()));
    match r.build_execution_plan(&route, &Value::Null) {
        Ok(_) => return Err("a route that produces the wrong asset is refused".to_string()),
        Err(e) => {
            if !e.message.contains("produces BTC, not the requested ETH") {
                return Err(format!("wrong refusal for a produces mismatch: {e}"));
            }
        }
    }
    let mut route = one_leg_route("buy", "BTC", "USDT", 0.1, 100.0);
    OrderRouter::set_key(&mut route, "clientRequestedFrom", Value::Str("EUR".into()));
    OrderRouter::set_key(&mut route, "clientRequestedTo", Value::Str("BTC".into()));
    match r.build_execution_plan(&route, &Value::Null) {
        Ok(_) => return Err("a route that spends an unoffered asset is refused".to_string()),
        Err(e) => {
            if !e.message.contains("spends USDT, not the requested EUR") {
                return Err(format!("wrong refusal for a spends mismatch: {e}"));
            }
        }
    }
    // A well-formed route still plans.
    let mut route = one_leg_route("buy", "BTC", "USDT", 0.1, 100.0);
    OrderRouter::set_key(&mut route, "clientRequestedFrom", Value::Str("USDT".into()));
    OrderRouter::set_key(&mut route, "clientRequestedTo", Value::Str("BTC".into()));
    let plan = r.build_execution_plan(&route, &Value::Null).map_err(|e| e.to_string())?;
    if r.list_at(&plan, "steps").len() != 1 {
        return Err("a coherent route still plans".to_string());
    }
    Ok(())
}

fn format_number_never_uses_exponents(r: &OrderRouter) -> Result<(), String> {
    for probe in [0.0000001f64, 1234.5, 0.1, 1e17] {
        let rendered = r.format_number(probe).map_err(|e| e.to_string())?;
        if rendered.contains('e') || rendered.contains('E') {
            return Err(format!("format_number emitted an exponent for {probe}: {rendered}"));
        }
    }
    if r.format_number(0.0).map_err(|e| e.to_string())? != "0" {
        return Err("zero renders as 0".to_string());
    }
    // A magnitude no real amount reaches, where the six languages stop agreeing.
    if r.format_number(1e18).is_ok() {
        return Err("a number too large to render identically is refused".to_string());
    }
    Ok(())
}


fn route_url_is_deterministic(r: &OrderRouter) -> Result<(), String> {
    // The URL has to be byte-identical in six languages: the query keys go out
    // in a fixed order, numbers go through format_number rather than the
    // language's own float printer, and the escaping is encodeURIComponent's
    // rather than form-urlencoded's. This is the same assertion the TypeScript
    // suite makes, against the same expected string.
    let mut config = HashMap::new();
    config.insert("apiKey".to_string(), Value::Str("k".to_string().into()));
    config.insert("baseUrl".to_string(), Value::Str("https://example.test/api/".to_string().into()));
    let client = OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())?;
    let mut params = HashMap::new();
    params.insert("amountIn".to_string(), Value::Float(0.001));
    params.insert("strategy".to_string(), Value::Str("split_capped".to_string().into()));
    params.insert("maxVenues".to_string(), Value::Int(3));
    params.insert(
        "exchanges".to_string(),
        Value::List(vec![Value::Str("binance".into()), Value::Str("kraken".into())]),
    );
    params.insert("certified".to_string(), Value::Bool(true));
    let url = client
        .build_route_url("usdt", "btc", &Value::Map(params))
        .map_err(|e| e.to_string())?;
    let expected = "https://example.test/api/route?from=USDT&to=BTC&amountIn=0.001&strategy=split_capped&maxVenues=3&exchanges=binance%2Ckraken&certified=true";
    if url != expected {
        return Err(format!("expected\n  {expected}\ngot\n  {url}"));
    }
    // Exactly one of amountIn / amountOut — neither and both are both refused,
    // client-side, because a typo must not become a confidently wrong route.
    let empty = Value::Map(HashMap::new());
    if r.build_route_url("USDT", "BTC", &empty).is_ok() {
        return Err("neither amountIn nor amountOut is refused".to_string());
    }
    let mut both = HashMap::new();
    both.insert("amountIn".to_string(), Value::Float(1.0));
    both.insert("amountOut".to_string(), Value::Float(1.0));
    if r.build_route_url("USDT", "BTC", &Value::Map(both)).is_ok() {
        return Err("both amountIn and amountOut is refused".to_string());
    }
    let mut one = HashMap::new();
    one.insert("amountIn".to_string(), Value::Float(1.0));
    if r.build_route_url("", "BTC", &Value::Map(one)).is_ok() {
        return Err("an empty fromAsset is refused".to_string());
    }
    Ok(())
}

fn encode_uri_component_matches_javascript(r: &OrderRouter) -> Result<(), String> {
    // encodeURIComponent leaves !'()* alone and escapes a space as %20;
    // form-urlencoded escapes the former and renders a space as +. A balances
    // string or bridge list containing any of them would otherwise produce a
    // different URL here than in the other five ports.
    let mut params = HashMap::new();
    params.insert("amountIn".to_string(), Value::Float(1.0));
    params.insert("bridges".to_string(), Value::Str("a!b'c(d)e*f g".to_string().into()));
    let url = r
        .build_route_url("USDT", "BTC", &Value::Map(params))
        .map_err(|e| e.to_string())?;
    if !url.contains("bridges=a!b'c(d)e*f%20g") {
        return Err(format!("encodeURIComponent semantics, got {url}"));
    }
    // And a colon IS escaped. NOTE: fetch_route never sends `balances` through
    // this builder any more — holdings are POSTed, see route_body_carries_the
    // _holdings_and_the_url_never_does below — but the encoder is shared, and a
    // value carrying a colon can still reach the query string by another key.
    let mut params = HashMap::new();
    params.insert("amountIn".to_string(), Value::Float(1.0));
    params.insert("balanceMode".to_string(), Value::Str("cap:strict".to_string().into()));
    let url = r
        .build_route_url("USDT", "BTC", &Value::Map(params))
        .map_err(|e| e.to_string())?;
    if !url.contains("balanceMode=cap%3Astrict") {
        return Err(format!("a colon is escaped, got {url}"));
    }
    Ok(())
}

fn stream_url_and_close_codes(r: &OrderRouter) -> Result<(), String> {
    let mut config = HashMap::new();
    config.insert("apiKey".to_string(), Value::Str("k".to_string().into()));
    config.insert("baseUrl".to_string(), Value::Str("https://example.test/api".to_string().into()));
    let streamer = OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())?;
    let mut params = HashMap::new();
    params.insert("amountIn".to_string(), Value::Float(0.001));
    params.insert("strategy".to_string(), Value::Str("split_capped".to_string().into()));
    params.insert("maxVenues".to_string(), Value::Int(3));
    params.insert(
        "exchanges".to_string(),
        Value::List(vec![Value::Str("binance".into()), Value::Str("kraken".into())]),
    );
    params.insert("certified".to_string(), Value::Bool(true));
    let url = streamer
        .stream_url("usdt", "btc", &Value::Map(params))
        .map_err(|e| e.to_string())?;
    let expected = "wss://example.test/api/stream/route?from=USDT&to=BTC&amountIn=0.001&strategy=split_capped&maxVenues=3&exchanges=binance%2Ckraken&certified=true";
    if url != expected {
        return Err(format!("expected\n  {expected}\ngot\n  {url}"));
    }
    // includeQuotes is NOT defaulted: the endpoint's own default is false
    if url.contains("includeQuotes") {
        return Err("includeQuotes is left to the endpoint default".to_string());
    }
    // a plain-http base becomes ws://, not wss://
    let mut plain_config = HashMap::new();
    plain_config.insert("apiKey".to_string(), Value::Str("k".to_string().into()));
    plain_config.insert("baseUrl".to_string(), Value::Str("http://localhost:8080".to_string().into()));
    let insecure = OrderRouter::new(&Value::Map(plain_config)).map_err(|e| e.to_string())?;
    let mut one = HashMap::new();
    one.insert("amountIn".to_string(), Value::Float(1.0));
    let plain = insecure
        .stream_url("USDT", "BTC", &Value::Map(one.clone()))
        .map_err(|e| e.to_string())?;
    if !plain.starts_with("ws://localhost:8080/stream/route?") {
        return Err(format!("http becomes ws, got {plain}"));
    }
    // a socket outlives the holdings it was opened with, so the service refuses both
    let mut with_balances = one.clone();
    with_balances.insert("balances".to_string(), Value::Str("binance.USDT:1000".to_string().into()));
    if streamer.stream_url("USDT", "BTC", &Value::Map(with_balances)).is_ok() {
        return Err("balances are refused on the stream".to_string());
    }
    let mut with_mode = one.clone();
    with_mode.insert("balanceMode".to_string(), Value::Str("require".to_string().into()));
    if streamer.stream_url("USDT", "BTC", &Value::Map(with_mode)).is_ok() {
        return Err("balanceMode is refused with them".to_string());
    }
    // the same exclusivity fetch_route enforces — one parser server-side, one rule here
    if streamer.stream_url("USDT", "BTC", &Value::Map(HashMap::new())).is_ok() {
        return Err("neither amount is refused".to_string());
    }
    if streamer.stream_url("", "BTC", &Value::Map(one)).is_ok() {
        return Err("an empty fromAsset is refused".to_string());
    }
    // close codes carry the same meaning the REST statuses do
    let mut refusal_frame = HashMap::new();
    refusal_frame.insert(
        "error".to_string(),
        Value::Str("exact_out_multi_hop_unsupported".to_string().into()),
    );
    match r.stream_close_error(1008, &Value::Map(refusal_frame)) {
        Some(e) => {
            if e.kind != "BadRequest" || !e.to_string().contains("exact_out_multi_hop_unsupported") {
                return Err(format!("1008 is the same refusal a 400 is, got {e}"));
            }
        }
        None => return Err("1008 must refuse".to_string()),
    }
    let mut cold_frame = HashMap::new();
    cold_frame.insert("error".to_string(), Value::Str("cache is cold".to_string().into()));
    cold_frame.insert("bookCount".to_string(), Value::Int(12));
    cold_frame.insert("freshCount".to_string(), Value::Int(0));
    cold_frame.insert("minFreshBooksForReady".to_string(), Value::Int(1));
    match r.stream_close_error(1013, &Value::Map(cold_frame)) {
        Some(e) => {
            if e.kind != "ExchangeNotAvailable" || !e.to_string().contains("0 of 12 books fresh") {
                return Err(format!("1013 is a cold cache, got {e}"));
            }
        }
        None => return Err("1013 must refuse".to_string()),
    }
    if r.stream_close_error(1000, &Value::Map(HashMap::new())).is_some() {
        return Err("a clean close is not an error".to_string());
    }
    match r.stream_close_error(1011, &Value::Map(HashMap::new())) {
        Some(e) if e.kind == "ExchangeNotAvailable" => {}
        other => return Err(format!("an unexpected close raises, got {other:?}")),
    }
    // and a failed upgrade keeps the REST vocabulary
    if r.stream_handshake_error("Unexpected server response: 401").kind != "AuthenticationError" {
        return Err("401 at the handshake is an auth error".to_string());
    }
    if r.stream_handshake_error("Unexpected server response: 429").kind != "RateLimitExceeded" {
        return Err("429 at the handshake is a rate limit".to_string());
    }
    Ok(())
}

fn balances_echo_is_verified(r: &OrderRouter) -> Result<(), String> {
    // /route declares its query without a JSON schema, so a server that predates the balances
    // feature answers byte-identically to one that never received any. It is the EMPTY wallet
    // that used to slip through, because the old check skipped itself whenever the balances
    // string was "".
    let asked = |balances: &str| -> Value {
        let mut params = HashMap::new();
        params.insert("balances".to_string(), Value::Str(balances.to_string().into()));
        Value::Map(params)
    };
    let empty_route = Value::Map(HashMap::new());
    if r.assert_balances_applied(&empty_route, &asked("binance.USDT:1000")).is_ok() {
        return Err("a non-empty wallet the server ignored must be refused".to_string());
    }
    if r.assert_balances_applied(&empty_route, &asked("")).is_ok() {
        return Err("an EMPTY wallet the server ignored must be refused".to_string());
    }
    // an echo is proof enough
    let mut echoed = HashMap::new();
    echoed.insert("balancesApplied".to_string(), Value::Str("binance.USDT:1000".to_string().into()));
    if r.assert_balances_applied(&Value::Map(echoed), &asked("binance.USDT:1000")).is_err() {
        return Err("an echoed wallet is accepted".to_string());
    }
    // and balanceEntryCount 0 is how a CURRENT server confirms an empty one: presence, not value
    let mut counted = HashMap::new();
    counted.insert("balanceEntryCount".to_string(), Value::Int(0));
    if r.assert_balances_applied(&Value::Map(counted), &asked("")).is_err() {
        return Err("balanceEntryCount 0 confirms an empty wallet".to_string());
    }
    // the caller can opt out with their eyes open
    let mut opted = HashMap::new();
    opted.insert("balances".to_string(), Value::Str("binance.USDT:1000".to_string().into()));
    opted.insert("requireBalancesApplied".to_string(), Value::Bool(false));
    if r.assert_balances_applied(&empty_route, &Value::Map(opted)).is_err() {
        return Err("the opt-out is honoured".to_string());
    }
    Ok(())
}

fn fee_is_not_subtracted_twice(r: &OrderRouter) -> Result<(), String> {
    // THE REGRESSION THIS EXISTS FOR. execute reports realisedOut NET of a fee charged in
    // the asset the step produced, because that is what the wallet receives. The router had
    // already done the same: hop 0 sells 500 DOGE at 0.089 for 44.5 gross, reports amountOut
    // 44.47482324238088 after a 0.025176757619121304 USDT fee, and hop 1's amountIn is that
    // net figure to the last digit. Measuring the expectation GROSS against a NET realised
    // amount reported a shortfall on a perfect fill and shrank hop 1 by the fee all over
    // again, stranding it in the bridge asset.
    let fixture = fixture()?;
    let routes = r.dict_at(&fixture, "routes");
    let route = r.dict_at(&routes, "multiHop");
    let hops = r.list_at(&route, "hops");
    let hop_zero = &hops[0];
    let hop_one = &hops[1];
    let hop_zero_out = r.number_at(hop_zero, "amountOut", 0.0);
    let hop_zero_fee = r.number_at(hop_zero, "feeCost", 0.0);
    // the premise, asserted rather than assumed: the router's own numbers really are net
    if (hop_zero_out - (500.0 * 0.089 - hop_zero_fee)).abs() > TOLERANCE {
        return Err(format!("the hop amountOut is net of its fee, got {hop_zero_out}"));
    }
    if (r.number_at(hop_one, "amountIn", 0.0) - hop_zero_out).abs() > TOLERANCE {
        return Err("hop 1 was sized from the NET proceeds of hop 0".to_string());
    }
    let plan = r
        .build_execution_plan(&route, &Value::Map(HashMap::new()))
        .map_err(|e| e.to_string())?;
    let steps = r.list_at(&plan, "steps");
    let leg_fee = r.number_at(&r.list_at(hop_zero, "legs")[0], "feeCost", 0.0);
    if (r.number_at(&steps[0], "expectedFeeCost", -1.0) - leg_fee).abs() > TOLERANCE {
        return Err("the step carries the predicted fee".to_string());
    }
    let verdict = r
        .reconcile_execution_step(&plan, 0, hop_zero_out)
        .map_err(|e| e.to_string())?;
    if (r.number_at(&verdict, "expectedOut", 0.0) - hop_zero_out).abs() > TOLERANCE {
        return Err("expected equals what the router said the hop produces".to_string());
    }
    if r.number_at(&verdict, "shortfall", -1.0).abs() > TOLERANCE {
        return Err("a perfect fill is not a shortfall".to_string());
    }
    if (r.number_at(&verdict, "scale", 0.0) - 1.0).abs() > TOLERANCE {
        return Err("and does not resize anything".to_string());
    }
    for entry in r.list_at(&verdict, "resizedSteps") {
        let before = r.number_at(&entry, "previousAmount", 0.0);
        let after = r.number_at(&entry, "amount", 0.0);
        if (before - after).abs() > TOLERANCE {
            return Err("hop 1 keeps the size the router gave it".to_string());
        }
    }
    // notionalQuote is what the order is worth to the VENUE and stays gross
    if (r.number_at(&steps[0], "notionalQuote", 0.0) - 44.5).abs() > TOLERANCE {
        return Err("the order notional stays gross".to_string());
    }
    // a BUY produces base, and the predicted fee is quote-denominated
    if (r.step_expected_out(&steps[1]) - r.number_at(hop_one, "amountOut", 0.0)).abs() > TOLERANCE {
        return Err("a buy is unaffected".to_string());
    }
    // a hand-built plan carries no expectedFeeCost, and behaves exactly as before
    let mut hand = HashMap::new();
    hand.insert("side".to_string(), Value::Str("sell".to_string().into()));
    hand.insert("amount".to_string(), Value::Float(10.0));
    hand.insert("expectedPrice".to_string(), Value::Float(2.0));
    if (r.step_expected_out(&Value::Map(hand)) - 20.0).abs() > TOLERANCE {
        return Err("a hand-built plan is unchanged".to_string());
    }
    Ok(())
}

fn route_body_carries_the_holdings_and_the_url_never_does(r: &OrderRouter) -> Result<(), String> {
    // The service scrubs balances from its own logs, but the URL leaves the
    // process: a reverse proxy, an ALB and a CDN all log the full request line,
    // as do browser history and client-side tracing. This is the assertion that
    // keeps the wallet out of them.
    let mut params = HashMap::new();
    params.insert("amountIn".to_string(), Value::Float(10.0));
    params.insert("balances".to_string(), Value::Str("binance.USDT:1000,binance.BTC:1".to_string().into()));
    params.insert("certified".to_string(), Value::Bool(true));
    params.insert("maxVenues".to_string(), Value::Int(2));
    let body = r
        .build_route_body("usdt", "btc", &Value::Map(params))
        .map_err(|e| e.to_string())?;
    if r.string_at(&body, "from", "") != "USDT" || r.string_at(&body, "to", "") != "BTC" {
        return Err("the body carries from and to, uppercased".to_string());
    }
    if r.string_at(&body, "balances", "") != "binance.USDT:1000,binance.BTC:1" {
        return Err("the body carries the holdings verbatim, unescaped".to_string());
    }
    // numbers and booleans travel as themselves: the body is JSON, and the
    // service's own schema types amountIn as a number. Asserted on the encoded
    // JSON rather than the in-memory Value, because the wire form is what the
    // service actually parses — a number quoted into a string would read the
    // same in a Value and differently to the router.
    let encoded = body.to_json().to_string();
    for expected in ["\"amountIn\":10.0", "\"certified\":true", "\"maxVenues\":2"] {
        if !encoded.contains(expected) {
            return Err(format!("{expected} in the encoded body, got {encoded}"));
        }
    }
    if encoded.contains("\"amountIn\":\"") {
        return Err(format!("amountIn must not be quoted into a string, got {encoded}"));
    }
    // and the same exclusivity rule the url builder enforces
    let empty = Value::Map(HashMap::new());
    if r.build_route_body("USDT", "BTC", &empty).is_ok() {
        return Err("neither amountIn nor amountOut is refused".to_string());
    }
    Ok(())
}

fn stub_fee(cost: f64, currency: &str) -> Value {
    let mut fee = HashMap::new();
    fee.insert("cost".to_string(), Value::Float(cost));
    fee.insert("currency".to_string(), Value::Str(currency.to_string().into()));
    Value::Map(fee)
}

fn fixture_format_number(r: &OrderRouter, f: &Value) -> Result<(), String> {
    // format_number builds the balances query string. A balance spelled
    // differently per language is a DIFFERENT QUESTION asked of the router, so
    // the tie cases here are load-bearing: Rust's `{:.12}` rounds half to EVEN
    // and answered ...312 where the TypeScript reference answers ...313.
    for test_case in cases(f, "formatNumberCases")? {
        let id = text(&test_case, "id");
        let value = at(&test_case, "value")
            .and_then(as_number)
            .ok_or_else(|| format!("formatNumberCase {id}: no value"))?;
        let expected = text(&test_case, "expected");
        let actual = r.format_number(value).map_err(|e| e.to_string())?;
        if actual != expected {
            return Err(format!("formatNumberCase {id}: expected {expected}, got {actual}"));
        }
    }
    Ok(())
}

/// The route shape the fee-netting cases plan from — the same one the
/// TypeScript suite's oneLegRoute builds, with the direction taken from `side`
/// so a sell case is coherent too.
fn fee_netting_route(side: &str, base_code: &str, quote: &str, amount: f64, price: f64) -> Value {
    let buying = side == "buy";
    let amount_in = if buying { amount * price } else { amount };
    let amount_out = if buying { amount } else { amount * price };
    let mut leg = HashMap::new();
    leg.insert("exchangeId".to_string(), Value::Str("stub".into()));
    leg.insert("amount".to_string(), Value::Float(amount));
    leg.insert("averagePrice".to_string(), Value::Float(price));
    leg.insert("takerFeeRate".to_string(), Value::Float(0.0));
    leg.insert("feeCost".to_string(), Value::Float(0.0));
    leg.insert("effectivePrice".to_string(), Value::Float(price));
    let mut hop = HashMap::new();
    hop.insert("pair".to_string(), Value::Str(format!("{base_code}/{quote}").into()));
    hop.insert("side".to_string(), Value::Str(side.to_string().into()));
    hop.insert("base".to_string(), Value::Str(base_code.to_string().into()));
    hop.insert("quote".to_string(), Value::Str(quote.to_string().into()));
    hop.insert("amountIn".to_string(), Value::Float(amount_in));
    hop.insert("amountOut".to_string(), Value::Float(amount_out));
    hop.insert("legs".to_string(), Value::List(vec![Value::Map(leg)]));
    hop.insert("fullyFillable".to_string(), Value::Bool(true));
    let mut route = HashMap::new();
    route.insert("requestId".to_string(), next_test_request_id());
    route.insert("from".to_string(), Value::Str((if buying { quote.to_string() } else { base_code.to_string() }).into()));
    route.insert("to".to_string(), Value::Str((if buying { base_code.to_string() } else { quote.to_string() }).into()));
    route.insert("strategy".to_string(), Value::Str("best_single".into()));
    route.insert("exactSide".to_string(), Value::Str("in".into()));
    route.insert("amountIn".to_string(), Value::Float(amount_in));
    route.insert("amountOut".to_string(), Value::Float(amount_out));
    route.insert("fullyFillable".to_string(), Value::Bool(true));
    route.insert("fillRatio".to_string(), Value::Float(1.0));
    route.insert("hops".to_string(), Value::List(vec![Value::Map(hop)]));
    Value::Map(route)
}

fn fixture_fee_netting(r: &OrderRouter, f: &Value) -> Result<(), String> {
    // Fee netting is the one place_step behaviour that CHANGES the size of the
    // next order, and until this section existed it was asserted in TypeScript
    // and nowhere else — a port that silently stopped netting would have shipped
    // green in its own language.
    for test_case in cases(f, "feeNettingCases")? {
        let id = text(&test_case, "id");
        let route = fee_netting_route(
            &text(&test_case, "side"),
            &text(&test_case, "base"),
            &text(&test_case, "quote"),
            r.number_at(&test_case, "amount", 0.0),
            r.number_at(&test_case, "price", 0.0),
        );
        let plan_options = at(&test_case, "planOptions").cloned().unwrap_or(Value::Null);
        let plan = r.build_execution_plan(&route, &plan_options).map_err(|e| e.to_string())?;
        let mut venue = StubVenue::new("stub");
        let fee = at(&test_case, "fee").cloned().unwrap_or(Value::Null);
        let currency = r.string_at(&fee, "currency", "");
        if !currency.is_empty() {
            venue.fee_to_charge = Some((r.number_at(&fee, "cost", 0.0), currency));
        }
        for entry in r.list_at(&test_case, "tradeFees") {
            venue.trade_fees_to_charge.push((
                r.number_at(&entry, "cost", 0.0),
                r.string_at(&entry, "currency", ""),
            ));
        }
        let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues.insert("stub".to_string(), Box::new(venue));
        let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
            .map_err(|e| e.to_string())?;
        let steps = r.list_at(&report, "steps");
        if steps.len() != 1 {
            return Err(format!("feeNettingCase {id}: expected one step, got {}", steps.len()));
        }
        let step = &steps[0];
        let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
        for field in ["filledAmount", "grossOutAmount", "outAmount", "feeCost"] {
            let actual = r.number_at(step, field, 0.0);
            let want = r.number_at(&expected, field, 0.0);
            if !numbers_match(actual, want) {
                return Err(format!("feeNettingCase {id}: {field} expected {want}, got {actual}"));
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// onStep and the retry policy — the four checks the TypeScript reference added,
// ported honestly. In THIS port the hook is a field on the router rather than an
// options key, because `Value` cannot carry a closure; see `OnStepHook`.
// ---------------------------------------------------------------------------

/// The two-hop route needs both markets declared, or the second hop is refused
/// for want of one.
fn two_hop_execute_options() -> Value {
    let mut options = execute_options(true, "sequential");
    let market = |symbol: &str, base_code: &str, quote: &str| {
        let mut m = HashMap::new();
        m.insert("symbol".to_string(), Value::Str(symbol.to_string().into()));
        m.insert("base".to_string(), Value::Str(base_code.to_string().into()));
        m.insert("quote".to_string(), Value::Str(quote.to_string().into()));
        Value::Map(m)
    };
    let mut by_symbol = HashMap::new();
    by_symbol.insert("BTC/USDT".to_string(), market("BTC/USDT", "BTC", "USDT"));
    by_symbol.insert("BTC/ETH".to_string(), market("BTC/ETH", "BTC", "ETH"));
    let mut markets = HashMap::new();
    markets.insert("stub".to_string(), Value::Map(by_symbol));
    OrderRouter::set_key(&mut options, "markets", Value::Map(markets));
    let mut usd_rates = HashMap::new();
    usd_rates.insert("USDT".to_string(), Value::Float(1.0));
    usd_rates.insert("ETH".to_string(), Value::Float(10.0));
    OrderRouter::set_key(&mut options, "usdRates", Value::Map(usd_rates));
    options
}

fn on_step_sees_every_step_and_can_stop_the_route() -> Result<(), String> {
    // The one thing a caller cannot do from outside execute(): look at what just happened
    // and decide not to continue. Before this hook the method was opaque from call to return.
    let mut r = router()?;
    let plan = r.build_execution_plan(&two_hop_route(), &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    let steps_total = r.list_at(&plan, "steps").len();
    let seen: StdArc<std::sync::Mutex<Vec<Value>>> = StdArc::new(std::sync::Mutex::new(Vec::new()));
    let recorded = StdArc::clone(&seen);
    r.set_on_step(std::sync::Arc::new(move |event: &Value| {
        recorded.lock().unwrap().push(event.clone());
        match event.as_map().and_then(|m| m.get("stepIndex")) {
            Some(Value::Float(index)) if *index == 0.0 => "halt".to_string(),
            _ => String::new(),
        }
    }));
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let venues = stub_venues(venue);
    let report = block_on(r.execute(&plan, &venues, &two_hop_execute_options())).map_err(|e| e.to_string())?;
    let events = seen.lock().unwrap().clone();
    if events.len() != 1 {
        return Err(format!("the hook is not called for steps that never ran, got {} calls", events.len()));
    }
    if r.number_at(&events[0], "stepIndex", -1.0) != 0.0 {
        return Err("the event names the step".to_string());
    }
    if r.string_at(&events[0], "status", "") != "filled" {
        return Err(format!("the event carries the outcome, got {}", r.string_at(&events[0], "status", "")));
    }
    if r.number_at(&events[0], "stepsRemaining", -1.0) != (steps_total - 1) as f64 {
        return Err("the event says how much of the route is left".to_string());
    }
    if events[0].as_map().and_then(|m| m.get("reconciliation")).is_none() {
        return Err("the verdict it is judging is in the event".to_string());
    }
    if !r.bool_at(&report, "halted", false) {
        return Err("the hook stopped the route".to_string());
    }
    if r.string_at(&report, "haltReason", "") != "halted_by_on_step" {
        return Err(format!("the halt names the hook, got {}", r.string_at(&report, "haltReason", "")));
    }
    if r.number_at(&report, "haltStepIndex", -1.0) != 0.0 {
        return Err("and the step it halted at".to_string());
    }
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[1], "status", "") != "skipped" {
        return Err("the rest of the route is skipped".to_string());
    }
    if r.number_at(&report, "ordersPlaced", -1.0) != 1.0 || counter.load(Ordering::SeqCst) != 1 {
        return Err("the step after the halt was never placed".to_string());
    }
    Ok(())
}

fn an_on_step_that_panics_is_recorded_and_does_not_take_the_run_down() -> Result<(), String> {
    // The report is the ONLY account of orders that are already live. A panic raised by
    // observability code must never destroy it — trigger.dev logs and ignores hook errors
    // for the same reason, and Go's port contains the equivalent panic with defer/recover.
    //
    // NOTE on the adaptation: the reference test is "a hook that THROWS". Rust has no
    // exceptions, so the nearest thing a caller's closure can do to take the run down is
    // panic, and the containment is `catch_unwind` rather than try/catch. The property under
    // test is identical; only the mechanism differs. It does NOT hold under a panic=abort
    // profile, where no construct in any language can save the process.
    let mut r = router()?;
    let plan = one_leg_plan(&r)?;
    r.set_on_step(std::sync::Arc::new(|_event: &Value| -> String {
        panic!("hook is broken");
    }));
    let venues = stub_venues(StubVenue::new("stub"));
    // The panic is contained, but the default panic hook still prints the unwind to stderr;
    // silenced so a passing suite does not read like a crashing one.
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let executed = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")));
    std::panic::set_hook(previous);
    let report = executed.map_err(|e| e.to_string())?;
    if r.bool_at(&report, "halted", true) {
        return Err("the route finished".to_string());
    }
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "filled" {
        return Err("and the order it placed is still reported".to_string());
    }
    let errors = r.list_at(&report, "errors");
    let mut found = false;
    for entry in &errors {
        if r.string_at(entry, "code", "").starts_with("on_step_hook_failed") {
            found = true;
        }
    }
    if !found {
        return Err(format!("the broken hook is reported rather than swallowed, got {errors:?}"));
    }
    Ok(())
}

fn on_step_can_only_narrow_and_cannot_resume_a_halted_route() -> Result<(), String> {
    // The halt is a money decision made in one pure place precisely so it cannot be omitted.
    // A hook that could wave it through would be a way to omit it.
    let mut r = router()?;
    let plan = r.build_execution_plan(&two_hop_route(), &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    r.set_on_step(std::sync::Arc::new(|_event: &Value| "continue".to_string()));
    let mut starved = StubVenue::new("stub");
    starved.fill_ratio = 0.1;
    let counter = StdArc::clone(&starved.orders_placed);
    let venues = stub_venues(starved);
    let report = block_on(r.execute(&plan, &venues, &two_hop_execute_options())).map_err(|e| e.to_string())?;
    if !r.bool_at(&report, "halted", false) {
        return Err("the reconciliation halt stands".to_string());
    }
    if r.string_at(&report, "haltReason", "") != "shortfall_exceeds_tolerance" {
        return Err(format!(
            "the reconciliation reason survives, it is not replaced by the hook; got {}",
            r.string_at(&report, "haltReason", "")
        ));
    }
    if r.number_at(&report, "ordersPlaced", -1.0) != 1.0 || counter.load(Ordering::SeqCst) != 1 {
        return Err("the hook did not wave the route onward".to_string());
    }
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[1], "status", "") != "skipped" {
        return Err("the second hop never ran".to_string());
    }
    Ok(())
}

fn retry_replaces_under_a_new_id_and_never_retries_an_unknown_outcome() -> Result<(), String> {
    // A rejected order was not placed, so re-placing it cannot double-fill. Re-sending the
    // original client order id would have the venue reject the retry as a duplicate of the
    // very order it just refused, so each attempt carries its own.
    let r = router()?;
    let plan = one_leg_plan(&r)?;
    let relents = StubVenue::new("stub");
    relents.fail_create_times.store(1, Ordering::SeqCst);
    let seen = StdArc::clone(&relents.params_seen);
    let venues = stub_venues(relents);
    let mut options = options_with(
        &execute_options(true, "sequential"),
        "retryFailedSteps",
        Value::Float(2.0),
    );
    options = options_with(&options, "retryDelayMs", Value::Float(0.0));
    let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "filled" {
        return Err(format!("the retry succeeded, got {}", r.string_at(&results[0], "status", "")));
    }
    if r.number_at(&results[0], "attempt", -1.0) != 1.0 {
        return Err(format!("the report says which attempt won, got {}", r.number_at(&results[0], "attempt", -1.0)));
    }
    let params = seen.lock().unwrap().clone();
    if params.len() != 2 {
        return Err(format!("one rejection and one retry, got {} calls", params.len()));
    }
    // No client order id is injected on EITHER attempt. An id derived from the plan identity
    // used to be forced onto every order, but venues disagree on its length and charset —
    // gate refuses one over 28 characters, okx and mexc cap at 32, lighter parses it as an
    // integer — so the router now sets none and the venue's own generation applies to the
    // retry exactly as it did to the first try.
    for (index, params_seen) in params.iter().enumerate() {
        let injected = r.string_at(params_seen, "clientOrderId", "");
        if !injected.is_empty() {
            return Err(format!("no client order id is injected, found {injected} on placement {index}"));
        }
    }

    // The outcome the policy must NEVER touch.
    let plan2 = r
        .build_execution_plan(&one_leg_route("buy", "BTC", "USDT", 0.2, 100.0), &Value::Map(HashMap::new()))
        .map_err(|e| e.to_string())?;
    let mut unknown = StubVenue::new("stub");
    unknown.fail_with = Some("RequestTimeout");
    let attempts = StdArc::clone(&unknown.orders_placed);
    let venues = stub_venues(unknown);
    let second_options = options_with(&options, "retryFailedSteps", Value::Float(5.0));
    let second_report = block_on(r.execute(&plan2, &venues, &second_options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&second_report, "steps");
    if r.string_at(&results[0], "status", "") != "outcome_unknown" {
        return Err("a timed-out placement stays outcome_unknown".to_string());
    }
    if attempts.load(Ordering::SeqCst) != 1 {
        return Err(format!(
            "an order whose outcome is unknown may already be live; it is never re-placed, saw {} calls",
            attempts.load(Ordering::SeqCst)
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// entry point
// ---------------------------------------------------------------------------

/// Runs the OrderRouter suite. Returns the number of checks that passed.
pub fn run() -> Result<usize, String> {
    let f = fixture()?;
    let r = router()?;
    let mut passed = 0usize;
    let checks: Vec<(&str, Box<dyn Fn() -> Result<(), String>>)> = vec![
        ("fixture: buildExecutionPlan", Box::new(|| fixture_build_execution_plan(&router()?, &fixture()?))),
        ("fixture: buildExecutionPlan is deterministic and does not mutate its input", Box::new(|| fixture_plan_is_deterministic(&router()?, &fixture()?))),
        ("fixture: checkExecutionPlanSafety", Box::new(|| fixture_check_execution_plan_safety(&router()?, &fixture()?))),
        ("fixture: reconcileExecutionStep", Box::new(|| fixture_reconcile_execution_step(&router()?, &fixture()?))),
        ("fixture: a sequence of reconciliations on one hop", Box::new(|| fixture_reconcile_sequence(&router()?, &fixture()?))),
        ("fixture: buildUnwindPlan", Box::new(|| fixture_build_unwind_plan(&router()?, &fixture()?))),
        ("a buy-side unwind order never spends more quote than the residual actually holds", Box::new(|| unwind_buy_is_fundable(&router()?, &fixture()?))),
        ("fixture: numberAt reads one number grammar in all six languages", Box::new(|| fixture_number_at(&router()?, &fixture()?))),
        ("fixture: formatNumber spells one number one way in all six languages", Box::new(|| fixture_format_number(&router()?, &fixture()?))),
        ("fixture: a fee in the acquired asset resizes what the next hop is sized on", Box::new(|| fixture_fee_netting(&router()?, &fixture()?))),
        ("constructor: the service is public, and maxNotionalUsd is an opt-in guardrail at any size", Box::new(constructor_guards)),
        ("a hand-built plan carrying only the required fields is executable", Box::new(|| a_hand_built_plan_with_only_the_required_fields_is_executable(&router()?))),
        ("the derived limit price and notional follow amount and expectedPrice", Box::new(|| derived_limit_price_and_notional_follow_amount_and_expected_price(&router()?))),
        ("the limit price sits on the side that costs you, and only there", Box::new(|| limit_price_side(&router()?))),
        ("an empty plan is not a safe plan", Box::new(|| empty_plan_is_not_safe(&router()?))),
        ("a cap that IS set binds exactly, at whatever size, and includes the slippage", Box::new(|| a_cap_that_is_set_binds_exactly(&router()?))),
        ("with no cap set, no notional check runs at all", Box::new(|| with_no_cap_no_notional_check_runs(&router()?))),
        ("a per-call cap overrides the client-level one, in both directions", Box::new(a_per_call_cap_overrides_the_client_one)),
        ("USDT is not assumed to be one dollar, and an unvaluable step blocks only under a cap", Box::new(|| usdt_is_not_a_dollar(&router()?))),
        ("a route that does not match the question asked is refused", Box::new(|| refuses_incoherent_routes(&router()?))),
        ("formatNumber never emits exponent notation", Box::new(|| format_number_never_uses_exponents(&router()?))),
        ("fetchRoute builds a deterministic query", Box::new(|| route_url_is_deterministic(&router()?))),
        ("the query escaping is encodeURIComponent's, not form-urlencoded's", Box::new(|| encode_uri_component_matches_javascript(&router()?))),
        ("a route carrying balances is POSTed, and the holdings never appear in the url", Box::new(|| route_body_carries_the_holdings_and_the_url_never_does(&router()?))),
        ("a fee the router already subtracted is not subtracted a second time", Box::new(|| fee_is_not_subtracted_twice(&router()?))),
        ("a router that ignored the balances is caught, including when the wallet is empty", Box::new(|| balances_echo_is_verified(&router()?))),
        ("streamUrl upgrades the scheme, and close codes keep the REST vocabulary", Box::new(|| stream_url_and_close_codes(&router()?))),
        ("balances accept the shape a caller actually writes", Box::new(|| balances_shapes(&router()?))),
        ("plan-shaping options with a built plan are refused, not ignored", Box::new(|| plan_shaping_refused(&router()?))),
        ("execute: a rehearsal is asked for by dryRun and places nothing", Box::new(|| dry_run_places_nothing(&router()?))),
        ("options.live is refused, not ignored: the old knob cannot silently place orders", Box::new(|| live_option_is_refused(&router()?))),
        ("watchRoute applies the same venue filter fetchRoute does", Box::new(|| stream_url_applies_the_venue_filter(&router()?))),
        ("joinBalances spells an unqualified holding without a leading dot", Box::new(|| join_balances_separator(&router()?))),
        ("execute: an unknown strategy is refused even in dry run", Box::new(|| an_unknown_strategy_is_refused_even_in_dry_run(&router()?))),
        ("execute: sequential places IOC limit orders in plan order", Box::new(|| sequential_places_and_fills(&router()?))),
        ("execute: a failure BEFORE dispatch records no open order", Box::new(|| a_failure_before_dispatch_records_no_open_order(&router()?))),
        ("execute: a createOrder that times out is outcome-unknown, not a plain failure", Box::new(|| a_timeout_is_outcome_unknown_not_a_plain_failure(&router()?))),
        ("execute: a definite rejection stays a plain failure and reports no open order", Box::new(|| a_definite_rejection_stays_a_plain_failure(&router()?))),
        ("execute: a throttled request is a plain failure, not a possibly-live order", Box::new(|| a_rate_limit_rejection_is_a_plain_failure(&router()?))),
        ("execute: limit_protected refuses a non-positive pollIntervalMs before placing anything", Box::new(|| limit_protected_refuses_a_zero_poll_interval(&router()?))),
        ("execute: a fill that stays unknown after the re-read halts instead of guessing", Box::new(|| a_fill_that_stays_unknown_halts_instead_of_guessing(&router()?))),
        ("execute: refuses to go live above a cap the caller set", Box::new(|| execute_refuses_to_go_live_above_the_cap(&router()?))),
        ("execute: the same trade goes through when nobody asked for a cap", Box::new(|| execute_places_the_same_trade_with_no_cap(&router()?))),
        ("execute: a resting order is cancelled, and a cancel that fails halts the route", Box::new(|| a_resting_order_is_cancelled(&router()?))),
        ("execute: a throw after createOrder still reports the id and an open order", Box::new(|| a_known_order_id_survives_a_throw_after_create(&router()?))),
        ("execute: a spend the venue DID report survives an unknown fill", Box::new(|| a_reported_spend_survives_an_unknown_fill(&router()?))),
        ("execute: a report is summarised in the assets it names, not across currencies", Box::new(|| a_report_is_summarised_in_the_assets_it_names(&router()?))),
        ("execute: a plan carries its age, and a stale one is refused only when asked", Box::new(|| plan_age_is_reported_and_refused_only_when_asked(&router()?))),
        ("execute: a market order and a notional cap are refused together", Box::new(|| a_market_order_and_a_cap_are_refused_together(&router()?))),
        ("execute: atomic_ish demands the whole route pre-funded", Box::new(|| atomic_ish_demands_the_whole_route_prefunded(&router()?))),
        ("execute: best_effort demands both of its acknowledgements", Box::new(|| best_effort_demands_its_acknowledgements(&router()?))),
        ("execute: a live plan with no identity is refused, and an idempotencyKey supplies one", Box::new(|| live_requires_an_identity(&router()?))),
        ("execute: no clientOrderId is injected, and a caller-supplied one travels untouched", Box::new(|| client_order_id_is_never_injected(&router()?))),
        ("execute: the same plan is refused on a second live execution unless the caller opts in", Box::new(|| reexecution_is_refused(&router()?))),
        ("execute: a dry run never consumes a plan, and a halted live run always does", Box::new(|| a_dry_run_does_not_consume_a_plan(&router()?))),
        ("execute: onStep sees every step and can stop the route", Box::new(on_step_sees_every_step_and_can_stop_the_route)),
        ("execute: an onStep that panics is recorded, and does not take the run down with it", Box::new(an_on_step_that_panics_is_recorded_and_does_not_take_the_run_down)),
        ("execute: onStep can only narrow — it cannot resume a route the reconciliation already halted", Box::new(on_step_can_only_narrow_and_cannot_resume_a_halted_route)),
        ("execute: retryFailedSteps re-places a rejected step under a NEW client order id, and never retries an unknown outcome", Box::new(retry_replaces_under_a_new_id_and_never_retries_an_unknown_outcome)),
        ("execute: the re-execution ledger is bounded, evicts oldest-first, and re-allows an evicted plan", Box::new(|| the_ledger_is_bounded(&router()?))),
    ];
    let _ = (&f, &r);
    for (name, check) in checks {
        match check() {
            Ok(()) => {
                println!("ok   {name}");
                passed += 1;
            }
            Err(message) => return Err(format!("{name} — {message}")),
        }
    }
    Ok(passed)
}


#[cfg(test)]
mod tests {
    /// The whole cross-language contract, runnable without the generated
    /// exchange surface. `cargo test -p ccxt-base`.
    #[test]
    fn order_router_matches_the_shared_fixture() {
        match super::run() {
            Ok(passed) => assert!(passed > 0, "the suite ran no checks"),
            Err(message) => panic!("{message}"),
        }
    }
}

// ---------------------------------------------------------------------------
// execute, against stub venues
//
// The money path. It cannot be exercised against a real exchange from a test,
// and should not be — CLAUDE.md §5.5 caps a live trade at 25 USD and this suite
// places none. What IS testable, and is what the other five ports test too, is
// the behaviour around the placement: that dry_run touches nothing, that a
// forgotten `live` flag places nothing, that a refusal before dispatch records
// no open order, and that an unknown outcome halts rather than reconciling on a
// number nobody observed.
// ---------------------------------------------------------------------------

use crate::order_router::RouterVenue;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc as StdArc;

struct StubVenue {
    id: String,
    supports_ioc: bool,
    /// Counts createOrder calls, so "placed nothing" is asserted rather than
    /// assumed.
    orders_placed: StdArc<AtomicUsize>,
    /// When set, createOrder fails with this error kind instead of filling.
    fail_with: Option<&'static str>,
    /// When true the order comes back with no `filled` at all — the case that
    /// used to be read as a zero fill.
    omit_filled: bool,
    /// When true createOrder returns a RESTING order, so limit_protected enters
    /// its poll loop and the fetch_order failure below is reached.
    created_open: bool,
    /// When set, the re-read still has no `filled` but DOES carry these
    /// (cost, average) — the venue is certain what it charged and silent about
    /// what it bought.
    reread_cost: Option<(f64, f64)>,
    /// The `free` map fetch_balance reports. `None` means "richly funded", so a
    /// prefunding check passes without every other test having to declare
    /// balances it does not care about.
    free_balances: Option<Vec<(String, f64)>>,
    /// When true, cancel_order errors — the venue refuses to take the resting
    /// order back off the book.
    cancel_fails: bool,
    /// Counts cancel_order calls, so "the resting order was cancelled" is
    /// asserted rather than assumed.
    cancels: StdArc<AtomicUsize>,
    /// When set, fetch_order hands this back instead of erroring — the order as
    /// it looks on the re-read after a cancel.
    reread_order: Option<(String, f64, f64, f64)>,
    /// (cost, currency) attached to the created order as its `fee`, as real
    /// venues report it.
    fee_to_charge: Option<(f64, String)>,
    /// (cost, currency) entries attached as per-trade fees, as venues that
    /// report a fill as a list of trades do.
    trade_fees_to_charge: Vec<(f64, String)>,
    /// Every params dictionary create_order was called with, in call order.
    params_seen: StdArc<std::sync::Mutex<Vec<Value>>>,
    /// Refuse this many create_order calls, then behave: a venue that rejects
    /// and then relents, which is the only shape a retry can be tested against.
    /// An atomic because `create_order` takes `&self`.
    fail_create_times: StdArc<AtomicUsize>,
    /// The fraction of the requested amount the venue actually fills. 1.0 is a
    /// full fill; a smaller number is the shortfall a reconciliation halts on.
    fill_ratio: f64,
}

impl StubVenue {
    fn new(id: &str) -> Self {
        StubVenue {
            id: id.to_string(),
            supports_ioc: true,
            orders_placed: StdArc::new(AtomicUsize::new(0)),
            fail_with: None,
            omit_filled: false,
            created_open: false,
            reread_cost: None,
            free_balances: None,
            cancel_fails: false,
            cancels: StdArc::new(AtomicUsize::new(0)),
            reread_order: None,
            fee_to_charge: None,
            trade_fees_to_charge: Vec::new(),
            params_seen: StdArc::new(std::sync::Mutex::new(Vec::new())),
            fail_create_times: StdArc::new(AtomicUsize::new(0)),
            fill_ratio: 1.0,
        }
    }
}

#[async_trait::async_trait]
impl RouterVenue for StubVenue {
    fn id(&self) -> String {
        self.id.clone()
    }
    fn amount_to_precision(&self, _symbol: &str, amount: f64) -> String {
        format!("{amount}")
    }
    fn price_to_precision(&self, _symbol: &str, price: f64) -> String {
        format!("{price}")
    }
    fn supports_ioc(&self) -> bool {
        self.supports_ioc
    }
    async fn create_order(
        &self,
        _symbol: &str,
        _order_type: &str,
        _side: &str,
        amount: f64,
        price: f64,
        params: &Value,
    ) -> Result<Value, crate::error::ExchangeError> {
        self.orders_placed.fetch_add(1, Ordering::SeqCst);
        self.params_seen.lock().unwrap().push(params.clone());
        if let Some(kind) = self.fail_with {
            return Err(crate::error::ExchangeError::new(kind, "stub refuses"));
        }
        if self.fail_create_times.load(Ordering::SeqCst) > 0 {
            self.fail_create_times.fetch_sub(1, Ordering::SeqCst);
            return Err(crate::error::ExchangeError::new("ExchangeError", "stub refuses, for now"));
        }
        let mut order = HashMap::new();
        order.insert("id".to_string(), Value::Str("stub-1".to_string().into()));
        if let Value::Dict(given) = params {
            // a real venue echoes the client order id it was given
            if let Some(client_order_id) = given.get("clientOrderId") {
                order.insert("clientOrderId".to_string(), client_order_id.clone());
            }
        }
        if self.created_open {
            // A venue that reports the order it just accepted as still OPEN — the
            // shape a dropped timeInForce leaves behind. It still answers with a
            // fill, exactly as the other five ports' stubs do, so that "the order
            // is resting" and "the fill is unknown" stay separate cases.
            order.insert("status".to_string(), Value::Str("open".to_string().into()));
        } else {
            order.insert("status".to_string(), Value::Str("closed".to_string().into()));
        }
        if !self.omit_filled {
            let filled = amount * self.fill_ratio;
            order.insert("filled".to_string(), Value::Float(filled));
            order.insert("average".to_string(), Value::Float(price));
            order.insert("cost".to_string(), Value::Float(filled * price));
        }
        if let Some((cost, currency)) = &self.fee_to_charge {
            order.insert("fee".to_string(), stub_fee(*cost, currency));
        }
        if !self.trade_fees_to_charge.is_empty() {
            let mut trades = Vec::new();
            for (cost, currency) in &self.trade_fees_to_charge {
                let mut trade = HashMap::new();
                trade.insert("fee".to_string(), stub_fee(*cost, currency));
                trades.push(Value::Map(trade));
            }
            order.insert("trades".to_string(), Value::List(trades));
        }
        Ok(Value::Map(order))
    }
    async fn fetch_order(&self, _id: &str, _symbol: &str) -> Result<Value, crate::error::ExchangeError> {
        if let Some((status, filled, average, cost)) = &self.reread_order {
            let mut order = HashMap::new();
            order.insert("id".to_string(), Value::Str("stub-1".to_string().into()));
            order.insert("status".to_string(), Value::Str(status.clone().into()));
            order.insert("filled".to_string(), Value::Float(*filled));
            order.insert("average".to_string(), Value::Float(*average));
            order.insert("cost".to_string(), Value::Float(*cost));
            return Ok(Value::Map(order));
        }
        if self.omit_filled {
            // Still incomplete on the re-read: the fill stays genuinely unknown.
            let mut order = HashMap::new();
            order.insert("id".to_string(), Value::Str("stub-1".to_string().into()));
            order.insert("status".to_string(), Value::Str("closed".to_string().into()));
            if let Some((cost, average)) = self.reread_cost {
                order.insert("cost".to_string(), Value::Float(cost));
                order.insert("average".to_string(), Value::Float(average));
            }
            return Ok(Value::Map(order));
        }
        Err(crate::error::ExchangeError::new("ExchangeError", "stub cannot read the order back"))
    }
    async fn cancel_order(&self, _id: &str, _symbol: &str) -> Result<Value, crate::error::ExchangeError> {
        self.cancels.fetch_add(1, Ordering::SeqCst);
        if self.cancel_fails {
            return Err(crate::error::ExchangeError::new("ExchangeError", "stub refuses to cancel"));
        }
        Ok(Value::Map(HashMap::new()))
    }
    async fn fetch_balance(&self) -> Result<Value, crate::error::ExchangeError> {
        let mut free = HashMap::new();
        match &self.free_balances {
            Some(entries) => {
                for (asset, amount) in entries {
                    free.insert(asset.clone(), Value::Float(*amount));
                }
            }
            None => {
                free.insert("USDT".to_string(), Value::Float(1_000_000.0));
                free.insert("BTC".to_string(), Value::Float(1_000_000.0));
                free.insert("ETH".to_string(), Value::Float(1_000_000.0));
            }
        }
        let mut balance = HashMap::new();
        balance.insert("free".to_string(), Value::Map(free));
        Ok(Value::Map(balance))
    }
}

fn one_leg_plan(r: &OrderRouter) -> Result<Value, String> {
    let route = one_leg_route("buy", "BTC", "USDT", 0.2, 100.0);
    r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())
}

fn block_on<F: std::future::Future>(future: F) -> F::Output {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("a tokio runtime")
        .block_on(future)
}

fn execute_options(live: bool, strategy: &str) -> Value {
    let mut usd_rates = HashMap::new();
    usd_rates.insert("USDT".to_string(), Value::Float(1.0));
    let mut market = HashMap::new();
    market.insert("symbol".to_string(), Value::Str("BTC/USDT".to_string().into()));
    market.insert("base".to_string(), Value::Str("BTC".to_string().into()));
    market.insert("quote".to_string(), Value::Str("USDT".to_string().into()));
    let mut by_symbol = HashMap::new();
    by_symbol.insert("BTC/USDT".to_string(), Value::Map(market));
    let mut markets = HashMap::new();
    markets.insert("stub".to_string(), Value::Map(by_symbol));
    let mut options = HashMap::new();
    options.insert("strategy".to_string(), Value::Str(strategy.to_string().into()));
    //  ONE knob: `dryRun` says whether, `strategy` says how. The helper keeps its
    //  live-shaped argument so every call site still reads the way it did — live=false
    //  means rehearse — and expresses it with the field the implementation now reads.
    options.insert("dryRun".to_string(), Value::Bool(!live));
    options.insert("usdRates".to_string(), Value::Map(usd_rates));
    options.insert("markets".to_string(), Value::Map(markets));
    Value::Map(options)
}

fn balances_shapes(r: &OrderRouter) -> Result<(), String> {
    //  A wallet map is the obvious thing to write, and it used to be rendered with Rust's own
    //  debug formatter and shipped for the server to reject.
    let mut inner = HashMap::new();
    inner.insert("USDT".to_string(), Value::Float(100.0));
    inner.insert("BTC".to_string(), Value::Float(0.5));
    let mut nested = HashMap::new();
    nested.insert("mexc".to_string(), Value::Map(inner));
    let rendered = r.render_balances(&Value::Map(nested)).map_err(|e| e.to_string())?;
    if rendered != "mexc.BTC:0.5,mexc.USDT:100" {
        return Err(format!("the nested wallet renders sorted, got {rendered}"));
    }
    let mut flat = HashMap::new();
    flat.insert("USDT".to_string(), Value::Float(100.0));
    let flat_text = r.render_balances(&Value::Map(flat)).map_err(|e| e.to_string())?;
    if flat_text != "USDT:100" {
        return Err(format!("a flat wallet renders without a venue, got {flat_text}"));
    }
    let passthrough = r
        .render_balances(&Value::Str("mexc.USDT:100".to_string().into()))
        .map_err(|e| e.to_string())?;
    if passthrough != "mexc.USDT:100" {
        return Err("a rendered string passes through untouched".to_string());
    }
    //  a value that is neither is refused HERE, not at the far end
    if r.render_balances(&Value::Float(12345.0)).is_ok() {
        return Err("a number is not a wallet".to_string());
    }
    Ok(())
}

fn plan_shaping_refused(r: &OrderRouter) -> Result<(), String> {
    //  slippageBps shapes a plan; passing it WITH a plan cannot do anything, and silently
    //  ignoring it means trading at a different limit than the caller asked for.
    let plan = one_leg_plan(r)?;
    let venue = StubVenue::new("stub");
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let mut options = match execute_options(true, "sequential").as_map() {
        Some(map) => map.clone(),
        None => HashMap::new(),
    };
    options.insert("slippageBps".to_string(), Value::Float(1000.0));
    match block_on(r.execute(&plan, &venues, &Value::Map(options))) {
        Err(e) if e.message.contains("slippageBps") => Ok(()),
        Err(e) => Err(format!("wrong refusal: {e}")),
        Ok(_) => Err("shaping an already-built plan is refused".to_string()),
    }
}

fn live_option_is_refused(r: &OrderRouter) -> Result<(), String> {
    // `live` used to gate execution and is gone. A call still carrying it was
    // written against the old contract, and the dangerous reading is the silent
    // one: `live: false` meant "place nothing" and now means nothing at all, so
    // the orders would go out while the caller believed they had opted out.
    let plan = one_leg_plan(r)?;
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    for flag in [false, true] {
        let mut options = execute_options(true, "sequential").as_map().cloned().unwrap_or_default();
        options.shift_remove("dryRun");
        options.insert("live".to_string(), Value::Bool(flag));
        match block_on(r.execute(&plan, &venues, &Value::map(options))) {
            Ok(_) => return Err(format!("options.live = {flag} must be refused, not ignored")),
            Err(error) => {
                if !error.to_string().contains("options.live is gone") {
                    return Err(format!("the refusal must name the replacement, got {error}"));
                }
            }
        }
    }
    if counter.load(Ordering::SeqCst) != 0 {
        return Err("refused before a single order reached the venue".to_string());
    }
    Ok(())
}

fn stream_url_applies_the_venue_filter(_r: &OrderRouter) -> Result<(), String> {
    // A router built with venues can only execute on those. A stream that quoted
    // the rest would hand back routes its own executor must refuse.
    let mut config = HashMap::new();
    config.insert("baseUrl".to_string(), Value::Str("https://example.test/api".to_string().into()));
    let mut held = OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())?;
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(StubVenue::new("stub")));
    venues.insert("other".to_string(), Box::new(StubVenue::new("other")));
    held.set_venues(venues);
    let mut params = HashMap::new();
    params.insert("amountIn".to_string(), Value::Float(1.0));
    let url = held
        .stream_url("USDT", "BTC", &Value::Map(params.clone()))
        .map_err(|e| e.to_string())?;
    if !url.contains("exchanges=other%2Cstub") {
        return Err(format!("the held venues are the default filter, got {url}"));
    }
    let mut explicit = params.clone();
    explicit.insert("exchanges".to_string(), Value::List(vec![Value::Str("kraken".into())]));
    let chosen = held
        .stream_url("USDT", "BTC", &Value::Map(explicit))
        .map_err(|e| e.to_string())?;
    if !chosen.contains("kraken") || chosen.contains("stub") {
        return Err(format!("an explicit exchanges parameter wins, got {chosen}"));
    }
    // and a router holding nothing adds nothing
    held.clear_venues();
    let plain = held
        .stream_url("USDT", "BTC", &Value::Map(params))
        .map_err(|e| e.to_string())?;
    if plain.contains("exchanges=") {
        return Err(format!("a router holding nothing adds nothing, got {plain}"));
    }
    Ok(())
}

fn join_balances_separator(r: &OrderRouter) -> Result<(), String> {
    // asserted EXACTLY, not by substring: `USDT:100` is also a substring of the
    // malformed `.USDT:100` a port produced by hard-coding the separator, so a
    // contains-check passes on the broken spelling and ships it to a server that
    // rejects that syntax.
    let mut unqualified = HashMap::new();
    unqualified.insert("asset".to_string(), Value::Str("USDT".to_string().into()));
    unqualified.insert("amount".to_string(), Value::Float(100.0));
    let bare = r
        .join_balances(&[Value::Map(unqualified)])
        .map_err(|e| e.to_string())?;
    if bare != "USDT:100" {
        return Err(format!("an unqualified holding carries no leading dot, got {bare}"));
    }
    let mut qualified = HashMap::new();
    qualified.insert("exchangeId".to_string(), Value::Str("mexc".to_string().into()));
    qualified.insert("asset".to_string(), Value::Str("USDT".to_string().into()));
    qualified.insert("amount".to_string(), Value::Float(100.0));
    let scoped = r
        .join_balances(&[Value::Map(qualified)])
        .map_err(|e| e.to_string())?;
    if scoped != "mexc.USDT:100" {
        return Err(format!("a qualified one does, got {scoped}"));
    }
    Ok(())
}

fn dry_run_places_nothing(r: &OrderRouter) -> Result<(), String> {
    // Asserted by counting createOrder calls rather than by reading the report,
    // because the report is exactly what a buggy implementation would still fill
    // in correctly. Placing is the DEFAULT now; this is the opt-out.
    let plan = one_leg_plan(r)?;
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));

    // strategy: sequential, but dryRun is TRUE — how and whether are independent.
    let report = block_on(r.execute(&plan, &venues, &execute_options(false, "sequential")))
        .map_err(|e| e.to_string())?;
    if counter.load(Ordering::SeqCst) != 0 {
        return Err("a non-live execute placed an order".to_string());
    }
    if r.string_at(&report, "strategy", "") != "sequential" {
        return Err("the strategy survives the rehearsal: how is not what".to_string());
    }
    if !r.bool_at(&report, "dryRun", false) {
        return Err("the report must say it was a dry run".to_string());
    }
    if r.number_at(&report, "wouldPlaceOrders", 0.0) != 1.0 {
        return Err("a dry run reports what it would have placed".to_string());
    }
    Ok(())
}

fn an_unknown_strategy_is_refused_even_in_dry_run(r: &OrderRouter) -> Result<(), String> {
    let plan = one_leg_plan(r)?;
    let venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    let outcome = block_on(r.execute(&plan, &venues, &execute_options(false, "sideways")));
    match outcome {
        Err(e) if e.message.contains("unknown execution strategy") => Ok(()),
        Err(e) => Err(format!("wrong refusal: {e}")),
        Ok(_) => Err("an unknown strategy is refused before anything else".to_string()),
    }
}

fn sequential_places_and_fills(r: &OrderRouter) -> Result<(), String> {
    let plan = one_leg_plan(r)?;
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    if counter.load(Ordering::SeqCst) != 1 {
        return Err(format!("expected 1 order, placed {}", counter.load(Ordering::SeqCst)));
    }
    let results = r.list_at(&report, "steps");
    let status = r.string_at(&results[0], "status", "");
    if status != "filled" {
        return Err(format!("expected filled, got {status}"));
    }
    if !r.bool_at(&results[0], "placementAttempted", false) {
        return Err("a dispatched order records placementAttempted".to_string());
    }
    Ok(())
}

fn a_failure_before_dispatch_records_no_open_order(r: &OrderRouter) -> Result<(), String> {
    // The distinction placementAttempted exists for. A venue that is not in the
    // map cannot have received anything, so reporting an unconfirmed placement
    // for it would be a false alarm — and a false alarm on this particular
    // signal sends someone hunting for an order that does not exist.
    let plan = one_leg_plan(r)?;
    let venue = StubVenue::new("other");
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("other".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.bool_at(&results[0], "placementAttempted", true) {
        return Err("nothing was dispatched, so placementAttempted must be false".to_string());
    }
    if r.string_at(&results[0], "errorCode", "") != "venue_missing" {
        return Err("the missing venue is named".to_string());
    }
    if !r.list_at(&report, "openOrders").is_empty() {
        return Err("a failure before dispatch records NO open order".to_string());
    }
    if r.string_at(&report, "haltReason", "") != "order_failed" {
        return Err("a definite failure halts as order_failed".to_string());
    }
    Ok(())
}

fn a_timeout_is_outcome_unknown_not_a_plain_failure(r: &OrderRouter) -> Result<(), String> {
    // A request that timed out may still have been received and acted on. The
    // report must say so: concluding that nothing was placed is the one
    // conclusion that can strand a real position on a real venue.
    let plan = one_leg_plan(r)?;
    let mut venue = StubVenue::new("stub");
    venue.fail_with = Some("RequestTimeout");
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "outcome_unknown" {
        return Err(format!("expected outcome_unknown, got {}", r.string_at(&results[0], "status", "")));
    }
    if r.string_at(&report, "haltReason", "") != "outcome_unknown" {
        return Err("the halt reason must not claim nothing_filled".to_string());
    }
    let open = r.list_at(&report, "openOrders");
    if open.len() != 1 || r.string_at(&open[0], "reason", "") != "placement_unconfirmed" {
        return Err("an unconfirmed placement is recorded".to_string());
    }
    Ok(())
}

fn a_definite_rejection_stays_a_plain_failure(r: &OrderRouter) -> Result<(), String> {
    // The counterpart. An ExchangeError is the venue ANSWERING — a definite
    // "no" — and treating it as unknown would send someone hunting for an order
    // that was never accepted.
    let plan = one_leg_plan(r)?;
    let mut venue = StubVenue::new("stub");
    venue.fail_with = Some("ExchangeError");
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "failed" {
        return Err("a definite rejection is a plain failure".to_string());
    }
    if !r.list_at(&report, "openOrders").is_empty() {
        return Err("a definite rejection leaves no open order".to_string());
    }
    Ok(())
}

fn limit_protected_refuses_a_zero_poll_interval(r: &OrderRouter) -> Result<(), String> {
    // The poll loop advances its clock by pollIntervalMs, so 0 never reaches
    // the timeout: it spins on fetch_order forever with a real order resting on
    // a real venue, and the timeout that exists to cancel that order never
    // arrives. Refused BEFORE create_order — refusing afterwards would leave
    // the very order the loop could not clean up.
    for interval in [0.0_f64, -1.0_f64] {
        let plan = one_leg_plan(r)?;
        let mut venue = StubVenue::new("stub");
        venue.created_open = true;
        let placed = StdArc::clone(&venue.orders_placed);
        let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues.insert("stub".to_string(), Box::new(venue));
        let mut options = execute_options(true, "limit_protected");
        OrderRouter::set_key(&mut options, "orderTimeoutMs", Value::Float(4.0));
        OrderRouter::set_key(&mut options, "pollIntervalMs", Value::Float(interval));
        if block_on(r.execute(&plan, &venues, &options)).is_ok() {
            return Err(format!("pollIntervalMs {interval} must be refused"));
        }
        if placed.load(Ordering::SeqCst) != 0 {
            return Err("nothing may reach the venue".to_string());
        }
    }
    Ok(())
}

fn a_rate_limit_rejection_is_a_plain_failure(r: &OrderRouter) -> Result<(), String> {
    // The classifier used to walk the error hierarchy, where DDoSProtection,
    // RateLimitExceeded and InvalidNonce all sit UNDER NetworkError — so every
    // throttled request was reported as a possibly-live order, halting a route
    // the other five ports complete and sending an operator hunting for an
    // order that was never accepted. The other five match four names exactly;
    // this pins Rust to the same list.
    for kind in ["RateLimitExceeded", "DDoSProtection", "InvalidNonce"] {
        let plan = one_leg_plan(r)?;
        let mut venue = StubVenue::new("stub");
        venue.fail_with = Some(kind);
        let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues.insert("stub".to_string(), Box::new(venue));
        let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
            .map_err(|e| e.to_string())?;
        let results = r.list_at(&report, "steps");
        let status = r.string_at(&results[0], "status", "");
        if status != "failed" {
            return Err(format!("{kind} is the venue answering; expected failed, got {status}"));
        }
        if !r.list_at(&report, "openOrders").is_empty() {
            return Err(format!("{kind} left an open order behind"));
        }
    }
    // The four that genuinely are ambiguous still are.
    for kind in ["RequestTimeout", "ExchangeNotAvailable", "NetworkError", "OnMaintenance"] {
        let plan = one_leg_plan(r)?;
        let mut venue = StubVenue::new("stub");
        venue.fail_with = Some(kind);
        let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues.insert("stub".to_string(), Box::new(venue));
        let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
            .map_err(|e| e.to_string())?;
        let results = r.list_at(&report, "steps");
        let status = r.string_at(&results[0], "status", "");
        if status != "outcome_unknown" {
            return Err(format!("{kind} may still have reached the venue; got {status}"));
        }
    }
    Ok(())
}

fn a_fill_that_stays_unknown_halts_instead_of_guessing(r: &OrderRouter) -> Result<(), String> {
    // "The venue said zero" and "the venue said nothing" are different facts.
    // A venue that omits `filled` used to yield 0, which reconciliation read as
    // nothing_filled and halted on — while a real position sat on a real venue.
    let plan = one_leg_plan(r)?;
    let mut venue = StubVenue::new("stub");
    venue.omit_filled = true;
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "outcome_unknown" {
        return Err(format!("expected outcome_unknown, got {}", r.string_at(&results[0], "status", "")));
    }
    let open = r.list_at(&report, "openOrders");
    if open.len() != 1 || r.string_at(&open[0], "reason", "") != "fill_unconfirmed" {
        return Err("the unconfirmed fill is recorded".to_string());
    }
    Ok(())
}

fn execute_refuses_to_go_live_above_the_cap(r: &OrderRouter) -> Result<(), String> {
    // 100 USD against a 25 USD guardrail the caller asked for, re-checked at
    // execute rather than only at plan time. The refusal happens BEFORE any
    // order goes out, which is the property worth asserting — a cap checked
    // after the fact is an incident report, not a guardrail.
    let route = one_leg_route("buy", "BTC", "USDT", 1.0, 100.0);
    let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let mut options = execute_options(true, "sequential");
    OrderRouter::set_key(&mut options, "maxNotionalUsd", Value::Float(25.0));
    let outcome = block_on(r.execute(&plan, &venues, &options));
    match outcome {
        Err(e) if e.message.contains("blocking safety violations") => {
            if counter.load(Ordering::SeqCst) != 0 {
                return Err("the cap must be refused BEFORE any order goes out".to_string());
            }
            Ok(())
        }
        Err(e) => Err(format!("wrong refusal: {e}")),
        Ok(_) => Err("a 100 USD notional is over a 25 USD cap the caller set".to_string()),
    }
}

fn execute_places_the_same_trade_with_no_cap(r: &OrderRouter) -> Result<(), String> {
    // The counterpart, and the point of the guardrail being opt-in: the very
    // same 100 USD trade goes through when nobody asked for a cap. It is also
    // the case the old hard ceiling made unreachable.
    let route = one_leg_route("buy", "BTC", "USDT", 1.0, 100.0);
    let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    if counter.load(Ordering::SeqCst) != 1 {
        return Err(format!("expected 1 order, placed {}", counter.load(Ordering::SeqCst)));
    }
    let results = r.list_at(&report, "steps");
    let status = r.string_at(&results[0], "status", "");
    if status != "filled" {
        return Err(format!("100 USD is a normal trade when nobody asked for a cap, got {status}"));
    }
    // And with no cap set, usdRates is not required either: there is no cap to
    // evaluate, so demanding the inputs for one would be asking for something
    // nobody wanted.
    let bare_venue = StubVenue::new("stub");
    let bare_counter = StdArc::clone(&bare_venue.orders_placed);
    let mut bare_venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    bare_venues.insert("stub".to_string(), Box::new(bare_venue));
    let mut bare_options = execute_options(true, "sequential");
    OrderRouter::set_key(&mut bare_options, "usdRates", Value::Map(HashMap::new()));
    // the same plan again on purpose: this check is about the cap, not about
    // idempotency, so the re-execution guard is explicitly waived
    OrderRouter::set_key(&mut bare_options, "allowReexecution", Value::Bool(true));
    let bare_report = block_on(r.execute(&plan, &bare_venues, &bare_options))
        .map_err(|e| e.to_string())?;
    if bare_counter.load(Ordering::SeqCst) != 1 {
        return Err("no usdRates are needed when no cap was asked for".to_string());
    }
    let bare_results = r.list_at(&bare_report, "steps");
    if r.string_at(&bare_results[0], "status", "") != "filled" {
        return Err("the order fills without usdRates when no cap is set".to_string());
    }
    Ok(())
}

fn a_resting_order_is_cancelled(r: &OrderRouter) -> Result<(), String> {
    // A venue that silently drops timeInForce turns an immediate-or-cancel order
    // into a plain resting limit order. Recording it and continuing means the
    // next hop is sized on a fill that is still growing behind it, and the
    // leftover order stays live on a real venue after the route has returned and
    // nobody is watching it.
    for strategy in ["sequential", "parallel_within_hop", "best_effort"] {
        let mut options = execute_options(true, strategy);
        if strategy == "best_effort" {
            OrderRouter::set_key(&mut options, "acknowledgeDispersion", Value::Bool(true));
            OrderRouter::set_key(&mut options, "maxOrders", Value::Float(4.0));
        }
        // 1. the cancel works: the order is gone, the re-read is what gets reported
        let plan = one_leg_plan(r)?;
        let mut venue = StubVenue::new("stub");
        venue.created_open = true;
        venue.reread_order = Some(("canceled".to_string(), 0.1, 100.0, 10.0));
        let cancels = StdArc::clone(&venue.cancels);
        let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues.insert("stub".to_string(), Box::new(venue));
        let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
        if cancels.load(Ordering::SeqCst) != 1 {
            return Err(format!("{strategy}: the resting order is cancelled, not merely noted"));
        }
        if !r.list_at(&report, "openOrders").is_empty() {
            return Err(format!("{strategy}: nothing is left resting after the cancel"));
        }
        let results = r.list_at(&report, "steps");
        // the re-read is authoritative — the cancel and a fill crossed
        if !numbers_match(r.number_at(&results[0], "filledAmount", 0.0), 0.1) {
            return Err(format!("{strategy}: the fill observed AFTER the cancel is the one reported"));
        }
        if text(&results[0], "status") != "partial" {
            return Err(format!("{strategy}: a real partial fill, not an unknown"));
        }
        // 2. the cancel fails: the order can still fill in full after this
        //    returns, so nothing downstream may be sized on what was observed
        let plan2 = one_leg_plan(r)?;
        let mut stubborn = StubVenue::new("stub");
        stubborn.created_open = true;
        stubborn.cancel_fails = true;
        let mut venues2: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues2.insert("stub".to_string(), Box::new(stubborn));
        let failed = block_on(r.execute(&plan2, &venues2, &options)).map_err(|e| e.to_string())?;
        let failed_steps = r.list_at(&failed, "steps");
        if text(&failed_steps[0], "status") != "outcome_unknown" {
            return Err(format!("{strategy}: an uncancellable resting order is never a settled step"));
        }
        let open = r.list_at(&failed, "openOrders");
        if open.len() != 1 || text(&open[0], "reason") != "cancel_failed" {
            return Err(format!("{strategy}: the operator is told what is still live"));
        }
        // 3. the cancel is accepted and the venue still calls it open: same rule
        let plan3 = one_leg_plan(r)?;
        let mut ghost = StubVenue::new("stub");
        ghost.created_open = true;
        ghost.reread_order = Some(("open".to_string(), 0.0, 0.0, 0.0));
        let mut venues3: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        venues3.insert("stub".to_string(), Box::new(ghost));
        let ghosted = block_on(r.execute(&plan3, &venues3, &options)).map_err(|e| e.to_string())?;
        let ghost_steps = r.list_at(&ghosted, "steps");
        if text(&ghost_steps[0], "status") != "outcome_unknown" {
            return Err(format!("{strategy}: a cancel the venue ignored leaves the outcome unknown"));
        }
        let ghost_open = r.list_at(&ghosted, "openOrders");
        if ghost_open.len() != 1 || text(&ghost_open[0], "reason") != "still_open" {
            return Err(format!("{strategy}: and it is reported as still open"));
        }
    }
    Ok(())
}

fn a_known_order_id_survives_a_throw_after_create(r: &OrderRouter) -> Result<(), String> {
    // createOrder RETURNED — the venue accepted something and named it — and the
    // first poll then died. This branch was missing from the Rust port entirely:
    // the step was reported as a plain failure and the id appeared nowhere in
    // the report, so an operator had a live order on a real venue and no way to
    // learn it existed. Two things must hold: the id reaches openOrders, and the
    // step is outcome_unknown rather than "failed", because "failed" reads as
    // "nothing happened" while openOrders says the opposite.
    let plan = one_leg_plan(r)?;
    let mut venue = StubVenue::new("stub");
    venue.created_open = true;
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let mut options = execute_options(true, "limit_protected");
    OrderRouter::set_key(&mut options, "orderTimeoutMs", Value::Float(4.0));
    OrderRouter::set_key(&mut options, "pollIntervalMs", Value::Float(1.0));
    let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    let status = r.string_at(&results[0], "status", "");
    if status != "outcome_unknown" {
        return Err(format!("a known id means an order exists, so the step is outcome_unknown, got {status}"));
    }
    if r.string_at(&results[0], "orderId", "") != "stub-1" {
        return Err("the id is captured the instant create_order returns, not after the read".to_string());
    }
    let open_orders = r.list_at(&report, "openOrders");
    if open_orders.len() != 1 {
        return Err(format!("a live order the caller cannot see is the worst outcome there is, got {open_orders:?}"));
    }
    if r.string_at(&open_orders[0], "orderId", "") != "stub-1"
        || r.string_at(&open_orders[0], "exchangeId", "") != "stub"
        || r.string_at(&open_orders[0], "reason", "") != "outcome_unknown" {
        return Err(format!("the open order must name the venue, the id and why, got {open_orders:?}"));
    }
    if r.string_at(&report, "haltReason", "") != "outcome_unknown" {
        return Err("the halt must name the ambiguity rather than claim an outright failure".to_string());
    }
    Ok(())
}

fn atomic_ish_demands_the_whole_route_prefunded(r: &OrderRouter) -> Result<(), String> {
    // atomic_ish skips the downstream resize every other strategy performs — it
    // is allowed to, BECAUSE the route is pre-funded end to end, so no hop is
    // sized off the previous hop's proceeds. This port accepted the strategy,
    // took the skip, and never ran the check that earns it: an underfunded route
    // executed anyway and sized hop 1 against BTC that was never bought.
    let plan = one_leg_plan(r)?;
    let funded = StubVenue::new("stub");
    let funded_counter = StdArc::clone(&funded.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(funded));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "atomic_ish")))
        .map_err(|e| e.to_string())?;
    if funded_counter.load(Ordering::SeqCst) != 1 {
        return Err("a pre-funded route runs end to end".to_string());
    }
    if r.number_at(&report, "ordersPlaced", 0.0) != 1.0 {
        return Err(format!("a pre-funded route places its order, got {report:?}"));
    }

    // The one-leg plan buys 0.2 BTC at 100 USDT, so it needs 20 USDT free.
    let mut broke = StubVenue::new("stub");
    broke.free_balances = Some(vec![("USDT".to_string(), 1.0), ("BTC".to_string(), 0.0)]);
    let broke_counter = StdArc::clone(&broke.orders_placed);
    let mut poor_venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    poor_venues.insert("stub".to_string(), Box::new(broke));
    // the same plan again on purpose: this check is about pre-funding, not about
    // idempotency, so the re-execution guard is explicitly waived
    let poor_options =
        options_with(&execute_options(true, "atomic_ish"), "allowReexecution", Value::Bool(true));
    match block_on(r.execute(&plan, &poor_venues, &poor_options)) {
        Err(e) if e.message.contains("pre-funded") => {}
        other => return Err(format!("an underfunded route must be refused, got {other:?}")),
    }
    // And refused BEFORE anything reaches a venue: a refusal that has already
    // traded is not a refusal.
    if broke_counter.load(Ordering::SeqCst) != 0 {
        return Err("the refusal must come before the first createOrder".to_string());
    }
    Ok(())
}

fn a_reported_spend_survives_an_unknown_fill(r: &OrderRouter) -> Result<(), String> {
    // The `if !filled_known` early return must come AFTER the assets and amounts
    // are filled in, not before. inAmount is what build_unwind_plan SUBTRACTS: a
    // buy whose venue reported a `cost` but no `filled` spent that quote for
    // certain, and dropping it leaves the unwind plan believing the money is
    // still on the venue and planning to route home funds that are already gone.
    // TypeScript was the outlier here; this pins the ordering in Rust too, since
    // the drift went unnoticed precisely because only one port had it covered.
    let plan = one_leg_plan(r)?;
    let mut venue = StubVenue::new("stub");
    venue.omit_filled = true;
    venue.reread_cost = Some((10.5, 105.0));
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    let step = &results[0];
    if r.string_at(step, "status", "") != "outcome_unknown" {
        return Err(format!("the fill is still unknown, got {step:?}"));
    }
    if r.bool_at(step, "filledKnown", true) {
        return Err("filledKnown must be false".to_string());
    }
    // The facts the venue gave are kept.
    if r.string_at(step, "inAsset", "") != "USDT" {
        return Err(format!("the asset actually spent must be named, got {step:?}"));
    }
    if (r.number_at(step, "inAmount", 0.0) - 10.5).abs() > 1e-9 {
        return Err(format!("the amount the venue reported spending must survive, got {step:?}"));
    }
    if !r.bool_at(step, "costKnown", false) {
        return Err("costKnown must be true: the venue really did report it".to_string());
    }
    // The fill itself is never invented.
    if r.number_at(step, "outAmount", -1.0) != 0.0 {
        return Err(format!("an unknown fill must not become a number, got {step:?}"));
    }
    // And the halt, not the missing fields, is what protects the next hop.
    if !r.bool_at(&report, "halted", false) || r.string_at(&report, "haltReason", "") != "outcome_unknown" {
        return Err(format!("the route must halt on the ambiguity, got {report:?}"));
    }
    Ok(())
}

fn a_market_order_and_a_cap_are_refused_together(r: &OrderRouter) -> Result<(), String> {
    // assert_under_cap values the order at the plan's LIMIT price; the market
    // call then sends no price at all and the venue fills wherever the book is,
    // which is the one thing the cap exists to bound. Passing the check and then
    // discarding the price it was computed from is a cap that silently
    // disappears — by this file's own rule, not a cap. So the two are refused
    // together, and refused BEFORE anything reaches a venue.
    let plan = one_leg_plan(r)?;
    let mut capped = StubVenue::new("stub");
    capped.supports_ioc = false;
    let capped_counter = StdArc::clone(&capped.orders_placed);
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(capped));
    let mut options = execute_options(true, "sequential");
    OrderRouter::set_key(&mut options, "allowMarketOrders", Value::Bool(true));
    OrderRouter::set_key(&mut options, "maxNotionalUsd", Value::Float(1000.0));
    let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "failed"
        || r.string_at(&results[0], "errorCode", "") != "NotSupported" {
        return Err(format!("a market order under a cap must be refused, got {:?}", results[0]));
    }
    if capped_counter.load(Ordering::SeqCst) != 0 {
        return Err("refused BEFORE dispatch: a cap checked against a price that is then discarded is worse than no cap".to_string());
    }

    // The refusal is about the CAP, not about market orders as such: with no cap
    // set, the identical call goes through.
    let mut uncapped = StubVenue::new("stub");
    uncapped.supports_ioc = false;
    let uncapped_counter = StdArc::clone(&uncapped.orders_placed);
    let mut open_venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    open_venues.insert("stub".to_string(), Box::new(uncapped));
    // the same plan again on purpose: this check is about the market-order rule, not
    // about idempotency, so the re-execution guard is explicitly waived
    let mut open_options =
        options_with(&execute_options(true, "sequential"), "allowReexecution", Value::Bool(true));
    OrderRouter::set_key(&mut open_options, "allowMarketOrders", Value::Bool(true));
    let open_report = block_on(r.execute(&plan, &open_venues, &open_options)).map_err(|e| e.to_string())?;
    if uncapped_counter.load(Ordering::SeqCst) != 1 {
        return Err(format!("with no cap the market order goes out, got {open_report:?}"));
    }
    Ok(())
}

fn plan_age_is_reported_and_refused_only_when_asked(r: &OrderRouter) -> Result<(), String> {
    // A plan is a snapshot of a book. `calculatedAt` was carried on every plan
    // and read by nothing, so execute() would happily trade an hour-old plan at
    // hour-old prices — and the notional cap, computed from those same prices,
    // was just as stale.
    let mut route = one_leg_route("buy", "BTC", "USDT", 0.2, 100.0);
    OrderRouter::set_key(&mut route, "calculatedAt", Value::Float(1_000_000.0));
    let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    let mut pinned = router()?;
    pinned.set_now_ms(1_060_000.0); // the plan is exactly 60s old
    // this check deliberately runs the same plan several times to isolate the age
    // rule, which is exactly what allowReexecution is for
    let execute_options = |live: bool, strategy: &str| {
        options_with(&execute_options(live, strategy), "allowReexecution", Value::Bool(true))
    };
    let venues = |v: StubVenue| {
        let mut m: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
        m.insert("stub".to_string(), Box::new(v));
        m
    };

    // Always reported, even with nothing enforced, and nothing is refused by
    // default: this class does not decide how stale a plan the caller may trade.
    let report = block_on(pinned.execute(&plan, &venues(StubVenue::new("stub")), &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    if pinned.number_at(&report, "planAgeMs", 0.0) != 60_000.0 {
        return Err(format!("the age belongs on the report whether or not it is checked, got {:?}", report));
    }
    let results = pinned.list_at(&report, "steps");
    if pinned.string_at(&results[0], "status", "") != "filled" {
        return Err("nothing is refused by default".to_string());
    }

    // Enforced exactly, at whatever value is asked for.
    let strict = StubVenue::new("stub");
    let strict_counter = StdArc::clone(&strict.orders_placed);
    let mut strict_options = execute_options(true, "sequential");
    OrderRouter::set_key(&mut strict_options, "maxPlanAgeMs", Value::Float(30_000.0));
    match block_on(pinned.execute(&plan, &venues(strict), &strict_options)) {
        Err(e) if e.message.contains("older than maxPlanAgeMs") => {}
        other => return Err(format!("a stale plan must be refused under a limit, got {other:?}")),
    }
    if strict_counter.load(Ordering::SeqCst) != 0 {
        return Err("refused before anything reached the venue".to_string());
    }
    let mut wide_options = execute_options(true, "sequential");
    OrderRouter::set_key(&mut wide_options, "maxPlanAgeMs", Value::Float(120_000.0));
    let passed = block_on(pinned.execute(&plan, &venues(StubVenue::new("stub")), &wide_options))
        .map_err(|e| e.to_string())?;
    let passed_results = pinned.list_at(&passed, "steps");
    if pinned.string_at(&passed_results[0], "status", "") != "filled" {
        return Err("a limit the plan is inside of lets it through".to_string());
    }

    // An age that cannot be determined BLOCKS under an active limit: a freshness
    // check that silently passes when the timestamp is missing is not one.
    let undated = one_leg_plan(r)?;
    let undated_report = block_on(pinned.execute(&undated, &venues(StubVenue::new("stub")), &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    if pinned.number_at(&undated_report, "planAgeMs", 0.0) != -1.0 {
        return Err("unknown is -1, never 0: 0 would read as fresh".to_string());
    }
    let mut undated_options = execute_options(true, "sequential");
    OrderRouter::set_key(&mut undated_options, "maxPlanAgeMs", Value::Float(30_000.0));
    match block_on(pinned.execute(&undated, &venues(StubVenue::new("stub")), &undated_options)) {
        Err(e) if e.message.contains("carries no calculatedAt") => Ok(()),
        other => Err(format!("an undatable plan must be refused under a limit, got {other:?}")),
    }
}

fn best_effort_demands_its_acknowledgements(r: &OrderRouter) -> Result<(), String> {
    let plan = one_leg_plan(r)?;
    let venue = StubVenue::new("stub");
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    // No acknowledgeDispersion.
    match block_on(r.execute(&plan, &venues, &execute_options(true, "best_effort"))) {
        Err(e) if e.message.contains("acknowledgeDispersion") => {}
        other => return Err(format!("expected an acknowledgeDispersion refusal, got {other:?}")),
    }
    // With the acknowledgement but no maxOrders.
    let mut options = execute_options(true, "best_effort");
    OrderRouter::set_key(&mut options, "acknowledgeDispersion", Value::Bool(true));
    match block_on(r.execute(&plan, &venues, &options)) {
        Err(e) if e.message.contains("maxOrders") => Ok(()),
        other => Err(format!("expected a maxOrders refusal, got {other:?}")),
    }
}

// ---------------------------------------------------------------------------
// idempotency (audit finding 35): execute used to build fresh state on every
// call and consult nothing, so running the same plan twice placed every order
// twice — including the ones that had already filled.
// ---------------------------------------------------------------------------

/// Sets one extra key on an execute options dictionary.
fn options_with(base: &Value, key: &str, value: Value) -> Value {
    let mut map = base.as_map().cloned().unwrap_or_default();
    map.insert(key.to_string(), value);
    Value::Map(map)
}

fn stub_venues(venue: StubVenue) -> BTreeMap<String, Box<dyn RouterVenue>> {
    let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
    venues.insert("stub".to_string(), Box::new(venue));
    venues
}

fn live_requires_an_identity(r: &OrderRouter) -> Result<(), String> {
    // a plan with no identity of its own — the shape a hand-assembled plan has
    let route = options_with(
        &one_leg_route("buy", "BTC", "USDT", 0.2, 100.0),
        "requestId",
        Value::Str(Cow::Borrowed("")),
    );
    let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
    let venue = StubVenue::new("stub");
    let counter = StdArc::clone(&venue.orders_placed);
    let venues = stub_venues(venue);
    match block_on(r.execute(&plan, &venues, &execute_options(true, "sequential"))) {
        Ok(_) => return Err("a live plan with no identity must be refused".to_string()),
        Err(e) if e.is("BadRequest") => {}
        Err(e) => return Err(format!("expected BadRequest, got {e}")),
    }
    if counter.load(Ordering::SeqCst) != 0 {
        return Err("refused before a single order reached the venue".to_string());
    }
    // A rehearsal needs no identity: it places nothing.
    let dry = block_on(r.execute(&plan, &venues, &execute_options(false, "sequential")))
        .map_err(|e| e.to_string())?;
    if !r.bool_at(&dry, "dryRun", false) {
        return Err("a dry run needs no identity".to_string());
    }
    // ...and a HAND-ASSEMBLED plan is a supported input: execute takes any
    // dictionary of the plan shape, and such a plan never went through a routing
    // request, so requestId is the one identity it cannot have. idempotencyKey is
    // how it supplies one.
    let keyed_options = options_with(
        &execute_options(true, "sequential"),
        "idempotencyKey",
        Value::Str("hand-built-1".to_string().into()),
    );
    let supplied = StubVenue::new("stub");
    let seen = StdArc::clone(&supplied.params_seen);
    let venues = stub_venues(supplied);
    let report = block_on(r.execute(&plan, &venues, &keyed_options)).map_err(|e| e.to_string())?;
    if r.string_at(&report, "planId", "") != "hand-built-1" {
        return Err("the supplied key is the identity".to_string());
    }
    let params = seen.lock().unwrap().clone();
    if params.is_empty() || !r.string_at(&params[0], "clientOrderId", "").is_empty() {
        return Err("no client order id is injected".to_string());
    }
    // And the guard keys off it, exactly as it does off a requestId.
    let again = stub_venues(StubVenue::new("stub"));
    match block_on(r.execute(&plan, &again, &keyed_options)) {
        Ok(_) => return Err("the same key must be refused a second time".to_string()),
        Err(e) if e.is("BadRequest") => {}
        Err(e) => return Err(format!("expected BadRequest, got {e}")),
    }
    // An explicit key OVERRIDES a plan's requestId: passing one is a deliberate
    // statement about what this execution is, and the caller is closer to that
    // than the plan is.
    let routed = one_leg_plan(r)?;
    let override_options = options_with(
        &execute_options(true, "sequential"),
        "idempotencyKey",
        Value::Str("override-1".to_string().into()),
    );
    let overridden = StubVenue::new("stub");
    let seen = StdArc::clone(&overridden.params_seen);
    let venues = stub_venues(overridden);
    let report = block_on(r.execute(&routed, &venues, &override_options)).map_err(|e| e.to_string())?;
    if r.string_at(&report, "planId", "") != "override-1" {
        return Err("the option overrides the plan's requestId".to_string());
    }
    let params = seen.lock().unwrap().clone();
    if !r.string_at(&params[0], "clientOrderId", "").is_empty() {
        return Err("and no client order id is injected".to_string());
    }
    Ok(())
}

fn client_order_id_is_never_injected(r: &OrderRouter) -> Result<(), String> {
    let plan = one_leg_plan(r)?;
    let plan_id = r.string_at(&plan, "requestId", "");
    // By default nothing is injected: each exchange's create_order sends whatever
    // identifier it generates on its own.
    let bare = StubVenue::new("stub");
    let seen = StdArc::clone(&bare.params_seen);
    let venues = stub_venues(bare);
    let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    if r.string_at(&report, "planId", "") != plan_id {
        return Err("the report names the plan identity".to_string());
    }
    let params = seen.lock().unwrap().clone();
    if params.is_empty() || !r.string_at(&params[0], "clientOrderId", "").is_empty() {
        return Err("no client order id is forced onto the order".to_string());
    }
    let results = r.list_at(&report, "steps");
    if !r.string_at(&results[0], "clientOrderId", "").is_empty() {
        return Err("the report carries what the venue reported, which is nothing".to_string());
    }
    // A caller-supplied clientOrderId is forwarded as-is, alongside the caller's
    // other params.
    let mut caller_params = HashMap::new();
    caller_params.insert("clientOrderId".to_string(), Value::Str("caller-supplied".to_string().into()));
    caller_params.insert("reduceOnly".to_string(), Value::Bool(true));
    let options = options_with(
        &execute_options(true, "sequential"),
        "orderParams",
        Value::Map(caller_params),
    );
    let second = router()?;
    let venue = StubVenue::new("stub");
    let seen = StdArc::clone(&venue.params_seen);
    let venues = stub_venues(venue);
    let report = block_on(second.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let params = seen.lock().unwrap().clone();
    if r.string_at(&params[0], "clientOrderId", "") != "caller-supplied" {
        return Err("the caller's id travels untouched".to_string());
    }
    if !r.bool_at(&params[0], "reduceOnly", false) {
        return Err("the caller's other params still travel".to_string());
    }
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "clientOrderId", "") != "caller-supplied" {
        return Err("and the report says what the venue recorded".to_string());
    }
    Ok(())
}

fn reexecution_is_refused(r: &OrderRouter) -> Result<(), String> {
    let plan = one_leg_plan(r)?;
    let options = execute_options(true, "sequential");
    let venues = stub_venues(StubVenue::new("stub"));
    let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "filled" {
        return Err("the first run places the order".to_string());
    }
    let again = StubVenue::new("stub");
    let counter = StdArc::clone(&again.orders_placed);
    let venues = stub_venues(again);
    match block_on(r.execute(&plan, &venues, &options)) {
        Ok(_) => return Err("the second run must be refused".to_string()),
        Err(e) if e.is("BadRequest") => {}
        Err(e) => return Err(format!("expected BadRequest, got {e}")),
    }
    if counter.load(Ordering::SeqCst) != 0 {
        return Err("not one order may be re-placed".to_string());
    }
    // ...and the legitimate retry path is explicit.
    let allowed = StubVenue::new("stub");
    let placed = StdArc::clone(&allowed.orders_placed);
    let venues = stub_venues(allowed);
    let retry_options = options_with(&options, "allowReexecution", Value::Bool(true));
    let retry = block_on(r.execute(&plan, &venues, &retry_options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&retry, "steps");
    if r.string_at(&results[0], "status", "") != "filled" || placed.load(Ordering::SeqCst) != 1 {
        return Err("an explicit opt-in runs it again".to_string());
    }
    Ok(())
}

fn a_dry_run_does_not_consume_a_plan(r: &OrderRouter) -> Result<(), String> {
    let plan = one_leg_plan(r)?;
    let rehearsal = stub_venues(StubVenue::new("stub"));
    block_on(r.execute(&plan, &rehearsal, &execute_options(false, "sequential")))
        .map_err(|e| e.to_string())?;
    let real = stub_venues(StubVenue::new("stub"));
    let report = block_on(r.execute(&plan, &real, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "filled" {
        return Err("the rehearsal must not burn the plan".to_string());
    }
    // A run that FAILED still placed orders — or may have — so the retry is refused
    // just the same. The ledger records the attempt, not the outcome.
    let failed_plan = one_leg_plan(r)?;
    let mut broken = StubVenue::new("stub");
    broken.fail_with = Some("ExchangeError");
    let venues = stub_venues(broken);
    let failed = block_on(r.execute(&failed_plan, &venues, &execute_options(true, "sequential")))
        .map_err(|e| e.to_string())?;
    if !r.bool_at(&failed, "halted", false) {
        return Err("the failing run halted".to_string());
    }
    let retry = StubVenue::new("stub");
    let counter = StdArc::clone(&retry.orders_placed);
    let venues = stub_venues(retry);
    match block_on(r.execute(&failed_plan, &venues, &execute_options(true, "sequential"))) {
        Ok(_) => return Err("a failed run still consumed the plan".to_string()),
        Err(e) if e.is("BadRequest") => {}
        Err(e) => return Err(format!("expected BadRequest, got {e}")),
    }
    if counter.load(Ordering::SeqCst) != 0 {
        return Err("and the retry placed nothing".to_string());
    }
    Ok(())
}

fn the_ledger_is_bounded(r: &OrderRouter) -> Result<(), String> {
    let capacity = MAX_EXECUTED_PLAN_IDS;
    for i in 0..capacity {
        r.record_executed_plan(&format!("plan-{i}"));
    }
    if r.executed_plan_count() != capacity {
        return Err("the ledger fills to exactly the cap".to_string());
    }
    if !r.has_executed_plan("plan-0") {
        return Err("nothing is evicted before it is full".to_string());
    }
    // The cap holds no matter how far past it the process runs.
    for i in capacity..(capacity + 100) {
        r.record_executed_plan(&format!("plan-{i}"));
    }
    if r.executed_plan_count() != capacity {
        return Err("the ledger never grows past the cap".to_string());
    }
    // FIFO: the OLDEST 100 are the ones that went.
    for i in 0..100 {
        if r.has_executed_plan(&format!("plan-{i}")) {
            return Err(format!("the oldest entries are evicted first, plan-{i} survived"));
        }
    }
    if !r.has_executed_plan("plan-100") || !r.has_executed_plan(&format!("plan-{}", capacity + 99)) {
        return Err("nothing newer than the evicted window went with them".to_string());
    }
    if r.executed_plan_at(0) != "plan-100" {
        return Err("the queue is still in insertion order".to_string());
    }
    // Re-recording an id already held must not shuffle the eviction order, or a plan
    // re-executed in a loop could keep itself alive forever while newer ids fall out.
    r.record_executed_plan("plan-100");
    if r.executed_plan_count() != capacity || r.executed_plan_at(0) != "plan-100" {
        return Err("a duplicate record adds nothing and does not move the entry".to_string());
    }
    // AND THE TRADEOFF, STATED AS A TEST: an evicted plan is no longer refused. This is
    // the documented weakening at the cap, not an accident — if this check ever has to
    // change, the comment on MAX_EXECUTED_PLAN_IDS has to change with it.
    let plan = one_leg_plan(r)?;
    let options = execute_options(true, "sequential");
    let venues = stub_venues(StubVenue::new("stub"));
    block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let refused = StubVenue::new("stub");
    let counter = StdArc::clone(&refused.orders_placed);
    let venues = stub_venues(refused);
    match block_on(r.execute(&plan, &venues, &options)) {
        Ok(_) => return Err("while remembered, the duplicate is refused".to_string()),
        Err(e) if e.is("BadRequest") => {}
        Err(e) => return Err(format!("expected BadRequest, got {e}")),
    }
    if counter.load(Ordering::SeqCst) != 0 {
        return Err("and it placed nothing".to_string());
    }
    for i in 0..capacity {
        r.record_executed_plan(&format!("flush-{i}"));
    }
    if r.has_executed_plan(&r.string_at(&plan, "requestId", "")) {
        return Err("the plan has aged out of the ledger".to_string());
    }
    let reexecuted = StubVenue::new("stub");
    let placed = StdArc::clone(&reexecuted.orders_placed);
    let venues = stub_venues(reexecuted);
    let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
    let results = r.list_at(&report, "steps");
    if r.string_at(&results[0], "status", "") != "filled" || placed.load(Ordering::SeqCst) == 0 {
        return Err("an aged-out plan re-executes without the opt-in, and really places".to_string());
    }
    Ok(())
}