openpit 0.4.0

Embeddable pre-trade risk SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Please see https://github.com/openpitkit and the OWNERS file for details.

//! Unit tests for [`SpotFundsPolicy`].

use super::*;
use crate::core::AccountAdjustmentContext;
use crate::marketdata::{MarketDataBuilder, Quote, QuoteTtl};
use crate::param::{
    AccountId, AdjustmentAmount, Asset, PositionSize, Price, Quantity, Side, Trade, TradeAmount,
    Volume,
};
use crate::pretrade::{
    holdings::Holdings, PreTradeContext, PreTradeLock, PreTradePolicy, RejectCode,
    DEFAULT_POLICY_GROUP_ID,
};
use crate::{
    FullSync, HasAccountAdjustmentBalance, HasAccountAdjustmentBalanceLowerBound,
    HasAccountAdjustmentBalanceUpperBound, HasAccountAdjustmentHeld,
    HasAccountAdjustmentHeldLowerBound, HasAccountAdjustmentHeldUpperBound,
    HasAccountAdjustmentIncoming, HasAccountAdjustmentIncomingLowerBound,
    HasAccountAdjustmentIncomingUpperBound, HasAccountId, HasBalanceAsset,
    HasExecutionReportIsFinal, HasExecutionReportLastTrade, HasInstrument, HasLeavesQuantity,
    HasPreTradeLock, HasSide, Instrument, Mutations, OrderOperation, RequestFieldAccessError,
};
use std::sync::Arc;

// ── type aliases ──────────────────────────────────────────────────────────

type TestPolicy = SpotFundsPolicy<FullSync, FullSync>;
type TestOrder = OrderOperation;

// ── TestReport ────────────────────────────────────────────────────────────

struct TestReport {
    instrument: Instrument,
    account_id: AccountId,
    side: Side,
    last_trade: Option<Trade>,
    leaves_quantity: Quantity,
    is_final: bool,
    lock: PreTradeLock,
}

impl HasInstrument for TestReport {
    fn instrument(&self) -> Result<&Instrument, RequestFieldAccessError> {
        Ok(&self.instrument)
    }
}

impl HasAccountId for TestReport {
    fn account_id(&self) -> Result<AccountId, RequestFieldAccessError> {
        Ok(self.account_id)
    }
}

impl HasSide for TestReport {
    fn side(&self) -> Result<Side, RequestFieldAccessError> {
        Ok(self.side)
    }
}

impl HasExecutionReportLastTrade for TestReport {
    fn last_trade(&self) -> Result<Option<Trade>, RequestFieldAccessError> {
        Ok(self.last_trade)
    }
}

impl HasLeavesQuantity for TestReport {
    fn leaves_quantity(&self) -> Result<Quantity, RequestFieldAccessError> {
        Ok(self.leaves_quantity)
    }
}

impl HasExecutionReportIsFinal for TestReport {
    fn is_final(&self) -> Result<bool, RequestFieldAccessError> {
        Ok(self.is_final)
    }
}

impl HasPreTradeLock for TestReport {
    fn lock(&self) -> Result<PreTradeLock, RequestFieldAccessError> {
        Ok(self.lock.clone())
    }
}

// ── TestAdjustment ────────────────────────────────────────────────────────

struct TestAdjustment {
    asset: Asset,
    balance: Option<AdjustmentAmount>,
    balance_lower: Option<PositionSize>,
    balance_upper: Option<PositionSize>,
    held: Option<AdjustmentAmount>,
    held_lower: Option<PositionSize>,
    held_upper: Option<PositionSize>,
    incoming: Option<AdjustmentAmount>,
    incoming_lower: Option<PositionSize>,
    incoming_upper: Option<PositionSize>,
}

impl HasBalanceAsset for TestAdjustment {
    fn balance_asset(&self) -> Result<&Asset, RequestFieldAccessError> {
        Ok(&self.asset)
    }
}

impl HasAccountAdjustmentBalance for TestAdjustment {
    fn balance(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
        Ok(self.balance)
    }
}

impl HasAccountAdjustmentBalanceLowerBound for TestAdjustment {
    fn balance_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(self.balance_lower)
    }
}

impl HasAccountAdjustmentBalanceUpperBound for TestAdjustment {
    fn balance_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(self.balance_upper)
    }
}

impl HasAccountAdjustmentHeld for TestAdjustment {
    fn held(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
        Ok(self.held)
    }
}

impl HasAccountAdjustmentHeldLowerBound for TestAdjustment {
    fn held_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(self.held_lower)
    }
}

impl HasAccountAdjustmentHeldUpperBound for TestAdjustment {
    fn held_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(self.held_upper)
    }
}

impl HasAccountAdjustmentIncoming for TestAdjustment {
    fn incoming(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
        Ok(self.incoming)
    }
}

impl HasAccountAdjustmentIncomingLowerBound for TestAdjustment {
    fn incoming_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(self.incoming_lower)
    }
}

impl HasAccountAdjustmentIncomingUpperBound for TestAdjustment {
    fn incoming_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
        Ok(self.incoming_upper)
    }
}

// ── value helpers ─────────────────────────────────────────────────────────

fn asset(s: &str) -> Asset {
    Asset::new(s).expect("valid asset")
}

fn ps(s: &str) -> PositionSize {
    PositionSize::from_str(s).expect("valid position size")
}

fn px(s: &str) -> Price {
    Price::from_str(s).expect("valid price")
}

fn qty(s: &str) -> Quantity {
    Quantity::from_str(s).expect("valid quantity")
}

fn vol(s: &str) -> Volume {
    Volume::from_str(s).expect("valid volume")
}

fn account(n: u64) -> AccountId {
    AccountId::from_u64(n)
}

fn dummy_control(
    account_id: AccountId,
) -> crate::core::AccountControl<crate::storage::FullLocking> {
    use crate::core::account_control::BlockedAccounts;
    use crate::core::AccountBlockHandle;
    use crate::storage::{FullLocking, LockingPolicyFactory, StorageBuilder};
    let sb = StorageBuilder::new(FullLocking);
    let blocked = FullLocking::new_shared(BlockedAccounts::new(&sb));
    let handle = AccountBlockHandle::from_inner(blocked);
    crate::core::AccountControl::new(handle, account_id)
}

fn instr(under: &str, sett: &str) -> Instrument {
    Instrument::new(asset(under), asset(sett))
}

// ── policy builder ────────────────────────────────────────────────────────

fn engine_builder() -> crate::SyncedEngineBuilder<(), (), (), crate::FullSync> {
    crate::Engine::builder().full_sync()
}

/// Builds a `SpotFundsPolicy` with no market-order support.
fn build_policy(_mark: Option<()>, _slip_bps: Option<u16>) -> TestPolicy {
    let b = engine_builder();
    SpotFundsPolicy::new(None, b.storage_builder())
}

/// Builds a policy whose market-data service has `instrument` registered
/// with mark price `price` and slippage `slip_bps`.
fn build_policy_with_market_data(
    instrument: Instrument,
    price: Price,
    slip_bps: u16,
) -> TestPolicy {
    let b = engine_builder();
    let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
    let id = svc
        .register(instrument.clone())
        .expect("register must succeed");
    svc.push(id, Quote::new().with_mark(price))
        .expect("push must succeed");
    let bundle = SpotFundsMarketData::new(
        Arc::clone(&svc),
        slip_bps,
        SpotFundsPricingSource::Mark,
        std::iter::empty(),
    )
    .expect("bundle must build");
    SpotFundsPolicy::new(Some(bundle), b.storage_builder())
}

// ── request builders ──────────────────────────────────────────────────────

fn make_order(
    account_id: AccountId,
    instrument: Instrument,
    side: Side,
    trade_amount: TradeAmount,
    price: Option<Price>,
) -> TestOrder {
    OrderOperation {
        instrument,
        account_id,
        side,
        trade_amount,
        price,
    }
}

fn make_report(
    account_id: AccountId,
    instrument: Instrument,
    side: Side,
    last_trade: Option<Trade>,
    leaves: Quantity,
    is_final: bool,
    lock: Option<PreTradeLock>,
) -> TestReport {
    TestReport {
        instrument,
        account_id,
        side,
        last_trade,
        leaves_quantity: leaves,
        is_final,
        lock: lock.unwrap_or_default(),
    }
}

fn adj(asset: Asset, balance: Option<AdjustmentAmount>) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance,
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    }
}

fn bounded_adj(
    asset: Asset,
    balance: Option<AdjustmentAmount>,
    lower: Option<PositionSize>,
    upper: Option<PositionSize>,
) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance,
        balance_lower: lower,
        balance_upper: upper,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    }
}

fn held_adj(
    asset: Asset,
    held: Option<AdjustmentAmount>,
    lower: Option<PositionSize>,
    upper: Option<PositionSize>,
) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance: None,
        balance_lower: None,
        balance_upper: None,
        held,
        held_lower: lower,
        held_upper: upper,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    }
}

fn incoming_adj(
    asset: Asset,
    incoming: Option<AdjustmentAmount>,
    lower: Option<PositionSize>,
    upper: Option<PositionSize>,
) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance: None,
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming,
        incoming_lower: lower,
        incoming_upper: upper,
    }
}

fn all_fields_adj(
    asset: Asset,
    balance: Option<AdjustmentAmount>,
    held: Option<AdjustmentAmount>,
    incoming: Option<AdjustmentAmount>,
) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance,
        balance_lower: None,
        balance_upper: None,
        held,
        held_lower: None,
        held_upper: None,
        incoming,
        incoming_lower: None,
        incoming_upper: None,
    }
}

// ── seed / access helpers ─────────────────────────────────────────────────

fn seed(policy: &TestPolicy, account_id: AccountId, asset: Asset, amount: &str) {
    let adjustment = adj(asset, Some(AdjustmentAmount::Absolute(ps(amount))));
    let mut mutations = Mutations::with_capacity(1);
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::apply_account_adjustment(
        policy,
        &AccountAdjustmentContext::new_test(dummy_control(account_id)),
        account_id,
        &adjustment,
        &mut mutations,
    )
    .expect("seed must succeed");
    mutations.commit_all();
}

fn holdings_of(policy: &TestPolicy, account_id: AccountId, asset: &Asset) -> Option<Holdings> {
    policy.holdings.get(&(account_id, asset.clone()))
}

// ── trait call wrappers ───────────────────────────────────────────────────

fn pre_trade_check(
    policy: &TestPolicy,
    order: &TestOrder,
    mutations: &mut Mutations,
) -> Result<(), crate::pretrade::Rejects> {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::perform_pre_trade_check(
        policy,
        &PreTradeContext::new(None),
        order,
        mutations,
    )
    .map(|_| ())
}

fn apply_adj(
    policy: &TestPolicy,
    account_id: AccountId,
    adjustment: &TestAdjustment,
    mutations: &mut Mutations,
) -> Result<(), crate::pretrade::Rejects> {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::apply_account_adjustment(
        policy,
        &AccountAdjustmentContext::new_test(dummy_control(account_id)),
        account_id,
        adjustment,
        mutations,
    )
    .map(|_| ())
}

fn report_blocks(policy: &TestPolicy, report: &TestReport) -> Vec<crate::pretrade::AccountBlock> {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::apply_execution_report(
        policy,
        &crate::pretrade::PostTradeContext::new(),
        report,
    )
    .map(|r| r.account_blocks)
    .unwrap_or_default()
}

// ═══════════════════════════════════════════════════════════════════════════
// Constructor
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn new_creates_empty_holdings() {
    let policy = build_policy(None, None);
    assert!(holdings_of(&policy, account(99224416), &asset("USD")).is_none());
}

// ═══════════════════════════════════════════════════════════════════════════
// perform_pre_trade_check — §8.1
// ═══════════════════════════════════════════════════════════════════════════

// ── Buy Quantity + limit price ─────────────────────────────────────────────

#[test]
fn buy_qty_limit_sufficient_reserves_settlement() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    assert!(pre_trade_check(&policy, &order, &mut mutations).is_ok());
    assert!(!mutations.is_empty());

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("2000"));
    assert_eq!(h.available(), ps("8000"));
}

#[test]
fn buy_qty_limit_insufficient_rejects_insufficient_funds() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "1000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");

    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);
    assert!(mutations.is_empty());
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("1000"));
    assert_eq!(h.held(), ps("0"));
}

// ── Buy Volume ────────────────────────────────────────────────────────────

#[test]
fn buy_volume_sufficient_reserves_volume_amount() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Volume(vol("3000")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    assert!(pre_trade_check(&policy, &order, &mut mutations).is_ok());

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("3000"));
    assert_eq!(h.available(), ps("7000"));
}

#[test]
fn buy_volume_insufficient_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "2000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Volume(vol("3000")),
        Some(px("200")),
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);
}

#[test]
fn buy_volume_without_price_or_mark_rejects_as_unsupported() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Volume(vol("3000")),
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::UnsupportedOrderType);
}

// ── Buy market + mark ─────────────────────────────────────────────────────

#[test]
fn buy_market_with_mark_reserves_slippage_adjusted_amount() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 1500);
    seed(&policy, acc, asset("USD"), "10000");

    // effective = 200 * 1.15 = 230; charge = 10 * 230 = 2300
    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    assert!(pre_trade_check(&policy, &order, &mut mutations).is_ok());

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("2300"));
    assert_eq!(h.available(), ps("7700"));
}

#[test]
fn buy_market_no_bundle_rejects_unsupported_order_type() {
    let acc = account(99224416);
    // No SpotFundsMarketData → market orders are unsupported
    let policy = build_policy(None::<()>, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::UnsupportedOrderType);
}

// ── Sell Quantity ─────────────────────────────────────────────────────────

#[test]
fn sell_qty_sufficient_holds_underlying() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Quantity(qty("4")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    assert!(pre_trade_check(&policy, &order, &mut mutations).is_ok());

    let h = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(h.held(), ps("4"));
    assert_eq!(h.available(), ps("6"));
}

#[test]
fn sell_qty_insufficient_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "3");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Quantity(qty("4")),
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);

    let h = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(h.available(), ps("3"));
    assert_eq!(h.held(), ps("0"));
}

// ── Sell Volume + limit price ─────────────────────────────────────────────

#[test]
fn sell_volume_limit_holds_quantity_charge() {
    // AAPL=10, Sell vol=600 @ 200 → charge_qty = 600 / 200 = 3 AAPL
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Volume(vol("600")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    assert!(pre_trade_check(&policy, &order, &mut mutations).is_ok());

    let h = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(h.held(), ps("3"));
    assert_eq!(h.available(), ps("7"));
}

#[test]
fn sell_volume_limit_insufficient_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "2");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Volume(vol("600")),
        Some(px("200")),
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);
}

// ── Sell Volume + mark ────────────────────────────────────────────────────

#[test]
fn sell_volume_market_zero_slip_holds_correct_quantity() {
    // AAPL=10, mark=200, slip=0 → effective=200*(1-0)=200, vol=400, charge=2 AAPL
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 0);
    seed(&policy, acc, asset("AAPL"), "10");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Volume(vol("400")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    assert!(pre_trade_check(&policy, &order, &mut mutations).is_ok());

    let h = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(h.held(), ps("2"));
    assert_eq!(h.available(), ps("8"));
}

#[test]
fn sell_volume_market_full_slip_rejects_order_value_calculation_failed() {
    // slip=10000 → effective = mark * (1 - 1.0) = 0 → PriceUncomputable
    // → OrderValueCalculationFailed.
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 10_000);
    seed(&policy, acc, asset("AAPL"), "10");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Volume(vol("400")),
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    // With 100% slippage the effective sell price is zero, which the
    // pricer maps to PriceUncomputable → OrderValueCalculationFailed.
    assert_eq!(rejects[0].code, RejectCode::OrderValueCalculationFailed);
}

// ── Missing holdings treated as zero ──────────────────────────────────────

#[test]
fn missing_holdings_treated_as_zero_rejects_insufficient_funds() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    // EUR settlement, no EUR balance seeded → treated as zero
    let order = make_order(
        acc,
        instr("AAPL", "EUR"),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("200")),
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);
    assert!(mutations.is_empty());
}

// ── Phantom-entry prevention ──────────────────────────────────────────────

#[test]
fn insufficient_funds_on_missing_settlement_does_not_create_holdings_entry() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // EUR settlement not seeded — treated as zero → InsufficientFunds.

    let order = make_order(
        acc,
        instr("AAPL", "EUR"),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("100")),
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);
    assert!(
        holdings_of(&policy, acc, &asset("EUR")).is_none(),
        "phantom entry must not be created on reject"
    );
}

#[test]
fn bounds_exceeded_on_new_asset_does_not_create_holdings_entry() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // upper=0 blocks any positive balance; Delta(+10) on an unseen asset.
    let adjustment = bounded_adj(
        asset("EUR"),
        Some(AdjustmentAmount::Delta(ps("10"))),
        None,
        Some(ps("0")),
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::AccountAdjustmentBoundsExceeded);
    assert!(
        holdings_of(&policy, acc, &asset("EUR")).is_none(),
        "phantom entry must not be created on reject"
    );
}

#[test]
fn negative_result_on_new_asset_does_not_create_holdings_entry() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // lower=0 blocks negative result; Absolute(-1) on an unseen asset.
    let adjustment = bounded_adj(
        asset("EUR"),
        Some(AdjustmentAmount::Absolute(ps("-1"))),
        Some(ps("0")),
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::AccountAdjustmentBoundsExceeded);
    assert!(
        holdings_of(&policy, acc, &asset("EUR")).is_none(),
        "phantom entry must not be created on reject"
    );
}

// ── Rollback simulation ────────────────────────────────────────────────────

#[test]
fn rollback_restores_holdings_to_pre_reserve_state() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");

    // write is synchronous; state is already updated
    let after_check = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(after_check.held(), ps("2000"));
    assert_eq!(after_check.available(), ps("8000"));

    mutations.rollback_all();

    let after_rollback = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(after_rollback.held(), ps("0"));
    assert_eq!(after_rollback.available(), ps("10000"));
}

#[test]
fn concurrent_second_check_rejects_when_first_already_reserved() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "100");

    let order_a = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Volume(vol("100")),
        Some(px("1")),
    );
    let order_b = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Buy,
        TradeAmount::Volume(vol("100")),
        Some(px("1")),
    );

    let mut mutations_a = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order_a, &mut mutations_a).expect("A must pass");

    // B's check sees available already reduced to 0 by A's
    // synchronous write, so it is rejected immediately.
    let mut mutations_b = Mutations::new();
    let rejects = pre_trade_check(&policy, &order_b, &mut mutations_b)
        .expect_err("B must reject - funds already held by A");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);

    // Rolling back A returns the funds; B would now fit.
    mutations_a.rollback_all();
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("0"));
    assert_eq!(h.available(), ps("100"));
}

// ═══════════════════════════════════════════════════════════════════════════
// apply_execution_report — §8.2
// ═══════════════════════════════════════════════════════════════════════════

// ── Buy partial fill ──────────────────────────────────────────────────────

#[test]
fn buy_partial_fill_consumes_held_settlement_and_credits_underlying() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // held(USD)=2000, available(USD)=8000

    let report = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let blocks = report_blocks(&policy, &report);
    assert!(blocks.is_empty());

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("1200")); // 2000 - 4*200=800
    assert_eq!(usd.available(), ps("8000")); // unchanged

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("AAPL entry created");
    assert_eq!(aapl.available(), ps("4"));
    assert_eq!(aapl.held(), ps("0"));
}

// ── Sell partial fill ─────────────────────────────────────────────────────

#[test]
fn sell_partial_fill_consumes_held_underlying_and_credits_settlement() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // held(AAPL)=10, available(AAPL)=0

    let report = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        None,
    );
    report_blocks(&policy, &report);

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.held(), ps("6")); // 10 - 4
    assert_eq!(aapl.available(), ps("0")); // unchanged

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("USD entry created");
    assert_eq!(usd.available(), ps("800")); // 4 * 200
}

// ── Buy fill - missing lock price ─────────────────────────────────────────

#[test]
fn buy_fill_without_lock_price_blocks_account() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // held=2000, available=8000

    // Report with empty lock - no price for group.
    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        None,
    );
    let blocks = report_blocks(&policy, &fill);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].code, RejectCode::MissingRequiredField);

    // Holdings must not have changed.
    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("2000"));
    assert_eq!(usd.available(), ps("8000"));
}

// ── Buy fill - multiple lock prices ──────────────────────────────────────

#[test]
fn buy_fill_with_multiple_lock_prices_blocks_account() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // held=2000, available=8000

    // Lock with two prices for the same group - ambiguous, must block.
    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([
            (DEFAULT_POLICY_GROUP_ID, px("200")),
            (DEFAULT_POLICY_GROUP_ID, px("210")),
        ])),
    );
    let blocks = report_blocks(&policy, &fill);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].code, RejectCode::Other);

    // Holdings must not have changed.
    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("2000"));
    assert_eq!(usd.available(), ps("8000"));
}

// ── Cancel - Buy limit ────────────────────────────────────────────────────

// ── Cancel with leftover - Buy limit ──────────────────────────────────────

#[test]
fn buy_limit_cancel_leftover_releases_held_by_leaves_times_price() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // held=2000, available=8000

    let fill = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    report_blocks(&policy, &fill);
    // held=2000-800=1200

    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        None,
        qty("6"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    report_blocks(&policy, &cancel);
    // release=6*200=1200; held=0; available=8000+1200=9200

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("0"));
    assert_eq!(usd.available(), ps("9200"));
}

// ── Cancel - Buy market uses lock price for release ───────────────────────

#[test]
fn buy_market_cancel_uses_lock_price_for_release() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 1500);
    seed(&policy, acc, asset("USD"), "10000");

    // Reserve: effective=230, held=2300, available=7700.
    // The lock written during pre-trade is propagated by the caller into
    // every execution report for this order.
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let fill = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("195"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("230"),
        )])),
    );
    report_blocks(&policy, &fill);
    // Fill consumed 4*230=920 from held (lock price), savings=140 returned to available.
    // After fill: held=2300-920=1380, available=7700+140=7840.

    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("195"),
            quantity: qty("0"),
        }),
        qty("6"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("230"),
        )])),
    );
    report_blocks(&policy, &cancel);
    // Cancel: release = 6*230=1380; held=1380-1380=0, available=7840+1380=9220.

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("0"));
    assert_eq!(usd.available(), ps("9220"));
}

#[test]
fn buy_market_cancel_without_lock_price_blocks() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 1500);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let cancel = make_report(acc, aapl_usd, Side::Buy, None, qty("10"), true, None);
    let blocks = report_blocks(&policy, &cancel);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].code, RejectCode::MissingRequiredField);
}

// ── Cancel - Buy market, multiple lock prices ─────────────────────────────

#[test]
fn buy_market_cancel_with_multiple_lock_prices_blocks() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 1500);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        None,
        qty("10"),
        true,
        Some(PreTradeLock::from_entries([
            (DEFAULT_POLICY_GROUP_ID, px("230")),
            (DEFAULT_POLICY_GROUP_ID, px("240")),
        ])),
    );
    let blocks = report_blocks(&policy, &cancel);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].code, RejectCode::Other);
}

// ── Cancel - Buy market, no fills, with mark ──────────────────────────────

#[test]
fn buy_market_cancel_no_fills_with_lock_price_releases_full_amount() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("200"), 1500);
    seed(&policy, acc, asset("USD"), "10000");

    // Reserve: effective=230, held=2300.
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    // Cancel with the propagated lock price = 230:
    // release = 10*230 = 2300; held=0; available=7700+2300=10000.
    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        None,
        qty("10"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("230"),
        )])),
    );
    report_blocks(&policy, &cancel);

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("0"));
    assert_eq!(usd.available(), ps("10000"));
}

// ── Cancel - Buy market, no fills, no mark (stuck) ────────────────────────

#[test]
fn buy_market_cancel_no_fills_no_mark_held_stays_stuck() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let usd = asset("USD");

    // Inject held=2300 directly to simulate a prior market reservation
    policy
        .holdings
        .with_mut((acc, usd.clone()), Holdings::zero, |slot, _| {
            *slot = Holdings::new(ps("0"), ps("2300"));
        });

    // Cancel with no lock price recorded for the buy side surfaces an
    // AccountBlock with MissingRequiredField; held is left untouched
    // because compute_release_amount fails before any mutation runs.
    let cancel = make_report(acc, aapl_usd, Side::Buy, None, qty("10"), true, None);
    let blocks = report_blocks(&policy, &cancel);
    assert_eq!(blocks.len(), 1);
    assert_eq!(blocks[0].code, RejectCode::MissingRequiredField);

    let h = holdings_of(&policy, acc, &usd).expect("must exist");
    assert_eq!(h.held(), ps("2300"));
}

// ── Cancel Sell ───────────────────────────────────────────────────────────

#[test]
fn sell_cancel_leftover_releases_underlying_held() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");

    // Reserve Sell 10 → held(AAPL)=10, available(AAPL)=0
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    // Partial fill 4@200: consume(4) from held → held=6
    let fill = make_report(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        None,
    );
    report_blocks(&policy, &fill);

    // Cancel leaves=6: Side::Sell → release=6 directly; held=0; available=6
    let cancel = make_report(acc, aapl_usd, Side::Sell, None, qty("6"), true, None);
    report_blocks(&policy, &cancel);

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.held(), ps("0"));
    assert_eq!(aapl.available(), ps("6"));
}

// ── is_final + leaves=0 ───────────────────────────────────────────────────

#[test]
fn final_report_with_zero_leaves_triggers_no_release() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // held=2000

    // Full fill, leaves=0, is_final=true: consume(2000), no release triggered
    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    report_blocks(&policy, &final_fill);

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(usd.held(), ps("0"));
}

// ── Inflow creates entry ───────────────────────────────────────────────────

#[test]
fn buy_fill_creates_underlying_entry_in_holdings() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    assert!(holdings_of(&policy, acc, &asset("AAPL")).is_none());

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    report_blocks(&policy, &fill);

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("entry must be created");
    assert_eq!(aapl.available(), ps("1"));
}

// ═══════════════════════════════════════════════════════════════════════════
// apply_account_adjustment — §8.3
// ═══════════════════════════════════════════════════════════════════════════

// ── Absolute set positive ─────────────────────────────────────────────────

#[test]
fn absolute_positive_sets_available() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("15000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("15000"));
}

// ── Absolute set negative ─────────────────────────────────────────────────

#[test]
fn absolute_negative_sets_available() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("-100"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("-100"));
}

// ── Delta positive ────────────────────────────────────────────────────────

#[test]
fn delta_positive_adds_to_available() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Delta(ps("5000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("15000"));
}

// ── Delta negative happy ──────────────────────────────────────────────────

#[test]
fn delta_negative_reduces_available() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Delta(ps("-3000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("7000"));
}

// ── Delta negative below zero ─────────────────────────────────────────────

#[test]
fn delta_below_zero_sets_negative_available() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Delta(ps("-15000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("-5000"));
}

// ── Delta on missing holdings ─────────────────────────────────────────────

#[test]
fn delta_on_missing_creates_entry_from_zero() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = adj(asset("EUR"), Some(AdjustmentAmount::Delta(ps("100"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("EUR")).expect("entry must be created");
    assert_eq!(h.available(), ps("100"));
    assert_eq!(h.held(), ps("0"));
}

// ── Bounds exceeded ───────────────────────────────────────────────────────

#[test]
fn lower_bound_exceeded_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    // Delta(-15000) with lower=0 → new available=-5000 < 0 → reject
    let adjustment = bounded_adj(
        asset("USD"),
        Some(AdjustmentAmount::Delta(ps("-15000"))),
        Some(ps("0")),
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::AccountAdjustmentBoundsExceeded);

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("10000")); // unchanged
}

#[test]
fn upper_bound_exceeded_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    // Delta(+5000) with upper=12000 → new available=15000 > 12000 → reject
    let adjustment = bounded_adj(
        asset("USD"),
        Some(AdjustmentAmount::Delta(ps("5000"))),
        None,
        Some(ps("12000")),
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::AccountAdjustmentBoundsExceeded);

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("10000")); // unchanged
}

// ── Absolute creates entry ────────────────────────────────────────────────

#[test]
fn absolute_creates_entry_for_new_asset() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    assert!(holdings_of(&policy, acc, &asset("EUR")).is_none());

    let adjustment = adj(asset("EUR"), Some(AdjustmentAmount::Absolute(ps("1000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("EUR")).expect("entry must be created");
    assert_eq!(h.available(), ps("1000"));
    assert_eq!(h.held(), ps("0"));
}

// ── Rollback restores state ───────────────────────────────────────────────

#[test]
fn adjustment_rollback_restores_previous_state() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("15000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");

    // write is synchronous
    let after_adj = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(after_adj.available(), ps("15000"));

    mutations.rollback_all();

    let after_rollback = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(after_rollback.available(), ps("10000"));
}

#[test]
fn adjustment_rollback_removes_newly_created_entry() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = adj(asset("EUR"), Some(AdjustmentAmount::Absolute(ps("1000"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");

    assert!(holdings_of(&policy, acc, &asset("EUR")).is_some());

    mutations.rollback_all();

    assert!(holdings_of(&policy, acc, &asset("EUR")).is_none());
}

#[test]
fn adjustment_rollback_restores_pruned_existing_entry() {
    // Regression: when an adjustment drives an existing slot to zero the
    // main path prunes the entry via `remove_if_zero`. The rollback must
    // re-insert the slot and restore the previous balance rather than
    // silently doing nothing because the entry is absent.
    let acc = account(77112233);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "100");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("0"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");

    // Slot was pruned because the result is zero.
    assert!(holdings_of(&policy, acc, &asset("USD")).is_none());

    mutations.rollback_all();

    let after_rollback =
        holdings_of(&policy, acc, &asset("USD")).expect("rollback must restore the pruned entry");
    assert_eq!(after_rollback.available(), ps("100"));
}

#[test]
fn adjustment_rollback_restores_pruned_existing_entry_all_fields() {
    // Extends the pruned-entry regression to held and incoming. All three
    // fields are driven to zero in one adjustment so the slot is pruned,
    // then rollback must restore all three to their pre-adjustment values.
    let acc = account(55667788);
    let policy = build_policy(None, None);

    // Seed all three fields via a single all-fields adjustment.
    let setup = all_fields_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("100"))),
        Some(AdjustmentAmount::Absolute(ps("20"))),
        Some(AdjustmentAmount::Absolute(ps("5"))),
    );
    let mut setup_mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &setup, &mut setup_mutations).expect("seed must succeed");
    setup_mutations.commit_all();

    // Drive all three fields to zero so the slot is pruned.
    let zeroing = all_fields_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("0"))),
        Some(AdjustmentAmount::Absolute(ps("0"))),
        Some(AdjustmentAmount::Absolute(ps("0"))),
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &zeroing, &mut mutations).expect("must succeed");
    assert!(
        holdings_of(&policy, acc, &asset("USD")).is_none(),
        "slot must be pruned after all-zero adjustment"
    );

    mutations.rollback_all();

    let after_rollback =
        holdings_of(&policy, acc, &asset("USD")).expect("rollback must restore the pruned entry");
    assert_eq!(after_rollback.available(), ps("100"));
    assert_eq!(after_rollback.held(), ps("20"));
    assert_eq!(after_rollback.incoming(), ps("5"));
}

// ── Adjustment без balance_operation ─────────────────────────────────────

#[test]
fn adjustment_without_balance_asset_rejects_missing_required_field() {
    struct NoBalanceAsset;

    impl HasBalanceAsset for NoBalanceAsset {
        fn balance_asset(&self) -> Result<&Asset, RequestFieldAccessError> {
            Err(RequestFieldAccessError::new("balance_asset"))
        }
    }
    impl HasAccountAdjustmentBalance for NoBalanceAsset {
        fn balance(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentBalanceLowerBound for NoBalanceAsset {
        fn balance_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentBalanceUpperBound for NoBalanceAsset {
        fn balance_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentHeld for NoBalanceAsset {
        fn held(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentHeldLowerBound for NoBalanceAsset {
        fn held_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentHeldUpperBound for NoBalanceAsset {
        fn held_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentIncoming for NoBalanceAsset {
        fn incoming(&self) -> Result<Option<AdjustmentAmount>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentIncomingLowerBound for NoBalanceAsset {
        fn incoming_lower(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentIncomingUpperBound for NoBalanceAsset {
        fn incoming_upper(&self) -> Result<Option<PositionSize>, RequestFieldAccessError> {
            Ok(None)
        }
    }

    let acc = account(99224416);
    let policy = build_policy(None, None);
    let mut mutations = Mutations::new();
    let rejects = <TestPolicy as PreTradePolicy<
        TestOrder,
        TestReport,
        NoBalanceAsset,
        crate::core::FullSync,
    >>::apply_account_adjustment(
        &policy,
        &AccountAdjustmentContext::new_test(dummy_control(acc)),
        acc,
        &NoBalanceAsset,
        &mut mutations,
    )
    .expect_err("must reject");

    assert_eq!(rejects[0].code, RejectCode::MissingRequiredField);
    assert!(mutations.is_empty());
}

// ── Adjustment без balance ────────────────────────────────────────────────

#[test]
fn adjustment_with_all_none_fields_returns_ok_without_changes() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = adj(asset("USD"), None); // held and incoming also None
    let mut mutations = Mutations::new();
    let result = apply_adj(&policy, acc, &adjustment, &mut mutations);

    assert!(result.is_ok());
    assert!(mutations.is_empty());
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("5000")); // unchanged
}

// ── Held adjustment ───────────────────────────────────────────────────────

#[test]
fn held_absolute_sets_held_directly() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = held_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("3000"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("3000"));
    assert_eq!(h.available(), ps("10000")); // balance untouched
    assert_eq!(h.incoming(), ps("0"));
}

#[test]
fn held_delta_modifies_held() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let set = held_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("500"))),
        None,
        None,
    );
    apply_adj(&policy, acc, &set, &mut Mutations::with_capacity(1))
        .expect("seed held must succeed");

    let adjustment = held_adj(
        asset("USD"),
        Some(AdjustmentAmount::Delta(ps("200"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("700"));
}

#[test]
fn held_negative_value_is_allowed() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = held_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("-200"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("-200"));
}

#[test]
fn held_bounds_exceeded_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = held_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("1000"))),
        None,
        Some(ps("500")), // upper bound = 500 < 1000 → reject
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::AccountAdjustmentBoundsExceeded);
    assert!(mutations.is_empty());
}

#[test]
fn held_adjustment_returns_held_outcome_only() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = held_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("300"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);

    assert_eq!(entries.len(), 1);
    let entry = &entries[0];
    assert!(entry.balance.is_none(), "balance must be absent");
    assert!(entry.incoming.is_none(), "incoming must be absent");
    let held = entry.held.as_ref().expect("held outcome must be present");
    assert_eq!(held.delta, ps("300")); // Absolute(300) from zero → delta = 300
    assert_eq!(held.absolute, ps("300"));
}

// ── Incoming adjustment ───────────────────────────────────────────────────

#[test]
fn incoming_absolute_sets_incoming_directly() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let adjustment = incoming_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("2000"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.incoming(), ps("2000"));
    assert_eq!(h.available(), ps("10000")); // balance untouched
    assert_eq!(h.held(), ps("0"));
}

#[test]
fn incoming_delta_modifies_incoming() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let set = incoming_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("1000"))),
        None,
        None,
    );
    apply_adj(&policy, acc, &set, &mut Mutations::with_capacity(1))
        .expect("seed incoming must succeed");

    let adjustment = incoming_adj(
        asset("USD"),
        Some(AdjustmentAmount::Delta(ps("-300"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.incoming(), ps("700"));
}

#[test]
fn incoming_negative_value_is_allowed() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = incoming_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("-500"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");
    mutations.commit_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.incoming(), ps("-500"));
}

#[test]
fn incoming_bounds_exceeded_rejects() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    let adjustment = incoming_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("200"))),
        Some(ps("300")), // lower bound = 300 > 200 → reject
        None,
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");
    assert_eq!(rejects[0].code, RejectCode::AccountAdjustmentBoundsExceeded);
    assert!(mutations.is_empty());
}

#[test]
fn incoming_adjustment_returns_incoming_outcome_only() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = incoming_adj(
        asset("USD"),
        Some(AdjustmentAmount::Delta(ps("400"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);

    assert_eq!(entries.len(), 1);
    let entry = &entries[0];
    assert!(entry.balance.is_none(), "balance must be absent");
    assert!(entry.held.is_none(), "held must be absent");
    let incoming = entry
        .incoming
        .as_ref()
        .expect("incoming outcome must be present");
    assert_eq!(incoming.delta, ps("400")); // Delta(400) from zero → delta = 400
    assert_eq!(incoming.absolute, ps("400"));
}

// ── All three fields ──────────────────────────────────────────────────────

#[test]
fn all_three_fields_applied_and_reported() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = all_fields_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("8000"))),
        Some(AdjustmentAmount::Absolute(ps("1500"))),
        Some(AdjustmentAmount::Absolute(ps("600"))),
    );
    let mut mutations = Mutations::with_capacity(1);
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(entries.len(), 1);
    let entry = &entries[0];

    let balance = entry.balance.as_ref().expect("balance must be present");
    assert_eq!(balance.absolute, ps("8000"));
    assert_eq!(balance.delta, ps("3000")); // 8000 - 5000

    let held = entry.held.as_ref().expect("held must be present");
    assert_eq!(held.absolute, ps("1500"));
    assert_eq!(held.delta, ps("1500")); // from zero

    let incoming = entry.incoming.as_ref().expect("incoming must be present");
    assert_eq!(incoming.absolute, ps("600"));
    assert_eq!(incoming.delta, ps("600")); // from zero

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("8000"));
    assert_eq!(h.held(), ps("1500"));
    assert_eq!(h.incoming(), ps("600"));
}

#[test]
fn all_three_rollback_restores_all_fields() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    // Prime held and incoming with non-zero initial values.
    apply_adj(
        &policy,
        acc,
        &held_adj(
            asset("USD"),
            Some(AdjustmentAmount::Absolute(ps("100"))),
            None,
            None,
        ),
        &mut Mutations::with_capacity(1),
    )
    .expect("held seed must succeed");
    apply_adj(
        &policy,
        acc,
        &incoming_adj(
            asset("USD"),
            Some(AdjustmentAmount::Absolute(ps("200"))),
            None,
            None,
        ),
        &mut Mutations::with_capacity(1),
    )
    .expect("incoming seed must succeed");

    let adjustment = all_fields_adj(
        asset("USD"),
        Some(AdjustmentAmount::Absolute(ps("9000"))),
        Some(AdjustmentAmount::Absolute(ps("900"))),
        Some(AdjustmentAmount::Absolute(ps("400"))),
    );
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("must succeed");

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist after adjustment");
    assert_eq!(h.available(), ps("9000"));
    assert_eq!(h.held(), ps("900"));
    assert_eq!(h.incoming(), ps("400"));

    mutations.rollback_all();

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist after rollback");
    assert_eq!(h.available(), ps("5000"));
    assert_eq!(h.held(), ps("100"));
    assert_eq!(h.incoming(), ps("200"));
}

// ── Outcomes & lock from perform_pre_trade_check ──────────────────────────

fn run_pre_trade(
    policy: &TestPolicy,
    order: &TestOrder,
    mutations: &mut Mutations,
) -> crate::pretrade::PolicyPreTradeResult {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::perform_pre_trade_check(
        policy,
        &PreTradeContext::new(None),
        order,
        mutations,
    )
    .expect("pre-trade must succeed")
    .expect("spot funds policy must produce a result")
}

fn run_adjustment(
    policy: &TestPolicy,
    account_id: AccountId,
    adjustment: &TestAdjustment,
    mutations: &mut Mutations,
) -> Vec<crate::AccountOutcomeEntry> {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::apply_account_adjustment(
        policy,
        &AccountAdjustmentContext::new_test(dummy_control(account_id)),
        account_id,
        adjustment,
        mutations,
    )
    .expect("adjustment must succeed")
}

fn run_report(policy: &TestPolicy, report: &TestReport) -> crate::pretrade::PostTradeResult {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::apply_execution_report(
        policy,
        &crate::pretrade::PostTradeContext::new(),
        report,
    )
    .expect("apply_execution_report must produce a result")
}

#[test]
fn pre_trade_check_buy_returns_charge_outcome_and_lock_price() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_pre_trade(&policy, &order, &mut mutations);

    assert_eq!(outcome.account_adjustments.len(), 1);
    let entry = &outcome.account_adjustments[0];
    assert_eq!(entry.asset, asset("USD"));
    let balance = entry
        .balance
        .as_ref()
        .expect("balance delta must be present");
    assert_eq!(balance.delta, ps("-2000"));
    assert_eq!(balance.absolute, ps("8000"));
    let held = entry.held.as_ref().expect("held delta must be present");
    assert_eq!(held.delta, ps("2000"));
    assert_eq!(held.absolute, ps("2000"));
    assert!(entry.incoming.is_none());

    assert_eq!(outcome.lock_prices.as_slice(), &[px("200")]);
}

#[test]
fn pre_trade_check_buy_market_lock_price_is_effective_price() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("100"), 1000);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("5")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_pre_trade(&policy, &order, &mut mutations);

    // effective_buy_price = 100 * (1 + 0.10) = 110
    assert_eq!(outcome.lock_prices.as_slice(), &[px("110")]);
    let entry = &outcome.account_adjustments[0];
    assert_eq!(entry.asset, asset("USD"));
    let held = entry.held.as_ref().expect("held delta must be present");
    assert_eq!(held.delta, ps("550"));
}

#[test]
fn pre_trade_check_sell_returns_charge_outcome_and_no_lock_price() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "100");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Quantity(qty("3")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_pre_trade(&policy, &order, &mut mutations);

    assert_eq!(outcome.account_adjustments.len(), 1);
    let entry = &outcome.account_adjustments[0];
    assert_eq!(entry.asset, asset("AAPL"));
    let held = entry.held.as_ref().expect("held delta must be present");
    assert_eq!(held.delta, ps("3"));
    assert_eq!(held.absolute, ps("3"));

    assert!(outcome.lock_prices.is_empty());
}

// ── Outcomes from apply_account_adjustment ────────────────────────────────

#[test]
fn account_adjustment_returns_balance_delta_outcome_for_delta_amount() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Delta(ps("750"))));
    let mut mutations = Mutations::with_capacity(1);
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);

    assert_eq!(entries.len(), 1);
    let entry = &entries[0];
    assert_eq!(entry.asset, asset("USD"));
    let balance = entry
        .balance
        .as_ref()
        .expect("balance delta must be present");
    assert_eq!(balance.delta, ps("750"));
    assert_eq!(balance.absolute, ps("5750"));
    assert!(entry.held.is_none());
    assert!(entry.incoming.is_none());
}

#[test]
fn account_adjustment_returns_balance_delta_outcome_for_absolute_amount() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("8000"))));
    let mut mutations = Mutations::with_capacity(1);
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);

    assert_eq!(entries.len(), 1);
    let balance = entries[0]
        .balance
        .as_ref()
        .expect("balance delta must be present");
    assert_eq!(balance.delta, ps("3000"));
    assert_eq!(balance.absolute, ps("8000"));
}

#[test]
fn account_adjustment_returns_zero_delta_entry_for_same_absolute_amount() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("5000"))));
    let mut mutations = Mutations::with_capacity(1);
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);

    assert_eq!(entries.len(), 1);
    let balance = entries[0]
        .balance
        .as_ref()
        .expect("balance delta must be present");
    assert_eq!(balance.delta, ps("0"));
    assert_eq!(balance.absolute, ps("5000"));
}

#[test]
fn account_adjustment_returns_empty_when_balance_field_is_none() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    let adjustment = adj(asset("USD"), None);
    let mut mutations = Mutations::new();
    let entries = run_adjustment(&policy, acc, &adjustment, &mut mutations);

    assert!(entries.is_empty());
}

// ── Outcomes from apply_execution_report ──────────────────────────────────

#[test]
fn execution_report_buy_fill_returns_charge_and_counter_outcomes() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let result = run_report(&policy, &fill);

    assert!(result.account_blocks.is_empty());
    assert_eq!(result.account_adjustments.len(), 2);

    let usd_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("USD"))
        .expect("USD entry must exist");
    assert!(usd_entry.entry.balance.is_none());
    let usd_held = usd_entry
        .entry
        .held
        .as_ref()
        .expect("USD held delta must be present");
    assert_eq!(usd_held.delta, ps("-800"));
    assert_eq!(usd_held.absolute, ps("1200"));

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    let aapl_balance = aapl_entry
        .entry
        .balance
        .as_ref()
        .expect("AAPL balance delta must be present");
    assert_eq!(aapl_balance.delta, ps("4"));
    assert_eq!(aapl_balance.absolute, ps("4"));
    assert!(aapl_entry.entry.held.is_none());
}

#[test]
fn execution_report_buy_final_with_fill_and_release_merges_charge_outcome() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();

    let final_report = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let result = run_report(&policy, &final_report);

    let usd_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("USD"))
        .expect("USD entry must exist");
    let usd_held = usd_entry
        .entry
        .held
        .as_ref()
        .expect("USD held delta must be present");
    assert_eq!(usd_held.delta, ps("-2000"));
    assert_eq!(usd_held.absolute, ps("0"));
    let usd_balance = usd_entry
        .entry
        .balance
        .as_ref()
        .expect("USD balance delta must be present");
    assert_eq!(usd_balance.delta, ps("1200"));
    assert_eq!(usd_balance.absolute, ps("9200"));
}

#[test]
fn execution_report_buy_release_with_missing_lock_price_emits_block() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();

    let cancel = make_report(acc, aapl_usd, Side::Buy, None, qty("10"), true, None);
    let result = run_report(&policy, &cancel);

    assert_eq!(result.account_blocks.len(), 1);
    assert_eq!(
        result.account_blocks[0].code,
        RejectCode::MissingRequiredField
    );
    assert!(result.account_adjustments.is_empty());
}

#[test]
fn execution_report_buy_release_with_multiple_lock_prices_emits_block() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();

    let mut lock = PreTradeLock::new();
    lock.push(DEFAULT_POLICY_GROUP_ID, px("200"));
    lock.push(DEFAULT_POLICY_GROUP_ID, px("210"));
    let cancel = make_report(acc, aapl_usd, Side::Buy, None, qty("10"), true, Some(lock));
    let result = run_report(&policy, &cancel);

    assert_eq!(result.account_blocks.len(), 1);
    assert_eq!(result.account_blocks[0].code, RejectCode::Other);
}

#[test]
fn execution_report_sell_final_release_does_not_consult_lock() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "100");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();

    let cancel = make_report(acc, aapl_usd, Side::Sell, None, qty("10"), true, None);
    let result = run_report(&policy, &cancel);

    assert!(result.account_blocks.is_empty());
    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    let held = aapl_entry
        .entry
        .held
        .as_ref()
        .expect("AAPL held delta must be present");
    assert_eq!(held.delta, ps("-10"));
    assert_eq!(held.absolute, ps("0"));
    let balance = aapl_entry
        .entry
        .balance
        .as_ref()
        .expect("AAPL balance delta must be present");
    assert_eq!(balance.delta, ps("10"));
    assert_eq!(balance.absolute, ps("100"));
}

// ═══════════════════════════════════════════════════════════════════════════
// Venue-truth and arithmetic-overflow handling
// ═══════════════════════════════════════════════════════════════════════════

fn position_size_max() -> PositionSize {
    PositionSize::new(rust_decimal::Decimal::MAX)
}

/// Venue-truth: a Buy fill whose `lock_price * qty` exceeds the
/// currently reserved `held` records a negative `held` value and
/// must not block the account.
#[test]
fn fill_consume_exceeds_held_drives_held_negative_without_blocking_account() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let usd = asset("USD");

    // Inject held=100 directly to simulate a shrunk reservation.
    policy
        .holdings
        .with_mut((acc, usd.clone()), Holdings::zero, |slot, _| {
            *slot = Holdings::new(ps("0"), ps("100"));
        });

    // Buy lock price=200, qty=10 → consume = 200 * 10 = 2000 > held=100.
    let lock = PreTradeLock::from_entries([(DEFAULT_POLICY_GROUP_ID, px("200"))]);
    let report = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        Some(lock),
    );
    let blocks = report_blocks(&policy, &report);

    assert!(
        blocks.is_empty(),
        "venue-truth must not raise account block"
    );
    let h = holdings_of(&policy, acc, &usd).expect("must exist");
    assert_eq!(h.held(), ps("-1900"));
    assert_eq!(h.available(), ps("0"));
}

/// Overflow on the inflow side of an execution report must block
/// the account via the kill-switch path.
#[test]
fn fill_inflow_overflow_blocks_account() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let aapl = asset("AAPL");

    // Drive AAPL available to Decimal::MAX directly.
    policy
        .holdings
        .with_mut((acc, aapl.clone()), Holdings::zero, |slot, _| {
            *slot = Holdings::new(position_size_max(), PositionSize::ZERO);
        });
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("1")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    // Buy fill of 1 AAPL credits 1 to AAPL.available = MAX + 1 → overflow.
    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("1"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("1"),
        )])),
    );
    let result = <TestPolicy as PreTradePolicy<
        TestOrder,
        TestReport,
        TestAdjustment,
        crate::core::FullSync,
    >>::apply_execution_report(
        &policy, &crate::pretrade::PostTradeContext::new(), &fill
    )
    .expect("must report a result");

    assert_eq!(result.account_blocks.len(), 1);
    assert_eq!(
        result.account_blocks[0].code,
        RejectCode::ArithmeticOverflow
    );

    // Non-atomicity contract: the outflow-side (USD) mutation has
    // already been applied to storage, so the partial adjustment must be
    // present in the returned result alongside the inflow-side block.
    let usd_adjustment = result
        .account_adjustments
        .iter()
        .find(|a| a.entry.asset == asset("USD"))
        .expect("outflow-side USD adjustment must be reported");
    let held = usd_adjustment
        .entry
        .held
        .as_ref()
        .expect("USD held outcome must be present after partial outflow");
    assert_eq!(held.absolute, ps("0"));
    assert_eq!(held.delta, ps("-1"));
}

/// Round-trip companion to [`fill_inflow_overflow_blocks_account`]: drives
/// the same overflow scenario through a built [`crate::FullSyncEngine`] and
/// asserts that the engine actually marks the account as blocked after
/// `apply_execution_report` returns. The block originates from
/// `apply_trade_fill`'s overflow path in `execution.rs`; the engine collects
/// it into [`crate::pretrade::PostTradeResult::account_blocks`] and records
/// the first block via the engine's own `BlockedAccounts::record`.
#[test]
fn fill_inflow_overflow_round_trip_blocks_account_in_engine() {
    let acc = account(99224418);
    let aapl_usd = instr("AAPL", "USD");
    let engine = build_engine_with_spot_funds_policy();
    let aapl = asset("AAPL");

    // Seed AAPL.available = MAX so the upcoming Buy fill's inflow credit
    // (+1 AAPL) overflows. USD is seeded to cover the Buy hold.
    seed_balance_via_engine(&engine, acc, aapl.clone(), position_size_max());
    seed_balance_via_engine(&engine, acc, asset("USD"), ps("10000"));

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("1")),
    );
    let request = engine
        .start_pre_trade(order)
        .expect("start_pre_trade must succeed");
    request.execute().expect("execute must reserve").commit();

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("1"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("1"),
        )])),
    );
    let result = engine.apply_execution_report(&fill);
    assert_eq!(result.account_blocks.len(), 1);
    assert_eq!(
        result.account_blocks[0].code,
        RejectCode::ArithmeticOverflow
    );

    assert_account_blocked_with_arithmetic_overflow(&engine, acc);
}

/// Overflow during pre-trade hold (e.g., `held + amount` exceeds
/// the value range) must reject the order with
/// [`RejectCode::ArithmeticOverflow`] under
/// [`RejectScope::Order`].
#[test]
fn pre_trade_hold_overflow_rejects_with_arithmetic_overflow_code() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let usd = asset("USD");

    // Seed slot with available=MAX/2 and held=MAX so any hold of
    // a positive amount overflows held = MAX + amount.
    policy
        .holdings
        .with_mut((acc, usd.clone()), Holdings::zero, |slot, _| {
            *slot = Holdings::new(position_size_max(), position_size_max());
        });

    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("1")),
    );
    let mut mutations = Mutations::new();
    let rejects = pre_trade_check(&policy, &order, &mut mutations).expect_err("must reject");

    assert_eq!(rejects[0].code, RejectCode::ArithmeticOverflow);
    assert!(mutations.is_empty());
}

/// Account adjustment overflow on the delta path must reject
/// with [`RejectCode::ArithmeticOverflow`].
#[test]
fn account_adjustment_delta_overflow_rejects_with_arithmetic_overflow_code() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    let usd = asset("USD");

    // Pre-seed available to Decimal::MAX so any positive delta
    // overflows.
    policy
        .holdings
        .with_mut((acc, usd.clone()), Holdings::zero, |slot, _| {
            *slot = Holdings::new(position_size_max(), PositionSize::ZERO);
        });

    let adjustment = adj(
        asset("USD"),
        Some(AdjustmentAmount::Delta(position_size_max())),
    );
    let mut mutations = Mutations::new();
    let rejects = apply_adj(&policy, acc, &adjustment, &mut mutations).expect_err("must reject");

    assert_eq!(rejects[0].code, RejectCode::ArithmeticOverflow);
    let h = holdings_of(&policy, acc, &usd).expect("must exist");
    assert_eq!(h.available(), position_size_max());
}

// ═══════════════════════════════════════════════════════════════════════════
// Post-trade asymmetry fix — §8.3
// ═══════════════════════════════════════════════════════════════════════════

// Execution report for a Buy where the charge-side (USD) slot is absent:
// the outflow must still record held going negative and the counter side
// (AAPL) must be credited.
#[test]
fn buy_fill_missing_charge_slot_records_negative_held_and_credits_counter() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // No USD slot seeded intentionally.

    let report = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let blocks = report_blocks(&policy, &report);
    assert!(blocks.is_empty());

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("USD slot must be created");
    assert_eq!(usd.available(), ps("0"));
    assert_eq!(usd.held(), ps("-2000"));

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("AAPL slot must be created");
    assert_eq!(aapl.available(), ps("10"));
    assert_eq!(aapl.held(), ps("0"));
}

// Execution report for a Sell where the charge-side (AAPL) slot is absent:
// held goes negative and USD is credited.
#[test]
fn sell_fill_missing_charge_slot_records_negative_held_and_credits_counter() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // No AAPL slot seeded intentionally.

    let report = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("200"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        None,
    );
    let blocks = report_blocks(&policy, &report);
    assert!(blocks.is_empty());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("AAPL slot must be created");
    assert_eq!(aapl.available(), ps("0"));
    assert_eq!(aapl.held(), ps("-10"));

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("USD slot must be created");
    assert_eq!(usd.available(), ps("2000"));
    assert_eq!(usd.held(), ps("0"));
}

// Final-cancel execution report where the charge-side (USD) slot is absent:
// release_held must create the slot and reflect the authoritative delta.
#[test]
fn cancel_release_missing_charge_slot_applies_release_delta() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // No USD slot seeded intentionally.

    // Final cancel: leaves=10, lock price=200, no trade.
    let report = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        None,
        qty("10"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let blocks = report_blocks(&policy, &report);
    assert!(blocks.is_empty());

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("USD slot must be created");
    assert_eq!(usd.available(), ps("2000"));
    assert_eq!(usd.held(), ps("-2000"));
}

// Zero-valued adjustments on an absent slot must not create a phantom entry.
#[test]
fn zero_adjustment_on_missing_slot_does_not_create_entry() {
    let acc = account(99224416);
    let policy = build_policy(None, None);

    for amount in [
        AdjustmentAmount::Absolute(ps("0")),
        AdjustmentAmount::Delta(ps("0")),
    ] {
        let adjustment = adj(asset("EUR"), Some(amount));
        let mut mutations = Mutations::new();
        apply_adj(&policy, acc, &adjustment, &mut mutations).expect("zero adjustment must succeed");
        assert!(
            holdings_of(&policy, acc, &asset("EUR")).is_none(),
            "phantom entry must not be created for {amount:?}"
        );
    }
}

// After an adjustment drives all fields to zero the entry must be removed.
#[test]
fn slot_removed_when_adjustment_brings_all_fields_to_zero() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    assert!(
        holdings_of(&policy, acc, &asset("USD")).is_some(),
        "slot must exist after seed"
    );

    let adjustment = adj(asset("USD"), Some(AdjustmentAmount::Absolute(ps("0"))));
    let mut mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &adjustment, &mut mutations).expect("adjustment must succeed");

    assert!(
        holdings_of(&policy, acc, &asset("USD")).is_none(),
        "slot must be removed when adjustment drives it to zero"
    );
}

// After a fill outflow consumes all held the entry must be removed.
#[test]
fn slot_removed_when_fill_outflow_brings_all_fields_to_zero() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "5000");

    // Reserve all 5000 USD → available=0, held=5000.
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("25")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();

    // Final fill 25 @ 200 = 5000 notional; lock_consume = 5000 → held goes 0.
    let report = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("25"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let blocks = report_blocks(&policy, &report);
    assert!(blocks.is_empty());

    assert!(
        holdings_of(&policy, acc, &asset("USD")).is_none(),
        "USD slot must be pruned when fill drives it to (0, 0)"
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Regression: pre-trade try_hold(0) must not create a phantom slot
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn buy_qty_zero_pre_trade_check_does_not_create_phantom_slot() {
    // Regression for the phantom-slot bug: a Buy with qty=0 makes
    // charge_amount = 0; the previous implementation passed `try_hold(0)`
    // to `with_mut_or_insert`, which inserted and kept an all-zero slot.
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);

    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("0")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("zero-qty hold must succeed");
    mutations.commit_all();

    assert!(
        holdings_of(&policy, acc, &asset("USD")).is_none(),
        "no phantom USD slot must remain after zero-charge hold",
    );
}

#[test]
fn buy_volume_zero_pre_trade_check_does_not_create_phantom_slot() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);

    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Volume(vol("0")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("zero-volume hold must succeed");
    mutations.commit_all();

    assert!(
        holdings_of(&policy, acc, &asset("USD")).is_none(),
        "no phantom USD slot must remain after zero-charge hold",
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Regression: hold rollback must recreate a concurrently-pruned slot
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn hold_rollback_restores_pruned_existing_entry() {
    // Regression: a hold registers a delta-based rollback closure. If a
    // concurrent adjustment drives the slot to zero (and the main path
    // prunes it) between hold and rollback, the rollback must recreate
    // the slot and release the held amount instead of silently doing
    // nothing because the entry is absent.
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let usd = asset("USD");

    seed(&policy, acc, usd.clone(), "200");

    // Reserve 200 USD against a Buy 1@200. The hold writes the slot
    // synchronously even before commit; the synchronously-visible state
    // is available=0, held=200.
    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("200")),
    );
    let mut hold_mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut hold_mutations).expect("hold must succeed");
    assert_eq!(
        holdings_of(&policy, acc, &usd).expect("slot must exist after hold"),
        Holdings::new(ps("0"), ps("200")),
    );

    // Simulate a concurrent adjustment that drives the slot to zero and
    // prunes it (sets available -> 0 and held -> 0 via Absolute(0)).
    let zeroing = all_fields_adj(
        usd.clone(),
        Some(AdjustmentAmount::Absolute(ps("0"))),
        Some(AdjustmentAmount::Absolute(ps("0"))),
        None,
    );
    let mut adj_mutations = Mutations::with_capacity(1);
    apply_adj(&policy, acc, &zeroing, &mut adj_mutations).expect("zeroing must succeed");
    adj_mutations.commit_all();
    assert!(
        holdings_of(&policy, acc, &usd).is_none(),
        "slot must be pruned after zero adjustment",
    );

    // Now roll back the hold. The rollback uses delta semantics: it
    // recreates the pruned slot from `Holdings::zero` and applies the
    // inverse of the hold (release 200), so the released funds are not
    // lost. The resulting `held=-200` reflects the concurrent zeroing
    // that took precedence; what matters is that the slot exists again
    // and the cumulative `available` shift was applied.
    hold_mutations.rollback_all();

    let restored = holdings_of(&policy, acc, &usd).expect("rollback must recreate the pruned slot");
    assert_eq!(restored.available(), ps("200"));
    assert_eq!(restored.held(), ps("-200"));
}

// ═══════════════════════════════════════════════════════════════════════════
// Regression: lock_consume - outflow subtraction is checked
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn buy_fill_lock_savings_subtraction_at_decimal_extremes_does_not_panic() {
    // Regression: in `apply_trade_fill` the Buy branch computes
    // `lock_consume - outflow_amount` to derive price-improvement
    // savings. Previously this used raw `Decimal::-`, which panics on
    // overflow. The current implementation uses `PositionSize::checked_sub`
    // and surfaces overflow as an AccountBlock instead of panicking.
    //
    // Through the public order/fill construction path both operands are
    // non-negative volumes bounded by `Decimal::MAX`, so the result is
    // always in `[-MAX, MAX]` and the subtraction itself does not actually
    // overflow. This test still drives both sides toward the extreme so
    // the checked path runs and the result either succeeds cleanly or
    // surfaces as an account block - never panic.
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);

    let max_qty = Quantity::new_unchecked(rust_decimal::Decimal::MAX);
    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("1"),
            quantity: max_qty,
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("0"),
        )])),
    );
    let _ = report_blocks(&policy, &fill);
}

// ═══════════════════════════════════════════════════════════════════════════
// Task B regression: rollback overflow blocks the account via the engine
// ═══════════════════════════════════════════════════════════════════════════

/// Builds a single-policy FullSync engine. Any rollback overflow inside the
/// policy's mutation closures is recorded on the engine's blocked-accounts
/// storage through the [`AccountControl`](crate::core::AccountControl) the
/// engine injects into [`PreTradeContext`](crate::pretrade::PreTradeContext)
/// and [`AccountAdjustmentContext`](crate::AccountAdjustmentContext).
fn build_engine_with_spot_funds_policy(
) -> crate::FullSyncEngine<TestOrder, TestReport, TestAdjustment> {
    let builder = crate::Engine::builder::<TestOrder, TestReport, TestAdjustment>().full_sync();
    let policy: SpotFundsPolicy<FullSync, FullSync> =
        SpotFundsPolicy::new(None, builder.storage_builder());
    builder
        .pre_trade(policy)
        .build()
        .expect("engine must build")
}

/// Pre-seeds an account's slot with a non-overlapping `available` value
/// through the engine's own adjustment pipeline.
fn seed_balance_via_engine(
    engine: &crate::FullSyncEngine<TestOrder, TestReport, TestAdjustment>,
    account_id: AccountId,
    seeded_asset: Asset,
    amount: PositionSize,
) {
    let adjustment = TestAdjustment {
        asset: seeded_asset,
        balance: Some(AdjustmentAmount::Absolute(amount)),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    engine
        .apply_account_adjustment(account_id, &[adjustment])
        .expect("seed adjustment must succeed");
}

/// Asserts that `account_id` is recorded on the engine's [`BlockedAccounts`]:
/// any subsequent `start_pre_trade` for that account is rejected with the
/// engine's `AccountBlocked` reject carrying the original cause's policy
/// name and code.
fn assert_account_blocked_with_arithmetic_overflow(
    engine: &crate::FullSyncEngine<TestOrder, TestReport, TestAdjustment>,
    account_id: AccountId,
) {
    let probe = make_order(
        account_id,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Quantity(qty("0")),
        Some(px("1")),
    );
    let rejects = engine
        .start_pre_trade(probe)
        .expect_err("account must be blocked");
    assert!(
        rejects
            .iter()
            .any(|r| r.code == RejectCode::ArithmeticOverflow),
        "blocked-account reject must carry ArithmeticOverflow: {rejects:?}",
    );
}

/// Hold rollback overflow is reported through the engine's
/// [`BlockedAccounts`](crate::core::BlockedAccounts) sink instead of being
/// silently dropped.
#[test]
fn hold_rollback_overflow_blocks_account_via_engine() {
    use rust_decimal::Decimal;

    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let engine = build_engine_with_spot_funds_policy();
    let aapl = asset("AAPL");

    // Step 1: seed AAPL available = MAX - 50. Sell hold of qty=50 reserves
    // 50 of AAPL (charge = qty for Sell), leaving available = MAX - 100,
    // held = 50.
    let max_minus_fifty = PositionSize::new(Decimal::MAX - rust_decimal::Decimal::from(50));
    seed_balance_via_engine(&engine, acc, aapl.clone(), max_minus_fifty);

    let order = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Quantity(qty("50")),
        Some(px("1")),
    );
    let request = engine
        .start_pre_trade(order)
        .expect("start_pre_trade must succeed");
    let reservation = request.execute().expect("execute must reserve");

    // Step 2: drive AAPL available to MAX via an adjustment that
    // synchronously rewrites the slot. After this the slot is
    // available = MAX, held = 50.
    let bump = TestAdjustment {
        asset: aapl.clone(),
        balance: Some(AdjustmentAmount::Absolute(PositionSize::new(Decimal::MAX))),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    engine
        .apply_account_adjustment(acc, &[bump])
        .expect("bump must succeed");

    // Step 3: drop the reservation to trigger rollback. The hold's
    // `release(50)` closure computes `available + 50 = MAX + 50` which
    // overflows; the policy records the overflow on the engine's
    // blocked-accounts sink.
    drop(reservation);

    assert_account_blocked_with_arithmetic_overflow(&engine, acc);
}

/// Adjustment rollback overflow is reported through the engine's
/// [`BlockedAccounts`](crate::core::BlockedAccounts) sink instead of being
/// silently dropped.
///
/// Drives a two-element adjustment batch: the first element succeeds (writes
/// the slot synchronously and registers a delta-rollback closure), the second
/// element fails (causing the batch engine to roll back element 1 before
/// returning to the caller). Between the forward write and the rollback, the
/// slot is shifted to `available = MAX` by element 1 itself - achieved by
/// composing a Delta whose magnitude pushes the slot to its decimal extreme.
/// The rollback then subtracts the inverse delta, overflowing the lower bound.
#[test]
fn adjustment_rollback_overflow_blocks_account_via_engine() {
    use rust_decimal::Decimal;

    let acc = account(99224417);
    let engine = build_engine_with_spot_funds_policy();
    let usd = asset("USD");

    // Seed available = MIN + 100 so a Delta(+ MAX_-ish) cannot overflow
    // forward but the inverse Delta(- MAX_-ish) on rollback can underflow.
    // The forward direction: MIN+100 + (MAX/2) is finite; the inverse
    // direction: (MIN+100 + MAX/2) - MAX/2 ... that exactly inverts; no
    // overflow possible in single-threaded sequential rollback because the
    // arithmetic is associative.
    //
    // The realistic overflow path is purely concurrent: a rollback runs
    // after another mutation has shifted the slot independently. The
    // public batch engine API is synchronous, so we cannot trigger that
    // path through `apply_account_adjustment` alone.
    //
    // The wiring guarantee covered by `hold_rollback_overflow_blocks_account_via_engine`
    // applies symmetrically to adjustment rollback: both rollback closures
    // share the same `account_blocker` field and use the same
    // `record_rollback_overflow` helper. The test below asserts the same
    // wiring through a directly-triggered rollback: we issue a batch
    // whose second element causes the first's rollback to run, and verify
    // that even when rollback succeeds the engine's blocked-accounts state
    // remains untouched (the sink is only used on overflow, never on
    // ordinary rollback paths).
    seed_balance_via_engine(&engine, acc, usd.clone(), ps("1000"));

    // Two-element batch: first commits a Delta(+10); second fails because
    // the bound is violated (held_upper=0 but held still 0 stays valid -
    // we cause failure via a bound conflict on a freshly-touched field).
    let element_one = TestAdjustment {
        asset: usd.clone(),
        balance: Some(AdjustmentAmount::Delta(ps("10"))),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let element_two_fails = TestAdjustment {
        asset: usd.clone(),
        balance: Some(AdjustmentAmount::Delta(ps("1"))),
        balance_lower: None,
        balance_upper: Some(PositionSize::new(Decimal::from(5))),
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let outcome = engine.apply_account_adjustment(acc, &[element_one, element_two_fails]);
    assert!(outcome.is_err(), "batch with violating element must reject");

    // Rollback ran but did not overflow; the engine must NOT have blocked
    // the account in this happy-path rollback.
    let probe = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Quantity(qty("0")),
        Some(px("1")),
    );
    let probe_outcome = engine.start_pre_trade(probe);
    assert!(
        probe_outcome.is_ok(),
        "successful rollback must not block the account",
    );

    // To actually exercise the overflow path through public API we'd need
    // concurrent access to the slot between forward write and rollback,
    // which only a multi-threaded test can produce. The shared wiring is
    // already covered by the hold-rollback test above; here we document
    // the limitation explicitly: the adjustment-rollback closure uses the
    // same `record_rollback_overflow` helper, so an actual overflow on
    // that path would surface through the same sink. Adding a multi-
    // threaded reproducer is out of scope for this regression - the
    // single-thread engine API exposes no path to trigger the race.
}

// ═══════════════════════════════════════════════════════════════════════════
// Task B regression: LocalSync rollback overflow blocks the account
// ═══════════════════════════════════════════════════════════════════════════

/// Hold rollback overflow under [`LocalSync`](crate::core::LocalSync) is
/// reported through the engine's
/// [`BlockedAccounts`](crate::core::BlockedAccounts) instead of being silently
/// dropped.
///
/// The engine injects an [`AccountControl`](crate::core::AccountControl) into
/// [`PreTradeContext`](crate::pretrade::PreTradeContext) when dispatching
/// pre-trade checks. The rollback closure captures it so any overflow is
/// recorded on the engine's blocked-accounts storage even under `LocalSync`,
/// where storage is `!Send + !Sync`.
#[test]
fn hold_rollback_overflow_blocks_account_via_local_engine() {
    use rust_decimal::Decimal;

    let acc = account(99224418);
    let aapl_usd = instr("AAPL", "USD");
    let aapl = asset("AAPL");

    let builder = crate::Engine::builder::<TestOrder, TestReport, TestAdjustment>().no_sync();
    let policy: SpotFundsPolicy<crate::LocalSync, crate::LocalSync> =
        SpotFundsPolicy::new(None, builder.storage_builder());
    let engine: crate::LocalEngine<TestOrder, TestReport, TestAdjustment> = builder
        .pre_trade(policy)
        .build()
        .expect("engine must build");

    // Step 1: seed AAPL available = MAX - 50. Sell hold of qty=50 reserves
    // 50 of AAPL, leaving available = MAX - 100, held = 50.
    let max_minus_fifty = PositionSize::new(Decimal::MAX - rust_decimal::Decimal::from(50));
    let seed = TestAdjustment {
        asset: aapl.clone(),
        balance: Some(AdjustmentAmount::Absolute(max_minus_fifty)),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    engine
        .apply_account_adjustment(acc, &[seed])
        .expect("seed adjustment must succeed");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("50")),
        Some(px("1")),
    );
    let request = engine
        .start_pre_trade(order)
        .expect("start_pre_trade must succeed");
    let reservation = request.execute().expect("execute must reserve");

    // Step 2: drive AAPL available to MAX via an adjustment that
    // synchronously rewrites the slot. After this the slot is
    // available = MAX, held = 50.
    let bump = TestAdjustment {
        asset: aapl.clone(),
        balance: Some(AdjustmentAmount::Absolute(PositionSize::new(Decimal::MAX))),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    engine
        .apply_account_adjustment(acc, &[bump])
        .expect("bump must succeed");

    // Step 3: drop the reservation to trigger rollback. The hold's
    // `release(50)` closure computes `available + 50 = MAX + 50` which
    // overflows; the policy records the overflow on the engine's
    // blocked-accounts sink even though `LocalSync` storage is `!Send + !Sync`.
    drop(reservation);

    let probe = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Quantity(qty("0")),
        Some(px("1")),
    );
    let rejects = engine
        .start_pre_trade(probe)
        .expect_err("account must be blocked");
    assert!(
        rejects
            .iter()
            .any(|r| r.code == RejectCode::ArithmeticOverflow),
        "blocked-account reject must carry ArithmeticOverflow: {rejects:?}",
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Compile-time Send assertions
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn spot_funds_account_sync_is_send() {
    fn assert_send<T: Send>() {}
    assert_send::<SpotFundsPolicy<crate::AccountSync, FullSync>>();
}

// ═══════════════════════════════════════════════════════════════════════════
// Task B regression: AccountSync rollback overflow blocks the account
// ═══════════════════════════════════════════════════════════════════════════

/// Hold rollback overflow under the [`AccountSync`](crate::core::AccountSync)
/// storage flavor is reported through the engine's
/// [`BlockedAccounts`](crate::core::BlockedAccounts) facility.
/// `SpotFundsPolicy<AccountSync, FullSync>` is `Send` (the shared handles are
/// `IndexShared`, not bare `Arc`), exercising the `AccountSync` storage path
/// directly. The test constructs an [`AccountControl`](crate::core::AccountControl)
/// from the same `IndexShared<BlockedAccounts<IndexLocking>>` and passes it
/// via context, mirroring what the engine does at runtime.
#[test]
fn hold_rollback_overflow_blocks_account_with_account_sync_storage() {
    use crate::core::account_control::BlockedAccounts;
    use crate::core::{AccountBlockHandle, AccountControl};
    use crate::storage::{IndexLocking, LockingPolicyFactory, StorageBuilder};
    use crate::AccountKeyConstraint;
    use rust_decimal::Decimal;

    type AccountSyncFactory = IndexLocking<AccountKeyConstraint>;
    type AccountSyncPolicy = SpotFundsPolicy<crate::AccountSync, FullSync>;
    type Policy = dyn PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::AccountSync>;

    let acc = account(99224419);
    let aapl_usd = instr("AAPL", "USD");
    let aapl = asset("AAPL");

    let factory = IndexLocking::<AccountKeyConstraint>::default();
    let storage_builder = StorageBuilder::new(factory);
    let blocked = <AccountSyncFactory as LockingPolicyFactory>::new_shared(BlockedAccounts::new(
        &storage_builder,
    ));

    let policy: AccountSyncPolicy = SpotFundsPolicy::new(None, &storage_builder);

    let make_control = || AccountControl::new(AccountBlockHandle::from_inner(blocked.clone()), acc);

    // Seed AAPL available = MAX - 50.
    let mut seed_mutations = Mutations::new();
    let max_minus_fifty = PositionSize::new(Decimal::MAX - rust_decimal::Decimal::from(50));
    let seed = TestAdjustment {
        asset: aapl.clone(),
        balance: Some(AdjustmentAmount::Absolute(max_minus_fifty)),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    <Policy>::apply_account_adjustment(
        &policy,
        &AccountAdjustmentContext::new_test(make_control()),
        acc,
        &seed,
        &mut seed_mutations,
    )
    .expect("seed adjustment must succeed");
    seed_mutations.commit_all();

    // Reserve a Sell hold of qty=50: available = MAX - 100, held = 50, and a
    // hold-rollback closure is registered.
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("50")),
        Some(px("1")),
    );
    let mut hold_mutations = Mutations::new();
    <Policy>::perform_pre_trade_check(
        &policy,
        &PreTradeContext::new(Some(make_control())),
        &order,
        &mut hold_mutations,
    )
    .expect("pre-trade check must reserve");

    // Shift the slot to available = MAX so the hold's `release(50)` overflows
    // when the rollback closure runs.
    let mut bump_mutations = Mutations::new();
    let bump = TestAdjustment {
        asset: aapl.clone(),
        balance: Some(AdjustmentAmount::Absolute(PositionSize::new(Decimal::MAX))),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    <Policy>::apply_account_adjustment(
        &policy,
        &AccountAdjustmentContext::new_test(make_control()),
        acc,
        &bump,
        &mut bump_mutations,
    )
    .expect("bump adjustment must succeed");
    bump_mutations.commit_all();

    // Roll back the hold: `available + 50 = MAX + 50` overflows; the policy
    // records the overflow on the `IndexLocking`-backed blocked-accounts
    // store through the sealed adapter.
    hold_mutations.rollback_all();

    let probe = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Quantity(qty("0")),
        Some(px("1")),
    );
    let rejects = blocked
        .check(&probe, crate::pretrade::RejectScope::Order)
        .expect("account must be blocked");
    assert!(
        rejects
            .iter()
            .any(|r| r.code == RejectCode::ArithmeticOverflow),
        "blocked-account reject must carry ArithmeticOverflow: {rejects:?}",
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Signed two-leg reservation: side {Buy, Sell} x price sign {>0, =0, <0}
//   x trade_amount {Quantity, Volume}, each through
//   reserve -> partial fill -> final fill, and reserve -> cancel.
//
// Negative and zero prices are legitimate and never rejected for their sign.
// A buy at a negative price reserves nothing (pure inflow); a sell at a
// negative price reserves BOTH the underlying and the settlement leg.
// ═══════════════════════════════════════════════════════════════════════════

/// Reads the full pre-trade result so a test can assert the lock prices and
/// per-leg outcome entries the policy emits.
fn pre_trade_full(
    policy: &TestPolicy,
    order: &TestOrder,
    mutations: &mut Mutations,
) -> Result<crate::pretrade::PolicyPreTradeResult, crate::pretrade::Rejects> {
    <TestPolicy as PreTradePolicy<TestOrder, TestReport, TestAdjustment, crate::core::FullSync>>::perform_pre_trade_check(
        policy,
        &PreTradeContext::new(None),
        order,
        mutations,
    )
    .map(|opt| opt.expect("pre-trade must produce a result"))
}

fn maybe_holdings(policy: &TestPolicy, acc: AccountId, asset_code: &str) -> Option<Holdings> {
    holdings_of(policy, acc, &asset(asset_code))
}

/// Asserts `(available, held)` for an asset, treating a pruned (absent) slot as
/// all-zero.
fn assert_balance(policy: &TestPolicy, acc: AccountId, asset_code: &str, avail: &str, held: &str) {
    let h = maybe_holdings(policy, acc, asset_code).unwrap_or_else(Holdings::zero);
    assert_eq!(
        h.available(),
        ps(avail),
        "{asset_code} available mismatch (held {})",
        h.held()
    );
    assert_eq!(
        h.held(),
        ps(held),
        "{asset_code} held mismatch (available {})",
        h.available()
    );
}

// ── Buy Quantity @ price = 0 ──────────────────────────────────────────────

#[test]
fn buy_qty_zero_price_reserves_nothing_and_settles() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // No USD seeded: a zero-price buy owes no settlement, so the gate passes
    // even with no funds.
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("0")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert!(
        result.account_adjustments.is_empty(),
        "zero-reservation buy emits no leg adjustments",
    );
    assert_eq!(result.lock_prices.as_slice(), &[px("0")]);
    assert!(maybe_holdings(&policy, acc, "USD").is_none());

    // Partial then final fill at price 0: underlying delivered for free,
    // settlement untouched.
    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("0"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("0"),
        )])),
    );
    assert!(report_blocks(&policy, &partial).is_empty());
    assert_balance(&policy, acc, "AAPL", "4", "0");
    assert!(maybe_holdings(&policy, acc, "USD").is_none());

    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("0"),
            quantity: qty("6"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("0"),
        )])),
    );
    assert!(report_blocks(&policy, &final_fill).is_empty());
    assert_balance(&policy, acc, "AAPL", "10", "0");
    assert!(maybe_holdings(&policy, acc, "USD").is_none());
}

#[test]
fn buy_qty_zero_price_cancel_releases_nothing() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("0")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();

    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        None,
        qty("10"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("0"),
        )])),
    );
    assert!(report_blocks(&policy, &cancel).is_empty());
    assert!(maybe_holdings(&policy, acc, "USD").is_none());
}

// ── Buy Quantity @ price < 0 ──────────────────────────────────────────────

#[test]
fn buy_qty_negative_price_reserves_nothing_and_receives_cash_on_fill() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Negative price: a buy is a pure inflow (receive asset + cash), so it
    // reserves nothing and needs no funds.
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert!(result.account_adjustments.is_empty());
    assert_eq!(result.lock_prices.as_slice(), &[px("-50")]);
    assert!(maybe_holdings(&policy, acc, "USD").is_none());

    // Fill 4 @ -50: receive 4 AAPL and 4*50 = 200 USD.
    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("-50"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &partial).is_empty());
    assert_balance(&policy, acc, "AAPL", "4", "0");
    assert_balance(&policy, acc, "USD", "200", "0");

    // Final fill 6 @ -50: receive 6 AAPL and 6*50 = 300 USD.
    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("-50"),
            quantity: qty("6"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &final_fill).is_empty());
    assert_balance(&policy, acc, "AAPL", "10", "0");
    assert_balance(&policy, acc, "USD", "500", "0");
}

#[test]
fn buy_qty_negative_price_cancel_releases_nothing() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();

    // Fill 4 @ -50 then cancel the unfilled 6: nothing was reserved, so the
    // cancel releases nothing and leaves only the received inflow.
    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("-50"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    report_blocks(&policy, &partial);
    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        None,
        qty("6"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &cancel).is_empty());
    assert_balance(&policy, acc, "AAPL", "4", "0");
    assert_balance(&policy, acc, "USD", "200", "0");
}

// ── Buy Volume @ price = 0 / < 0 ──────────────────────────────────────────

#[test]
fn buy_volume_zero_price_reserves_nothing() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Volume(vol("2000")),
        Some(px("0")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert!(
        result.account_adjustments.is_empty(),
        "zero-price volume buy reserves no settlement (no stuck held)",
    );
    assert!(maybe_holdings(&policy, acc, "USD").is_none());
}

#[test]
fn buy_volume_negative_price_reserves_nothing() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Volume(vol("2000")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert!(result.account_adjustments.is_empty());
    assert!(maybe_holdings(&policy, acc, "USD").is_none());
}

// ── Sell Quantity @ price = 0 ─────────────────────────────────────────────

#[test]
fn sell_qty_zero_price_reserves_only_underlying() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("0")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    // Only the underlying leg is reserved; no settlement leg, no lock price.
    assert_eq!(result.account_adjustments.len(), 1);
    assert!(result.lock_prices.is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "10");

    // Fill 4 @ 0: gives 4 AAPL, receives 0 USD.
    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        Some(Trade {
            price: px("0"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        None,
    );
    assert!(report_blocks(&policy, &partial).is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "6");
    assert!(maybe_holdings(&policy, acc, "USD").is_none());

    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("0"),
            quantity: qty("6"),
        }),
        qty("0"),
        true,
        None,
    );
    assert!(report_blocks(&policy, &final_fill).is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "0");
}

#[test]
fn sell_qty_zero_price_cancel_releases_underlying() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("0")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();

    let cancel = make_report(acc, aapl_usd, Side::Sell, None, qty("10"), true, None);
    assert!(report_blocks(&policy, &cancel).is_empty());
    assert_balance(&policy, acc, "AAPL", "10", "0");
}

// ── Sell Quantity @ price < 0 (TWO legs) ──────────────────────────────────

#[test]
fn sell_qty_negative_price_reserves_both_legs_and_settles() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");
    seed(&policy, acc, asset("USD"), "1000");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    // BOTH legs reserved: 10 AAPL underlying and 10*50 = 500 USD settlement.
    assert_eq!(
        result.account_adjustments.len(),
        2,
        "sell at negative price reserves both underlying and settlement legs",
    );
    assert_eq!(result.lock_prices.as_slice(), &[px("-50")]);
    assert_balance(&policy, acc, "AAPL", "0", "10");
    assert_balance(&policy, acc, "USD", "500", "500");

    // Fill 4 @ -50: give 4 AAPL, pay 4*50 = 200 USD (consumed from settlement
    // held).
    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        Some(Trade {
            price: px("-50"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &partial).is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "6");
    assert_balance(&policy, acc, "USD", "500", "300");

    // Final fill 6 @ -50: both legs fully consumed; held returns to zero.
    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("-50"),
            quantity: qty("6"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &final_fill).is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "0");
    // Paid 500 USD total for disposing 10 AAPL at -50.
    assert_balance(&policy, acc, "USD", "500", "0");
}

#[test]
fn sell_qty_negative_price_cancel_releases_both_legs() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");
    seed(&policy, acc, asset("USD"), "1000");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();

    // Fill 4 @ -50 then cancel the unfilled 6: both legs release their
    // remainder; held returns to zero on both assets.
    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        Some(Trade {
            price: px("-50"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    report_blocks(&policy, &partial);
    let cancel = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        None,
        qty("6"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &cancel).is_empty());
    // AAPL: 6 unfilled released back to available.
    assert_balance(&policy, acc, "AAPL", "6", "0");
    // USD: reserved 500, consumed 200 on fill, released 300 on cancel; net
    // paid 200, so available = 1000 - 200 = 800.
    assert_balance(&policy, acc, "USD", "800", "0");
}

// ── Sell Volume @ price < 0 (TWO legs) ────────────────────────────────────

#[test]
fn sell_volume_negative_price_reserves_both_legs() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Volume 2000 @ -50 -> quantity = 2000 / 50 = 40 AAPL; settlement leg =
    // 40 * 50 = 2000 USD.
    seed(&policy, acc, asset("AAPL"), "40");
    seed(&policy, acc, asset("USD"), "5000");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Volume(vol("2000")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert_eq!(result.account_adjustments.len(), 2);
    assert_eq!(result.lock_prices.as_slice(), &[px("-50")]);
    assert_balance(&policy, acc, "AAPL", "0", "40");
    assert_balance(&policy, acc, "USD", "3000", "2000");

    // Full fill 40 @ -50: both legs consumed exactly; held returns to zero.
    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("-50"),
            quantity: qty("40"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("-50"),
        )])),
    );
    assert!(report_blocks(&policy, &final_fill).is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "0");
    assert_balance(&policy, acc, "USD", "3000", "0");
}

#[test]
fn sell_volume_zero_price_calc_failure_not_sign_reject() {
    // A Volume sell at price 0 cannot be sized (quantity = volume / 0 is
    // undefined). This is a calculation failure, NOT a price-sign rejection:
    // the engine still treats zero/negative prices as legitimate everywhere a
    // quantity is determinable.
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "100");
    let order = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Volume(vol("1000")),
        Some(px("0")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let err = pre_trade_check(&policy, &order, &mut mutations).unwrap_err();
    assert!(
        err.iter()
            .any(|r| r.code == RejectCode::OrderValueCalculationFailed),
        "zero-price volume sell is a sizing calc failure: {err:?}",
    );
    assert!(mutations.is_empty());
    assert_balance(&policy, acc, "AAPL", "100", "0");
}

// ── Buy/Sell at positive price: held returns to pre-reservation level ──────

#[test]
fn buy_qty_positive_price_held_returns_to_zero_after_full_settlement() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert_balance(&policy, acc, "USD", "8000", "2000");

    let partial = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("4"),
        }),
        qty("6"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    report_blocks(&policy, &partial);
    assert_balance(&policy, acc, "USD", "8000", "1200");

    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("200"),
            quantity: qty("6"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    report_blocks(&policy, &final_fill);
    // held back to its pre-reservation level (0); paid 2000 for 10 AAPL.
    assert_balance(&policy, acc, "USD", "8000", "0");
    assert_balance(&policy, acc, "AAPL", "10", "0");
}

#[test]
fn sell_volume_positive_price_reserves_only_underlying_and_settles() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Volume 2000 @ 200 -> quantity = 10 AAPL; settlement leg = 0 (sell
    // receives cash, owes none).
    seed(&policy, acc, asset("AAPL"), "10");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Volume(vol("2000")),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let result = pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    mutations.commit_all();
    assert_eq!(result.account_adjustments.len(), 1);
    assert!(result.lock_prices.is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "10");

    let final_fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("200"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        None,
    );
    assert!(report_blocks(&policy, &final_fill).is_empty());
    assert_balance(&policy, acc, "AAPL", "0", "0");
    assert_balance(&policy, acc, "USD", "2000", "0");
}

// ── Two-leg rollback and partial-reservation atomicity ────────────────────

#[test]
fn sell_negative_price_rollback_restores_both_legs() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("AAPL"), "10");
    seed(&policy, acc, asset("USD"), "1000");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("-50")),
    );
    let mut mutations = Mutations::with_capacity(2);
    pre_trade_full(&policy, &order, &mut mutations).expect("must pass");
    // Both legs held synchronously.
    assert_balance(&policy, acc, "AAPL", "0", "10");
    assert_balance(&policy, acc, "USD", "500", "500");

    // Rolling back the reservation must undo BOTH legs back to their
    // pre-reservation levels.
    mutations.rollback_all();
    assert_balance(&policy, acc, "AAPL", "10", "0");
    assert_balance(&policy, acc, "USD", "1000", "0");
}

#[test]
fn sell_negative_price_settlement_insufficient_rolls_back_underlying_leg() {
    // The underlying leg holds first; if the settlement leg then fails for
    // insufficient funds, the engine's pre-trade pipeline rolls back the
    // already-held underlying leg so no partial reservation escapes.
    let acc = account(99224418);
    let aapl_usd = instr("AAPL", "USD");
    let engine = build_engine_with_spot_funds_policy();
    seed_balance_via_engine(&engine, acc, asset("AAPL"), ps("10"));
    // Only 100 USD: the settlement leg needs 10*50 = 500, so it must reject.
    seed_balance_via_engine(&engine, acc, asset("USD"), ps("100"));

    let order = make_order(
        acc,
        aapl_usd,
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("-50")),
    );
    let rejects = match engine.execute_pre_trade(order) {
        Ok(_) => panic!("settlement leg must reject for insufficient funds"),
        Err(rejects) => rejects,
    };
    assert!(
        rejects
            .iter()
            .any(|r| r.code == RejectCode::InsufficientFunds),
        "settlement leg must reject with InsufficientFunds: {rejects:?}",
    );

    // Both legs back to their seeded levels: the underlying hold was rolled
    // back, the settlement hold never committed.
    let probe = make_order(
        acc,
        instr("AAPL", "USD"),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("200")),
    );
    let mut reservation = engine
        .execute_pre_trade(probe)
        .expect("a positive-price sell of the full 10 AAPL must still fit");
    reservation.rollback();
}

// ═══════════════════════════════════════════════════════════════════════════
// Stage 4: post-trade signed price
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn buy_fill_zero_price_nonzero_qty_consumes_held_by_lock_price() {
    // With a zero fill price the old abs-based guard skipped held consumption,
    // leaving the reservation stale. The fixed guard checks qty != 0 instead.
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("2")),
        Some(px("100")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // USD: available=9800, held=200

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("0"),
            quantity: qty("2"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let blocks = report_blocks(&policy, &fill);
    assert!(blocks.is_empty());

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    // lock_consume = 100*2 = 200 consumed from held;
    // savings = 200 - outflow(0) = 200 returned to available
    assert_eq!(usd.held(), ps("0"), "held must be fully consumed");
    assert_eq!(
        usd.available(),
        ps("10000"),
        "full amount returned as savings"
    );

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("AAPL credited");
    // inflow = qty = 2 (zero-price fill still delivers the underlying)
    assert_eq!(aapl.available(), ps("2"));
}

#[test]
fn buy_fill_negative_trade_price_uses_signed_not_abs() {
    // Negative fill price: outflow = -50*2 = -100 (signed, not abs=100).
    // lock_consume = 100*2 = 200; savings = 200 - (-100) = 300.
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("2")),
        Some(px("100")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    mutations.commit_all();
    // USD: available=9800, held=200

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("-50"),
            quantity: qty("2"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let blocks = report_blocks(&policy, &fill);
    assert!(blocks.is_empty());

    let usd = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    // held: 200 -> 0 (lock_consume=200 consumed)
    // available: 9800 + savings(300) = 10100
    assert_eq!(usd.held(), ps("0"));
    assert_eq!(
        usd.available(),
        ps("10100"),
        "signed savings = lock(200) - notional(-100) = 300 credited to available",
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Slippage cascade through the pre-trade entry point
// ═══════════════════════════════════════════════════════════════════════════

/// Builds a `PreTradeContext<FullLocking>` where `account_id` is registered
/// in `group_id`, so `ctx.group()` returns `Some(group_id)` during the
/// pre-trade check.
fn ctx_with_group(
    account_id: AccountId,
    group_id: crate::param::AccountGroupId,
) -> crate::pretrade::PreTradeContext<crate::storage::FullLocking> {
    use crate::core::{AccountGroups, AccountGroupsHandle};
    use crate::storage::{FullLocking, LockingPolicyFactory, StorageBuilder};
    let sb = StorageBuilder::new(FullLocking);
    let groups = AccountGroups::new(&sb);
    groups
        .register_group(&[account_id], group_id)
        .expect("registration must succeed");
    let handle = AccountGroupsHandle::from_inner(FullLocking::new_shared(groups));
    crate::pretrade::PreTradeContext::with_groups(None, handle, Some(account_id))
}

// ── group-tier override selects correct slippage for buy ──────────────────

#[test]
fn buy_market_group_override_reserves_group_slippage_not_global() {
    // mark=100, global=0 bps, group=2000 bps; account is in the group.
    // Expected: effective = 100 * (1 + 0.20) = 120; held = 10 * 120 = 1200.
    // Without the group override global=0 would give held = 10 * 100 = 1000.
    let acc = account(99224416);
    let grp = crate::param::AccountGroupId::from_u32(5).expect("valid group id");
    let aapl_usd = instr("AAPL", "USD");

    let b = engine_builder();
    let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
    let id = svc
        .register(aapl_usd.clone())
        .expect("register must succeed");
    svc.push(id, Quote::new().with_mark(px("100")))
        .expect("push must succeed");

    // Account-scoped override at a different account (must not fire) and
    // group-scoped override at (instrument, group).
    let overrides = [
        (
            SpotFundsOverrideTarget::InstrumentAccount(id, account(9999)),
            SpotFundsOverride {
                slippage_bps: Some(5000),
            },
        ),
        (
            SpotFundsOverrideTarget::InstrumentAccountGroup(id, grp),
            SpotFundsOverride {
                slippage_bps: Some(2000),
            },
        ),
    ];
    let bundle = SpotFundsMarketData::new(
        Arc::clone(&svc),
        0, // global = 0 bps
        SpotFundsPricingSource::Mark,
        overrides,
    )
    .expect("bundle must build");
    let policy = SpotFundsPolicy::new(Some(bundle), b.storage_builder());
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None, // market order
    );
    let mut mutations = Mutations::with_capacity(1);

    // Use a context that maps `acc` -> `grp`, so the group tier fires.
    let ctx = ctx_with_group(acc, grp);
    <TestPolicy as crate::pretrade::PreTradePolicy<
        TestOrder,
        TestReport,
        TestAdjustment,
        crate::core::FullSync,
    >>::perform_pre_trade_check(&policy, &ctx, &order, &mut mutations)
    .expect("must succeed");

    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    // Group tier: 2000 bps -> effective = 120 -> held = 10 * 120 = 1200.
    assert_eq!(
        h.held(),
        ps("1200"),
        "group override (2000 bps) must be used, not global (0 bps)",
    );
    assert_eq!(h.available(), ps("8800"));
}