openpit 0.5.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
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
// 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://openpit.dev 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, Pnl, PositionSize, Price, Quantity, Side, Trade,
    TradeAmount, Volume,
};
use crate::pretrade::{
    holdings::Holdings, PreTradeContext, PreTradeLock, PreTradePolicy, RejectCode,
    DEFAULT_POLICY_GROUP_ID,
};
use crate::{
    FullSync, HasAccountAdjustmentBalance, HasAccountAdjustmentBalanceAverageEntryPrice,
    HasAccountAdjustmentBalanceLowerBound, HasAccountAdjustmentBalanceRealizedPnl,
    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_average_entry_price: Option<Price>,
    balance_realized_pnl: Option<Pnl>,
    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 HasAccountAdjustmentBalanceAverageEntryPrice for TestAdjustment {
    fn balance_average_entry_price(&self) -> Result<Option<Price>, RequestFieldAccessError> {
        Ok(self.balance_average_entry_price)
    }
}

impl HasAccountAdjustmentBalanceRealizedPnl for TestAdjustment {
    fn balance_realized_pnl(&self) -> Result<Option<Pnl>, RequestFieldAccessError> {
        Ok(self.balance_realized_pnl)
    }
}

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 pnl_value(s: &str) -> Pnl {
    Pnl::from_str(s).expect("valid pnl")
}

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()
}

/// Default-cascade settings: global `slip_bps`, `Mark` pricing, no overrides.
fn settings(slip_bps: u16) -> SpotFundsSettings {
    SpotFundsSettings::new(slip_bps, SpotFundsPricingSource::Mark, std::iter::empty())
        .expect("settings must build")
}

/// Builds a `SpotFundsPolicy` with no market-order support.
fn build_policy(_mark: Option<()>, _slip_bps: Option<u16>) -> TestPolicy {
    let b = engine_builder();
    SpotFundsPolicy::new(settings(0), 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));
    SpotFundsPolicy::new(settings(slip_bps), 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_average_entry_price: None,
        balance_realized_pnl: None,
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    }
}

/// Builds a balance adjustment carrying an average entry price.
fn adj_with_avg(
    asset: Asset,
    balance: Option<AdjustmentAmount>,
    average_entry_price: Option<Price>,
) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance,
        balance_average_entry_price: average_entry_price,
        balance_realized_pnl: None,
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    }
}

/// Builds a balance adjustment that force-sets the slot's realized PnL.
fn adj_with_realized_pnl(
    asset: Asset,
    balance: Option<AdjustmentAmount>,
    realized_pnl: Option<Pnl>,
) -> TestAdjustment {
    TestAdjustment {
        asset,
        balance,
        balance_average_entry_price: None,
        balance_realized_pnl: realized_pnl,
        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_average_entry_price: None,
        balance_realized_pnl: None,
        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_average_entry_price: None,
        balance_realized_pnl: 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_average_entry_price: None,
        balance_realized_pnl: 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_average_entry_price: None,
        balance_realized_pnl: None,
        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 dry_run_check(
    policy: &TestPolicy,
    order: &TestOrder,
) -> Result<Option<crate::pretrade::PolicyPreTradeResult>, crate::pretrade::Rejects> {
    let mut mutations = Mutations::new();
    let result = <TestPolicy as PreTradePolicy<
        TestOrder,
        TestReport,
        TestAdjustment,
        crate::core::FullSync,
    >>::perform_pre_trade_check_dry_run(
        policy, &PreTradeContext::new(None), order, &mut mutations
    );
    // A dry-run must never register a mutation.
    assert!(mutations.is_empty(), "dry-run must push no mutations");
    result
}

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,
        &post_trade_ctx(report),
        report,
    )
    .map(|r| r.account_blocks)
    .unwrap_or_default()
}

fn post_trade_ctx(
    report: &TestReport,
) -> crate::pretrade::PostTradeContext<crate::storage::FullLocking> {
    crate::pretrade::PostTradeContext::with_account_currency(
        report.account_id,
        report.instrument.settlement_asset().clone(),
    )
}

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

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

// ═══════════════════════════════════════════════════════════════════════════
// SpotFundsSettings construction + validation
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn settings_new_rejects_out_of_range_global_slippage() {
    let result = SpotFundsSettings::new(10_001, SpotFundsPricingSource::Mark, std::iter::empty());
    assert_eq!(
        result.err(),
        Some(SpotFundsConfigError::SlippageOutOfRange { bps: 10_001 })
    );
}

#[test]
fn settings_new_accepts_max_slippage_boundary() {
    // 10_000 bps is the inclusive upper bound and must build.
    assert!(
        SpotFundsSettings::new(10_000, SpotFundsPricingSource::Mark, std::iter::empty()).is_ok()
    );
}

#[test]
fn settings_set_global_slippage_bps_boundary_and_reject() {
    let mut s = settings(0);
    // Boundary value succeeds.
    assert!(s.set_global_slippage_bps(10_000).is_ok());
    // Above the bound is rejected and the prior value is retained.
    assert_eq!(
        s.set_global_slippage_bps(10_001).err(),
        Some(SpotFundsConfigError::SlippageOutOfRange { bps: 10_001 })
    );
    // The 10_000 bps value is still in effect: a sell at 100% slippage prices
    // to zero and is uncomputable, whereas a fresh 0-bps default would not.
    let (svc, id) = {
        let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
        let id = svc
            .register(instr("AAPL", "USD"))
            .expect("register must succeed");
        svc.push(id, Quote::new().with_mark(px("100")))
            .expect("push must succeed");
        (svc, id)
    };
    let md = SpotFundsMarketData::<FullSync>::new(Arc::clone(&svc));
    let quote = md.quote(id, account(7), &None).expect("quote present");
    assert!(s
        .effective_sell_price(&quote, id, account(7), &None)
        .is_err());
}

#[test]
fn settings_set_override_above_bound_is_rejected() {
    let mut s = settings(0);
    let id = {
        let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
        svc.register(instr("AAPL", "USD"))
            .expect("register must succeed")
    };
    assert_eq!(
        s.set_override(
            SpotFundsOverrideTarget::Instrument(id),
            SpotFundsOverride {
                slippage_bps: Some(10_001),
            },
        )
        .err(),
        Some(SpotFundsConfigError::SlippageOutOfRange { bps: 10_001 })
    );
}

#[test]
fn settings_set_override_then_clear_falls_back_to_global() {
    // Global 0 bps; set an instrument override at 1000 bps, observe it, then
    // clear it (None) and observe the cascade fall back to the global tier.
    let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
    let id = svc
        .register(instr("AAPL", "USD"))
        .expect("register must succeed");
    svc.push(id, Quote::new().with_mark(px("100")))
        .expect("push must succeed");
    let md = SpotFundsMarketData::<FullSync>::new(Arc::clone(&svc));
    let quote = md.quote(id, account(7), &None).expect("quote present");

    let mut s = settings(0);
    s.set_override(
        SpotFundsOverrideTarget::Instrument(id),
        SpotFundsOverride {
            slippage_bps: Some(1000),
        },
    )
    .expect("override must set");
    // 100 * (1 + 0.10) = 110.
    assert_eq!(
        s.effective_buy_price(&quote, id, account(7), &None),
        Ok(px("110"))
    );

    s.set_override(
        SpotFundsOverrideTarget::Instrument(id),
        SpotFundsOverride { slippage_bps: None },
    )
    .expect("override must clear");
    // Back to global 0 bps: 100 * 1.00 = 100.
    assert_eq!(
        s.effective_buy_price(&quote, id, account(7), &None),
        Ok(px("100"))
    );
}

#[test]
fn settings_set_pricing_source_switches_quote_field() {
    // Mark unset, ask = 100: Mark source has no base (QuoteUnavailable),
    // BookTop source reads `ask` and prices the buy.
    let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
    let id = svc
        .register(instr("AAPL", "USD"))
        .expect("register must succeed");
    svc.push(id, Quote::new().with_ask(px("100")))
        .expect("push must succeed");
    let md = SpotFundsMarketData::<FullSync>::new(Arc::clone(&svc));
    let quote = md.quote(id, account(7), &None).expect("quote present");

    let mut s = settings(0);
    assert!(s
        .effective_buy_price(&quote, id, account(7), &None)
        .is_err());
    s.set_pricing_source(SpotFundsPricingSource::BookTop);
    assert_eq!(
        s.effective_buy_price(&quote, id, account(7), &None),
        Ok(px("100"))
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Policy group tag + ConfigurablePolicy
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn with_policy_group_id_records_tag_observed_by_policy() {
    use crate::pretrade::PreTradePolicy;
    let id = DEFAULT_POLICY_GROUP_ID;
    let policy = build_policy(None, None);
    assert_eq!(
        <TestPolicy as PreTradePolicy<
            TestOrder,
            TestReport,
            TestAdjustment,
            crate::core::FullSync,
        >>::policy_group_id(&policy),
        id
    );

    let tag = crate::pretrade::PolicyGroupId::new(7);
    let tagged = build_policy(None, None).with_policy_group_id(tag);
    assert_eq!(
        <TestPolicy as PreTradePolicy<
            TestOrder,
            TestReport,
            TestAdjustment,
            crate::core::FullSync,
        >>::policy_group_id(&tagged),
        tag
    );
}

#[test]
fn settings_cell_clone_shares_state_with_running_policy() {
    use crate::pretrade::ConfigurablePolicy;
    use crate::storage::ConfigCell;

    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    // Start at global 0 bps so a market buy of qty 10 @ mark 100 reserves 1000.
    let policy = build_policy_with_market_data(aapl_usd.clone(), px("100"), 0);
    seed(&policy, acc, asset("USD"), "10000");

    // Publish a new global slippage (2000 bps) through the registry-side clone;
    // the running policy must observe it on its next hot-path read.
    let cell =
        <TestPolicy as ConfigurablePolicy<crate::storage::FullLocking>>::settings_cell(&policy);
    cell.update(|s| s.set_global_slippage_bps(2000))
        .expect("update must publish");

    // effective = 100 * (1 + 0.20) = 120; held = 10 * 120 = 1200.
    let order = make_order(
        acc,
        aapl_usd,
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut mutations).expect("must succeed");
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.held(), ps("1200"));
    assert_eq!(h.available(), ps("8800"));
}

// ═══════════════════════════════════════════════════════════════════════════
// 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 dry-run ─────────────────────────────────────────────────────────────

#[test]
fn dry_run_buy_reports_outcome_and_leaves_holdings_untouched() {
    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 outcome = dry_run_check(&policy, &order)
        .expect("dry-run must pass")
        .expect("dry-run must report an outcome");

    // The would-be settlement leg matches a real reservation: held +2000 to
    // absolute 2000, balance -2000 to absolute 8000, lock price 200.
    assert_eq!(outcome.account_adjustments.len(), 1);
    let entry = &outcome.account_adjustments[0];
    assert_eq!(entry.asset, asset("USD"));
    let held = entry.held.expect("held outcome present");
    assert_eq!(held.delta, ps("2000"));
    assert_eq!(held.absolute, ps("2000"));
    let balance = entry.balance.expect("balance outcome present");
    assert_eq!(balance.delta, ps("-2000"));
    assert_eq!(balance.absolute, ps("8000"));
    assert_eq!(outcome.lock_prices.to_vec(), vec![px("200")]);

    // Holdings are untouched by the dry-run.
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("10000"));
    assert_eq!(h.held(), ps("0"));
}

#[test]
fn dry_run_buy_matches_real_reservation_holdings_then_leaves_them_for_the_real_call() {
    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")),
    );

    // Two dry-runs in a row must not move state.
    dry_run_check(&policy, &order).expect("first dry-run must pass");
    dry_run_check(&policy, &order).expect("second dry-run must pass");
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("10000"));
    assert_eq!(h.held(), ps("0"));

    // A real reservation afterwards still reserves the full amount: the
    // dry-runs consumed nothing.
    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("2000"));
    assert_eq!(h.available(), ps("8000"));
}

#[test]
fn dry_run_buy_insufficient_reports_same_reject_and_leaves_holdings_untouched() {
    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 rejects = dry_run_check(&policy, &order).expect_err("dry-run must reject");
    assert_eq!(rejects[0].code, RejectCode::InsufficientFunds);

    // Repeated rejecting dry-runs must not create or mutate holdings.
    dry_run_check(&policy, &order).expect_err("dry-run must reject again");
    let h = holdings_of(&policy, acc, &asset("USD")).expect("must exist");
    assert_eq!(h.available(), ps("1000"));
    assert_eq!(h.held(), ps("0"));
}

#[test]
fn dry_run_sell_reports_underlying_hold_and_leaves_holdings_untouched() {
    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")),
        Some(px("200")),
    );

    let outcome = dry_run_check(&policy, &order)
        .expect("dry-run must pass")
        .expect("dry-run must report an outcome");
    assert_eq!(outcome.account_adjustments.len(), 1);
    let entry = &outcome.account_adjustments[0];
    assert_eq!(entry.asset, asset("AAPL"));
    let held = entry.held.expect("held outcome present");
    assert_eq!(held.delta, ps("4"));
    assert_eq!(held.absolute, ps("4"));

    let h = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(h.available(), ps("10"));
    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 HasAccountAdjustmentBalanceAverageEntryPrice for NoBalanceAsset {
        fn balance_average_entry_price(&self) -> Result<Option<Price>, RequestFieldAccessError> {
            Ok(None)
        }
    }
    impl HasAccountAdjustmentBalanceRealizedPnl for NoBalanceAsset {
        fn balance_realized_pnl(&self) -> Result<Option<Pnl>, 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_adjustment_result(
    policy: &TestPolicy,
    account_id: AccountId,
    adjustment: &TestAdjustment,
    mutations: &mut Mutations,
) -> Result<Vec<crate::AccountOutcomeEntry>, 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,
    )
}

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

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

fn run_report_without_account_currency(
    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, &post_trade_ctx(&fill), &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(settings(0), 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_average_entry_price: None,
        balance_realized_pnl: None,
        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_average_entry_price: None,
        balance_realized_pnl: None,
        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_average_entry_price: None,
        balance_realized_pnl: None,
        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_average_entry_price: None,
        balance_realized_pnl: None,
        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(settings(0), 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_average_entry_price: None,
        balance_realized_pnl: None,
        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_average_entry_price: None,
        balance_realized_pnl: None,
        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 groups = crate::core::account_groups::AccountGroups::new(&storage_builder);

    let policy: AccountSyncPolicy = SpotFundsPolicy::new(settings(0), 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_average_entry_price: None,
        balance_realized_pnl: None,
        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_average_entry_price: None,
        balance_realized_pnl: None,
        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(&groups, &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 result = run_report(&policy, &fill);
    assert!(result.account_blocks.is_empty());

    // Opening AAPL from flat at a zero fill price seeds the average at 0 and
    // realizes nothing; the settlement (USD) leg never carries either.
    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("0")));
    assert!(aapl_entry.entry.realized_pnl.is_none());

    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"));
    assert_eq!(aapl.avg_entry_price(), Some(px("0")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[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 result = run_report(&policy, &fill);
    assert!(result.account_blocks.is_empty());

    // Opening AAPL from flat at a negative fill price seeds the average at that
    // negative price and realizes nothing.
    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("-50")));
    assert!(aapl_entry.entry.realized_pnl.is_none());

    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",
    );

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("AAPL credited");
    assert_eq!(aapl.avg_entry_price(), Some(px("-50")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

// ═══════════════════════════════════════════════════════════════════════════
// 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 settings = SpotFundsSettings::new(
        0, // global = 0 bps
        SpotFundsPricingSource::Mark,
        overrides,
    )
    .expect("settings must build");
    let bundle = SpotFundsMarketData::new(Arc::clone(&svc));
    let policy = SpotFundsPolicy::new(settings, 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"));
}

// ── average entry price / realized PnL ─────────────────────────────────────

/// Seeds a balance with an average entry price through the adjustment pipeline.
fn seed_with_avg(
    policy: &TestPolicy,
    account_id: AccountId,
    asset: Asset,
    amount: &str,
    avg: Price,
) {
    let adjustment = TestAdjustment {
        asset,
        balance: Some(AdjustmentAmount::Absolute(ps(amount))),
        balance_average_entry_price: Some(avg),
        balance_realized_pnl: Some(Pnl::ZERO),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    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();
}

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

    let adjustment = adj_with_avg(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(px("150")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome.len(), 1);
    let entry = &outcome[0];
    assert_eq!(entry.average_entry_price, Some(px("150")));
    assert!(entry.realized_pnl.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("150")));
    assert_eq!(aapl.realized_pnl(), None);
}

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

    let adjustment = adj_with_avg(asset("AAPL"), None, Some(px("150")));
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome.len(), 1);
    assert!(outcome[0].balance.is_none());
    assert_eq!(outcome[0].average_entry_price, Some(px("150")));
    assert!(outcome[0].realized_pnl.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.available(), ps("10"));
    assert_eq!(aapl.avg_entry_price(), Some(px("150")));
}

#[test]
fn balance_adjustment_without_avg_leaves_prior_average() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("150"));

    // A later balance-only adjustment (no avg) must not wipe the average.
    let adjustment = adj(asset("AAPL"), Some(AdjustmentAmount::Delta(ps("5"))));
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome[0].average_entry_price, Some(px("150")));
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("150")));
}

#[test]
fn balance_adjustment_to_flat_clears_average_and_prunes_zero_slot() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("150"));

    let adjustment = adj(asset("AAPL"), Some(AdjustmentAmount::Absolute(ps("0"))));
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome.len(), 1);
    assert!(outcome[0].average_entry_price.is_none());
    assert!(
        holdings_of(&policy, acc, &asset("AAPL")).is_none(),
        "flat zero-PnL slot must not survive only because of a stale average",
    );
}

#[test]
fn held_adjustment_to_net_flat_clears_average() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("150"));

    let adjustment = held_adj(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("-10"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome.len(), 1);
    assert!(outcome[0].average_entry_price.is_none());
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("slot must remain");
    assert_eq!(aapl.available(), ps("10"));
    assert_eq!(aapl.held(), ps("-10"));
    assert!(aapl.avg_entry_price().is_none());
}

#[test]
fn held_only_adjustment_emits_no_average() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("150"));

    let adjustment = held_adj(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("2"))),
        None,
        None,
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    // Held-only request: no balance, so no average is surfaced and no PnL.
    assert!(outcome[0].average_entry_price.is_none());
    assert!(outcome[0].realized_pnl.is_none());
    // The stored average is untouched.
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("150")));
}

#[test]
fn buy_fill_emits_average_entry_price_and_no_pnl() {
    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);

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    // Opening a long from flat: average is the fill price, no realized PnL.
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("200")));
    assert!(aapl_entry.entry.realized_pnl.is_none());

    // Settlement (USD) leg never carries average or PnL.
    let usd_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("USD"))
        .expect("USD entry must exist");
    assert!(usd_entry.entry.average_entry_price.is_none());
    assert!(usd_entry.entry.realized_pnl.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("200")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn fill_without_account_currency_does_not_track_pnl_or_average() {
    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("pretrade must succeed");
    mutations.commit_all();

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("100"),
            quantity: qty("2"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let result = run_report_without_account_currency(&policy, &fill);
    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");
    assert!(aapl_entry.entry.average_entry_price.is_none());
    assert!(aapl_entry.entry.realized_pnl.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.available(), ps("2"));
    assert!(aapl.avg_entry_price().is_none());
    assert!(aapl.realized_pnl().is_none());
}

#[test]
fn non_position_touching_fill_without_account_currency_preserves_tracking() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    let seed = TestAdjustment {
        asset: asset("AAPL"),
        balance: Some(AdjustmentAmount::Absolute(ps("10"))),
        balance_average_entry_price: Some(px("100")),
        balance_realized_pnl: Some(pnl_value("7")),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed, &mut mutations);
    mutations.commit_all();

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("100"),
            quantity: qty("0"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let result = <TestPolicy as PreTradePolicy<
        TestOrder,
        TestReport,
        TestAdjustment,
        crate::core::FullSync,
    >>::apply_execution_report(
        &policy, &crate::pretrade::PostTradeContext::new(), &fill
    );

    assert!(
        result.is_none(),
        "zero-quantity fill must not emit outcomes"
    );
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.available(), ps("10"));
    assert_eq!(aapl.avg_entry_price(), Some(px("100")));
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("7")));
}

#[test]
fn quote_equals_account_currency_tracks_without_market_data() {
    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("123")),
    );
    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("123"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("123"),
        )])),
    );
    let result = run_report_with_currency(&policy, &fill, asset("USD"));
    assert!(result.account_blocks.is_empty());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("123")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn fresh_fx_tracks_average_and_realized_pnl_in_account_currency() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let usd_eur = instr("USD", "EUR");
    let b = engine_builder();
    let svc = MarketDataBuilder::<FullSync>::new(QuoteTtl::Infinite).build();
    let fx_id = svc.register(usd_eur).expect("register must succeed");
    svc.push(fx_id, Quote::new().with_mark(px("0.9")))
        .expect("push must succeed");
    let bundle = SpotFundsMarketData::new(Arc::clone(&svc));
    let policy = SpotFundsPolicy::new(settings(0), Some(bundle), b.storage_builder());
    seed(&policy, acc, asset("USD"), "10000");

    let buy = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("10")),
        Some(px("100")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &buy, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();
    let buy_fill = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("100"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let buy_result = run_report_with_currency(&policy, &buy_fill, asset("EUR"));
    assert!(buy_result.account_blocks.is_empty());
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("90")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));

    let sell = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("4")),
        Some(px("120")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &sell, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();
    let sell_fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("120"),
            quantity: qty("4"),
        }),
        qty("0"),
        true,
        None,
    );
    let sell_result = run_report_with_currency(&policy, &sell_fill, asset("EUR"));
    assert!(sell_result.account_blocks.is_empty());
    let pnl = sell_result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .and_then(|o| o.entry.realized_pnl.as_ref())
        .expect("realized pnl must be tracked");
    assert_eq!(pnl.delta, pnl_value("72"));
    assert_eq!(pnl.absolute, pnl_value("72"));
}

#[test]
fn stale_fx_quote_is_used_for_accounting() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let usd_eur = instr("USD", "EUR");
    let b = engine_builder();
    let svc =
        MarketDataBuilder::<FullSync>::new(QuoteTtl::Within(std::time::Duration::from_millis(1)))
            .build();
    let fx_id = svc.register(usd_eur).expect("register must succeed");
    svc.push(fx_id, Quote::new().with_mark(px("0.8")))
        .expect("push must succeed");
    std::thread::sleep(std::time::Duration::from_millis(5));
    let bundle = SpotFundsMarketData::new(Arc::clone(&svc));
    let policy = SpotFundsPolicy::new(settings(0), Some(bundle), b.storage_builder());
    seed(&policy, acc, asset("USD"), "10000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("100")),
    );
    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("100"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let result = run_report_with_currency(&policy, &fill, asset("EUR"));
    assert!(result.account_blocks.is_empty());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("80")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn missing_fx_resets_tracking_without_block_or_reject() {
    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("pretrade must succeed");
    mutations.commit_all();

    let fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("100"),
            quantity: qty("2"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let result = run_report_with_currency(&policy, &fill, asset("EUR"));
    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");
    assert!(aapl_entry.entry.average_entry_price.is_none());
    assert!(aapl_entry.entry.realized_pnl.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.available(), ps("2"));
    assert!(aapl.avg_entry_price().is_none());
    assert!(aapl.realized_pnl().is_none());
}

#[test]
fn force_set_revives_reset_slot_then_missing_fx_resets_again() {
    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("pretrade must succeed");
    mutations.commit_all();
    let fill = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("100"),
            quantity: qty("2"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    let _ = run_report_with_currency(&policy, &fill, asset("EUR"));
    let reset = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert!(reset.avg_entry_price().is_none());
    assert!(reset.realized_pnl().is_none());

    let force = TestAdjustment {
        asset: asset("AAPL"),
        balance: None,
        balance_average_entry_price: Some(px("100")),
        balance_realized_pnl: Some(Pnl::ZERO),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &force, &mut mutations);
    mutations.commit_all();
    let revived = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(revived.avg_entry_price(), Some(px("100")));
    assert_eq!(revived.realized_pnl(), Some(Pnl::ZERO));

    let sell = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("1")),
        Some(px("120")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &sell, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();
    let sell_fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("120"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        None,
    );
    let result = run_report_with_currency(&policy, &sell_fill, asset("EUR"));
    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");
    assert!(aapl_entry.entry.average_entry_price.is_none());
    assert!(aapl_entry.entry.realized_pnl.is_none());

    let reset_again = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(reset_again.available(), ps("1"));
    assert!(reset_again.avg_entry_price().is_none());
    assert!(reset_again.realized_pnl().is_none());
}

#[test]
fn sell_fill_against_seeded_long_realizes_pnl() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Long 10 AAPL at average 100, plus USD is irrelevant for a sell.
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("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();
    // Reservation moved 10 AAPL available -> held; owned still 10 @ 100.

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

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    let pnl = aapl_entry
        .entry
        .realized_pnl
        .as_ref()
        .expect("AAPL pnl must be present");
    // Sell 4 of a long at 200 vs avg 100: realized = (200 - 100) * 4 = 400.
    assert_eq!(pnl.delta, pnl_value("400"));
    assert_eq!(pnl.absolute, pnl_value("400"));
    // Average is unchanged while the position is only reduced.
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("100")));

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("400")));
    assert_eq!(aapl.avg_entry_price(), Some(px("100")));
}

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

    let first_order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("100")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &first_order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();
    let first_fill = make_report(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        Some(Trade {
            price: px("100"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("100"),
        )])),
    );
    assert!(run_report(&policy, &first_fill).account_blocks.is_empty());

    let second_order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("1")),
        Some(px("120")),
    );
    let mut mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &second_order, &mut mutations).expect("pretrade must succeed");
    mutations.commit_all();
    let second_fill = make_report(
        acc,
        aapl_usd,
        Side::Buy,
        Some(Trade {
            price: px("120"),
            quantity: qty("1"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("120"),
        )])),
    );
    let result = run_report(&policy, &second_fill);

    assert!(
        result.account_blocks.is_empty(),
        "second fill in account currency must not block",
    );
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.available(), ps("2"));
    assert_eq!(aapl.avg_entry_price(), Some(px("110")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn short_open_then_buy_to_close_realizes_pnl() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Seed a short -10 AAPL at average 100 directly via adjustment.
    seed_with_avg(&policy, acc, asset("AAPL"), "-10", px("100"));
    seed(&policy, acc, asset("USD"), "100000");

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Buy,
        TradeAmount::Quantity(qty("4")),
        Some(px("70")),
    );
    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("70"),
            quantity: qty("4"),
        }),
        qty("0"),
        false,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("70"),
        )])),
    );
    let result = run_report(&policy, &fill);

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    let pnl = aapl_entry
        .entry
        .realized_pnl
        .as_ref()
        .expect("AAPL pnl must be present");
    // Buy 4 to cover a short at 70 vs avg 100: realized = (70 - 100) * -(4) = 120.
    assert_eq!(pnl.delta, pnl_value("120"));
    // No prior realized PnL on the slot, so the cumulative equals this fill.
    assert_eq!(pnl.absolute, pnl_value("120"));
    // Still short -6, average unchanged.
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("100")));
}

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

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("130")),
    );
    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::Sell,
        Some(Trade {
            price: px("130"),
            quantity: qty("10"),
        }),
        qty("0"),
        true,
        None,
    );
    let result = run_report(&policy, &fill);

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    let pnl = aapl_entry
        .entry
        .realized_pnl
        .as_ref()
        .expect("AAPL pnl must be present");
    // Close the whole long at 130 vs avg 100: realized = (130 - 100) * 10 = 300.
    assert_eq!(pnl.delta, pnl_value("300"));
    // No prior realized PnL on the slot, so the cumulative equals this fill.
    assert_eq!(pnl.absolute, pnl_value("300"));
    // Position is flat: no average, but realized PnL persists so the slot
    // survives pruning.
    assert!(aapl_entry.entry.average_entry_price.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("slot must survive");
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("300")));
    assert_eq!(aapl.avg_entry_price(), None);
    assert!(!aapl.is_zero());
}

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

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

    // A final report with no fill and a leftover quantity cancels the reservation.
    let cancel = make_report(acc, aapl_usd, Side::Sell, None, qty("10"), true, None);
    let _ = run_report(&policy, &cancel);

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    // Funds returned to available; the average and realized PnL are unchanged.
    assert_eq!(aapl.available(), ps("10"));
    assert_eq!(aapl.held(), PositionSize::ZERO);
    assert_eq!(aapl.avg_entry_price(), Some(px("100")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn adjustment_rollback_restores_prior_average() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("100"));

    // Apply a balance adjustment that also overwrites the average, then roll it
    // back without committing. The prior average must be restored.
    let adjustment = adj_with_avg(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("5"))),
        Some(px("200")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    // Forward write is synchronous: the average is now 200, balance 15.
    let after_forward = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after_forward.avg_entry_price(), Some(px("200")));
    assert_eq!(after_forward.available(), ps("15"));

    mutations.rollback_all();

    let after_rollback = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after_rollback.avg_entry_price(), Some(px("100")));
    assert_eq!(after_rollback.available(), ps("10"));
    assert_eq!(after_rollback.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn balance_adjustment_force_sets_realized_pnl_and_emits_delta_and_absolute() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // Seed a slot that already carries a non-zero realized PnL via a force-set,
    // so the second force-set produces a meaningful, non-trivial delta.
    let seed_pnl = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(pnl_value("30")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed_pnl, &mut mutations);
    mutations.commit_all();

    // Force-set realized PnL to 50: delta = 50 - 30 = 20, absolute = 50.
    let adjustment = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("0"))),
        Some(pnl_value("50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome.len(), 1);
    let pnl = outcome[0]
        .realized_pnl
        .as_ref()
        .expect("realized PnL outcome must be emitted on a force-set");
    assert_eq!(pnl.delta, pnl_value("20"));
    assert_eq!(pnl.absolute, pnl_value("50"));

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("50")));
}

#[test]
fn metadata_only_realized_pnl_adjustment_sets_and_emits_delta() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    let seed_pnl = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(pnl_value("30")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed_pnl, &mut mutations);
    mutations.commit_all();

    let adjustment = adj_with_realized_pnl(asset("AAPL"), None, Some(pnl_value("50")));
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert_eq!(outcome.len(), 1);
    assert!(outcome[0].balance.is_none());
    let pnl = outcome[0]
        .realized_pnl
        .as_ref()
        .expect("realized PnL outcome must be emitted on a force-set");
    assert_eq!(pnl.delta, pnl_value("20"));
    assert_eq!(pnl.absolute, pnl_value("50"));

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("50")));
}

#[test]
fn balance_adjustment_without_realized_pnl_emits_no_pnl_and_leaves_it() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    let seed_pnl = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(pnl_value("30")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed_pnl, &mut mutations);
    mutations.commit_all();

    // A balance-only adjustment that does not force-set realized PnL must leave
    // the booked PnL untouched and emit no realized-PnL outcome.
    let adjustment = adj(asset("AAPL"), Some(AdjustmentAmount::Delta(ps("5"))));
    let mut mutations = Mutations::with_capacity(1);
    let outcome = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    mutations.commit_all();

    assert!(outcome[0].realized_pnl.is_none());
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("30")));
}

#[test]
fn adjustment_rollback_restores_realized_pnl_to_prior() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    let seed_pnl = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(pnl_value("30")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed_pnl, &mut mutations);
    mutations.commit_all();

    // Force-set realized PnL to 50, then roll back without committing.
    let adjustment = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("0"))),
        Some(pnl_value("50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    let after_forward = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after_forward.realized_pnl(), Some(pnl_value("50")));

    mutations.rollback_all();

    // Realized PnL is restored from the prior snapshot (30), symmetric to the
    // average entry price.
    let after_rollback = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after_rollback.realized_pnl(), Some(pnl_value("30")));
}

#[test]
fn adjustment_rollback_restores_untracked_realized_pnl_to_none() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // Seed a non-flat slot that is NOT tracking realized PnL (balance only, no
    // realized force-set): realized_pnl stays `None`.
    let seed = adj(asset("AAPL"), Some(AdjustmentAmount::Absolute(ps("10"))));
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed, &mut mutations);
    mutations.commit_all();
    assert_eq!(
        holdings_of(&policy, acc, &asset("AAPL"))
            .expect("must exist")
            .realized_pnl(),
        None,
    );

    // Force-set realized PnL to 25, then roll back without committing.
    let force = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("0"))),
        Some(pnl_value("25")),
    );
    let mut adj_mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &force, &mut adj_mutations);
    assert_eq!(
        holdings_of(&policy, acc, &asset("AAPL"))
            .expect("must exist")
            .realized_pnl(),
        Some(pnl_value("25")),
    );

    adj_mutations.rollback_all();

    // The snapshot restore returns the slot to the untracked `None` state, not
    // to `Some(0)` (which a delta-based reversal would have produced).
    let after = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after.realized_pnl(), None);
    assert_eq!(after.available(), ps("10"));
}

#[test]
fn realized_pnl_stays_untracked_after_rollback_to_none() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // Seed a long with an average but NO realized-PnL tracking. The average lets
    // a later fill have a basis; realized_pnl is `None`.
    let seed = adj_with_avg(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(px("100")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed, &mut mutations);
    mutations.commit_all();
    assert_eq!(
        holdings_of(&policy, acc, &asset("AAPL"))
            .expect("must exist")
            .realized_pnl(),
        None,
    );

    // Force-set realized PnL, then roll back: the slot returns to untracked.
    let force = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("0"))),
        Some(pnl_value("25")),
    );
    let mut adj_mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &force, &mut adj_mutations);
    adj_mutations.rollback_all();
    assert_eq!(
        holdings_of(&policy, acc, &asset("AAPL"))
            .expect("must exist")
            .realized_pnl(),
        None,
    );

    // A subsequent non-flat fill must NOT auto-resume realized-PnL tracking:
    // sell 4 of the long at 130. Tracking stays absent (mirrors the
    // `realize_position_fill` short-circuit for an untracked slot).
    let aapl_usd = instr("AAPL", "USD");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("4")),
        Some(px("130")),
    );
    let mut pt_mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut pt_mutations).expect("pretrade must succeed");
    pt_mutations.commit_all();
    let fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("130"),
            quantity: qty("4"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("130"),
        )])),
    );
    let result = run_report(&policy, &fill);
    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    assert!(aapl_entry.entry.realized_pnl.is_none());
    let after = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after.realized_pnl(), None);
}

#[test]
fn metadata_only_average_and_pnl_roll_back_to_prior_values() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    let seed = TestAdjustment {
        asset: asset("AAPL"),
        balance: Some(AdjustmentAmount::Absolute(ps("10"))),
        balance_average_entry_price: Some(px("100")),
        balance_realized_pnl: Some(pnl_value("30")),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed, &mut mutations);
    mutations.commit_all();

    let adjustment = TestAdjustment {
        asset: asset("AAPL"),
        balance: None,
        balance_average_entry_price: Some(px("150")),
        balance_realized_pnl: Some(pnl_value("50")),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &adjustment, &mut mutations);
    let after_forward = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after_forward.avg_entry_price(), Some(px("150")));
    assert_eq!(after_forward.realized_pnl(), Some(pnl_value("50")));

    mutations.rollback_all();

    let after_rollback = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after_rollback.avg_entry_price(), Some(px("100")));
    assert_eq!(after_rollback.realized_pnl(), Some(pnl_value("30")));
}

#[test]
fn adjustment_rollback_restores_realized_pnl_snapshot_last_writer_wins() {
    let acc = account(99224416);
    let policy = build_policy(None, None);
    // Seed a long with an average so a later fill realizes PnL, and an initial
    // booked realized PnL of 30.
    let seed = TestAdjustment {
        asset: asset("AAPL"),
        balance: Some(AdjustmentAmount::Absolute(ps("10"))),
        balance_average_entry_price: Some(px("100")),
        balance_realized_pnl: Some(pnl_value("30")),
        balance_lower: None,
        balance_upper: None,
        held: None,
        held_lower: None,
        held_upper: None,
        incoming: None,
        incoming_lower: None,
        incoming_upper: None,
    };
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed, &mut mutations);
    mutations.commit_all();

    // Force-set realized PnL to 50 but hold the rollback. The snapshot captured
    // for rollback is the prior value, 30.
    let adjustment = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("0"))),
        Some(pnl_value("50")),
    );
    let mut adj_mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &adjustment, &mut adj_mutations);
    assert_eq!(
        holdings_of(&policy, acc, &asset("AAPL"))
            .expect("must exist")
            .realized_pnl(),
        Some(pnl_value("50")),
    );

    // A concurrent fill books additional realized PnL before the adjustment is
    // rolled back. Sell 4 of the long at 130 vs avg 100 -> realized += 120.
    let aapl_usd = instr("AAPL", "USD");
    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("4")),
        Some(px("130")),
    );
    let mut pt_mutations = Mutations::with_capacity(1);
    pre_trade_check(&policy, &order, &mut pt_mutations).expect("pretrade must succeed");
    pt_mutations.commit_all();
    let fill = make_report(
        acc,
        aapl_usd,
        Side::Sell,
        Some(Trade {
            price: px("130"),
            quantity: qty("4"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("130"),
        )])),
    );
    let _ = run_report(&policy, &fill);
    // Cumulative is now 50 (force-set) + 120 (fill) = 170.
    assert_eq!(
        holdings_of(&policy, acc, &asset("AAPL"))
            .expect("must exist")
            .realized_pnl(),
        Some(pnl_value("170")),
    );

    // Realized PnL rolls back by absolute snapshot, not inverse delta (a forced
    // value can overwrite an untracked `None` that no delta can restore). When a
    // force-set races a concurrent fill the snapshot restore is last-writer-wins
    // for realized PnL, exactly like the average entry price: the prior 30 is
    // restored, dropping the fill's concurrent 120. Quantities still roll back by
    // their (here zero) inverse delta, so the fill's position change survives.
    adj_mutations.rollback_all();
    let after = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(after.realized_pnl(), Some(pnl_value("30")));
    // The fill reduced the long from 10 to 6; the adjustment's zero quantity
    // delta leaves that untouched on rollback.
    assert_eq!(after.available(), ps("6"));
}

#[test]
fn buy_fill_adding_to_long_recomputes_weighted_average() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Seed an existing long 10 AAPL at average 100, plus cash to buy more.
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("100"));
    seed(&policy, acc, asset("USD"), "100000");

    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("10"),
        }),
        qty("0"),
        true,
        Some(PreTradeLock::from_entries([(
            DEFAULT_POLICY_GROUP_ID,
            px("200"),
        )])),
    );
    let result = run_report(&policy, &fill);

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    // Adding to the position weights the average: (10*100 + 10*200)/20 = 150,
    // and realizes nothing.
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("150")));
    assert!(aapl_entry.entry.realized_pnl.is_none());

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("150")));
    assert_eq!(aapl.realized_pnl(), Some(Pnl::ZERO));
}

#[test]
fn sell_fill_flipping_long_to_short_realizes_and_reopens_at_price() {
    let acc = account(99224416);
    let aapl_usd = instr("AAPL", "USD");
    let policy = build_policy(None, None);
    // Long 10 AAPL at average 100. Reserve a sell of 10 (all that is owned),
    // then the venue over-fills 15, flipping through zero to a short -5.
    seed_with_avg(&policy, acc, asset("AAPL"), "10", px("100"));

    let order = make_order(
        acc,
        aapl_usd.clone(),
        Side::Sell,
        TradeAmount::Quantity(qty("10")),
        Some(px("130")),
    );
    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::Sell,
        Some(Trade {
            price: px("130"),
            quantity: qty("15"),
        }),
        qty("0"),
        true,
        None,
    );
    let result = run_report(&policy, &fill);

    let aapl_entry = result
        .account_adjustments
        .iter()
        .find(|o| o.entry.asset == asset("AAPL"))
        .expect("AAPL entry must exist");
    let pnl = aapl_entry
        .entry
        .realized_pnl
        .as_ref()
        .expect("AAPL pnl must be present");
    // Flip closes the whole long (realized = (130 - 100) * 10 = 300) and opens
    // the -5 remainder at the fill price 130.
    assert_eq!(pnl.delta, pnl_value("300"));
    assert_eq!(pnl.absolute, pnl_value("300"));
    assert_eq!(aapl_entry.entry.average_entry_price, Some(px("130")));

    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.avg_entry_price(), Some(px("130")));
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("300")));
}

#[test]
fn batch_force_setting_realized_pnl_then_rejected_rolls_back_to_prior() {
    // End-to-end through the engine batch API: a balance + realized-PnL force-set
    // that is later rejected in the same batch must roll the realized PnL back to
    // its prior value via the inverse delta.
    let acc = account(99224416);
    let policy = build_policy(None, None);
    let seed_pnl = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Absolute(ps("10"))),
        Some(pnl_value("30")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &seed_pnl, &mut mutations);
    mutations.commit_all();

    // Force-set realized PnL to 50, then drive the same closure to reject via an
    // out-of-range balance bound so the whole adjustment is rolled back.
    let force = adj_with_realized_pnl(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("0"))),
        Some(pnl_value("50")),
    );
    let mut mutations = Mutations::with_capacity(1);
    let _ = run_adjustment(&policy, acc, &force, &mut mutations);

    let rejecting = bounded_adj(
        asset("AAPL"),
        Some(AdjustmentAmount::Delta(ps("1"))),
        None,
        Some(ps("0")),
    );
    let mut reject_mutations = Mutations::with_capacity(1);
    let rejected = run_adjustment_result(&policy, acc, &rejecting, &mut reject_mutations);
    assert!(rejected.is_err());

    // Roll back the force-set adjustment: realized PnL returns to the prior 30.
    mutations.rollback_all();
    let aapl = holdings_of(&policy, acc, &asset("AAPL")).expect("must exist");
    assert_eq!(aapl.realized_pnl(), Some(pnl_value("30")));
}