fraiseql-core 2.16.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
//! Tests for the mutation runner, co-located with `runners/mutation.rs`.

#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code, panics are acceptable

use std::sync::Arc;

use async_trait::async_trait;
use fraiseql_db::ChangeLogWrite;

use crate::{
    backend::{
        traits::DatabaseAdapter,
        types::{DatabaseType, JsonbValue, PoolMetrics, sql_hints::OrderByClause},
        where_clause::WhereClause,
    },
    error::{FraiseQLError, Result},
    runtime::{
        Executor, RuntimeConfig,
        executor::{
            mutation::any_write_selections,
            test_support::{MockAdapter, ReadOnlyMockAdapter},
        },
    },
    schema::CompiledSchema,
};

// ── mod mutation: mutation execution and adapter capability guard ─────────

mod mutation {
    use super::*;

    /// Mock adapter for testing mutations with selection set filtering.
    /// Returns a mutation response with multiple entity fields.
    struct SelectionSetFilterMockAdapter;

    #[async_trait]
    impl DatabaseAdapter for SelectionSetFilterMockAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl SelectionSetFilterMockAdapter {
        async fn execute_function_call(
            &self,
            _function_name: &str,
            _args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            let mut row = std::collections::HashMap::new();

            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert(
                "entity".to_string(),
                json!({
                    "id": "123",
                    "name": "Alice",
                    "email": "alice@example.com",
                    "bio": "Software engineer"
                }),
            );
            row.insert("entity_type".to_string(), json!("User"));
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&fraiseql_db::ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            let rows = self.execute_function_call(function_name, args).await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for SelectionSetFilterMockAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// Mock adapter that returns a mutation response for empty selection set tests.
    struct EmptySelectionMockAdapter;

    #[async_trait]
    impl DatabaseAdapter for EmptySelectionMockAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl EmptySelectionMockAdapter {
        async fn execute_function_call(
            &self,
            _function_name: &str,
            _args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            let mut row = std::collections::HashMap::new();

            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert(
                "entity".to_string(),
                json!({
                    "id": "123",
                    "name": "Alice",
                    "email": "alice@example.com"
                }),
            );
            row.insert("entity_type".to_string(), json!("User"));
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&fraiseql_db::ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            let rows = self.execute_function_call(function_name, args).await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for EmptySelectionMockAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    // Regression tests for issue #53 ──────────────────────────────────────
    //
    // The executor must fall back to operation.table when mutation_def.sql_source
    // is None.  Before the fix, the "has no sql_source configured" error was
    // returned unconditionally whenever sql_source was absent (e.g. when a schema
    // was compiled via the core Rust codegen path rather than the CLI converter).

    /// A mutation compiled without an explicit `sql_source` (only operation.table set)
    /// must NOT return a "has no `sql_source` configured" error.  Instead it should
    /// fall back to operation.table and attempt to call the SQL function, which in
    /// this test returns "function returned no rows" (the mock adapter is empty) —
    /// proving the executor reached the function-call stage (issue #53 regression).
    #[tokio::test]
    async fn test_mutation_falls_back_to_operation_table_when_sql_source_none() {
        use crate::schema::{MutationDefinition, MutationOperation};

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            name: "createUser".to_string(),
            return_type: "User".to_string(),
            // sql_source deliberately absent — simulates codegen path before the fix.
            sql_source: None,
            operation: MutationOperation::Insert {
                table: "fn_create_user".to_string(),
            },
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(MockAdapter::new(vec![]));
        let executor = Executor::new(schema, adapter);

        let err = executor.execute("mutation { createUser { id } }", None).await.unwrap_err();

        let msg = err.to_string();
        assert!(
            !msg.contains("has no sql_source configured"),
            "executor still failed on missing sql_source instead of using operation.table: {msg}"
        );
        assert!(
            msg.contains("function returned no rows") || msg.contains("no rows"),
            "expected 'no rows' error after fallback, got: {msg}"
        );
    }

    /// Mutations against a non-capable adapter must return `FraiseQLError::Validation`
    /// with a diagnostic message, not silently call `execute_function_call`.
    #[tokio::test]
    async fn test_mutation_rejected_by_non_capable_adapter() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(ReadOnlyMockAdapter);
        let executor = Executor::read_only(schema, adapter);

        let err = executor.execute("mutation { createUser { id } }", None).await.unwrap_err();

        let msg = err.to_string();
        assert!(msg.contains("read-only"), "expected a read-only diagnostic, got: {msg}");
        // The message must tell an adapter author what to do about it: this is the error an
        // out-of-tree adapter that never implemented the write capability will hit.
        assert!(
            msg.contains("`Writer`") && msg.contains("execute_write"),
            "the diagnostic must name the capability, got: {msg}"
        );
        assert!(msg.contains("createUser"), "error message should name the mutation, got: {msg}");
    }

    /// The capability gate is adjudicated at step 0, before the gate that names the
    /// mutation.
    ///
    /// The sibling test above proves the dispatch is not reached. That much is also true
    /// of a gate sitting *at* the dispatch — and a capability refusal that arrives there
    /// has already let the operation authorizer, `requires_role`, `requires_actor`,
    /// argument validation and the `before:mutation` chain run. `78f91c9e2` is the whole
    /// argument for why that is not good enough, so "not reached" cannot be the only
    /// assertion.
    ///
    /// What discriminates: a read-only executor asked for a mutation that **does not
    /// exist**. Step 1 is `find_mutation`, whose miss produces a did-you-mean error. If
    /// the capability question is asked first, the answer is read-only regardless of the
    /// name — which is also why this leaks nothing: the refusal is identical for a name
    /// that exists and one that does not.
    #[tokio::test]
    async fn the_capability_gate_is_adjudicated_before_the_mutation_is_looked_up() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let executor = Executor::read_only(schema, Arc::new(ReadOnlyMockAdapter));

        let msg = executor
            .execute_mutation("noSuchMutation", None, any_write_selections())
            .await
            .expect_err("a read-only executor refuses")
            .to_string();

        assert!(
            msg.contains("read-only"),
            "capability must be adjudicated before the name is looked up, got: {msg}"
        );
        assert!(
            !msg.contains("did you mean") && !msg.contains("Did you mean"),
            "a did-you-mean answer means step 1 ran before the capability gate, got: {msg}"
        );
    }

    /// When both `sql_source` and operation.table are absent the executor must still
    /// return a clear validation error (not panic or silently succeed).
    #[tokio::test]
    async fn test_mutation_errors_when_both_sql_source_and_table_absent() {
        use crate::schema::{MutationDefinition, MutationOperation};

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            name: "deleteUser".to_string(),
            return_type: "User".to_string(),
            sql_source: None,
            // Custom operation has no table — no fallback available.
            operation: MutationOperation::Custom,
            ..MutationDefinition::new("deleteUser", "User")
        });

        let adapter = Arc::new(MockAdapter::new(vec![]));
        let executor = Executor::new(schema, adapter);

        let err = executor.execute("mutation { deleteUser { id } }", None).await.unwrap_err();

        assert!(
            err.to_string().contains("has no sql_source configured"),
            "expected sql_source error, got: {err}"
        );
    }

    // R9: SQLite/read-only adapter mutation guard — error type verification ─

    /// Mutations against a read-only adapter must return `FraiseQLError::Validation`
    /// specifically — not `FraiseQLError::Database` or `FraiseQLError::Internal`.
    /// This pins the error type so a future refactor cannot silently change it.
    #[tokio::test]
    async fn test_mutation_guard_returns_validation_error_not_database_or_internal() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(ReadOnlyMockAdapter);
        let executor = Executor::read_only(schema, adapter);

        let err = executor.execute("mutation { createUser { id } }", None).await.unwrap_err();

        // Must be Validation — not Internal, Database, or any other variant.
        assert!(
            matches!(err, FraiseQLError::Validation { .. }),
            "expected FraiseQLError::Validation for read-only adapter, got: {err:?}"
        );
    }

    /// The error message from the mutation guard must mention the mutation name
    /// so the caller can identify which mutation triggered the guard.
    #[tokio::test]
    async fn test_mutation_guard_error_message_is_actionable() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_delete_account".to_string()),
            ..MutationDefinition::new("deleteAccount", "User")
        });

        let adapter = Arc::new(ReadOnlyMockAdapter);
        let executor = Executor::read_only(schema, adapter);

        let err = executor.execute("mutation { deleteAccount { id } }", None).await.unwrap_err();

        let msg = err.to_string();
        assert!(
            msg.contains("deleteAccount"),
            "mutation guard message should name the mutation, got: {msg}"
        );
        assert!(
            msg.contains("mutation") || msg.contains("does not support"),
            "mutation guard message should explain the reason, got: {msg}"
        );
    }

    /// When a mutation includes a restricted selection set (e.g., `{ id name }`),
    /// the response must only include those requested fields — and, matching the
    /// query path and the GraphQL spec, `__typename` only when explicitly selected.
    #[tokio::test]
    async fn test_mutation_selection_set_filters_response_fields() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(SelectionSetFilterMockAdapter);
        let executor = Executor::new(schema, adapter);

        // Restricted selection: only id and name (no __typename selected).
        let result = executor.execute("mutation { createUser { id name } }", None).await.unwrap();

        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert!(data.get("id").is_some(), "response must include selected field 'id'");
        assert!(data.get("name").is_some(), "response must include selected field 'name'");

        // __typename is NOT auto-injected — only returned when the client selects it.
        assert!(
            data.get("__typename").is_none(),
            "response must NOT include __typename unless selected"
        );

        // Must NOT have the non-selected fields
        assert!(
            data.get("email").is_none(),
            "response must NOT include non-selected field 'email'"
        );
        assert!(data.get("bio").is_none(), "response must NOT include non-selected field 'bio'");
    }

    /// `__typename` is returned when, and only when, the client selects it.
    #[tokio::test]
    async fn test_mutation_typename_returned_when_selected() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(SelectionSetFilterMockAdapter);
        let executor = Executor::new(schema, adapter);

        let result = executor
            .execute("mutation { createUser { __typename id } }", None)
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert_eq!(data.get("__typename").and_then(|v| v.as_str()), Some("User"));
        assert!(data.get("id").is_some());
    }

    /// A mutation named with no selection set (`mutation { createUser }`) is an
    /// invalid document (GraphQL § 5.3.3) and is refused.
    ///
    /// ⚠ This test asserted the opposite until #1357 — that the response "passes the
    /// stored entity through unfiltered" — and that is how the behaviour survived two
    /// releases of review: an empty selection set is the *permissive* shape, so the
    /// response carried every `authorize`-gated field of the stored row while
    /// `selection_set_selects_gated_field` reported nothing gated was selected and the
    /// #423 field authorizer took zero calls.
    ///
    /// âš  Its schema pushed `createUser` **without** pushing the `User` type, so
    /// `find_type` missed and the validator's "every unknown is a pass" rule applied.
    /// With the fix in place the old assertions still passed — the test could not see
    /// the defect it pinned, nor the fix that closed it. The type is pushed here for
    /// that reason: without it this test is green either way.
    #[tokio::test]
    async fn test_mutation_empty_selection_set_is_refused() {
        use crate::schema::{FieldDefinition, FieldType, MutationDefinition, TypeDefinition};

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });
        let mut user = TypeDefinition::new("User", "v_user");
        user.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("name", FieldType::String),
            FieldDefinition::nullable("email", FieldType::String),
        ];
        schema.types.push(user);
        schema.build_indexes();

        let adapter = Arc::new(EmptySelectionMockAdapter);
        let executor = Executor::new(schema, adapter);

        let err = executor
            .execute("mutation { createUser }", None)
            .await
            .expect_err("a composite return type named with no selection set is invalid");

        assert!(
            matches!(err, FraiseQLError::Validation { .. }),
            "§ 5.3.3 is a document rule, so the refusal must be a validation error: {err:?}"
        );
        assert!(
            err.to_string().contains("User"),
            "the refusal must name the type that needed a selection set, got: {err}"
        );
    }

    /// Named fragment spreads and `@skip`/`@include` directives on a mutation
    /// selection must be resolved and evaluated before projection — exactly like
    /// the query path — so a client that factors mutation fields into a fragment
    /// (or guards them with a directive) gets the same shape it would from a query.
    #[tokio::test]
    async fn test_mutation_resolves_fragments_and_directives() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(SelectionSetFilterMockAdapter);
        let executor = Executor::new(schema, adapter);

        // `id`/`name` come from a named fragment; `name` is gated true (kept) and
        // `email` is skipped true (dropped).
        let doc = r"
            mutation { createUser { ...F email @skip(if: true) } }
            fragment F on User { id name @include(if: true) }
        ";
        let result = executor.execute(doc, None).await.unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert!(data.get("id").is_some(), "fragment-spread field 'id' must be projected");
        assert!(data.get("name").is_some(), "@include(if: true) field 'name' must be projected");
        assert!(data.get("email").is_none(), "@skip(if: true) field 'email' must be omitted");
        assert!(data.get("bio").is_none(), "unselected field 'bio' must be omitted");
    }

    /// Mock adapter that returns a failed `mutation_response` row (an error
    /// outcome with no entity), driving the executor down the mutation-error
    /// path. `entity_type` is the optional concrete error type a real failure
    /// branch stamps on the response (e.g. `"DuplicateEmailError"`); `None`
    /// leaves the column absent, exercising the union-fallback resolution (#465).
    struct MutationErrorMockAdapter {
        entity_type: Option<&'static str>,
    }

    impl MutationErrorMockAdapter {
        /// A failure row with no `entity_type` stamped (the union-fallback case).
        const fn bare() -> Self {
            Self { entity_type: None }
        }
    }

    #[async_trait]
    impl DatabaseAdapter for MutationErrorMockAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl MutationErrorMockAdapter {
        async fn execute_function_call(
            &self,
            _function_name: &str,
            _args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            let mut row = std::collections::HashMap::new();
            row.insert("succeeded".to_string(), json!(false));
            row.insert("state_changed".to_string(), json!(false));
            row.insert("error_class".to_string(), json!("conflict"));
            row.insert("message".to_string(), json!("already exists"));
            row.insert("http_status".to_string(), json!(409));
            if let Some(et) = self.entity_type {
                row.insert("entity_type".to_string(), json!(et));
            }
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&fraiseql_db::ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            let rows = self.execute_function_call(function_name, args).await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for MutationErrorMockAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// The mutation-error fallback (no matching error type declared in the return
    /// union) emits `__typename` only when the client selects it. That detection
    /// must recurse into inline fragments — `... on T { __typename }` — exactly
    /// like the query projector does, so a client that nests `__typename` inside
    /// an inline fragment still gets it. Regression test for #419.
    #[tokio::test]
    async fn test_mutation_error_fallback_detects_typename_in_inline_fragment() {
        use crate::schema::MutationDefinition;

        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });

        let adapter = Arc::new(MutationErrorMockAdapter::bare());
        let executor = Executor::new(schema, adapter);

        // `__typename` is selected ONLY inside an inline fragment, never at the
        // top level of the mutation selection set.
        let result = executor
            .execute("mutation { createUser { ... on User { __typename } } }", None)
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert_eq!(
            data.get("__typename").and_then(|v| v.as_str()),
            Some("User"),
            "error fallback must surface __typename selected inside an inline fragment"
        );
    }

    /// On the error arm, a declared error type surfaces the `app.mutation_response`
    /// composite's first-class fields — `message`, `httpStatus`, `errorClass` — as
    /// ordinary projected fields (in addition to the always-injected `status`), so a
    /// shared `MutationError` need not carry those values inside the `error_detail` JSONB.
    #[tokio::test]
    async fn test_mutation_error_surfaces_composite_fields() {
        use crate::schema::{
            FieldDefinition, FieldType, MutationDefinition, TypeDefinition, UnionDefinition,
        };

        let mut schema = CompiledSchema::new();
        schema.types.push(TypeDefinition::new("User", "v_user"));
        schema.types.push(TypeDefinition {
            is_error: true,
            fields: vec![
                FieldDefinition::new("status", FieldType::String),
                FieldDefinition::new("message", FieldType::String),
                FieldDefinition::new("httpStatus", FieldType::Int),
                FieldDefinition::new("errorClass", FieldType::String),
            ],
            ..TypeDefinition::new("MutationError", "")
        });
        schema.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["User".to_string(), "MutationError".to_string()]),
        );
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "CreateUserResult")
        });

        let adapter = Arc::new(MutationErrorMockAdapter::bare());
        let executor = Executor::new(schema, adapter);

        let result = executor
            .execute(
                "mutation { createUser { ... on MutationError { status message httpStatus \
                 errorClass } } }",
                None,
            )
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert_eq!(data.get("status").and_then(serde_json::Value::as_str), Some("conflict"));
        assert_eq!(
            data.get("message").and_then(serde_json::Value::as_str),
            Some("already exists"),
            "composite top-level message must be surfaced on the error member"
        );
        assert_eq!(
            data.get("httpStatus").and_then(serde_json::Value::as_i64),
            Some(409),
            "composite http_status must be surfaced as httpStatus"
        );
        assert_eq!(
            data.get("errorClass").and_then(serde_json::Value::as_str),
            Some("conflict"),
            "error_class must be surfaced as errorClass"
        );
    }

    /// #1424: a constraint the mutation's function violates answers as the mutation's
    /// typed error, not a top-level `CONSTRAINT_VIOLATION`, when its result union has
    /// one error member. No constraint name reaches the response.
    mod constraint_violation {
        use std::sync::Arc;

        use fraiseql_test_utils::failing_adapter::{FailError, FailingAdapter};

        use crate::{
            error::FraiseQLError,
            runtime::Executor,
            schema::{
                CompiledSchema, FieldDefinition, FieldType, MutationDefinition, TypeDefinition,
                UnionDefinition,
            },
        };

        const CONSTRAINT: &str = "tb_invoice_line_mapping_source_excl";
        const DOCUMENT: &str = "mutation { createUser { __typename ... on MutationError { \
                                status message httpStatus errorClass } } }";

        fn error_type(name: &str) -> TypeDefinition {
            TypeDefinition {
                is_error: true,
                fields: vec![
                    FieldDefinition::new("status", FieldType::String),
                    FieldDefinition::new("message", FieldType::String),
                    FieldDefinition::new("httpStatus", FieldType::Int),
                    FieldDefinition::new("errorClass", FieldType::String),
                ],
                ..TypeDefinition::new(name, "")
            }
        }

        /// `createUser` returning `return_type`; the union holds `User` and `error_members`.
        fn schema(return_type: &str, error_members: &[&str]) -> CompiledSchema {
            let mut schema = CompiledSchema::new();
            schema.types.push(TypeDefinition::new("User", "v_user"));
            let mut members = vec!["User".to_string()];
            for name in error_members {
                schema.types.push(error_type(name));
                members.push((*name).to_string());
            }
            schema
                .unions
                .push(UnionDefinition::new("CreateUserResult").with_members(members));
            schema.mutations.push(MutationDefinition {
                sql_source: Some("fn_create_user".to_string()),
                ..MutationDefinition::new("createUser", return_type)
            });
            schema
        }

        async fn run(
            schema: CompiledSchema,
            sql_state: &str,
        ) -> crate::error::Result<serde_json::Value> {
            let adapter = FailingAdapter::new().fail_with_error(FailError::Database {
                message:   format!(
                    "conflicting key value violates exclusion constraint \"{CONSTRAINT}\""
                ),
                sql_state: Some(sql_state.to_string()),
            });
            Executor::new(schema, Arc::new(adapter)).execute(DOCUMENT, None).await
        }

        #[tokio::test]
        async fn a_conflict_answers_as_the_typed_error() {
            let response = run(schema("CreateUserResult", &["MutationError"]), "23P01")
                .await
                .expect("a typed failure, not a request error");
            let data = &response["data"]["createUser"];
            assert_eq!(data["__typename"], "MutationError", "{response}");
            assert_eq!(data["status"], "conflict", "{response}");
            assert_eq!(data["errorClass"], "conflict", "{response}");
            assert_eq!(data["httpStatus"], 409, "{response}");
            assert_eq!(
                data["message"], "The request conflicts with the current state of the data",
                "{response}"
            );
            assert!(response.get("errors").is_none(), "{response}");
            assert!(!response.to_string().contains(CONSTRAINT), "no constraint name: {response}");
        }

        #[tokio::test]
        async fn a_check_violation_answers_as_a_validation_error() {
            let response = run(schema("CreateUserResult", &["MutationError"]), "23514")
                .await
                .expect("a typed failure, not a request error");
            let data = &response["data"]["createUser"];
            assert_eq!(data["errorClass"], "validation", "{response}");
            assert_eq!(data["httpStatus"], 422, "{response}");
            assert_eq!(data["message"], "The request contains an invalid value", "{response}");
        }

        /// A mutation returning its entity, not the union, has no typed error to answer
        /// with, even in a schema that declares one.
        #[tokio::test]
        async fn without_an_error_union_the_violation_stays_a_request_error() {
            let err = run(schema("User", &["MutationError"]), "23505")
                .await
                .expect_err("no error union");
            assert!(
                matches!(&err, FraiseQLError::Database { sql_state: Some(s), .. } if s == "23505"),
                "{err:?}"
            );
        }

        /// Two error members: nothing says which one a constraint violation is.
        #[tokio::test]
        async fn with_two_error_members_the_violation_stays_a_request_error() {
            let err = run(schema("CreateUserResult", &["MutationError", "OtherError"]), "23505")
                .await
                .expect_err("ambiguous");
            assert!(matches!(err, FraiseQLError::Database { .. }), "{err:?}");
        }

        /// Only integrity-constraint violations (class 23) are the data's answer.
        #[tokio::test]
        async fn another_database_error_stays_a_request_error() {
            let err = run(schema("CreateUserResult", &["MutationError"]), "40001")
                .await
                .expect_err("a serialization failure is not a constraint violation");
            assert!(matches!(err, FraiseQLError::Database { .. }), "{err:?}");
        }
    }

    /// #465: when the mutation's return type is the bare success entity (no result
    /// union) and the schema declares an `is_error` type, a genuine failure must
    /// project that declared error type — driven by the response's `entity_type` —
    /// not leak the success entity's typename onto the result. Before the fix the
    /// error arm consulted only `find_union(return_type)`, found nothing, and fell
    /// back to emitting `__typename = <success entity>` with no error fields.
    #[tokio::test]
    async fn test_mutation_failure_projects_declared_error_type_from_entity_type() {
        use crate::schema::{FieldDefinition, FieldType, MutationDefinition, TypeDefinition};

        let mut schema = CompiledSchema::new();
        // The success entity carries its own legacy `status` field (e.g. an order
        // status) — the field the bug surfaced in place of the error.
        let mut user = TypeDefinition::new("CreateUserSuccess", "v_user");
        user.fields = vec![
            FieldDefinition::new("id", FieldType::String),
            FieldDefinition::new("status", FieldType::String),
        ];
        schema.types.push(user);
        schema.types.push(TypeDefinition {
            is_error: true,
            fields: vec![
                FieldDefinition::new("message", FieldType::String),
                FieldDefinition::new("errorClass", FieldType::String),
            ],
            ..TypeDefinition::new("DuplicateEmailError", "")
        });
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            // Bare success entity as the return type — no synthesized result union.
            ..MutationDefinition::new("createUser", "CreateUserSuccess")
        });

        let adapter = Arc::new(MutationErrorMockAdapter {
            entity_type: Some("DuplicateEmailError"),
        });
        let executor = Executor::new(schema, adapter);

        let result = executor
            .execute(
                "mutation { createUser { __typename ... on CreateUserSuccess { id } \
                 ... on DuplicateEmailError { errorClass message } } }",
                None,
            )
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert_eq!(
            data.get("__typename").and_then(|v| v.as_str()),
            Some("DuplicateEmailError"),
            "a failed mutation must resolve to the declared error type, not the success entity"
        );
        assert_eq!(
            data.get("errorClass").and_then(|v| v.as_str()),
            Some("conflict"),
            "the error arm must project the declared error type's fields"
        );
        assert_eq!(data.get("message").and_then(|v| v.as_str()), Some("already exists"),);
        // The success entity arm must contribute nothing on a failure.
        assert!(data.get("id").is_none(), "success-arm field 'id' must be absent on failure");
    }

    /// #465 (specificity): with a result union carrying *several* `is_error`
    /// members, the response's `entity_type` selects the exact one the function
    /// reported — not merely the first error member in the union. This both fixes
    /// the mis-routing and sharpens multi-error unions.
    #[tokio::test]
    async fn test_mutation_failure_selects_specific_union_error_member() {
        use crate::schema::{
            FieldDefinition, FieldType, MutationDefinition, TypeDefinition, UnionDefinition,
        };

        let mut schema = CompiledSchema::new();
        schema.types.push(TypeDefinition::new("User", "v_user"));
        // First error member — the one the OLD `find_union` resolution would pick.
        schema.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("ValidationError", "")
        });
        // Second error member — the one the function actually produced.
        schema.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("DuplicateEmailError", "")
        });
        schema.unions.push(UnionDefinition::new("CreateUserResult").with_members(vec![
            "User".to_string(),
            "ValidationError".to_string(),
            "DuplicateEmailError".to_string(),
        ]));
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "CreateUserResult")
        });

        let adapter = Arc::new(MutationErrorMockAdapter {
            entity_type: Some("DuplicateEmailError"),
        });
        let executor = Executor::new(schema, adapter);

        let result = executor
            .execute(
                "mutation { createUser { __typename ... on ValidationError { message } \
                 ... on DuplicateEmailError { message } } }",
                None,
            )
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert_eq!(
            data.get("__typename").and_then(|v| v.as_str()),
            Some("DuplicateEmailError"),
            "entity_type must select the specific error member, not the first is_error member"
        );
    }

    /// #465 (fallback): when the function does *not* stamp `entity_type`, the error
    /// arm still resolves the union's `is_error` member, preserving the original
    /// auto-error-union behaviour.
    #[tokio::test]
    async fn test_mutation_failure_falls_back_to_union_error_member_without_entity_type() {
        use crate::schema::{
            FieldDefinition, FieldType, MutationDefinition, TypeDefinition, UnionDefinition,
        };

        let mut schema = CompiledSchema::new();
        schema.types.push(TypeDefinition::new("User", "v_user"));
        schema.types.push(TypeDefinition {
            is_error: true,
            fields: vec![
                FieldDefinition::new("status", FieldType::String),
                FieldDefinition::new("errorClass", FieldType::String),
            ],
            ..TypeDefinition::new("MutationError", "")
        });
        schema.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["User".to_string(), "MutationError".to_string()]),
        );
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "CreateUserResult")
        });

        // MutationErrorMockAdapter returns a failure row WITHOUT entity_type.
        let adapter = Arc::new(MutationErrorMockAdapter::bare());
        let executor = Executor::new(schema, adapter);

        let result = executor
            .execute(
                "mutation { createUser { __typename ... on MutationError { errorClass } } }",
                None,
            )
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("createUser")).unwrap();

        assert_eq!(
            data.get("__typename").and_then(|v| v.as_str()),
            Some("MutationError"),
            "without entity_type the union's is_error member must still be resolved"
        );
        assert_eq!(data.get("errorClass").and_then(|v| v.as_str()), Some("conflict"));
    }

    // ── Three-state field semantics (issue #221) ───────────────────────────
    //
    // Update mutations must preserve the absent/null/value distinction.
    // The executor passes the entire input object as a single JSONB arg so that
    // SQL functions can use `input ? 'field'` to test key presence.

    /// Mock adapter that captures the args passed to `execute_function_call`,
    /// plus the change-log `modification_type` (DML verb) routed through the
    /// outbox write. Returns a minimal v2 `mutation_response` so the full
    /// execution path runs.
    struct CapturingFunctionCallAdapter {
        captured_args:              std::sync::Mutex<Vec<serde_json::Value>>,
        /// Optional `updated_fields` value for the returned success row. `Null`
        /// (the default) omits the column so `parse_mutation_row` defaults it to an
        /// empty list; set via [`with_updated_fields`] to exercise the #433 path.
        updated_fields:             serde_json::Value,
        /// DML verb the executor handed the Change Spine on the last call, captured
        /// via `execute_function_call_with_changelog` to exercise the `input_style`
        /// path (the real verb must survive, not collapse to `UPDATE`).
        captured_modification_type: std::sync::Mutex<Option<String>>,
        /// Whether the executor opted the last change-log write into the pre-image
        /// (`ChangeLogWrite.pre_image`), captured to exercise the
        /// `changelog_pre_image` path. `None` if no change-log row was written.
        captured_pre_image:         std::sync::Mutex<Option<bool>>,
        /// The `object_type` fallback the executor handed the Change Spine on the last call
        /// (the type recorded when the function stamps none), or `None` if no change-log row
        /// was written.
        captured_object_type:       std::sync::Mutex<Option<String>>,
    }

    impl CapturingFunctionCallAdapter {
        fn new() -> Self {
            Self {
                captured_args:              std::sync::Mutex::new(Vec::new()),
                updated_fields:             serde_json::Value::Null,
                captured_modification_type: std::sync::Mutex::new(None),
                captured_pre_image:         std::sync::Mutex::new(None),
                captured_object_type:       std::sync::Mutex::new(None),
            }
        }

        /// Set the `updated_fields` column the success row reports (#433).
        fn with_updated_fields(mut self, updated_fields: serde_json::Value) -> Self {
            self.updated_fields = updated_fields;
            self
        }

        fn args(&self) -> Vec<serde_json::Value> {
            self.captured_args.lock().unwrap().clone()
        }

        /// The DML verb the executor handed the Change Spine for the last call
        /// (`"INSERT"`/`"UPDATE"`/`"DELETE"`/`"CUSTOM"`), or `None` if no
        /// change-log row was written.
        fn modification_type(&self) -> Option<String> {
            self.captured_modification_type.lock().unwrap().clone()
        }

        /// Whether the last change-log write opted into the pre-image
        /// (`changelog_pre_image`), or `None` if no change-log row was written.
        fn pre_image(&self) -> Option<bool> {
            *self.captured_pre_image.lock().unwrap()
        }

        /// The change-log `object_type` fallback of the last call.
        fn object_type(&self) -> Option<String> {
            self.captured_object_type.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl DatabaseAdapter for CapturingFunctionCallAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl CapturingFunctionCallAdapter {
        async fn execute_function_call(
            &self,
            _function_name: &str,
            args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            *self.captured_args.lock().unwrap() = args.to_vec();
            let mut row = std::collections::HashMap::new();

            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert("entity".to_string(), json!({"id": "1"}));
            // No `entity_type`: this double serves mutations of many return types, and a stamp
            // must name the one each returns (ruling AA 1). Unstamped, it resolves to it.
            // Only emit the column when set, so the default row stays unchanged for
            // the many existing tests that read `captured_args` and ignore the row.
            if !self.updated_fields.is_null() {
                row.insert("updated_fields".to_string(), self.updated_fields.clone());
            }
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            changelog: Option<&ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            // Capture the DML verb the executor derived from the mutation's
            // `operation` so a test can assert the Change Spine records the
            // real verb (not a blanket UPDATE). Then delegate so `args` are
            // captured by `execute_function_call` exactly as the real path does,
            // and put the rows to the gate as the PostgreSQL adapter does.
            *self.captured_modification_type.lock().unwrap() =
                changelog.map(|c| c.modification_type.to_string());
            *self.captured_pre_image.lock().unwrap() = changelog.map(|c| c.pre_image);
            *self.captured_object_type.lock().unwrap() =
                changelog.map(|c| c.object_type.to_string());
            let rows = self.execute_function_call(function_name, args).await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for CapturingFunctionCallAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    fn schema_with_update_mutation() -> CompiledSchema {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation,
        };
        let mut schema = CompiledSchema::new();
        schema.input_types.push(InputObjectDefinition {
            name:        "UpdateUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("id", "ID!"),
                InputFieldDefinition::new("name", "String"),
                InputFieldDefinition::new("email", "String"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "update_user".to_string(),
            return_type: "User".to_string(),
            sql_source: Some("update_user".to_string()),
            operation: MutationOperation::Update {
                table: "update_user".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("UpdateUserInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("update_user", "User")
        });
        schema
    }

    fn schema_with_camelcase_update_mutation() -> CompiledSchema {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        // GraphQL surface is camelCase over snake_case canonical field names.
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "BillingAddressInput".to_string(),
            fields:      vec![InputFieldDefinition::new("postal_code", "String")],
            description: None,
            metadata:    None,
        });
        schema.input_types.push(InputObjectDefinition {
            name:        "UpdateUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("id", "ID!"),
                InputFieldDefinition::new("full_name", "String"),
                InputFieldDefinition::new("billing_address", "BillingAddressInput"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "update_user".to_string(),
            return_type: "User".to_string(),
            sql_source: Some("update_user".to_string()),
            operation: MutationOperation::Update {
                table: "update_user".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("UpdateUserInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("update_user", "User")
        });
        schema
    }

    fn schema_with_insert_mutation() -> CompiledSchema {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation,
        };
        let mut schema = CompiledSchema::new();
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("name", "String!"),
                InputFieldDefinition::new("email", "String!"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "create_user".to_string(),
            return_type: "User".to_string(),
            sql_source: Some("create_user".to_string()),
            operation: MutationOperation::Insert {
                table: "create_user".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateUserInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("create_user", "User")
        });
        schema
    }

    /// #1418: one mutation serves a direct token and a delegated one. The function
    /// receives the optional `act` claim as NULL when the token lacks it, after the
    /// required `sub` claim, and the call goes through.
    #[tokio::test]
    async fn an_optional_claim_the_token_lacks_is_passed_to_the_function_as_null() {
        use crate::schema::InjectedParamSource;
        let mut schema = schema_with_insert_mutation();
        let mutation = &mut schema.mutations[0];
        mutation
            .inject_params
            .insert("p_user".to_string(), InjectedParamSource::Jwt("sub".to_string()));
        mutation
            .inject_params
            .insert("p_actor".to_string(), InjectedParamSource::JwtOptional("act".to_string()));
        schema.build_indexes();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);
        let direct = crate::security::SecurityContext {
            user_id:          "user-1".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       std::collections::HashMap::default(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            expires_at:       chrono::Utc::now() + chrono::Duration::hours(1),
            authenticated_at: chrono::Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        };

        executor
            .execute_mutation_with_security(
                "create_user",
                &serde_json::json!({"input": {"name": "Alice", "email": "a@example.com"}}),
                Some(&direct),
            )
            .await
            .expect("a direct token, with no `act` claim, must still call the function");

        let args = adapter_ref.args();
        assert_eq!(
            &args[args.len() - 2..],
            &[serde_json::json!("user-1"), serde_json::Value::Null],
            "inject params follow the arguments, the absent optional claim as NULL: {args:?}"
        );
    }

    /// Update mutations must pass the entire input object as a single JSONB arg,
    /// not flattened positional args. This is the prerequisite for three-state semantics.
    #[tokio::test]
    async fn update_mutation_passes_input_as_single_jsonb_arg() {
        let schema = schema_with_update_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": { "id": "abc", "name": "Alice", "email": "alice@example.com" }
        });
        executor
            .execute_mutation("update_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "update mutation must pass exactly one JSONB arg");
        assert!(
            captured[0].is_object(),
            "the single arg must be a JSON object (JSONB), got: {:?}",
            captured[0]
        );
        assert_eq!(captured[0]["id"], "abc");
        assert_eq!(captured[0]["name"], "Alice");
    }

    /// #400 — Update-path payload keys must be re-cased from the GraphQL
    /// (`camelCase`) surface to the schema's canonical (`snake_case`) field names
    /// before the JSONB reaches the SQL function. The Insert path gets this for
    /// free (positional args); the Update path forwarded the object verbatim, so
    /// a `camelCase` surface delivered `camelCase` keys a `snake_case` function can't read.
    #[tokio::test]
    async fn update_payload_keys_recased_to_naming_convention() {
        let schema = schema_with_camelcase_update_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        // Client speaks the camelCase GraphQL surface, including a nested object.
        let vars = serde_json::json!({
            "input": {
                "id": "abc",
                "fullName": "Alice",
                "billingAddress": { "postalCode": "75001" }
            }
        });
        executor
            .execute_mutation("update_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "update mutation must pass exactly one JSONB arg");
        let payload = &captured[0];

        // Top-level multi-word key must be recased to the canonical snake_case name.
        assert_eq!(
            payload["full_name"], "Alice",
            "camelCase 'fullName' must reach the function as snake_case 'full_name'; got {payload:?}"
        );
        assert!(
            payload.get("fullName").is_none(),
            "verbatim camelCase key must not survive; got {payload:?}"
        );

        // Nested input objects must be recursed and recased too.
        assert_eq!(
            payload["billing_address"]["postal_code"], "75001",
            "nested camelCase keys must be recased; got {payload:?}"
        );

        // Single-word keys are unchanged (camelCase == snake_case).
        assert_eq!(payload["id"], "abc");
    }

    /// #400 / acronym registry — Update-path recasing must honour digit-boundary
    /// and acronym field names: `dns1Id` → `dns_1_id`, `s3Key` → `s3_key`,
    /// `ipv4Cidr` → `ipv4_cidr`, `oauth2Token` → `oauth2_token`. The mechanism is
    /// forward-matching (`to_camel_case(canonical) == surface_key`), which is
    /// acronym-safe by construction — this pins it as a regression guard so the
    /// write path stays consistent with the acronym-aware read path.
    #[tokio::test]
    async fn update_payload_keys_recased_for_acronym_and_digit_names() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "UpdateResourceInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("id", "ID!"),
                InputFieldDefinition::new("dns_1_id", "String"),
                InputFieldDefinition::new("s3_key", "String"),
                InputFieldDefinition::new("ipv4_cidr", "String"),
                InputFieldDefinition::new("oauth2_token", "String"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "update_resource".to_string(),
            return_type: "Resource".to_string(),
            sql_source: Some("update_resource".to_string()),
            operation: MutationOperation::Update {
                table: "update_resource".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("UpdateResourceInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("update_resource", "Resource")
        });

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": {
                "id": "abc",
                "dns1Id": "d-1",
                "s3Key": "k-2",
                "ipv4Cidr": "10.0.0.0/8",
                "oauth2Token": "t-3"
            }
        });
        executor
            .execute_mutation("update_resource", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        let payload = &captured[0];
        assert_eq!(payload["dns_1_id"], "d-1", "digit-boundary key must recase; got {payload:?}");
        assert_eq!(payload["s3_key"], "k-2", "acronym key must recase; got {payload:?}");
        assert_eq!(payload["ipv4_cidr"], "10.0.0.0/8", "acronym key must recase; got {payload:?}");
        assert_eq!(payload["oauth2_token"], "t-3", "acronym key must recase; got {payload:?}");
        // No surface-cased key may survive.
        for stale in ["dns1Id", "s3Key", "ipv4Cidr", "oauth2Token"] {
            assert!(
                payload.get(stale).is_none(),
                "verbatim '{stale}' must not survive: {payload:?}"
            );
        }
    }

    /// Insert mutations must still flatten Input type fields to positional args
    /// (no three-state problem: absent ≡ NULL is correct for creates).
    #[tokio::test]
    async fn insert_mutation_flattens_fields_to_positional_args() {
        let schema = schema_with_insert_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": { "name": "Bob", "email": "bob@example.com" }
        });
        executor
            .execute_mutation("create_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        // Two positional args (name, email), not one JSONB object.
        assert_eq!(captured.len(), 2, "insert mutation must flatten to two positional args");
        assert_eq!(captured[0], "Bob");
        assert_eq!(captured[1], "bob@example.com");
    }

    /// End-to-end wiring for nested variables in an inline mutation-input literal:
    /// `create_user(input: { name: $n, email: $e })` with `$n`/`$e` supplied as
    /// request variables. The inline `input` literal is not in the `variables`
    /// map, so `classify` must carry the root field's arguments and
    /// `execute_mutation_impl` must merge them (resolving the nested `$var`s)
    /// before flattening — otherwise the SQL function sees the literal strings
    /// `"$n"`/`"$e"` (or the required-arg check rejects the call).
    #[tokio::test]
    async fn inline_mutation_input_literal_resolves_nested_variables() {
        let schema = schema_with_insert_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "n": "Bob", "e": "bob@example.com" });
        executor
            .execute(
                "mutation M($n: String!, $e: String!) { \
                 create_user(input: { name: $n, email: $e }) { id } }",
                Some(&vars),
            )
            .await
            .unwrap();

        let captured = adapter_ref.args();
        // Insert flattens CreateUserInput → positional [name, email], with the
        // nested $n/$e substituted (not the verbatim "$n"/"$e").
        assert_eq!(captured.len(), 2, "insert flattens to two positional args, got {captured:?}");
        assert_eq!(captured[0], "Bob", "nested $n must resolve, got {:?}", captured[0]);
        assert_eq!(captured[1], "bob@example.com", "nested $e must resolve, got {:?}", captured[1]);
    }

    /// #1154 — an argument the mutation does not declare must be refused rather
    /// than dropped. Binding is positional over `mutation_def.arguments`, so an
    /// undeclared argument never reached the SQL function: the write ran without
    /// it and reported success.
    #[tokio::test]
    async fn undeclared_mutation_argument_is_rejected() {
        let schema = schema_with_insert_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let doc = r#"mutation { create_user(input: { name: "Bob", email: "b@x.tld" },
                                            dryRun: true) { id } }"#;
        let err = executor
            .execute(doc, None)
            .await
            .expect_err("an argument the mutation does not declare must not execute");

        assert!(
            matches!(&err, FraiseQLError::Validation { message, .. }
                if message.contains("Unknown argument 'dryRun'")
                    && message.contains("Mutation.create_user")),
            "message must name the argument and the field: {err:?}"
        );
        assert!(
            adapter_ref.args().is_empty(),
            "the write must not run at all, got args: {:?}",
            adapter_ref.args()
        );
    }

    /// The declared argument still binds — this refuses unknown *names*, not
    /// arguments.
    #[tokio::test]
    async fn declared_mutation_argument_is_accepted() {
        let schema = schema_with_insert_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let doc = r#"mutation { create_user(input: { name: "Bob", email: "b@x.tld" }) { id } }"#;
        executor.execute(doc, None).await.unwrap();

        assert_eq!(adapter_ref.args().len(), 2, "the declared input must still bind positionally");
    }

    /// #400 — On the Insert/Custom flatten path, a field whose type is a nested
    /// input object is passed as one positional JSONB arg. Its *keys* must be
    /// recased to canonical names too (recursing into nested objects/lists), or a
    /// `jsonb_populate_record(NULL::config, $arg)` in the SQL function sees
    /// camelCase keys it cannot read — the same #400 no-op the Update path fixes.
    #[tokio::test]
    async fn insert_recases_nested_composite_input_keys() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "ServerConfigInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("s3_bucket", "String"),
                InputFieldDefinition::new("max_connections", "Int"),
            ],
            description: None,
            metadata:    None,
        });
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateServerInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("name", "String!"),
                InputFieldDefinition::new("config", "ServerConfigInput"),
                InputFieldDefinition::new("tags", "[ServerConfigInput!]"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "create_server".to_string(),
            return_type: "Server".to_string(),
            sql_source: Some("create_server".to_string()),
            operation: MutationOperation::Insert {
                table: "create_server".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateServerInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("create_server", "Server")
        });

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": {
                "name": "web-1",
                "config": { "s3Bucket": "assets", "maxConnections": 10 },
                "tags": [{ "s3Bucket": "logs", "maxConnections": 2 }]
            }
        });
        executor
            .execute_mutation("create_server", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        // Positional: [name, config, tags].
        assert_eq!(captured.len(), 3, "insert flattens top-level fields positionally");
        assert_eq!(captured[0], "web-1");
        // Nested composite object keys must be recased.
        assert_eq!(
            captured[1]["s3_bucket"], "assets",
            "nested composite key must recase on the insert path; got {:?}",
            captured[1]
        );
        assert_eq!(captured[1]["max_connections"], 10);
        assert!(captured[1].get("s3Bucket").is_none(), "verbatim nested key must not survive");
        // Lists of nested composites must recase each element.
        assert_eq!(
            captured[2][0]["s3_bucket"], "logs",
            "nested composite key in a list must recase; got {:?}",
            captured[2]
        );
        assert_eq!(captured[2][0]["max_connections"], 2);
    }

    // ── input_style: decouple input-passing from the DML verb ────────────────
    //
    // A backend using the single-JSONB wrapper convention
    // (`fn(input_payload jsonb, …)`) can register the *real* verb
    // (`Insert`/`Delete`/`Custom`) plus `input_style = jsonb` instead of being
    // forced to `Update` purely to opt into single-JSONB passing — so the
    // Change Spine records the true `modification_type`. `flatten` (the default)
    // is byte-for-byte today's behaviour.

    /// Build a single-`input`-arg mutation with an explicit `operation` and
    /// `input_style`, over a *registered* Input type and a `CamelCase` surface —
    /// so `flatten` flattens to positional args while `jsonb` forwards one
    /// re-cased JSONB blob. (`full_name` exercises the #400 recasing.)
    fn schema_input_style_mutation(
        operation: crate::schema::MutationOperation,
        input_style: crate::schema::InputStyle,
    ) -> CompiledSchema {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "SaveUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("id", "ID!"),
                InputFieldDefinition::new("full_name", "String"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "save_user".to_string(),
            return_type: "User".to_string(),
            sql_source: Some("save_user".to_string()),
            operation,
            input_style,
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("SaveUserInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("save_user", "User")
        });
        schema
    }

    /// A mutation registered with the real verb (`Insert`) **plus**
    /// `input_style = jsonb` must forward the whole `input` as ONE JSONB arg —
    /// exactly as an `Update` does today, including the #400 acronym-aware key
    /// recasing — instead of flattening to positional columns. Because the verb
    /// is no longer forced to `Update`, the Change Spine records the true
    /// `INSERT`.
    #[tokio::test]
    async fn insert_with_jsonb_input_style_forwards_single_jsonb_and_logs_real_verb() {
        use crate::schema::{InputStyle, MutationOperation};
        let schema = schema_input_style_mutation(
            MutationOperation::Insert {
                table: "save_user".to_string(),
            },
            InputStyle::Jsonb,
        );
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "id": "u1", "fullName": "Alice" } });
        executor
            .execute_mutation("save_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(
            captured.len(),
            1,
            "input_style=jsonb must pass exactly one JSONB arg, got {captured:?}"
        );
        assert!(
            captured[0].is_object(),
            "the single arg must be a JSON object (JSONB): {:?}",
            captured[0]
        );
        assert_eq!(captured[0]["id"], "u1");
        // #400 recasing composes on the forced single-JSONB path.
        assert_eq!(
            captured[0]["full_name"], "Alice",
            "camelCase key must recase to canonical on the jsonb path: {:?}",
            captured[0]
        );
        assert!(
            captured[0].get("fullName").is_none(),
            "verbatim camelCase key must not survive: {:?}",
            captured[0]
        );
        // The real verb survives → Change Spine logs INSERT, not a blanket UPDATE.
        assert_eq!(
            adapter_ref.modification_type().as_deref(),
            Some("INSERT"),
            "Change Spine must record the real verb"
        );
    }

    /// `input_style = jsonb` is orthogonal to the verb: a `Delete` keeps its
    /// verb (Change Spine logs `DELETE`) while still receiving the whole input
    /// as one JSONB arg.
    #[tokio::test]
    async fn delete_with_jsonb_input_style_forwards_single_jsonb_and_logs_delete_verb() {
        use crate::schema::{InputStyle, MutationOperation};
        let schema = schema_input_style_mutation(
            MutationOperation::Delete {
                table: "save_user".to_string(),
            },
            InputStyle::Jsonb,
        );
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "id": "u1" } });
        executor
            .execute_mutation("save_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(
            captured.len(),
            1,
            "input_style=jsonb must pass one JSONB arg for a Delete too, got {captured:?}"
        );
        assert_eq!(captured[0]["id"], "u1");
        assert_eq!(adapter_ref.modification_type().as_deref(), Some("DELETE"));
    }

    /// Regression guard: the default / explicit `flatten` input style is
    /// unchanged — a non-`Update` mutation still flattens its Input type to
    /// positional args (and logs its real verb).
    #[tokio::test]
    async fn flatten_input_style_insert_still_flattens_to_positional_args() {
        use crate::schema::{InputStyle, MutationOperation};
        let schema = schema_input_style_mutation(
            MutationOperation::Insert {
                table: "save_user".to_string(),
            },
            InputStyle::Flatten,
        );
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "id": "u1", "fullName": "Alice" } });
        executor
            .execute_mutation("save_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 2, "flatten must keep positional args, got {captured:?}");
        assert_eq!(captured[0], "u1");
        assert_eq!(captured[1], "Alice");
        assert_eq!(adapter_ref.modification_type().as_deref(), Some("INSERT"));
    }

    /// #456 regression: a declared Input type whose field names are stored
    /// **already camelCased** — exactly what the Python SDK emits (it
    /// pre-camelCases field names, `registry.py:233`) — must still reach the SQL
    /// function as `snake_case` on the single-JSONB path. Before the fix the
    /// field-driven recase mapped the surface key back to the *stored* camelCase
    /// name (a no-op), so a function reading `p_input->>'shipping_address'` saw
    /// NULL. The recase now normalises every canonical key with the engine's
    /// acronym-aware `to_snake_case`, matching the raw-`JSON` fallback path.
    #[tokio::test]
    async fn jsonb_input_style_camelcase_input_fields_recased_to_snake() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, InputStyle, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        // Field names stored already-camelCased, mirroring real SDK output.
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateOrderInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("shippingAddress", "String!"),
                InputFieldDefinition::new("customerNote", "String!"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "create_order".to_string(),
            return_type: "Order".to_string(),
            sql_source: Some("create_order".to_string()),
            operation: MutationOperation::Insert {
                table: "create_order".to_string(),
            },
            input_style: InputStyle::Jsonb,
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateOrderInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("create_order", "Order")
        });

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": { "shippingAddress": "1 Main St", "customerNote": "gift" }
        });
        executor
            .execute_mutation("create_order", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "jsonb path passes one JSONB arg, got {captured:?}");
        assert_eq!(
            captured[0]["shipping_address"], "1 Main St",
            "camelCase-stored input field must reach the function as snake_case: {:?}",
            captured[0]
        );
        assert_eq!(captured[0]["customer_note"], "gift");
        assert!(
            captured[0].get("shippingAddress").is_none(),
            "verbatim camelCase key must not survive to the SQL function: {:?}",
            captured[0]
        );
    }

    /// #456 ROOT CAUSE: the compiler emits an input-type mutation argument as
    /// `FieldType::Object(name)` — never `FieldType::Input` — so a *real compiled*
    /// schema's `input` arg is `Object("CreateOrderInput")`. The runtime must
    /// recognise an `Object` naming a registered input type as a structured input
    /// (via `find_input_type`), or it skips both the single-JSONB and flatten
    /// branches and forwards the payload verbatim — camelCase keys to the SQL
    /// function, no recasing, regardless of `naming_convention`. This mirrors the
    /// beta-tester's `createEmailTemplate` (Object arg + `input_style=jsonb` +
    /// camelCase surface); before the fix it forwarded camelCase verbatim.
    #[tokio::test]
    async fn jsonb_object_typed_input_arg_recased_to_snake() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, InputStyle, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateOrderInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("shippingAddress", "String!"),
                InputFieldDefinition::new("customerNote", "String!"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "createOrder".to_string(),
            return_type: "Order".to_string(),
            sql_source: Some("app.create_order".to_string()),
            operation: MutationOperation::Insert {
                table: "app.create_order".to_string(),
            },
            input_style: InputStyle::Jsonb,
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                // The real compiled shape: Object naming a registered input type
                // (NOT FieldType::Input, which the compiler never emits).
                arg_type:      FieldType::Object("CreateOrderInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("createOrder", "Order")
        });

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": { "shippingAddress": "1 Main St", "customerNote": "gift" }
        });
        executor
            .execute_mutation("createOrder", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "jsonb path passes one JSONB arg, got {captured:?}");
        assert_eq!(
            captured[0]["shipping_address"], "1 Main St",
            "Object-typed input arg must be recognised and recased to snake_case: {:?}",
            captured[0]
        );
        assert_eq!(captured[0]["customer_note"], "gift");
        assert!(
            captured[0].get("shippingAddress").is_none(),
            "verbatim camelCase key must not survive: {:?}",
            captured[0]
        );
    }

    /// The flatten path (Insert without `input_style=jsonb`) must likewise
    /// recognise an `Object`-typed input arg and flatten its camelCase fields to
    /// positional args with `snake_case` column names — not fall through to verbatim
    /// forwarding (#456).
    #[tokio::test]
    async fn flatten_object_typed_input_arg_recognised_and_flattened() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, InputStyle, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateOrderInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("id", "ID!"),
                InputFieldDefinition::new("fullName", "String!"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "createOrder".to_string(),
            return_type: "Order".to_string(),
            sql_source: Some("app.create_order".to_string()),
            operation: MutationOperation::Insert {
                table: "app.create_order".to_string(),
            },
            input_style: InputStyle::Flatten,
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Object("CreateOrderInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("createOrder", "Order")
        });

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "id": "u1", "fullName": "Alice" } });
        executor
            .execute_mutation("createOrder", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(
            captured.len(),
            2,
            "Object-typed input arg must flatten to positional args, got {captured:?}"
        );
        assert_eq!(captured[0], "u1");
        assert_eq!(captured[1], "Alice");
    }

    /// End-to-end guard for the #456 follow-up: a camelCase schema serialized to
    /// JSON and re-loaded via `CompiledSchema::from_json` (the server's real load
    /// path) must keep `naming_convention = CamelCase`, and an **inline-literal**
    /// `input_style="jsonb"` mutation driven through `Executor::execute` (the real
    /// GraphQL request path, not the typed API) must reach the SQL function as
    /// `snake_case`. The follow-up report suspected the convention was dropped to
    /// `Preserve` somewhere between load and the runner; this reproduces that whole
    /// pipeline in one test so any such regression fails here.
    #[tokio::test]
    async fn jsonb_inline_literal_recases_after_from_json_roundtrip() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, InputStyle, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateOrderInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("shippingAddress", "String!"),
                InputFieldDefinition::new("customerNote", "String!"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "createOrder".to_string(),
            return_type: "Order".to_string(),
            sql_source: Some("app.create_order".to_string()),
            operation: MutationOperation::Insert {
                table: "app.create_order".to_string(),
            },
            input_style: InputStyle::Jsonb,
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateOrderInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("createOrder", "Order")
        });

        // Round-trip through the real load path: serialize **with a
        // `_content_hash`** so `from_json` takes the same canonicalize → reserialize
        // → deserialize branch the CLI-produced server file does (not the
        // hash-absent shortcut), then re-parse exactly as `CompiledSchemaLoader`
        // does on the server.
        let mut value: serde_json::Value =
            serde_json::from_str(&schema.to_json().unwrap()).unwrap();
        value
            .as_object_mut()
            .unwrap()
            .insert("_content_hash".to_string(), serde_json::Value::String(schema.content_hash()));
        let json = serde_json::to_string(&value).unwrap();
        let loaded = CompiledSchema::from_json(&json, false).unwrap();
        assert_eq!(
            loaded.naming_convention,
            NamingConvention::CamelCase,
            "naming_convention must survive the serialize/from_json round-trip"
        );

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(loaded, adapter);

        // Inline-literal argument (no `$variable`) — the report's exact repro and
        // the standard GraphQL surface.
        let doc = r#"mutation { createOrder(input: { shippingAddress: "1 Main St", customerNote: "x" }) { id } }"#;
        executor.execute(doc, None).await.unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "jsonb path passes one JSONB arg, got {captured:?}");
        assert_eq!(
            captured[0]["shipping_address"], "1 Main St",
            "inline-literal camelCase input must reach the function as snake_case: {:?}",
            captured[0]
        );
        assert_eq!(captured[0]["customer_note"], "x");
        assert!(
            captured[0].get("shippingAddress").is_none(),
            "verbatim camelCase key must not survive to the SQL function: {:?}",
            captured[0]
        );
    }

    /// Server-path guard for the #456 follow-up: the GraphQL handler calls
    /// `execute_with_security` for authenticated requests (handler.rs:649) — a
    /// different dispatch entry than `execute`. A jsonb mutation driven through it
    /// must recase `camelCase` input to `snake_case` identically, so the
    /// authenticated path cannot silently diverge from the anonymous one.
    #[tokio::test]
    async fn jsonb_mutation_recases_through_execute_with_security() {
        use chrono::Utc;

        use crate::{
            schema::{
                FieldType, InputFieldDefinition, InputObjectDefinition, InputStyle,
                MutationDefinition, MutationOperation, NamingConvention,
            },
            security::SecurityContext,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateOrderInput".to_string(),
            fields:      vec![InputFieldDefinition::new("shippingAddress", "String!")],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "createOrder".to_string(),
            return_type: "Order".to_string(),
            sql_source: Some("app.create_order".to_string()),
            operation: MutationOperation::Insert {
                table: "app.create_order".to_string(),
            },
            input_style: InputStyle::Jsonb,
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateOrderInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("createOrder", "Order")
        });
        schema.build_indexes();

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let sec_ctx = SecurityContext {
            user_id:          "u".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       std::collections::HashMap::default(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        };

        let doc = r#"mutation { createOrder(input: { shippingAddress: "1 Main St" }) { id } }"#;
        executor.execute_with_security(doc, None, &sec_ctx).await.unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "jsonb path passes one JSONB arg, got {captured:?}");
        assert_eq!(
            captured[0]["shipping_address"], "1 Main St",
            "authenticated dispatch must recase camelCase input to snake_case: {:?}",
            captured[0]
        );
        assert!(
            captured[0].get("shippingAddress").is_none(),
            "verbatim camelCase key must not survive: {:?}",
            captured[0]
        );
    }

    // ── changelog_pre_image threading (opt-in pre-image) ──────────────────
    //
    // The per-mutation `changelog_pre_image` flag rides on the `ChangeLogWrite`
    // the executor hands the adapter: when set, the outbox CTE also records the
    // entity's before-state into `object_data_before`. The flag must reach the
    // adapter intact; off (the default) is byte-for-byte today's behaviour.

    /// `changelog_pre_image = true` reaches the adapter's `ChangeLogWrite`, so the
    /// outbox CTE opts into the `object_data_before` pre-image.
    #[tokio::test]
    async fn changelog_pre_image_flag_reaches_the_change_log_write() {
        use crate::schema::{InputStyle, MutationOperation};
        let mut schema = schema_input_style_mutation(
            MutationOperation::Update {
                table: "save_user".to_string(),
            },
            InputStyle::Flatten,
        );
        schema.mutations[0].changelog_pre_image = true;
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "id": "u1", "fullName": "Alice" } });
        executor
            .execute_mutation("save_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        assert_eq!(
            adapter_ref.pre_image(),
            Some(true),
            "changelog_pre_image=true must reach the ChangeLogWrite"
        );
    }

    /// Ruling AA 1: the change-log records the type the write produced. When the function
    /// stamps none, that is the one type a success can be — `User` for a mutation returning
    /// `User | ValidationError` — never the union's name, which is no entity type.
    #[tokio::test]
    async fn the_change_log_records_the_type_an_unstamped_success_is() {
        use crate::schema::{
            FieldDefinition, FieldType, MutationDefinition, TypeDefinition, UnionDefinition,
        };
        let mut schema = CompiledSchema::new();
        let mut user = TypeDefinition::new("User", "v_user");
        user.fields = vec![FieldDefinition::new("id", FieldType::Id)];
        schema.types.push(user);
        schema.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("ValidationError", "")
        });
        schema.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["User".to_string(), "ValidationError".to_string()]),
        );
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "CreateUserResult")
        });
        schema.build_indexes();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        Executor::new(schema, adapter)
            .execute("mutation { createUser { ... on User { id } } }", None)
            .await
            .unwrap();

        assert_eq!(adapter_ref.object_type().as_deref(), Some("User"));
    }

    /// Default / absent `changelog_pre_image` leaves the pre-image off — the
    /// outbox CTE writes only the after-image, byte-for-byte today's behaviour.
    #[tokio::test]
    async fn changelog_pre_image_defaults_off() {
        use crate::schema::{InputStyle, MutationOperation};
        let schema = schema_input_style_mutation(
            MutationOperation::Insert {
                table: "save_user".to_string(),
            },
            InputStyle::Flatten,
        );
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "id": "u1", "fullName": "Alice" } });
        executor
            .execute_mutation("save_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        assert_eq!(
            adapter_ref.pre_image(),
            Some(false),
            "an unset changelog_pre_image must leave the pre-image off"
        );
    }

    // ── #400 tail: single-JSONB-arg recasing when no Input type drives it ──
    //
    // The field-driven `recase_input_payload` only fires when a *registered*
    // Input type supplies the per-field name map. A custom `mutation(input: JSON)`
    // — or an Update whose Input type is absent from the compiled schema — reaches
    // the SQL function with the whole object as one verbatim camelCase JSONB blob.
    // These pin the acronym-aware key-driven `to_snake_case` fallback on that path.

    /// Build a single-`input`-arg mutation with an explicit operation and arg type;
    /// optionally register `input_type` so the field-driven path is/ isn't available.
    fn schema_single_input_arg(
        operation: crate::schema::MutationOperation,
        arg_type: crate::schema::FieldType,
        input_type: Option<crate::schema::InputObjectDefinition>,
    ) -> CompiledSchema {
        use crate::schema::{MutationDefinition, NamingConvention};
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        if let Some(it) = input_type {
            schema.input_types.push(it);
        }
        schema.mutations.push(MutationDefinition {
            name: "m".to_string(),
            return_type: "Res".to_string(),
            sql_source: Some("m".to_string()),
            operation,
            arguments: vec![crate::schema::ArgumentDefinition {
                name: "input".to_string(),
                arg_type,
                nullable: false,
                default_value: None,
                description: None,
                deprecation: None,
            }],
            ..MutationDefinition::new("m", "Res")
        });
        schema
    }

    /// A digit/acronym/nested payload to assert the bijective `to_snake_case`
    /// mapping matches the read path on the key-driven single-JSONB path.
    fn acronym_digit_nested_vars() -> serde_json::Value {
        serde_json::json!({
            "input": {
                "dns1Id": "d",
                "s3Key": "k",
                "ipv4Cidr": "10.0.0.0/8",
                "oauth2Token": "t",
                "locationId": "loc",
                "nested": { "fullName": "Alice", "s3Key": "n" },
                "tags": [{ "maxConnections": 2 }]
            }
        })
    }

    fn assert_acronym_digit_nested_recased(p: &serde_json::Value) {
        assert_eq!(p["dns_1_id"], "d", "digit boundary split: {p:?}");
        assert_eq!(p["s3_key"], "k", "s3 acronym kept whole: {p:?}");
        assert_eq!(p["ipv4_cidr"], "10.0.0.0/8", "ipv4 acronym kept whole: {p:?}");
        assert_eq!(p["oauth2_token"], "t", "oauth2 acronym kept whole: {p:?}");
        assert_eq!(p["location_id"], "loc", "plain camel→snake: {p:?}");
        // Recurse into nested objects and lists of objects.
        assert_eq!(p["nested"]["full_name"], "Alice", "nested object recased: {p:?}");
        assert_eq!(p["nested"]["s3_key"], "n", "nested acronym recased: {p:?}");
        assert_eq!(p["tags"][0]["max_connections"], 2, "list element recased: {p:?}");
        for stale in ["dns1Id", "s3Key", "ipv4Cidr", "oauth2Token", "locationId"] {
            assert!(p.get(stale).is_none(), "verbatim '{stale}' must not survive: {p:?}");
        }
    }

    /// A custom `mutation(input: JSON)` passes the whole input object as one JSONB
    /// arg with NO registered Input type. Its keys must still be recased with the
    /// canonical acronym-aware `to_snake_case`, recursing into nested objects/lists.
    #[tokio::test]
    async fn custom_json_input_arg_recases_keys_to_snake_case() {
        use crate::schema::{FieldType, MutationOperation};
        let schema = schema_single_input_arg(MutationOperation::Custom, FieldType::Json, None);
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        executor
            .execute_mutation("m", Some(&acronym_digit_nested_vars()), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "custom JSON input must pass as exactly one JSONB arg");
        assert_acronym_digit_nested_recased(&captured[0]);
    }

    /// Same key-driven recasing on an Update whose `input` arg is a raw `JSON`
    /// scalar (no Input type) — exercises the three-state single-JSONB path too.
    #[tokio::test]
    async fn update_json_input_arg_recases_keys_to_snake_case() {
        use crate::schema::{FieldType, MutationOperation};
        let schema = schema_single_input_arg(
            MutationOperation::Update {
                table: "m".to_string(),
            },
            FieldType::Json,
            None,
        );
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        executor
            .execute_mutation("m", Some(&acronym_digit_nested_vars()), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "update JSON input must pass as exactly one JSONB arg");
        assert_acronym_digit_nested_recased(&captured[0]);
    }

    /// An Update whose declared Input type is ABSENT from the compiled schema
    /// (incomplete schema) must not leak verbatim camelCase: `recase_input_payload`
    /// falls back to the key-driven transform instead of forwarding the object as-is.
    #[tokio::test]
    async fn update_unregistered_input_type_recases_keys() {
        use crate::schema::{FieldType, MutationOperation};
        let schema = schema_single_input_arg(
            MutationOperation::Update {
                table: "m".to_string(),
            },
            FieldType::Input("MissingInput".to_string()),
            None, // deliberately not registered
        );
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        executor
            .execute_mutation("m", Some(&acronym_digit_nested_vars()), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "unregistered-input update must still pass one JSONB arg");
        assert_acronym_digit_nested_recased(&captured[0]);
    }

    /// A raw `input: JSON` arg may be a top-level array (not an object): each
    /// object element's keys must be recased, and the whole array forwarded as one
    /// JSONB arg (no regression vs. the old catch-all path, which passed it through).
    #[tokio::test]
    async fn custom_json_input_array_value_recases_elements() {
        use crate::schema::{FieldType, MutationOperation};
        let schema = schema_single_input_arg(MutationOperation::Custom, FieldType::Json, None);
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": [{ "s3Key": "a", "maxConnections": 1 }, { "dns1Id": "b" }]
        });
        executor
            .execute_mutation("m", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "array input must pass as exactly one JSONB arg");
        let arr = &captured[0];
        assert_eq!(arr[0]["s3_key"], "a", "array element keys recased: {arr:?}");
        assert_eq!(arr[0]["max_connections"], 1, "{arr:?}");
        assert_eq!(arr[1]["dns_1_id"], "b", "{arr:?}");
    }

    /// `Preserve` naming leaves a single-JSONB custom input untouched (the GraphQL
    /// surface already uses canonical names — recasing must be opt-in via `CamelCase`).
    #[tokio::test]
    async fn custom_json_input_preserve_convention_unchanged() {
        use crate::schema::{FieldType, MutationOperation, NamingConvention};
        let mut schema = schema_single_input_arg(MutationOperation::Custom, FieldType::Json, None);
        schema.naming_convention = NamingConvention::Preserve;
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "dns1Id": "d", "s3Key": "k" } });
        executor
            .execute_mutation("m", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let p = &adapter_ref.args()[0];
        assert_eq!(p["dns1Id"], "d", "Preserve must not recase: {p:?}");
        assert_eq!(p["s3Key"], "k", "Preserve must not recase: {p:?}");
    }

    /// A single scalar `input` arg (e.g. `String`) is NOT a JSONB payload — it must
    /// still pass straight through as a positional scalar, not be misrouted to the
    /// single-JSONB path (which would reject it as a missing object). Regression
    /// guard for the structured-arg gate.
    #[tokio::test]
    async fn single_scalar_input_arg_passes_through() {
        use crate::schema::{FieldType, MutationOperation};
        let schema = schema_single_input_arg(MutationOperation::Custom, FieldType::String, None);
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": "hello" });
        executor
            .execute_mutation("m", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "scalar input passes as one positional arg");
        assert_eq!(captured[0], "hello", "scalar input value must pass through verbatim");
    }

    /// A free-form `JSON` argument on a MULTI-argument mutation is out of scope:
    /// only the single-`input` convention is recased, so its camelCase keys survive.
    #[tokio::test]
    async fn multiarg_json_argument_not_recased() {
        use crate::schema::{FieldType, MutationDefinition, MutationOperation, NamingConvention};
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.mutations.push(MutationDefinition {
            name: "m".to_string(),
            return_type: "Res".to_string(),
            sql_source: Some("m".to_string()),
            operation: MutationOperation::Custom,
            arguments: vec![
                crate::schema::ArgumentDefinition {
                    name:          "name".to_string(),
                    arg_type:      FieldType::String,
                    nullable:      false,
                    default_value: None,
                    description:   None,
                    deprecation:   None,
                },
                crate::schema::ArgumentDefinition {
                    name:          "metadata".to_string(),
                    arg_type:      FieldType::Json,
                    nullable:      false,
                    default_value: None,
                    description:   None,
                    deprecation:   None,
                },
            ],
            ..MutationDefinition::new("m", "Res")
        });
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "name": "x", "metadata": { "s3Key": "k" } });
        executor
            .execute_mutation("m", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 2);
        assert_eq!(captured[0], "x");
        assert_eq!(
            captured[1]["s3Key"], "k",
            "free-form JSON arg on a multi-arg mutation must NOT be recased: {:?}",
            captured[1]
        );
    }

    // ── #414: required input-field enforcement on the flatten path ─────────

    /// Insert/Delete/Custom flatten path schema with a required field
    /// (`contract_id`: non-null, no default), an optional field (`currency`),
    /// and a non-null field that has a default (`active` — NOT required).
    fn schema_with_required_field_insert() -> CompiledSchema {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation,
        };
        let mut schema = CompiledSchema::new();
        schema.input_types.push(InputObjectDefinition {
            name:        "CreatePriceInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("contract_id", "ID").with_nullable(false),
                InputFieldDefinition::new("currency", "String").with_nullable(true),
                InputFieldDefinition::new("active", "Boolean")
                    .with_nullable(false)
                    .with_default_value("true"),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "create_price".to_string(),
            return_type: "Price".to_string(),
            sql_source: Some("create_price".to_string()),
            operation: MutationOperation::Insert {
                table: "create_price".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreatePriceInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("create_price", "Price")
        });
        schema
    }

    /// A required input field omitted from a create must be rejected with a
    /// validation error before the DB call — not passed through as SQL NULL.
    #[tokio::test]
    async fn insert_rejects_omitted_required_input_field() {
        let schema = schema_with_required_field_insert();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        // contract_id (required) is omitted; active has a default, so absent is fine.
        let vars = serde_json::json!({ "input": { "currency": "USD" } });
        let err = executor
            .execute_mutation("create_price", Some(&vars), any_write_selections())
            .await
            .unwrap_err();

        match err {
            FraiseQLError::Validation { message, .. } => {
                assert!(
                    message.contains("contract_id"),
                    "validation error must name the missing field; got: {message}"
                );
            },
            other => panic!("expected Validation error, got: {other:?}"),
        }
        assert!(
            adapter_ref.args().is_empty(),
            "the DB function must NOT be called when a required field is missing"
        );
    }

    /// An explicit `null` for a required input field is just as invalid as omitting it.
    #[tokio::test]
    async fn insert_rejects_explicit_null_required_input_field() {
        let schema = schema_with_required_field_insert();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({ "input": { "contract_id": null, "currency": "USD" } });
        let err = executor
            .execute_mutation("create_price", Some(&vars), any_write_selections())
            .await
            .unwrap_err();

        assert!(
            matches!(err, FraiseQLError::Validation { .. }),
            "expected Validation, got {err:?}"
        );
        assert!(
            adapter_ref.args().is_empty(),
            "DB must not be called for an explicit-null required field"
        );
    }

    /// When the required field is present (and a non-null-with-default field is
    /// omitted), the mutation proceeds and the field reaches the DB.
    #[tokio::test]
    async fn insert_accepts_present_required_input_field() {
        let schema = schema_with_required_field_insert();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        // contract_id present; active (non-null but defaulted) omitted → still OK.
        let vars = serde_json::json!({ "input": { "contract_id": "c1", "currency": "USD" } });
        executor
            .execute_mutation("create_price", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 3, "all three input fields flatten to positional args");
        assert_eq!(captured[0], "c1");
        assert_eq!(captured[1], "USD");
    }

    /// A non-null input field that carries a default is NOT required: omitting it
    /// must not be rejected (the default covers it).
    #[tokio::test]
    async fn insert_non_null_field_with_default_is_not_required() {
        let schema = schema_with_required_field_insert();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let executor = Executor::new(schema, adapter);

        // Provide the genuinely-required field; omit `active` (non-null + default).
        let vars = serde_json::json!({ "input": { "contract_id": "c1" } });
        let result = executor
            .execute_mutation("create_price", Some(&vars), any_write_selections())
            .await;
        assert!(
            result.is_ok(),
            "omitting a defaulted non-null field must not be rejected: {result:?}"
        );
    }

    /// Update mutations use partial-update (three-state) semantics: an omitted
    /// required field means "leave unchanged" and must NOT be rejected here.
    /// (`schema_with_update_mutation`'s input has a non-null `id`.)
    #[tokio::test]
    async fn update_does_not_enforce_required_input_field() {
        let mut schema = schema_with_update_mutation();
        // Make `id` genuinely required to prove the update path still skips enforcement.
        if let Some(input) = schema.input_types.iter_mut().find(|t| t.name == "UpdateUserInput") {
            if let Some(id) = input.fields.iter_mut().find(|f| f.name == "id") {
                id.nullable = false;
            }
        }
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let executor = Executor::new(schema, adapter);

        // `id` (now required) omitted — update must still proceed (three-state).
        let vars = serde_json::json!({ "input": { "name": "Alice" } });
        let result = executor
            .execute_mutation("update_user", Some(&vars), any_write_selections())
            .await;
        assert!(result.is_ok(), "update path must not enforce required input fields: {result:?}");
    }

    /// Under `CamelCase` naming the client sends the surface (camelCase) key for a
    /// canonical `snake_case` required field. The required check must look it up by
    /// the surface name (`display_name`) so a present field is not falsely rejected
    /// — and the value must actually reach the DB (fixes a latent value-pass miss).
    #[tokio::test]
    async fn insert_camelcase_required_field_found_by_surface_name() {
        use crate::schema::{
            FieldType, InputFieldDefinition, InputObjectDefinition, MutationDefinition,
            MutationOperation, NamingConvention,
        };
        let mut schema = CompiledSchema::new();
        schema.naming_convention = NamingConvention::CamelCase;
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("full_name", "String").with_nullable(false),
            ],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            name: "create_user".to_string(),
            return_type: "User".to_string(),
            sql_source: Some("create_user".to_string()),
            operation: MutationOperation::Insert {
                table: "create_user".to_string(),
            },
            arguments: vec![crate::schema::ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateUserInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("create_user", "User")
        });

        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        // Client speaks camelCase: `fullName` maps to canonical `full_name`.
        let vars = serde_json::json!({ "input": { "fullName": "Alice" } });
        executor
            .execute_mutation("create_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1, "single field flattens to one positional arg");
        assert_eq!(
            captured[0], "Alice",
            "camelCase 'fullName' must be found by surface name and reach the DB; got {captured:?}"
        );
    }

    /// Explicitly-null fields in an update input must survive as key-present-null
    /// in the JSONB arg, not be dropped. This is what allows SET field = NULL.
    #[tokio::test]
    async fn update_mutation_preserves_explicit_null_in_jsonb() {
        let schema = schema_with_update_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        let vars = serde_json::json!({
            "input": { "id": "abc", "name": null }
        });
        executor
            .execute_mutation("update_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1);
        let obj = captured[0].as_object().unwrap();
        assert!(obj.contains_key("name"), "key 'name' must be present in JSONB (explicit null)");
        assert!(obj["name"].is_null(), "'name' must be null, not absent");
    }

    /// Absent fields in an update input must not appear in the JSONB arg at all,
    /// distinguishing "leave unchanged" from "set to NULL".
    #[tokio::test]
    async fn update_mutation_absent_field_not_in_jsonb() {
        let schema = schema_with_update_mutation();
        let adapter = Arc::new(CapturingFunctionCallAdapter::new());
        let adapter_ref = Arc::clone(&adapter);
        let executor = Executor::new(schema, adapter);

        // Only provide id and name; email is absent.
        let vars = serde_json::json!({
            "input": { "id": "abc", "name": "Alice" }
        });
        executor
            .execute_mutation("update_user", Some(&vars), any_write_selections())
            .await
            .unwrap();

        let captured = adapter_ref.args();
        assert_eq!(captured.len(), 1);
        let obj = captured[0].as_object().unwrap();
        assert!(
            !obj.contains_key("email"),
            "absent field 'email' must NOT appear in JSONB (leave DB value unchanged)"
        );
    }

    // ── #433: updated_fields surfaced as updatedFields, selection-gated ─────

    fn updated_fields_executor(updated_fields: serde_json::Value) -> Executor {
        use crate::schema::MutationDefinition;
        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_update_user".to_string()),
            ..MutationDefinition::new("updateUser", "User")
        });
        let adapter = CapturingFunctionCallAdapter::new().with_updated_fields(updated_fields);
        Executor::new(schema, Arc::new(adapter))
    }

    /// When the client selects `updatedFields`, the success arm surfaces the
    /// mutation's changed field names (symmetric with `cascade`).
    #[tokio::test]
    async fn mutation_surfaces_updated_fields_when_selected() {
        use serde_json::json;
        let executor = updated_fields_executor(json!(["name", "email"]));
        let result = executor
            .execute("mutation { updateUser { __typename updatedFields } }", None)
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("updateUser")).unwrap();
        assert_eq!(
            data.get("updatedFields"),
            Some(&json!(["name", "email"])),
            "updatedFields must surface the changed field names; got {data}"
        );
    }

    /// When `updatedFields` is NOT selected, it must be absent — projected shapes
    /// stay exact for field-count assertions.
    #[tokio::test]
    async fn mutation_omits_updated_fields_when_not_selected() {
        use serde_json::json;
        let executor = updated_fields_executor(json!(["name"]));
        let result = executor.execute("mutation { updateUser { id } }", None).await.unwrap();
        let data = result.get("data").and_then(|d| d.get("updateUser")).unwrap();
        assert!(
            data.get("updatedFields").is_none(),
            "updatedFields must be absent when not selected; got {data}"
        );
    }

    /// An empty `updated_fields` (a noop) surfaces as `[]` when selected, not absent.
    #[tokio::test]
    async fn mutation_surfaces_empty_updated_fields_as_array() {
        use serde_json::json;
        let executor = updated_fields_executor(json!([]));
        let result = executor
            .execute("mutation { updateUser { updatedFields } }", None)
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("updateUser")).unwrap();
        assert_eq!(
            data.get("updatedFields"),
            Some(&json!([])),
            "an empty updated_fields must surface as [] when selected; got {data}"
        );
    }

    /// `updatedFields` selection is detected inside an inline fragment too (mirrors
    /// the `__typename` detection), so a client nesting it still gets it.
    #[tokio::test]
    async fn mutation_surfaces_updated_fields_selected_in_inline_fragment() {
        use serde_json::json;
        let executor = updated_fields_executor(json!(["name"]));
        let result = executor
            .execute("mutation { updateUser { ... on User { updatedFields } } }", None)
            .await
            .unwrap();
        let data = result.get("data").and_then(|d| d.get("updateUser")).unwrap();
        assert_eq!(data.get("updatedFields"), Some(&json!(["name"])), "got {data}");
    }
}

// ── mod mutation_audit: audit event emission ──────────────────────────────

mod mutation_audit {
    use std::sync::{Arc, Mutex};

    use tracing::Subscriber;
    use tracing_subscriber::{Layer, Registry, layer::Context, prelude::*};

    use super::*;
    use crate::{
        backend::types::{DatabaseType, PoolMetrics},
        schema::MutationOperation,
    };

    /// Minimal mock adapter that returns a valid `mutation_response` row.
    struct AuditMockAdapter;

    #[async_trait]
    impl DatabaseAdapter for AuditMockAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl AuditMockAdapter {
        async fn execute_function_call(
            &self,
            _function_name: &str,
            _args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            let mut row = std::collections::HashMap::new();
            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert("entity".to_string(), json!({"id": "1"}));
            row.insert("entity_type".to_string(), json!("User"));
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&fraiseql_db::ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            let rows = self.execute_function_call(function_name, args).await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for AuditMockAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// Tracing layer that captures events from the `fraiseql::mutation_audit` target.
    struct CapturingLayer {
        events: Arc<Mutex<Vec<String>>>,
    }

    impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S>
        for CapturingLayer
    {
        fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
            if event.metadata().target() == "fraiseql::mutation_audit" {
                self.events.lock().unwrap().push(event.metadata().name().to_string());
            }
        }
    }

    fn schema_with_insert_mutation() -> CompiledSchema {
        use crate::schema::MutationDefinition;
        let mut schema = CompiledSchema::new();
        let mut def = MutationDefinition::new("createUser", "User");
        def.sql_source = Some("fn_create_user".to_string());
        def.operation = MutationOperation::Insert {
            table: "users".to_string(),
        };
        schema.mutations.push(def);
        schema
    }

    // ── kind_str() unit tests ────────────────────────────────────────────

    #[test]
    fn kind_str_insert() {
        assert_eq!(
            MutationOperation::Insert {
                table: "users".to_string(),
            }
            .kind_str(),
            "insert"
        );
    }

    #[test]
    fn kind_str_update() {
        assert_eq!(
            MutationOperation::Update {
                table: "users".to_string(),
            }
            .kind_str(),
            "update"
        );
    }

    #[test]
    fn kind_str_delete() {
        assert_eq!(
            MutationOperation::Delete {
                table: "users".to_string(),
            }
            .kind_str(),
            "delete"
        );
    }

    #[test]
    fn kind_str_custom() {
        assert_eq!(MutationOperation::Custom.kind_str(), "custom");
    }

    // ── RuntimeConfig.audit_mutations default ────────────────────────────

    #[test]
    fn audit_mutations_default_false() {
        assert!(
            !RuntimeConfig::default().audit_mutations,
            "audit_mutations must default to false"
        );
    }

    // ── tracing event emission ────────────────────────────────────────────

    // A dry run executed nothing, so there is nothing to audit (ruling AD 3).
    #[tokio::test]
    async fn no_audit_event_for_a_dry_run() {
        let captured = Arc::new(Mutex::new(Vec::<String>::new()));
        let layer = CapturingLayer {
            events: captured.clone(),
        };
        let subscriber = Registry::default().with(layer);
        let _guard = tracing::subscriber::set_default(subscriber);

        let config = RuntimeConfig {
            audit_mutations: true,
            dry_run_mutations: true,
            ..RuntimeConfig::default()
        };
        Executor::with_config(
            super::dry_run::schema(),
            Arc::new(super::dry_run::DryRunAdapter::default()),
            config,
        )
        .execute("mutation { createPost { id } }", None)
        .await
        .expect("the dry run answers");
        assert!(captured.lock().unwrap().is_empty(), "audited: {:?}", captured.lock().unwrap());
    }

    /// A-E1: Mutation audit event is emitted when `audit_mutations=true`.
    #[tokio::test]
    async fn audit_event_emitted_when_enabled() {
        let captured = Arc::new(Mutex::new(Vec::<String>::new()));
        let layer = CapturingLayer {
            events: captured.clone(),
        };
        let subscriber = Registry::default().with(layer);
        let _guard = tracing::subscriber::set_default(subscriber);

        let schema = schema_with_insert_mutation();
        let config = RuntimeConfig {
            audit_mutations: true,
            ..RuntimeConfig::default()
        };
        let executor = Executor::with_config(schema, Arc::new(AuditMockAdapter), config);

        executor
            .execute_mutation("createUser", None, any_write_selections())
            .await
            .unwrap();

        let events = captured.lock().unwrap();
        assert!(
            !events.is_empty(),
            "Expected a mutation audit event when audit_mutations=true, got none"
        );
    }

    /// A-E2: No mutation audit event when `audit_mutations=false` (default).
    #[tokio::test]
    async fn no_audit_event_when_disabled() {
        let captured = Arc::new(Mutex::new(Vec::<String>::new()));
        let layer = CapturingLayer {
            events: captured.clone(),
        };
        let subscriber = Registry::default().with(layer);
        let _guard = tracing::subscriber::set_default(subscriber);

        let schema = schema_with_insert_mutation();
        // Default config: audit_mutations=false
        let executor = Executor::new(schema, Arc::new(AuditMockAdapter));

        executor
            .execute_mutation("createUser", None, any_write_selections())
            .await
            .unwrap();

        let events = captured.lock().unwrap();
        assert!(
            events.is_empty(),
            "Expected no audit events when audit_mutations=false, got: {events:?}"
        );
    }
}

// ── mod mutation_rbac: requires_role enforcement on mutations (#149) ───────
mod mutation_rbac {
    use std::collections::HashMap;

    use chrono::Utc;

    use super::*;
    use crate::{schema::MutationDefinition, security::SecurityContext};

    fn schema_with_gated_mutation() -> CompiledSchema {
        let mut schema = CompiledSchema::new();
        let mut m = MutationDefinition::new("upsert_transport_checkpoint", "TransportCheckpoint");
        m.sql_source = Some("core.fn_upsert_transport_checkpoint".to_string());
        m.requires_role = Some("changelog_writer".to_string());
        schema.mutations.push(m);
        schema.build_indexes();
        schema
    }

    fn ctx_with_roles(roles: &[&str]) -> SecurityContext {
        SecurityContext {
            user_id:          "sidecar".into(),
            roles:            roles.iter().map(ToString::to_string).collect(),
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::default(),
            request_id:       "req-1".to_string(),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    #[tokio::test]
    async fn mutation_denied_without_role_reports_not_found() {
        let executor =
            Executor::new(schema_with_gated_mutation(), Arc::new(MockAdapter::new(vec![])));
        let ctx = ctx_with_roles(&["viewer"]);

        let err = executor
            .execute_with_security(
                r#"mutation { upsert_transport_checkpoint(transport_name: "s1", last_pk: 1) { last_pk } }"#,
                None,
                &ctx,
            )
            .await
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("not found in schema"),
            "enumeration-prevention message, got: {err}"
        );
        assert!(
            !err.to_lowercase().contains("forbidden"),
            "must not reveal the gate, got: {err}"
        );
    }

    #[tokio::test]
    async fn mutation_with_no_security_context_reports_not_found() {
        let executor =
            Executor::new(schema_with_gated_mutation(), Arc::new(MockAdapter::new(vec![])));
        let err = executor
            .execute(
                r#"mutation { upsert_transport_checkpoint(transport_name: "s1", last_pk: 1) { last_pk } }"#,
                None,
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("not found in schema"), "no roles → not found, got: {err}");
    }

    #[tokio::test]
    async fn mutation_allowed_with_role_passes_rbac_gate() {
        let executor =
            Executor::new(schema_with_gated_mutation(), Arc::new(MockAdapter::new(vec![])));
        let ctx = ctx_with_roles(&["changelog_writer"]);

        let err = executor
            .execute_with_security(
                r#"mutation { upsert_transport_checkpoint(transport_name: "s1", last_pk: 1) { last_pk } }"#,
                None,
                &ctx,
            )
            .await
            .unwrap_err()
            .to_string();

        // The RBAC gate is passed; execution proceeds and fails only because the
        // mock adapter returns no rows — NOT because of the role check.
        assert!(
            !err.contains("not found in schema"),
            "role holder must pass the gate (error should be downstream), got: {err}"
        );
    }
}

// ── mod field_authz: #423 dynamic field-level authorization on mutations ──

mod field_authz {
    #![allow(clippy::panic)] // Reason: test doubles panic to assert they are never called

    use std::collections::HashMap;

    use async_trait::async_trait;
    use chrono::Utc;

    use super::*;
    use crate::{
        backend::types::{DatabaseType, PoolMetrics, sql_hints::OrderByClause},
        graphql::{FieldSelection, GraphQLArgument},
        runtime::WriteSelections,
        schema::{FieldDefinition, FieldDenyPolicy, FieldType, MutationDefinition, TypeDefinition},
        security::{FieldAuthorizer, FieldAuthzDecision, FieldAuthzRequest, SecurityContext},
    };

    /// Adapter whose mutation returns a `User` entity carrying a policy-gated `email`,
    /// and which records whether that write was ever allowed to stand.
    ///
    /// `committed` is the whole point of #1353. A real adapter records it by having
    /// committed the transaction; this one records it by flipping the flag on exactly
    /// the paths that commit — the ungated entry point unconditionally, the gated one
    /// only once the gate has agreed. A test that finds the flag clear after a refusal is finding
    /// the same thing the PostgreSQL integration test finds by counting rows.
    ///
    /// `ran` records whether the SQL function was called at all, committed or not: a
    /// refusal the selection and the principal already decide must leave it clear.
    ///
    /// `rows` is what the SQL function returned: the canned `User` row by default, or
    /// whatever a test needs the gate to be handed — no rows, or a row that is not a
    /// `mutation_response`.
    struct GatedEntityAdapter {
        ran:       std::sync::atomic::AtomicBool,
        committed: std::sync::atomic::AtomicBool,
        rows:      Vec<HashMap<String, serde_json::Value>>,
    }

    impl Default for GatedEntityAdapter {
        fn default() -> Self {
            Self::returning(Self::canned_row())
        }
    }

    impl GatedEntityAdapter {
        fn returning(rows: Vec<HashMap<String, serde_json::Value>>) -> Self {
            Self {
                ran: std::sync::atomic::AtomicBool::new(false),
                committed: std::sync::atomic::AtomicBool::new(false),
                rows,
            }
        }

        fn ran(&self) -> bool {
            self.ran.load(std::sync::atomic::Ordering::SeqCst)
        }

        fn mark_ran(&self) {
            self.ran.store(true, std::sync::atomic::Ordering::SeqCst);
        }

        fn committed(&self) -> bool {
            self.committed.load(std::sync::atomic::Ordering::SeqCst)
        }

        fn mark_committed(&self) {
            self.committed.store(true, std::sync::atomic::Ordering::SeqCst);
        }

        /// The row the SQL function returns — built once, used by both entry points.
        fn canned_row() -> Vec<HashMap<String, serde_json::Value>> {
            use serde_json::json;
            let mut row = HashMap::new();
            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert(
                "entity".to_string(),
                json!({ "id": "123", "name": "Alice", "email": "alice@x.com", "owner_id": "user-1" }),
            );
            row.insert("entity_type".to_string(), json!("User"));
            row.insert("message".to_string(), json!(""));
            vec![row]
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait]
    impl DatabaseAdapter for GatedEntityAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl GatedEntityAdapter {
        /// The commit gate (#1353), for a test double with no durable state.
        ///
        /// The runner routes every write through `execute_function_call_gated` (ruling
        /// Z 1), so the field authorizer can refuse the write and not merely its result,
        /// and a response that cannot be built takes the write with it. The trait default
        /// refuses outright — an adapter that cannot roll back must not be the one to
        /// decide a refused write is survivable. This one has nothing to roll back (its
        /// "write" is a canned row), so running the call and then adjudicating it is
        /// exactly what the PostgreSQL adapter does, minus the durability.
        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            session_vars: &[(&str, &str)],
            changelog: Option<&ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            let _ = (function_name, args, session_vars, changelog);
            self.mark_ran();
            let rows = self.rows.clone();
            // The function has run; the transaction has not committed. A refusal
            // here returns without ever marking the write as having stood.
            gate(&rows)?;
            self.mark_committed();
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for GatedEntityAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    struct DenyMask;
    impl FieldAuthorizer for DenyMask {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            Ok(FieldAuthzDecision::Deny {
                code:    "no".into(),
                on_deny: FieldDenyPolicy::Mask,
            })
        }
    }

    struct Raising;
    impl FieldAuthorizer for Raising {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            Err(FraiseQLError::Validation {
                message: "policy backend down".into(),
                path:    None,
            })
        }
    }

    struct DenyReject;
    impl FieldAuthorizer for DenyReject {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            Ok(FieldAuthzDecision::Deny {
                code:    "not_owner".into(),
                on_deny: FieldDenyPolicy::Reject,
            })
        }
    }

    struct PanicIfCalled;
    impl FieldAuthorizer for PanicIfCalled {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            panic!("field authorizer must not be consulted here");
        }
    }

    // ── #1353: a refused write must not have happened ────────────────────────
    //
    // The four gates that can refuse a mutation before it dispatches — the operation
    // `Authorizer` (#422), `requires_role`, `requires_actor` and the `before:mutation`
    // chain — all answer from the principal and the arguments. The field authorizer
    // cannot: its contract takes the resolved entity as `parent`, so it has nothing to
    // decide on until the row exists. It therefore used to run after the transaction
    // had committed, and a caller it rejected lost the field and kept the side effect.
    //
    // These pin the ruling: the write commits only if adjudication completed without
    // refusal. Any error from adjudication rolls it back and reaches the caller as
    // itself — the rollback is decided by the flow, not by the variant — so each case
    // below asserts both halves: the write did not stand, and the error is the one the
    // adjudication raised. `Mask` is not a refusal, and commits.

    /// Run `createUser` selecting `{ id email }` against `adapter`, as `ctx()`.
    async fn refused_write(
        adapter: &Arc<GatedEntityAdapter>,
        authorizer: Arc<dyn FieldAuthorizer>,
    ) -> FraiseQLError {
        Executor::with_config(
            schema(),
            Arc::clone(adapter),
            RuntimeConfig::default().with_field_authorizer(authorizer),
        )
        .execute_with_security("mutation { createUser { id email } }", None, &ctx())
        .await
        .expect_err("adjudication failed, so the mutation must fail")
    }

    // The server wraps every adapter in the caching one, so it has to be a `Writer`
    // whenever the adapter it wraps is: this compiles only if it is (ruling AA 6).
    #[test]
    fn the_caching_adapter_writes_when_its_adapter_does() {
        use crate::cache::{CacheConfig, CachedDatabaseAdapter, QueryResultCache};
        let cached = CachedDatabaseAdapter::new(
            GatedEntityAdapter::default(),
            QueryResultCache::new(CacheConfig::enabled()),
            "1.0.0".to_string(),
        );
        let executor = Executor::with_config(schema(), Arc::new(cached), RuntimeConfig::default());
        drop(executor);
    }

    // A `Reject` decision refuses the operation, not just the value: the write the
    // function performed never commits.
    #[tokio::test]
    async fn mutation_deny_reject_does_not_commit_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = refused_write(&adapter, Arc::new(DenyReject)).await;

        assert!(
            matches!(err, FraiseQLError::Authorization { .. }),
            "a Reject decision reports as Authorization, got: {err:?}"
        );
        assert!(
            !adapter.committed(),
            "the write must not stand after the authorizer rejected the caller (#1353)"
        );
    }

    // A policy error fails closed. It is reported as `ServiceUnavailable` — the backend
    // could not answer, the caller was not refused (#1374) — without surfacing the
    // policy's own error (the `Raising` double returns a `Validation`), on the read path
    // and here alike. The rollback does not depend on the variant (#1353).
    #[tokio::test]
    async fn mutation_raising_policy_does_not_commit_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = refused_write(&adapter, Arc::new(Raising)).await;

        assert!(
            matches!(err, FraiseQLError::ServiceUnavailable { .. }),
            "a policy error fails closed as ServiceUnavailable (#1374), got: {err:?}"
        );
        assert!(
            !format!("{err}").contains("policy backend down"),
            "the policy's own error is not surfaced: {err}"
        );
        assert!(
            !adapter.committed(),
            "a fail-closed policy error must not leave the write standing"
        );
    }

    // A gated field whose arguments cannot be read is a server fault, reported as
    // `Internal` exactly as on the read path — and the authorizer was never asked, so
    // the write was never adjudicated and rolls back. The GraphQL parser cannot emit
    // unreadable argument JSON, so the selection set is handed in directly.
    #[tokio::test]
    async fn mutation_unreadable_gated_arguments_do_not_commit_the_write() {
        let field = |name: &str, arguments| FieldSelection {
            name: name.to_string(),
            alias: None,
            arguments,
            nested_fields: vec![],
            directives: vec![],
        };
        let selections = vec![
            field("id", vec![]),
            field(
                "email",
                vec![GraphQLArgument {
                    name:       "format".to_string(),
                    value_type: "string".to_string(),
                    value_json: "{not json".to_string(),
                }],
            ),
        ];

        let adapter = Arc::new(GatedEntityAdapter::default());
        let executor = Executor::with_config(
            schema(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        );
        let err = executor
            .execute_mutation_detailed(
                "createUser",
                "createUser",
                None,
                Some(&ctx()),
                WriteSelections::new(&selections).expect("two fields"),
                &[],
            )
            .await
            .expect_err("unreadable gated-field arguments must fail the mutation");

        assert!(
            matches!(err, FraiseQLError::Internal { .. }),
            "unreadable arguments report as Internal on both paths, got: {err:?}"
        );
        assert!(
            !adapter.committed(),
            "a write whose gated field could not be adjudicated must not stand"
        );
    }

    // A row that is not a `mutation_response` cannot be adjudicated at all. Before
    // this ruling it committed and then failed, so the client was told the write
    // failed while it had landed. On a gated schema it now rolls back, and the parse
    // error is reported as itself.
    #[tokio::test]
    async fn mutation_unparseable_response_does_not_commit_the_write() {
        let mut row = HashMap::new();
        row.insert("succeeded".to_string(), serde_json::json!("not a boolean"));
        let adapter = Arc::new(GatedEntityAdapter::returning(vec![row]));
        let err = refused_write(&adapter, Arc::new(PanicIfCalled)).await;

        assert!(
            matches!(err, FraiseQLError::Validation { .. }),
            "an unparseable mutation_response reports as Validation, got: {err:?}"
        );
        assert!(
            format!("{err}").contains("failed to deserialize"),
            "the parse error is reported unchanged: {err}"
        );
        assert!(
            !adapter.committed(),
            "a write whose response could not be parsed was never adjudicated"
        );
    }

    // A function that returned no rows gave the gate nothing to adjudicate. Same
    // ruling as the unparseable row: roll back, report the error as itself.
    #[tokio::test]
    async fn mutation_returning_no_rows_does_not_commit_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::returning(vec![]));
        let err = refused_write(&adapter, Arc::new(PanicIfCalled)).await;

        assert!(
            matches!(err, FraiseQLError::Validation { .. }),
            "no rows reports as Validation, got: {err:?}"
        );
        assert!(
            format!("{err}").contains("function returned no rows"),
            "the no-rows error is reported unchanged: {err}"
        );
        assert!(!adapter.committed(), "a write with no row to adjudicate must not stand");
    }

    // ── Ruling Y 2: what the selection already decides is decided before the write ──
    //
    // Of the #423 refusals, only a `Reject` needs the written row: it is the authorizer's
    // decision over `parent`. The other four follow from the selection, the principal and
    // the configuration — a gated field selected with no principal, with no authorizer
    // configured, a gated field nested below the top level, a gated field whose arguments
    // cannot be read. They used to be discovered while serving the written row. Now the
    // function is never called: `ran` stays clear, not only `committed`.

    /// `User` with a `profile: Profile` whose `secret` is policy-gated, for the nested case.
    fn schema_with_nested_gated_field() -> CompiledSchema {
        let mut s = schema();
        let user = s.types.iter_mut().find(|t| t.name == "User").unwrap();
        user.fields
            .push(FieldDefinition::nullable("profile", FieldType::Object("Profile".to_string())));
        let mut profile = TypeDefinition::new("Profile", "v_profile");
        profile.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("secret", FieldType::String).with_authorize(true),
        ];
        s.types.push(profile);
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn a_gated_field_without_a_principal_is_refused_before_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        )
        .execute("mutation { createUser { id email } }", None)
        .await
        .expect_err("a gated field needs a principal");

        assert!(format!("{err}").contains("not authenticated"), "{err}");
        assert!(!adapter.ran(), "decided by the principal alone, so the function never runs");
    }

    #[tokio::test]
    async fn a_gated_field_without_an_authorizer_is_refused_before_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(schema(), Arc::clone(&adapter), RuntimeConfig::default())
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await
            .expect_err("a gated field needs an authorizer");

        assert!(format!("{err}").contains("no field authorizer is configured"), "{err}");
        assert!(!adapter.ran(), "decided by the configuration alone, so the function never runs");
    }

    #[tokio::test]
    async fn a_nested_gated_field_is_refused_before_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema_with_nested_gated_field(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        )
        .execute_with_security("mutation { createUser { id profile { secret } } }", None, &ctx())
        .await
        .expect_err("a nested gated field is not supported on a payload");

        assert!(format!("{err}").contains("not supported in this version"), "{err}");
        assert!(!adapter.ran(), "decided by the selection alone, so the function never runs");
    }

    #[tokio::test]
    async fn unreadable_gated_arguments_are_refused_before_the_write() {
        let field = |name: &str, arguments| FieldSelection {
            name: name.to_string(),
            alias: None,
            arguments,
            nested_fields: vec![],
            directives: vec![],
        };
        let selections = vec![
            field("id", vec![]),
            field(
                "email",
                vec![GraphQLArgument {
                    name:       "format".to_string(),
                    value_type: "string".to_string(),
                    value_json: "{not json".to_string(),
                }],
            ),
        ];
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        )
        .execute_mutation_detailed(
            "createUser",
            "createUser",
            None,
            Some(&ctx()),
            WriteSelections::new(&selections).expect("two fields"),
            &[],
        )
        .await
        .expect_err("unreadable gated-field arguments must fail the mutation");

        assert!(matches!(err, FraiseQLError::Internal { .. }), "{err:?}");
        assert!(!adapter.ran(), "decided by the selection alone, so the function never runs");
    }

    // The refusal is asked of every root the payload can be served as, not only the first:
    // here the error types come first and the gated `User` is a union member after them.
    #[tokio::test]
    async fn a_gated_field_on_a_later_payload_root_is_refused_before_the_write() {
        use crate::schema::UnionDefinition;
        let mut s = schema();
        s.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("ValidationError", "")
        });
        s.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["ValidationError".to_string(), "User".to_string()]),
        );
        s.mutations[0].return_type = "CreateUserResult".to_string();
        s.build_indexes();
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            s,
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        )
        .execute("mutation { createUser { ... on User { id email } } }", None)
        .await
        .expect_err("a gated field needs a principal, whichever root it is on");

        assert!(format!("{err}").contains("not authenticated"), "{err}");
        assert!(!adapter.ran(), "decided by the principal alone, so the function never runs");
    }

    // ── Ruling Z 1: every write is adjudicated before its commit ──────────────────
    //
    // Building the response from the row can fail on any schema, gated or not: no rows, a
    // row that is not a `mutation_response`, a malformed cascade entry, an over-large
    // cascade. On a schema nothing could refuse, the write used to commit first and fail
    // after, so the client was told it failed while it had landed — and no idempotency
    // record was stored, so a retry ran it again. The commit now waits for the response on
    // every write, and these roll back as they do on a gated schema.

    /// [`schema`] without the `authorize` field: nothing in it can refuse a payload.
    fn ungated_schema() -> CompiledSchema {
        let mut s = schema();
        let user = s.types.iter_mut().find(|t| t.name == "User").unwrap();
        for field in &mut user.fields {
            field.authorize = false;
        }
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn an_ungated_write_returning_no_rows_does_not_commit() {
        let adapter = Arc::new(GatedEntityAdapter::returning(vec![]));
        let err =
            Executor::with_config(ungated_schema(), Arc::clone(&adapter), RuntimeConfig::default())
                .execute_with_security("mutation { createUser { id } }", None, &ctx())
                .await
                .expect_err("no rows cannot be adjudicated");

        assert!(format!("{err}").contains("function returned no rows"), "{err}");
        assert!(!adapter.committed(), "a write with no row to adjudicate must not stand");
    }

    #[tokio::test]
    async fn an_ungated_write_with_an_unparseable_response_does_not_commit() {
        let mut row = HashMap::new();
        row.insert("succeeded".to_string(), serde_json::json!("not a boolean"));
        let adapter = Arc::new(GatedEntityAdapter::returning(vec![row]));
        let err =
            Executor::with_config(ungated_schema(), Arc::clone(&adapter), RuntimeConfig::default())
                .execute_with_security("mutation { createUser { id } }", None, &ctx())
                .await
                .expect_err("an unparseable mutation_response cannot be adjudicated");

        assert!(format!("{err}").contains("failed to deserialize"), "{err}");
        assert!(
            !adapter.committed(),
            "a write whose response could not be parsed must not stand"
        );
    }

    // Control: the ungated write that adjudicates commits.
    #[tokio::test]
    async fn an_ungated_write_that_adjudicates_commits() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let out =
            Executor::with_config(ungated_schema(), Arc::clone(&adapter), RuntimeConfig::default())
                .execute_with_security("mutation { createUser { id email } }", None, &ctx())
                .await
                .unwrap();

        assert_eq!(out["data"]["createUser"]["email"], "alice@x.com", "{out}");
        assert!(adapter.committed());
    }

    // ── Ruling Y 6: a payload root's own type `requires_role` ─────────────────────
    //
    // A type's `requires_role` gates every read of the type (#677). It is lowered onto a
    // mutation only when the mutation returns that exact type, and the payload gates check
    // it only below the root. So a role-gated type served at a payload root by any other
    // route — a union member, a cascade's entity, an entity a cascade reports as updated —
    // was served to a caller without the role. Each is refused where it is served, inside
    // the write's transaction, so the write goes with it.

    /// [`schema`] with `User` gated on `admin` and `createUser` returning a union of it.
    fn schema_with_role_gated_union_member() -> CompiledSchema {
        use crate::schema::UnionDefinition;
        let mut s = schema();
        let user = s.types.iter_mut().find(|t| t.name == "User").unwrap();
        user.requires_role = Some("admin".to_string());
        for field in &mut user.fields {
            field.authorize = false;
        }
        s.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("ValidationError", "")
        });
        s.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["User".to_string(), "ValidationError".to_string()]),
        );
        s.mutations[0].return_type = "CreateUserResult".to_string();
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn a_role_gated_union_member_is_not_served_without_the_role() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let res = Executor::with_config(
            schema_with_role_gated_union_member(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute_with_security("mutation { createUser { ... on User { id name } } }", None, &ctx())
        .await;

        let err = res.expect_err("`User` requires `admin`, which the caller does not hold");
        assert!(matches!(err, FraiseQLError::Authorization { .. }), "{err:?}");
        assert!(!format!("{err}").contains("Alice"), "the gated value must not appear: {err}");
        assert!(!adapter.committed(), "a refused payload takes its write with it");
    }

    // No principal holds no role.
    #[tokio::test]
    async fn a_role_gated_union_member_is_not_served_to_an_anonymous_caller() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema_with_role_gated_union_member(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute("mutation { createUser { ... on User { id name } } }", None)
        .await
        .expect_err("an anonymous caller holds no role");

        assert!(matches!(err, FraiseQLError::Authorization { .. }), "{err:?}");
        assert!(!adapter.committed(), "a refused payload takes its write with it");
    }

    // Holding a role is not holding this one.
    #[tokio::test]
    async fn a_role_gated_union_member_is_not_served_for_another_role() {
        let mut viewer = ctx();
        viewer.roles = vec!["viewer".to_string()];
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema_with_role_gated_union_member(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute_with_security("mutation { createUser { ... on User { id name } } }", None, &viewer)
        .await
        .expect_err("`viewer` is not `admin`");

        assert!(matches!(err, FraiseQLError::Authorization { .. }), "{err:?}");
        assert!(!adapter.committed(), "a refused payload takes its write with it");
    }

    // Control: the caller holding the role is served.
    #[tokio::test]
    async fn a_role_gated_union_member_is_served_with_the_role() {
        let mut admin = ctx();
        admin.roles = vec!["admin".to_string()];
        let adapter = Arc::new(GatedEntityAdapter::default());
        let out = Executor::with_config(
            schema_with_role_gated_union_member(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute_with_security("mutation { createUser { ... on User { id name } } }", None, &admin)
        .await
        .unwrap();

        assert_eq!(out["data"]["createUser"]["name"], "Alice", "{out}");
        assert!(adapter.committed());
    }

    // A type read anywhere but its own root query is read under its own read's gates: the
    // list query's `requires_role` (else the type's) and `requires_actor` — as a nested level
    // is. A deployment gating `users` rather than `User` is gated here too.
    fn schema_with_union_member_behind_its_reads_role() -> CompiledSchema {
        let mut s = schema_with_role_gated_union_member();
        s.types.iter_mut().find(|t| t.name == "User").unwrap().requires_role = None;
        s.queries.retain(|q| q.return_type != "User");
        let mut users = crate::schema::QueryDefinition::new("users", "User")
            .returning_list()
            .with_sql_source("v_user");
        users.requires_role = Some("admin".to_string());
        s.queries.push(users);
        s.build_indexes();
        s
    }

    /// **Reproduction.** `User` itself is ungated; its own read, `users`, requires `admin`.
    #[tokio::test]
    async fn a_union_member_whose_own_read_requires_a_role_is_not_served_without_it() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema_with_union_member_behind_its_reads_role(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute_with_security("mutation { createUser { ... on User { id name } } }", None, &ctx())
        .await
        .expect_err("`users` requires `admin`, which the caller does not hold");
        assert!(matches!(err, FraiseQLError::Authorization { .. }), "{err:?}");
        assert!(!adapter.committed(), "a refused payload takes its write with it");

        let mut admin = ctx();
        admin.roles = vec!["admin".to_string()];
        let adapter = Arc::new(GatedEntityAdapter::default());
        let out = Executor::with_config(
            schema_with_union_member_behind_its_reads_role(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute_with_security("mutation { createUser { ... on User { id name } } }", None, &admin)
        .await
        .unwrap();
        assert_eq!(out["data"]["createUser"]["name"], "Alice", "{out}");
    }

    // ── Ruling AA 1 (Z 3): the type a write's payload is served as is the contract's ─────
    //
    // A payload position holds an exact set of types, derived from the schema. A function
    // stamping a type outside it — another type, or a name the schema does not know, which no
    // gate can classify — broke its contract, and the write rolls back with a contract error
    // naming the stamp. A NULL stamp stands for the one type the outcome can be; where there
    // are several, the function's silence must not pick one. An interface return holds its
    // implementors, classified before the write like a union's members.

    /// The canned row, stamped `stamp` (or not stamped).
    fn stamped(stamp: Option<&str>) -> Vec<HashMap<String, serde_json::Value>> {
        let mut rows = GatedEntityAdapter::canned_row();
        match stamp {
            Some(s) => {
                rows[0].insert("entity_type".to_string(), serde_json::json!(s));
            },
            None => {
                rows[0].remove("entity_type");
            },
        }
        rows
    }

    /// [`schema`] without its `authorize` field, plus an `Admin` type no payload position of
    /// `createUser` holds.
    fn schema_with_admin() -> CompiledSchema {
        let mut s = schema();
        let user = s.types.iter_mut().find(|t| t.name == "User").unwrap();
        for field in &mut user.fields {
            field.authorize = false;
        }
        let mut admin = TypeDefinition::new("Admin", "v_admin");
        admin.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("name", FieldType::String),
        ];
        s.types.push(admin);
        s.build_indexes();
        s
    }

    async fn stamped_write(
        schema: CompiledSchema,
        stamp: Option<&str>,
        query: &str,
    ) -> (Arc<GatedEntityAdapter>, Result<serde_json::Value>) {
        let adapter = Arc::new(GatedEntityAdapter::returning(stamped(stamp)));
        let res = Executor::with_config(schema, Arc::clone(&adapter), RuntimeConfig::default())
            .execute_with_security(query, None, &ctx())
            .await;
        (adapter, res)
    }

    #[tokio::test]
    async fn a_stamp_the_return_type_cannot_hold_is_a_contract_error() {
        let (adapter, res) = stamped_write(
            schema_with_admin(),
            Some("Admin"),
            "mutation { createUser { id name } }",
        )
        .await;
        let err = res.expect_err("`createUser` returns `User`; its function stamped `Admin`");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        assert!(format!("{err}").contains("'Admin'"), "names the stamp: {err}");
        assert!(!adapter.committed(), "a write that broke its contract does not stand");
    }

    #[tokio::test]
    async fn a_stamp_naming_no_type_is_a_contract_error() {
        let (adapter, res) = stamped_write(
            schema_with_admin(),
            Some("tb_user"),
            "mutation { createUser { id name } }",
        )
        .await;
        let err = res.expect_err("`tb_user` is no GraphQL type: nothing could gate it");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        assert!(format!("{err}").contains("'tb_user'"), "names the stamp: {err}");
        assert!(!adapter.committed(), "a write that broke its contract does not stand");
    }

    /// `createUser` returning `User | Admin | ValidationError`: two success members.
    fn schema_with_two_success_members() -> CompiledSchema {
        use crate::schema::UnionDefinition;
        let mut s = schema_with_admin();
        s.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("ValidationError", "")
        });
        s.unions.push(UnionDefinition::new("CreateUserResult").with_members(vec![
            "User".to_string(),
            "Admin".to_string(),
            "ValidationError".to_string(),
        ]));
        s.mutations[0].return_type = "CreateUserResult".to_string();
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn an_unstamped_success_with_two_possible_types_is_a_contract_error() {
        let (adapter, res) = stamped_write(
            schema_with_two_success_members(),
            None,
            "mutation { createUser { ... on User { id } ... on Admin { id } } }",
        )
        .await;
        let err = res.expect_err("the function did not say whether it produced a User or an Admin");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        assert!(!adapter.committed(), "a write that broke its contract does not stand");
    }

    // Error types are classified at the root for the error arm; a *success* stamped as one
    // is still off-contract, and is refused where the stamp is resolved.
    #[tokio::test]
    async fn a_success_stamped_as_an_error_type_is_a_contract_error() {
        let (adapter, res) = stamped_write(
            schema_with_two_success_members(),
            Some("ValidationError"),
            "mutation { createUser { ... on User { id } } }",
        )
        .await;
        let err = res.expect_err("a success is not a ValidationError");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        assert!(format!("{err}").contains("'ValidationError'"), "names the stamp: {err}");
        assert!(!adapter.committed(), "a write that broke its contract does not stand");
    }

    // Control: an unstamped success with one possible type — the helper's default
    // (`fraiseql.mutation_ok(entity)` stamps NULL) — is served as that type.
    #[tokio::test]
    async fn an_unstamped_success_with_one_possible_type_is_that_type() {
        use crate::schema::UnionDefinition;
        let mut s = schema_with_admin();
        s.types.push(TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new("ValidationError", "")
        });
        s.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["User".to_string(), "ValidationError".to_string()]),
        );
        s.mutations[0].return_type = "CreateUserResult".to_string();
        s.build_indexes();
        let (adapter, res) =
            stamped_write(s, None, "mutation { createUser { ... on User { id name } } }").await;
        let out = res.unwrap();
        assert_eq!(out["data"]["createUser"]["name"], "Alice", "{out}");
        assert!(adapter.committed());
    }

    /// `createNode` returning the interface `Node`, implemented by `User`, whose `email`
    /// requires a scope the caller lacks and rejects.
    fn schema_with_interface_return() -> CompiledSchema {
        use crate::schema::{InterfaceDefinition, MutationDefinition};
        let mut s = schema();
        let user = s.types.iter_mut().find(|t| t.name == "User").unwrap();
        user.implements = vec!["Node".to_string()];
        for field in &mut user.fields {
            field.authorize = false;
            if field.name == "email" {
                field.requires_scope = Some("read:email".to_string());
                field.on_deny = FieldDenyPolicy::Reject;
            }
        }
        s.interfaces.push(InterfaceDefinition::new("Node"));
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createNode", "Node")
        });
        s.security = Some(crate::schema::SecurityConfig::default());
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn an_interface_return_is_classified_as_its_implementors_before_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let err = Executor::with_config(
            schema_with_interface_return(),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        )
        .execute_with_security("mutation { createNode { ... on User { id email } } }", None, &ctx())
        .await
        .expect_err("`User.email` rejects a caller without `read:email`");

        assert!(matches!(err, FraiseQLError::Authorization { .. }), "{err:?}");
        assert!(!adapter.ran(), "decidable before the write, so the function never runs");
    }

    // ── Ruling AG 2–3: the error arm holds an exact set of error types ──────────────────
    //
    // A failure is served as one of the error types its mutation can return: a union's (or
    // an interface's) `is_error` members, or — for an object return, where nothing narrower
    // is declared — the schema's error types. A stamp outside that set broke the function's
    // contract; an unstamped failure among several error members must not pick one.

    /// The failure row the SQL function returns, stamped `stamp` (or not stamped).
    fn failure(stamp: Option<&str>) -> Vec<HashMap<String, serde_json::Value>> {
        let mut row = HashMap::new();
        row.insert("succeeded".to_string(), serde_json::json!(false));
        row.insert("state_changed".to_string(), serde_json::json!(false));
        row.insert("error_class".to_string(), serde_json::json!("conflict"));
        row.insert("message".to_string(), serde_json::json!("duplicate"));
        if let Some(s) = stamp {
            row.insert("entity_type".to_string(), serde_json::json!(s));
        }
        vec![row]
    }

    /// An error type carrying `message`.
    fn error_type(name: &str) -> TypeDefinition {
        TypeDefinition {
            is_error: true,
            fields: vec![FieldDefinition::new("message", FieldType::String)],
            ..TypeDefinition::new(name, "")
        }
    }

    /// `createUser` returning `User | ValidationError | ConflictError`, plus `StrayError`,
    /// an error type no member of that union.
    fn schema_with_two_error_members() -> CompiledSchema {
        use crate::schema::UnionDefinition;
        let mut s = schema_with_admin();
        for name in ["ValidationError", "ConflictError", "StrayError"] {
            s.types.push(error_type(name));
        }
        s.unions.push(UnionDefinition::new("CreateUserResult").with_members(vec![
            "User".to_string(),
            "ValidationError".to_string(),
            "ConflictError".to_string(),
        ]));
        s.mutations[0].return_type = "CreateUserResult".to_string();
        s.build_indexes();
        s
    }

    /// `createUser` returning `User | ValidationError`: one error member.
    fn schema_with_one_error_member() -> CompiledSchema {
        use crate::schema::UnionDefinition;
        let mut s = schema_with_admin();
        s.types.push(error_type("ValidationError"));
        s.unions.push(
            UnionDefinition::new("CreateUserResult")
                .with_members(vec!["User".to_string(), "ValidationError".to_string()]),
        );
        s.mutations[0].return_type = "CreateUserResult".to_string();
        s.build_indexes();
        s
    }

    const ERROR_SELECTION: &str = "mutation { createUser { __typename \
         ... on ValidationError { message } ... on ConflictError { message } } }";

    async fn failed_write(
        schema: CompiledSchema,
        stamp: Option<&str>,
        query: &str,
    ) -> (Arc<GatedEntityAdapter>, Result<serde_json::Value>) {
        let adapter = Arc::new(GatedEntityAdapter::returning(failure(stamp)));
        let res = Executor::with_config(schema, Arc::clone(&adapter), RuntimeConfig::default())
            .execute_with_security(query, None, &ctx())
            .await;
        (adapter, res)
    }

    fn assert_error_arm_contract_error(
        adapter: &GatedEntityAdapter,
        res: Result<serde_json::Value>,
        stamp: Option<&str>,
    ) {
        let err = match res {
            Ok(out) => panic!("a failure stamped {stamp:?} was served: {out}"),
            Err(err) => err,
        };
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        if let Some(stamp) = stamp {
            assert!(format!("{err}").contains(&format!("'{stamp}'")), "names the stamp: {err}");
        }
        assert!(!adapter.committed(), "a write that broke its contract does not stand");
    }

    #[tokio::test]
    async fn a_failure_stamped_with_an_error_type_its_mutation_cannot_return_is_a_contract_error() {
        let (adapter, res) =
            failed_write(schema_with_two_error_members(), Some("StrayError"), ERROR_SELECTION)
                .await;
        assert_error_arm_contract_error(&adapter, res, Some("StrayError"));
    }

    #[tokio::test]
    async fn a_failure_stamped_with_a_success_type_is_a_contract_error() {
        let (adapter, res) =
            failed_write(schema_with_two_error_members(), Some("User"), ERROR_SELECTION).await;
        assert_error_arm_contract_error(&adapter, res, Some("User"));
    }

    #[tokio::test]
    async fn a_failure_stamped_with_no_type_is_a_contract_error() {
        let (adapter, res) =
            failed_write(schema_with_two_error_members(), Some("tb_user"), ERROR_SELECTION).await;
        assert_error_arm_contract_error(&adapter, res, Some("tb_user"));
    }

    #[tokio::test]
    async fn an_unstamped_failure_with_two_possible_error_types_is_a_contract_error() {
        let (adapter, res) =
            failed_write(schema_with_two_error_members(), None, ERROR_SELECTION).await;
        assert_error_arm_contract_error(&adapter, res, None);
    }

    #[tokio::test]
    async fn a_failure_of_an_object_return_stamped_with_no_type_is_a_contract_error() {
        let mut s = schema_with_admin();
        s.types.push(error_type("ValidationError"));
        s.build_indexes();
        let (adapter, res) = failed_write(
            s,
            Some("tb_user"),
            "mutation { createUser { __typename ... on ValidationError { message } } }",
        )
        .await;
        assert_error_arm_contract_error(&adapter, res, Some("tb_user"));
    }

    // Controls: what the contract admits.

    #[tokio::test]
    async fn a_failure_stamped_with_one_of_its_error_members_is_served_as_it() {
        let (_, res) =
            failed_write(schema_with_two_error_members(), Some("ConflictError"), ERROR_SELECTION)
                .await;
        let out = res.unwrap();
        assert_eq!(out["data"]["createUser"]["__typename"], "ConflictError", "{out}");
        assert_eq!(out["data"]["createUser"]["message"], "duplicate", "{out}");
    }

    #[tokio::test]
    async fn an_unstamped_failure_with_one_possible_error_type_is_that_type() {
        let (_, res) = failed_write(
            schema_with_one_error_member(),
            None,
            "mutation { createUser { __typename ... on ValidationError { message } } }",
        )
        .await;
        let out = res.unwrap();
        assert_eq!(out["data"]["createUser"]["__typename"], "ValidationError", "{out}");
    }

    #[tokio::test]
    async fn an_unstamped_failure_of_an_object_return_is_the_untyped_failure() {
        let mut s = schema_with_admin();
        s.types.push(error_type("ValidationError"));
        s.build_indexes();
        let (_, res) = failed_write(s, None, "mutation { createUser { __typename } }").await;
        let out = res.unwrap();
        assert_eq!(out["data"]["createUser"]["__typename"], "User", "{out}");
        assert_eq!(out["data"]["createUser"]["status"], "conflict", "{out}");
    }

    // `Mask` is a statement about the value, not about the operation: the caller may
    // do this, they just may not see that field. The write stands.
    #[tokio::test]
    async fn mutation_deny_mask_still_commits_the_write() {
        let adapter = Arc::new(GatedEntityAdapter::default());
        let executor = Executor::with_config(
            schema(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(DenyMask)),
        );
        let res = executor
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await
            .expect("a masked field is a success, not a refusal");

        assert!(res["data"]["createUser"]["email"].is_null(), "the field is masked");
        assert!(adapter.committed(), "a masked field must not roll the write back");
    }

    // An allowed caller commits, which is what makes the two refusals above mean
    // something: the difference is the decision, not the path.
    #[tokio::test]
    async fn mutation_allowed_field_commits_the_write() {
        struct AllowAll;
        impl FieldAuthorizer for AllowAll {
            fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
                Ok(FieldAuthzDecision::Allow)
            }
        }

        let adapter = Arc::new(GatedEntityAdapter::default());
        let executor = Executor::with_config(
            schema(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(AllowAll)),
        );
        let res = executor
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await
            .expect("an allowed field is returned");

        assert_eq!(res["data"]["createUser"]["email"], "alice@x.com");
        assert!(adapter.committed(), "an allowed write commits");
    }

    // The gate is not a second authorizer pass: the decision is taken once, inside
    // the transaction, and the response is built from that same pass. An authorizer
    // with an audit side effect must not see the write twice.
    #[tokio::test]
    async fn the_authorizer_is_consulted_exactly_once_per_gated_field() {
        struct CountingAllow(std::sync::atomic::AtomicUsize);
        impl FieldAuthorizer for CountingAllow {
            fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Ok(FieldAuthzDecision::Allow)
            }
        }

        let authorizer = Arc::new(CountingAllow(std::sync::atomic::AtomicUsize::new(0)));
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default()
                .with_field_authorizer(Arc::clone(&authorizer) as Arc<dyn FieldAuthorizer>),
        );
        executor
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await
            .expect("allowed");

        assert_eq!(
            authorizer.0.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "one gated field selected, one authorizer call"
        );
    }

    fn schema() -> CompiledSchema {
        let mut s = CompiledSchema::new();
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("createUser", "User")
        });
        let mut user = TypeDefinition::new("User", "v_user");
        user.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("name", FieldType::String),
            FieldDefinition::nullable("email", FieldType::String).with_authorize(true),
            FieldDefinition::nullable("owner_id", FieldType::String),
        ];
        s.types.push(user);
        s.build_indexes();
        s
    }

    fn ctx() -> SecurityContext {
        SecurityContext {
            user_id:          "user-1".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::default(),
            request_id:       "req-authz".to_string(),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    // The static `requires_scope` gate and the #423 authorizer AND-compose on a write's
    // payload as they do on a read (`payload_gates`): a field the static gate already
    // masked is not put to the authorizer, so a `Reject` it would have returned cannot
    // refuse a write whose value was never going to be served. The field is masked, and
    // the write stands.
    #[tokio::test]
    async fn a_statically_masked_payload_field_is_not_put_to_the_field_authorizer() {
        let mut schema = schema();
        let user = schema.types.iter_mut().find(|t| t.name == "User").unwrap();
        let email = user.fields.iter_mut().find(|f| f.name == "email").unwrap();
        email.requires_scope = Some("read:email".to_string());
        email.on_deny = FieldDenyPolicy::Mask;
        schema.security = Some(crate::schema::SecurityConfig::default());
        schema.build_indexes();
        let adapter = Arc::new(GatedEntityAdapter::default());
        let out = Executor::with_config(
            schema,
            Arc::clone(&adapter),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        )
        .execute_with_security("mutation { createUser { id email } }", None, &ctx())
        .await
        .unwrap();
        assert_eq!(out["data"]["createUser"]["id"], "123", "{out}");
        assert!(out["data"]["createUser"]["email"].is_null(), "{out}");
        assert!(adapter.committed(), "a masked field does not refuse the write");
    }

    // A raising policy on a gated mutation field fails the whole mutation closed (503).
    #[tokio::test]
    async fn mutation_raising_policy_denies() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(Raising)),
        );
        let res = executor
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await;
        let err = res.expect_err("raising policy must fail closed on the mutation path");
        assert!(matches!(err, FraiseQLError::ServiceUnavailable { .. }), "{err:?}");
        assert!(!format!("{err}").contains("alice@x.com"), "must not leak the value");
    }

    // Deny{Mask} nulls the gated field in the success payload.
    #[tokio::test]
    async fn mutation_deny_mask_nulls_field() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(DenyMask)),
        );
        let res = executor
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await
            .unwrap();
        let payload = &res["data"]["createUser"];
        assert_eq!(payload["id"], "123");
        assert!(payload["email"].is_null(), "masked gated field must be null: {payload}");
    }

    // An unauthenticated mutation selecting a gated field fails closed (no principal).
    #[tokio::test]
    async fn mutation_gated_without_principal_fails_closed() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(DenyMask)),
        );
        let res = executor.execute("mutation { createUser { id email } }", None).await;
        assert!(res.is_err(), "gated field on an unauthenticated mutation must fail closed");
    }

    // A gated field selected with no authorizer configured fails closed.
    #[tokio::test]
    async fn mutation_gated_without_authorizer_fails_closed() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default(),
        );
        let res = executor
            .execute_with_security("mutation { createUser { id email } }", None, &ctx())
            .await;
        assert!(res.is_err(), "gated field with no authorizer configured must fail closed");
    }

    // No gated field selected → authorizer never consulted, payload unchanged.
    #[tokio::test]
    async fn mutation_no_gated_field_skips_authorizer() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        );
        let res = executor
            .execute_with_security("mutation { createUser { id name } }", None, &ctx())
            .await
            .unwrap();
        let payload = &res["data"]["createUser"];
        assert_eq!(payload["name"], "Alice");
        assert!(payload.get("email").is_none(), "email not selected → absent");
    }

    // #1357: the document that bypassed this whole module.
    //
    // `mutation { createUser }` carried an empty selection set into the chokepoint,
    // and an empty selection set is the *permissive* shape:
    // `selection_set_selects_gated_field` is false for it, so the gate at the top of
    // `enforce_mutation_field_authz` returned `Ok(())` with zero authorizer calls,
    // and `project_entity` returned the stored entity unchanged. The three tests
    // above — mask, raise, no-principal, no-authorizer — all pin
    // `mutation { createUser { id email } }`, and every one of them was sidestepped
    // by deleting the braces.
    //
    // `PanicIfCalled` is the load-bearing double: it proves the refusal is not the
    // authorizer denying, but § 5.3.3 refusing the document before the authorizer is
    // ever a question.
    #[tokio::test]
    async fn mutation_with_no_selection_set_is_refused_and_never_serves_the_gated_field() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        );
        let err = executor
            .execute_with_security("mutation { createUser }", None, &ctx())
            .await
            .expect_err("a composite return type named with no selection set is invalid");

        assert!(
            !format!("{err}").contains("alice@x.com"),
            "the gated value must not appear, not even in the refusal: {err}"
        );
    }

    /// The runtime half of #1358, and S2's reason for existing.
    ///
    /// `schema_validator` refuses a leaf-returning mutation, but it is only a gate
    /// for schemas that go *through* the compiler — `schema.compiled.json` can be
    /// hand-authored. This builds one directly: `act` returns an enum, so § 5.3.3
    /// correctly does not refuse `mutation { act }` (a leaf needs no selection set)
    /// and the empty set reaches the write entry.
    ///
    /// Before `WriteSelections` that answered with the whole stored entity —
    /// `alice@x.com` included — with zero authorizer calls. `PanicIfCalled` is what
    /// proves the refusal is not the authorizer denying.
    #[tokio::test]
    async fn a_hand_authored_leaf_returning_mutation_fails_closed() {
        use crate::schema::{EnumDefinition, MutationDefinition};

        let mut s = CompiledSchema::new();
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            ..MutationDefinition::new("act", "Status")
        });
        s.enums.push(EnumDefinition {
            name:        "Status".into(),
            values:      vec![],
            description: None,
        });
        s.build_indexes();

        let executor = Executor::with_config(
            s,
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        );

        let err = executor
            .execute_with_security("mutation { act }", None, &ctx())
            .await
            .expect_err("a write with no selection set must fail closed");

        assert!(
            !format!("{err}").contains("alice@x.com"),
            "the gated value must not appear, not even in the refusal: {err}"
        );
    }

    // The same document, unauthenticated. The anonymous caller was the sharper half
    // of #1352's REST twin: no principal, no authorizer call, gated field served.
    #[tokio::test]
    async fn anonymous_mutation_with_no_selection_set_is_refused() {
        let executor = Executor::with_config(
            schema(),
            Arc::new(GatedEntityAdapter::default()),
            RuntimeConfig::default().with_field_authorizer(Arc::new(PanicIfCalled)),
        );
        let err = executor
            .execute("mutation { createUser }", None)
            .await
            .expect_err("an anonymous caller must not receive the unfiltered entity either");

        assert!(
            !format!("{err}").contains("alice@x.com"),
            "the gated value must not appear: {err}"
        );
    }
}

// ── mod cascade: typed cascade payload projection + per-entity enforcement ────
mod cascade {
    #![allow(clippy::panic)] // Reason: test doubles panic to assert they are never called

    use std::collections::HashMap;

    use async_trait::async_trait;
    use chrono::Utc;
    use serde_json::json;

    use super::*;
    use crate::{
        backend::types::{DatabaseType, PoolMetrics, sql_hints::OrderByClause},
        runtime::CascadeLimits,
        schema::{FieldDefinition, FieldDenyPolicy, FieldType, MutationDefinition, TypeDefinition},
        security::{FieldAuthorizer, FieldAuthzDecision, FieldAuthzRequest, SecurityContext},
    };

    /// A mutation adapter returning a fixed `app.mutation_response` row whose
    /// `cascade` JSONB the test supplies. The primary entity is a `Post` with a
    /// `snake_case` source key (`author_id`) to exercise `camelCase` projection.
    struct CannedMutationAdapter {
        row:               HashMap<String, serde_json::Value>,
        /// Accumulates every view name passed to `invalidate_views`.
        invalidated_views: std::sync::Mutex<Vec<String>>,
    }

    impl CannedMutationAdapter {
        fn new(cascade: serde_json::Value) -> Self {
            let mut row = HashMap::new();
            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert(
                "entity".to_string(),
                json!({ "id": "p1", "title": "Hello", "author_id": "u1" }),
            );
            row.insert("entity_type".to_string(), json!("Post"));
            row.insert("updated_fields".to_string(), json!(["title"]));
            row.insert("cascade".to_string(), cascade);
            row.insert("message".to_string(), json!(""));
            Self {
                row,
                invalidated_views: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait]
    impl DatabaseAdapter for CannedMutationAdapter {
        async fn invalidate_views(&self, views: &[fraiseql_db::ViewName]) -> Result<u64> {
            let mut captured = self.invalidated_views.lock().unwrap();
            captured.extend(views.iter().map(|v| v.as_str().to_string()));
            Ok(views.len() as u64)
        }

        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl CannedMutationAdapter {
        async fn execute_function_call(
            &self,
            _function_name: &str,
            _args: &[serde_json::Value],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![self.row.clone()])
        }

        async fn execute_function_call_with_session(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call(function_name, args).await
        }

        async fn execute_function_call_with_changelog(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            session_vars: &[(&str, &str)],
            _changelog: Option<&crate::backend::traits::ChangeLogWrite<'_>>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_with_session(function_name, args, session_vars).await
        }

        /// The commit gate (#1353) — see `field_authz::GatedEntityAdapter` for why a
        /// double on a policy-gated schema has to implement this rather than inherit
        /// the refusing default.
        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            session_vars: &[(&str, &str)],
            changelog: Option<&ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            let rows = self
                .execute_function_call_with_changelog(function_name, args, session_vars, changelog)
                .await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for CannedMutationAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// Field authorizer that masks (nulls) every gated field.
    struct MaskAll;
    impl FieldAuthorizer for MaskAll {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            Ok(FieldAuthzDecision::Deny {
                code:    "no".into(),
                on_deny: FieldDenyPolicy::Mask,
            })
        }
    }

    fn auth_ctx() -> SecurityContext {
        SecurityContext {
            user_id:          "user-1".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::default(),
            request_id:       "req-cascade".to_string(),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    /// A `createPost` cascade mutation over a `Post` entity carrying a `snake_case`
    /// source key (`author_id` → `authorId`) and a policy-gated `email`.
    fn cascade_schema() -> CompiledSchema {
        let mut s = CompiledSchema::new();
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_post".to_string()),
            cascade: true,
            ..MutationDefinition::new("createPost", "CreatePostPayload")
        });
        let mut post = TypeDefinition::new("Post", "v_post");
        post.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("title", FieldType::String),
            FieldDefinition::nullable("authorId", FieldType::String),
            FieldDefinition::nullable("email", FieldType::String).with_authorize(true),
        ];
        post.implements = vec!["CascadeNode".to_string()];
        s.types.push(post);
        // A type whose view is NOT `v_<lowercase>` (a pg_tviews materialized view),
        // so cache-invalidation resolution can't fall back to a string guess.
        let mut account = TypeDefinition::new("Account", "tv_account");
        account.fields = vec![FieldDefinition::new("id", FieldType::Id)];
        account.implements = vec!["CascadeNode".to_string()];
        s.types.push(account);
        s.build_indexes();
        s
    }

    /// A cascade with one updated `Post` (carrying a gated `email`) and one deletion.
    fn standard_cascade() -> serde_json::Value {
        json!({
            "updated": [
                {
                    "__typename": "Post", "id": "p2", "operation": "UPDATED",
                    "entity": { "id": "p2", "title": "Sibling", "author_id": "u9", "email": "secret@x.com" }
                }
            ],
            "deleted": [
                { "__typename": "Post", "id": "p3", "deletedAt": "2026-01-01T00:00:00Z" }
            ]
        })
    }

    /// The typed payload shape: `{ entity, cascade { updated, deleted }, updatedFields }`,
    /// with the primary entity AND each cascade entity projected to `camelCase`.
    #[tokio::test]
    async fn cascade_payload_shape_and_camelcase() {
        let executor = Executor::new(
            cascade_schema(),
            Arc::new(CannedMutationAdapter::new(standard_cascade())),
        );
        let q = r"mutation { createPost {
            entity { id title authorId }
            cascade {
                updated { id operation entity { ... on Post { title authorId } } }
                deleted { id deletedAt }
            }
            updatedFields
        } }";
        let res = executor.execute(q, None).await.unwrap();
        let payload = &res["data"]["createPost"];

        // Primary entity, camelCase (author_id → authorId).
        assert_eq!(payload["entity"], json!({ "id": "p1", "title": "Hello", "authorId": "u1" }));

        // Cascade updated entry: id + operation + projected, camelCased entity.
        let updated = &payload["cascade"]["updated"][0];
        assert_eq!(updated["id"], "p2");
        assert_eq!(updated["operation"], "UPDATED");
        assert_eq!(updated["entity"], json!({ "title": "Sibling", "authorId": "u9" }));

        // Deleted entry: id + deletedAt, no entity body.
        let deleted = &payload["cascade"]["deleted"][0];
        assert_eq!(deleted["id"], "p3");
        assert_eq!(deleted["deletedAt"], "2026-01-01T00:00:00Z");

        // updatedFields rehomed onto the payload.
        assert_eq!(payload["updatedFields"], json!(["title"]));
    }

    /// Cascade + updatedFields are selection-gated: unselected ⇒ absent (no more
    /// unrequested injection — eval finding 3).
    #[tokio::test]
    async fn cascade_selection_gated_to_requested_fields() {
        let executor = Executor::new(
            cascade_schema(),
            Arc::new(CannedMutationAdapter::new(standard_cascade())),
        );
        let res = executor
            .execute("mutation { createPost { entity { id } } }", None)
            .await
            .unwrap();
        let payload = &res["data"]["createPost"];
        assert_eq!(payload["entity"], json!({ "id": "p1" }));
        assert!(payload.get("cascade").is_none(), "unselected cascade must be absent: {payload}");
        assert!(payload.get("updatedFields").is_none(), "unselected updatedFields absent");
    }

    /// THE load-bearing fix (eval finding 1): a policy-gated field on a CASCADE
    /// entity is run through the field authorizer, exactly like a queried entity.
    /// Before this, cascade entities bypassed field authz entirely.
    #[tokio::test]
    async fn cascade_entity_gated_field_is_authorized() {
        let executor = Executor::with_config(
            cascade_schema(),
            Arc::new(CannedMutationAdapter::new(standard_cascade())),
            RuntimeConfig::default().with_field_authorizer(Arc::new(MaskAll)),
        );
        let q = r"mutation { createPost {
            cascade { updated { entity { ... on Post { id email } } } }
        } }";
        let res = executor.execute_with_security(q, None, &auth_ctx()).await.unwrap();
        let entity = &res["data"]["createPost"]["cascade"]["updated"][0]["entity"];
        assert_eq!(entity["id"], "p2");
        assert!(
            entity["email"].is_null(),
            "a gated field on a cascade entity must be authorized (masked): {entity}"
        );
    }

    /// `metadata` is populated: `affectedCount` counts what is actually returned
    /// and `truncated` is false for an under-limit cascade.
    #[tokio::test]
    async fn cascade_metadata_reports_affected_count() {
        let executor = Executor::new(
            cascade_schema(),
            Arc::new(CannedMutationAdapter::new(standard_cascade())),
        );
        let q = "mutation { createPost { cascade { metadata { affectedCount truncated } } } }";
        let res = executor.execute(q, None).await.unwrap();
        let meta = &res["data"]["createPost"]["cascade"]["metadata"];
        // 1 updated + 1 deleted.
        assert_eq!(meta["affectedCount"], 2);
        assert_eq!(meta["truncated"], false);
    }

    /// A cascade over the affected-entity ceiling is truncated (each side to half
    /// the limit) and flagged `truncated` with the pre-truncation `originalCount`.
    #[tokio::test]
    async fn cascade_over_limit_is_truncated_and_flagged() {
        let updated: Vec<_> = (0..4)
            .map(|i| {
                json!({
                    "__typename": "Post", "id": format!("p{i}"), "operation": "UPDATED",
                    "entity": { "id": format!("p{i}") }
                })
            })
            .collect();
        let cascade = json!({ "updated": updated, "deleted": [] });
        let executor = Executor::with_config(
            cascade_schema(),
            Arc::new(CannedMutationAdapter::new(cascade)),
            RuntimeConfig::default().with_cascade_limits(CascadeLimits {
                max_depth:            3,
                max_updated_entities: 2,
                max_response_size_mb: 5,
            }),
        );
        let q = "mutation { createPost { cascade {
            updated { id }
            metadata { affectedCount truncated originalCount }
        } } }";
        let res = executor.execute(q, None).await.unwrap();
        let cascade = &res["data"]["createPost"]["cascade"];
        // 4 updated, 0 deleted, limit 2 ⇒ greedy fill keeps 2 updated (a half-each
        // split would have wasted the deleted headroom and kept only 1).
        assert_eq!(cascade["updated"].as_array().unwrap().len(), 2);
        assert_eq!(cascade["metadata"]["truncated"], true);
        assert_eq!(cascade["metadata"]["affectedCount"], 2);
        assert_eq!(cascade["metadata"]["originalCount"], 4);
    }

    /// `timestamp` is a non-null `DateTime!`: the runtime stamps the server clock
    /// when the function's cascade omits a metadata timestamp, so a common cascade
    /// (no metadata block) never violates the SDL's non-null contract.
    #[tokio::test]
    async fn cascade_metadata_timestamp_is_runtime_stamped_when_absent() {
        // standard_cascade() carries no `metadata` block at all.
        let executor = Executor::new(
            cascade_schema(),
            Arc::new(CannedMutationAdapter::new(standard_cascade())),
        );
        let q = "mutation { createPost { cascade { metadata { timestamp } } } }";
        let res = executor.execute(q, None).await.unwrap();
        let ts = &res["data"]["createPost"]["cascade"]["metadata"]["timestamp"];
        assert!(ts.is_string(), "timestamp must be present (runtime-stamped): {ts}");
        assert!(!ts.as_str().unwrap().is_empty(), "timestamp must be non-empty");
    }

    /// Strict entry validation: an `updated` entry missing `operation` fails closed
    /// (would otherwise be an SDL-invalid non-null `CascadeOperation!` violation).
    #[tokio::test]
    async fn cascade_updated_missing_operation_fails_closed() {
        let cascade = json!({
            "updated": [ { "__typename": "Post", "id": "p2", "entity": { "id": "p2" } } ],
            "deleted": []
        });
        let executor =
            Executor::new(cascade_schema(), Arc::new(CannedMutationAdapter::new(cascade)));
        let res = executor
            .execute("mutation { createPost { cascade { updated { id } } } }", None)
            .await;
        assert!(res.is_err(), "a cascade updated entry missing operation must fail closed");
    }

    /// Strict entry validation: a `deleted` entry missing `deletedAt` fails closed.
    #[tokio::test]
    async fn cascade_deleted_missing_deleted_at_fails_closed() {
        let cascade = json!({
            "updated": [],
            "deleted": [ { "__typename": "Post", "id": "p3" } ]
        });
        let executor =
            Executor::new(cascade_schema(), Arc::new(CannedMutationAdapter::new(cascade)));
        let res = executor
            .execute("mutation { createPost { cascade { deleted { id } } } }", None)
            .await;
        assert!(res.is_err(), "a cascade deleted entry missing deletedAt must fail closed");
    }

    /// `invalidations` (client-side cache hints) pass through, filtered to the
    /// selection set — advisory hints, no projection or authz.
    #[tokio::test]
    async fn cascade_invalidations_pass_through() {
        let cascade = json!({
            "updated": [], "deleted": [],
            "invalidations": [
                { "queryName": "listPosts", "strategy": "INVALIDATE", "scope": "PREFIX" }
            ]
        });
        let executor =
            Executor::new(cascade_schema(), Arc::new(CannedMutationAdapter::new(cascade)));
        let q =
            "mutation { createPost { cascade { invalidations { queryName strategy scope } } } }";
        let res = executor.execute(q, None).await.unwrap();
        let inv = &res["data"]["createPost"]["cascade"]["invalidations"][0];
        assert_eq!(inv["queryName"], "listPosts");
        assert_eq!(inv["strategy"], "INVALIDATE");
        assert_eq!(inv["scope"], "PREFIX");
    }

    /// A cascade mutation invalidates its affected entities' caches server-side
    /// (finding 7) — independent of whether the client selected `cascade`, since
    /// stale caches on OTHER entity types are a server concern. The view is
    /// resolved from the compiled schema (`Account` → `tv_account`), NOT guessed as
    /// `v_<lowercase>` — a guess would invalidate a nonexistent view and silently
    /// no-op, re-hiding the stale-cache bug.
    #[tokio::test]
    async fn cascade_mutation_invalidates_resolved_cascade_entity_views() {
        let cascade = json!({
            "updated": [
                { "__typename": "Account", "id": "a1", "operation": "UPDATED", "entity": { "id": "a1" } }
            ],
            "deleted": []
        });
        let adapter = Arc::new(CannedMutationAdapter::new(cascade));
        let executor = Executor::new(cascade_schema(), Arc::clone(&adapter));
        // The client selects only the primary entity — cascade is not requested.
        executor
            .execute("mutation { createPost { entity { id } } }", None)
            .await
            .unwrap();
        let views = adapter.invalidated_views.lock().unwrap().clone();
        assert!(
            views.iter().any(|v| v == "tv_account"),
            "the cascade Account entity's real view (tv_account) must be invalidated, \
             not a v_<lowercase> guess: {views:?}"
        );
    }

    /// Fail-closed: a cascade entry naming an unknown type cannot be projected or
    /// authorized, so it aborts the response rather than shipping raw.
    #[tokio::test]
    async fn cascade_unknown_typename_fails_closed() {
        let cascade = json!({
            "updated": [
                { "__typename": "Ghost", "id": "x", "operation": "UPDATED", "entity": { "id": "x" } }
            ],
            "deleted": []
        });
        let executor =
            Executor::new(cascade_schema(), Arc::new(CannedMutationAdapter::new(cascade)));
        let q = "mutation { createPost { cascade { updated { entity { ... on Post { id } } } } } }";
        let res = executor.execute(q, None).await;
        assert!(res.is_err(), "unknown cascade __typename must fail closed");
    }

    /// Fail-closed: a cascade entry naming a framework-`internal` projection is rejected
    /// (#665, gate 5). A change-log/checkpoint view is the change-capture *mechanism*,
    /// never a cascade-deliverable entity — the compiler excludes internal types from
    /// cascade classification (`is_queryable_entity`), so they never implement
    /// `CascadeNode`. This pins that the runtime ALSO rejects a hand-crafted cascade
    /// JSONB entry that names one, turning "framework projections never appear in a
    /// payload" from emergent (the type IS in `schema.types`, so the bare existence
    /// check would pass it) into enforced. It reads `internal` off the compiled schema —
    /// the flag's first runtime consumer, which is why Phase 01 serializes it.
    #[tokio::test]
    async fn cascade_internal_typename_fails_closed() {
        let mut schema = cascade_schema();
        let mut ecl = TypeDefinition::new("EntityChangeLog", "core.v_entity_change_log");
        ecl.fields = vec![FieldDefinition::new("id", FieldType::Id)];
        ecl.internal = true;
        schema.types.push(ecl);
        schema.build_indexes();

        let cascade = json!({
            "updated": [
                { "__typename": "EntityChangeLog", "id": "e1", "operation": "UPDATED", "entity": { "id": "e1" } }
            ],
            "deleted": []
        });
        let executor = Executor::new(schema, Arc::new(CannedMutationAdapter::new(cascade)));
        let q = "mutation { createPost { cascade { updated { id } } } }";
        let res = executor.execute(q, None).await;
        let err = res.expect_err("a cascade entry naming an internal type must fail closed");
        let msg = err.to_string();
        assert!(
            msg.contains("EntityChangeLog") && msg.contains("internal"),
            "the error must legibly name the internal type, got: {msg}"
        );
    }

    // Ruling Y 6: an entity a cascade reports as updated is served as a read of its
    // type, so a role-gated `CascadeNode` implementor needs the role. `Account` is gated on
    // `admin`; the caller holds no role.
    #[tokio::test]
    async fn a_role_gated_cascade_entity_is_not_served_without_the_role() {
        let mut schema = cascade_schema();
        let account = schema.types.iter_mut().find(|t| t.name == "Account").unwrap();
        account.requires_role = Some("admin".to_string());
        schema.build_indexes();
        let cascade = json!({
            "updated": [
                { "__typename": "Account", "id": "a1", "operation": "UPDATED",
                  "entity": { "id": "a1-secret" } }
            ]
        });
        let res = Executor::new(schema, Arc::new(CannedMutationAdapter::new(cascade)))
            .execute_with_security(
                "mutation { createPost { cascade { updated { entity { ... on Account { id } } } } } }",
                None,
                &auth_ctx(),
            )
            .await;

        let err = res.expect_err("`Account` requires `admin`, which the caller does not hold");
        assert!(matches!(err, FraiseQLError::Authorization { .. }), "{err:?}");
        assert!(
            !format!("{err}").contains("a1-secret"),
            "the gated value must not appear: {err}"
        );
    }

    // An unstamped cascade entity is the payload's declared entity type — the shape the
    // compiler synthesises (`<Name>Payload { entity: T }`) and the helper's NULL default.
    #[tokio::test]
    async fn an_unstamped_cascade_entity_is_the_payloads_declared_entity_type() {
        let mut schema = cascade_schema();
        let mut payload = TypeDefinition::new("CreatePostPayload", "");
        payload.fields = vec![FieldDefinition::new(
            "entity",
            FieldType::Object("Post".to_string()),
        )];
        schema.types.push(payload);
        schema.build_indexes();
        let mut adapter = CannedMutationAdapter::new(standard_cascade());
        adapter.row.remove("entity_type");
        let out = Executor::new(schema, Arc::new(adapter))
            .execute_with_security(
                "mutation { createPost { entity { id title } } }",
                None,
                &auth_ctx(),
            )
            .await
            .unwrap();
        assert_eq!(out["data"]["createPost"]["entity"]["title"], "Hello", "{out}");
    }

    // Ruling AA 1 (Z 3): a cascade's entity is the payload's declared entity type, or a
    // `CascadeNode`; an entity a cascade reports updated is a `CascadeNode`. `Plain` is
    // neither.
    fn cascade_schema_with_plain() -> CompiledSchema {
        let mut s = cascade_schema();
        let mut plain = TypeDefinition::new("Plain", "v_plain");
        plain.fields = vec![FieldDefinition::new("id", FieldType::Id)];
        s.types.push(plain);
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn a_cascade_entity_stamped_with_a_type_it_cannot_hold_is_a_contract_error() {
        let mut adapter = CannedMutationAdapter::new(standard_cascade());
        adapter.row.insert("entity_type".to_string(), json!("Plain"));
        let err = Executor::new(cascade_schema_with_plain(), Arc::new(adapter))
            .execute_with_security("mutation { createPost { entity { id } } }", None, &auth_ctx())
            .await
            .expect_err("`Plain` is not a CascadeNode");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        assert!(format!("{err}").contains("'Plain'"), "names the stamp: {err}");
    }

    #[tokio::test]
    async fn an_updated_entity_of_a_type_that_is_no_cascade_node_is_a_contract_error() {
        let cascade = json!({
            "updated": [
                { "__typename": "Plain", "id": "x1", "operation": "UPDATED", "entity": { "id": "x1" } }
            ]
        });
        let err = Executor::new(
            cascade_schema_with_plain(),
            Arc::new(CannedMutationAdapter::new(cascade)),
        )
        .execute_with_security(
            "mutation { createPost { cascade { updated { entity { ... on Plain { id } } } } } }",
            None,
            &auth_ctx(),
        )
        .await
        .expect_err("`Plain` is not a CascadeNode");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
        assert!(format!("{err}").contains("'Plain'"), "names the stamp: {err}");
    }
}

// ── mod before_mutation_enforcement: #1327, the three bypasses ────────────

/// `before:mutation` is enforcement, so it must run for every executed mutation on
/// every transport. It used to run once per HTTP request in the GraphQL handler,
/// keyed on the *first* root field and handed `request.variables`, which left three
/// shapes that executed a mutation without running its chain: a second root field,
/// inline arguments, and the REST write route.
///
/// Every test here asserts the **write** — whether the mutation's SQL function was
/// called — and not only the response envelope: a repaired outer guard can make the
/// response say "refused" while the row lands anyway.
mod before_mutation_enforcement {
    use std::{
        collections::HashMap,
        sync::{Arc, Mutex},
    };

    use async_trait::async_trait;
    use chrono::Utc;

    use super::*;
    use crate::{
        schema::{
            ArgumentDefinition, FieldType, InputFieldDefinition, InputObjectDefinition,
            MutationDefinition, MutationOperation,
        },
        security::{
            BeforeMutationGate, BeforeMutationOutcome, BeforeMutationRequest, SecurityContext,
        },
    };

    /// Adapter that **appends** every SQL function call it is handed, with its name.
    ///
    /// The existing `CapturingFunctionCallAdapter` overwrites its capture and drops
    /// the function name, so it cannot answer "did `guarded` run?" for a document
    /// that also ran `harmless`. Here the call log *is* the durable-row assertion:
    /// no call, no row.
    struct MutationCallLog {
        calls: Mutex<Vec<(String, Vec<serde_json::Value>)>>,
    }

    impl MutationCallLog {
        fn new() -> Self {
            Self {
                calls: Mutex::new(Vec::new()),
            }
        }

        fn functions(&self) -> Vec<String> {
            self.calls.lock().unwrap().iter().map(|(name, _)| name.clone()).collect()
        }

        fn args_for(&self, function: &str) -> Vec<serde_json::Value> {
            self.calls
                .lock()
                .unwrap()
                .iter()
                .find(|(name, _)| name == function)
                .map(|(_, args)| args.clone())
                .unwrap_or_default()
        }
    }

    #[async_trait]
    impl DatabaseAdapter for MutationCallLog {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl MutationCallLog {
        async fn execute_function_call(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            self.calls.lock().unwrap().push((function_name.to_string(), args.to_vec()));
            let mut row = std::collections::HashMap::new();
            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert("entity".to_string(), json!({ "id": "1" }));
            row.insert("entity_type".to_string(), json!("User"));
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&fraiseql_db::ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            let rows = self.execute_function_call(function_name, args).await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for MutationCallLog {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// A gate that refuses exactly one mutation by name, records every mutation it
    /// was asked about in order, and records the arguments it was handed.
    struct AbortsOne {
        refuse:   &'static str,
        asked:    Mutex<Vec<String>>,
        observed: Mutex<Vec<serde_json::Value>>,
        rewrite:  Option<serde_json::Value>,
    }

    impl AbortsOne {
        fn new(refuse: &'static str) -> Arc<Self> {
            Arc::new(Self {
                refuse,
                asked: Mutex::new(Vec::new()),
                observed: Mutex::new(Vec::new()),
                rewrite: None,
            })
        }

        /// A gate that refuses nothing and rewrites every write's arguments.
        fn rewriting(rewrite: serde_json::Value) -> Arc<Self> {
            Arc::new(Self {
                refuse:   "",
                asked:    Mutex::new(Vec::new()),
                observed: Mutex::new(Vec::new()),
                rewrite:  Some(rewrite),
            })
        }

        fn asked(&self) -> Vec<String> {
            self.asked.lock().unwrap().clone()
        }

        fn observed(&self) -> Vec<serde_json::Value> {
            self.observed.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl BeforeMutationGate for AbortsOne {
        async fn before_mutation(
            &self,
            request: &BeforeMutationRequest<'_>,
        ) -> Result<BeforeMutationOutcome> {
            self.asked.lock().unwrap().push(request.mutation.to_string());
            self.observed.lock().unwrap().push(request.arguments.clone());
            if request.mutation == self.refuse {
                return Ok(BeforeMutationOutcome::Abort {
                    reason: format!("{} is not permitted", request.mutation),
                });
            }
            match &self.rewrite {
                Some(arguments) => Ok(BeforeMutationOutcome::ProceedWith {
                    arguments: arguments.clone(),
                }),
                None => Ok(BeforeMutationOutcome::Proceed),
            }
        }
    }

    /// Two Insert mutations, `harmless` and `guarded`, each flattening a
    /// `CreateUserInput` to positional `[name, email]` through its own SQL function —
    /// so the call log names which one ran.
    fn two_mutations() -> CompiledSchema {
        let mut schema = CompiledSchema::new();
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("name", "String!"),
                InputFieldDefinition::new("email", "String!"),
            ],
            description: None,
            metadata:    None,
        });
        for name in ["harmless", "guarded"] {
            schema.mutations.push(MutationDefinition {
                sql_source: Some(format!("fn_{name}")),
                operation: MutationOperation::Insert {
                    table: format!("fn_{name}"),
                },
                arguments: vec![ArgumentDefinition {
                    name:          "input".to_string(),
                    arg_type:      FieldType::Input("CreateUserInput".to_string()),
                    nullable:      false,
                    default_value: None,
                    description:   None,
                    deprecation:   None,
                }],
                ..MutationDefinition::new(name, "User")
            });
        }
        schema.build_indexes();
        schema
    }

    /// `guarded(name: String!)` — one flat scalar argument, the shape the REST write
    /// surface produces (`build_mutation_variables` spreads the body's keys at the top
    /// level rather than wrapping them in an `input` object).
    fn flat_argument_mutation() -> CompiledSchema {
        let mut schema = CompiledSchema::new();
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_guarded".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_guarded".to_string(),
            },
            arguments: vec![ArgumentDefinition {
                name:          "name".to_string(),
                arg_type:      FieldType::String,
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("guarded", "User")
        });
        schema.build_indexes();
        schema
    }

    fn gated(gate: Arc<AbortsOne>) -> (Executor, Arc<MutationCallLog>) {
        let adapter = Arc::new(MutationCallLog::new());
        let gate: Arc<dyn BeforeMutationGate> = gate;
        let executor = Executor::with_config(
            two_mutations(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_before_mutation_gate(gate),
        );
        (executor, adapter)
    }

    fn principal() -> SecurityContext {
        SecurityContext {
            user_id:          "u1".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::default(),
            request_id:       "req-1327".to_string(),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    const HARMLESS_AND_GUARDED: &str = r#"mutation {
        harmless(input: { name: "H", email: "h@x.tld" }) { id }
        guarded(input: { name: "G", email: "g@x.tld" }) { id }
    }"#;

    // ── bypass (a): a second root field ──────────────────────────────────

    /// The handler keyed the chain on `parse_query(…).root_field` — the *first* root
    /// — and since #759 the executor runs every root serially, so `guarded` executed
    /// after only `harmless`'s chain had run.
    #[tokio::test]
    async fn a_second_root_field_cannot_escape_its_chain() {
        let gate = AbortsOne::new("guarded");
        let (executor, adapter) = gated(Arc::clone(&gate));

        let response = executor
            .execute(HARMLESS_AND_GUARDED, None)
            .await
            .expect("the multi-root path reports per-root outcomes, it does not fail the request");

        assert_eq!(
            adapter.functions(),
            vec!["fn_harmless".to_string()],
            "`guarded` must not have written: only the approved root's function may be called"
        );
        let errors = response["errors"].as_array().expect("the refused root must be reported");
        assert_eq!(errors.len(), 1, "exactly the refused root errors: {errors:?}");
        assert_eq!(errors[0]["path"][0], "guarded");
        assert!(
            errors[0]["message"]
                .as_str()
                .unwrap_or_default()
                .contains("guarded is not permitted"),
            "the rule's own message must reach the client: {errors:?}"
        );
        assert_eq!(response["data"]["guarded"], serde_json::Value::Null);
    }

    /// The chain runs once per executed root, in document order — not once per
    /// request. Both roots are adjudicated, `harmless` first.
    #[tokio::test]
    async fn every_root_is_adjudicated_in_document_order() {
        let gate = AbortsOne::new("nothing");
        let (executor, adapter) = gated(Arc::clone(&gate));

        executor
            .execute(HARMLESS_AND_GUARDED, None)
            .await
            .expect("both roots are approved");

        assert_eq!(
            gate.asked(),
            vec!["harmless".to_string(), "guarded".to_string()],
            "the chain must run per root, in document order"
        );
        assert_eq!(
            adapter.functions(),
            vec!["fn_harmless".to_string(), "fn_guarded".to_string()],
            "both approved roots must write"
        );
    }

    /// Keyed on the field name, never the response alias: two roots calling the same
    /// mutation differ only by alias, so keying on the alias would run one chain
    /// twice and skip the other.
    #[tokio::test]
    async fn an_alias_does_not_hide_the_mutation_from_its_chain() {
        let gate = AbortsOne::new("guarded");
        let (executor, adapter) = gated(Arc::clone(&gate));

        let response = executor
            .execute(r#"mutation { somethingElse: guarded(input: { name: "G", email: "g@x.tld" }) { id } }"#, None)
            .await;

        assert!(adapter.functions().is_empty(), "an aliased guarded write must not run");
        let err = response.expect_err("a single refused root fails the request");
        assert!(
            err.to_string().contains("guarded is not permitted"),
            "the chain must be looked up by field name, not by `somethingElse`: {err}"
        );
        assert_eq!(gate.asked(), vec!["guarded".to_string()], "the gate is asked about the field");
    }

    // ── bypass (b): inline arguments ─────────────────────────────────────

    /// The chain was handed `request.variables`, so a write whose input is an inline
    /// literal was invisible to it: `guarded(input: { … })` with no variables ran
    /// with the chain seeing `null`.
    #[tokio::test]
    async fn an_inline_literal_input_is_visible_to_the_chain() {
        let gate = AbortsOne::new("guarded");
        let (executor, adapter) = gated(Arc::clone(&gate));

        let err = executor
            .execute(r#"mutation { guarded(input: { name: "G", email: "g@x.tld" }) { id } }"#, None)
            .await
            .expect_err("an inline-argument write must still be refused");

        assert!(adapter.functions().is_empty(), "the refused write must not run");
        assert!(err.to_string().contains("guarded is not permitted"), "{err}");
        assert_eq!(
            gate.observed()[0]["input"]["name"],
            "G",
            "the chain must see the inline literal, not only the variables map: {:?}",
            gate.observed()
        );
    }

    /// `Proceed(modified)` must reach the **executed** arguments, not just the
    /// request variables.
    ///
    /// The fixture makes the three spellings differ on purpose: the inline literal
    /// says `INLINE`, the request variables say `FROM_VARIABLES`, and the rewrite
    /// says `REWRITTEN`. Only the rewrite may reach the SQL function — a test whose
    /// fixtures agreed would pass with the wrong one plumbed through.
    #[tokio::test]
    async fn a_rewrite_reaches_the_executed_arguments() {
        let gate = AbortsOne::rewriting(serde_json::json!({
            "input": { "name": "REWRITTEN", "email": "r@x.tld" }
        }));
        let (executor, adapter) = gated(Arc::clone(&gate));

        let variables = serde_json::json!({ "name": "FROM_VARIABLES" });
        executor
            .execute(
                r#"mutation { guarded(input: { name: "INLINE", email: "i@x.tld" }) { id } }"#,
                Some(&variables),
            )
            .await
            .expect("the rewriting gate approves the write");

        let args = adapter.args_for("fn_guarded");
        assert_eq!(
            args,
            vec![serde_json::json!("REWRITTEN"), serde_json::json!("r@x.tld")],
            "the rewrite must be what the SQL function binds, not INLINE or FROM_VARIABLES"
        );
        assert_eq!(
            gate.observed()[0]["input"]["name"],
            "INLINE",
            "and the gate must have been shown the resolved inline literal: {:?}",
            gate.observed()
        );
    }

    // ── bypass (c): the REST write route ─────────────────────────────────

    /// `routes/rest/handler/mutation.rs` dispatched `after:mutation` only, so no
    /// before-chain ran on a REST write at all. The anonymous REST write reaches the
    /// engine through the direct `SupportsMutations` API, which is why the gate lives
    /// at the chokepoint both that API and the GraphQL branches converge on.
    #[tokio::test]
    async fn the_anonymous_rest_write_path_cannot_escape_its_chain() {
        let gate = AbortsOne::new("guarded");
        let (executor, adapter) = gated(Arc::clone(&gate));

        let variables = serde_json::json!({ "input": { "name": "G", "email": "g@x.tld" } });
        let err = executor
            .execute_mutation("guarded", Some(&variables), any_write_selections())
            .await
            .expect_err("the direct write API must run the chain too");

        assert!(adapter.functions().is_empty(), "the refused write must not run");
        assert!(err.to_string().contains("guarded is not permitted"), "{err}");
    }

    /// The authenticated REST write builds a synthetic document and goes through
    /// `execute_with_security`; it converges on the same chokepoint.
    ///
    /// The arguments are flat scalars because that is what the REST surface produces:
    /// `build_mutation_variables` spreads the request body's keys at the top level.
    /// (A body carrying a *nested* object cannot reach the engine on this path at all —
    /// `execute_mutation_with_security` renders each argument with `format!("{k}: {v}")`,
    /// which emits JSON object syntax with quoted keys and fails to parse. Filed
    /// separately, not widened into this phase.)
    #[tokio::test]
    async fn the_authenticated_rest_write_path_cannot_escape_its_chain() {
        let gate = AbortsOne::new("guarded");
        let adapter = Arc::new(MutationCallLog::new());
        let gate_dyn: Arc<dyn BeforeMutationGate> = Arc::clone(&gate) as _;
        let executor = Executor::with_config(
            flat_argument_mutation(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_before_mutation_gate(gate_dyn),
        );

        let arguments = serde_json::json!({ "name": "G" });
        let err = executor
            .execute_mutation_with_security("guarded", &arguments, Some(&principal()))
            .await
            .expect_err("the authenticated REST write must run the chain too");

        assert!(adapter.functions().is_empty(), "the refused write must not run");
        assert!(err.to_string().contains("guarded is not permitted"), "{err}");
        assert_eq!(
            gate.observed()[0]["name"],
            "G",
            "the gate must see the REST body's argument: {:?}",
            gate.observed()
        );
    }

    /// The authenticated GraphQL branch is gated too — the fourth entry path.
    #[tokio::test]
    async fn the_authenticated_graphql_path_cannot_escape_its_chain() {
        let gate = AbortsOne::new("guarded");
        let (executor, adapter) = gated(Arc::clone(&gate));

        let err = executor
            .execute_with_security(
                r#"mutation { guarded(input: { name: "G", email: "g@x.tld" }) { id } }"#,
                None,
                &principal(),
            )
            .await
            .expect_err("the authenticated GraphQL write must run the chain");

        assert!(adapter.functions().is_empty(), "the refused write must not run");
        assert!(err.to_string().contains("guarded is not permitted"), "{err}");
    }

    // ── the gate is optional and the approving path is unaffected ─────────

    /// With no gate configured the write runs with the arguments the engine
    /// resolved — the zero-overhead default for a schema that declares no
    /// `before:mutation` function.
    #[tokio::test]
    async fn no_gate_configured_leaves_the_write_alone() {
        let adapter = Arc::new(MutationCallLog::new());
        let executor = Executor::new(two_mutations(), Arc::clone(&adapter));

        executor
            .execute(r#"mutation { guarded(input: { name: "G", email: "g@x.tld" }) { id } }"#, None)
            .await
            .expect("an ungated write runs");

        assert_eq!(
            adapter.args_for("fn_guarded"),
            vec![serde_json::json!("G"), serde_json::json!("g@x.tld")],
            "the resolved inline literal must still bind"
        );
    }

    /// An approving gate does not disturb the arguments: `Proceed` keeps what the
    /// engine resolved, including the inline literal.
    #[tokio::test]
    async fn an_approving_gate_leaves_the_arguments_alone() {
        let gate = AbortsOne::new("nothing");
        let (executor, adapter) = gated(Arc::clone(&gate));

        executor
            .execute(r#"mutation { guarded(input: { name: "G", email: "g@x.tld" }) { id } }"#, None)
            .await
            .expect("an approved write runs");

        assert_eq!(
            adapter.args_for("fn_guarded"),
            vec![serde_json::json!("G"), serde_json::json!("g@x.tld")],
            "Proceed must not rewrite anything"
        );
    }

    /// Fail-closed: a gate that cannot decide refuses the write rather than falling
    /// through to the original input.
    #[tokio::test]
    async fn a_gate_that_errors_refuses_the_write() {
        struct Broken;

        #[async_trait]
        impl BeforeMutationGate for Broken {
            async fn before_mutation(
                &self,
                _request: &BeforeMutationRequest<'_>,
            ) -> Result<BeforeMutationOutcome> {
                Err(FraiseQLError::Internal {
                    message: "before:mutation hook execution failed".to_string(),
                    source:  None,
                })
            }
        }

        let adapter = Arc::new(MutationCallLog::new());
        let executor = Executor::with_config(
            two_mutations(),
            Arc::clone(&adapter),
            RuntimeConfig::default().with_before_mutation_gate(Arc::new(Broken)),
        );

        let err = executor
            .execute(r#"mutation { guarded(input: { name: "G", email: "g@x.tld" }) { id } }"#, None)
            .await
            .expect_err("a gate that cannot decide must refuse");

        assert!(adapter.functions().is_empty(), "nothing may be written: {err}");
    }

    /// The gate is consulted for a write with no arguments at all, and is handed
    /// `Null` — the payload shape the chain has always received.
    #[tokio::test]
    async fn an_argumentless_write_is_still_adjudicated() {
        let gate = AbortsOne::new("reindex");
        let adapter = Arc::new(MutationCallLog::new());
        let mut schema = CompiledSchema::new();
        let mut def = MutationDefinition::new("reindex", "User");
        def.sql_source = Some("fn_reindex".to_string());
        def.operation = MutationOperation::Custom;
        schema.mutations.push(def);
        schema.build_indexes();
        let executor = Executor::with_config(
            schema,
            Arc::clone(&adapter),
            RuntimeConfig::default().with_before_mutation_gate(Arc::clone(&gate) as _),
        );

        let err = executor
            .execute("mutation { reindex { id } }", None)
            .await
            .expect_err("an argument-less write is adjudicated like any other");

        assert!(adapter.functions().is_empty(), "the refused write must not run: {err}");
        assert_eq!(gate.observed()[0], serde_json::Value::Null);
    }
}

// ── mod before_mutation_read_bridge: #1328, the caller-scoped read ────────

/// A `before:mutation` rule that depends on data — a credit limit, a price, a
/// quota, the target row's current state — cannot be written unless the hook can
/// read. #1328 decided **A**: a read-only `fraiseql_query` bridge, executed as the
/// requesting principal.
///
/// Both halves of that sentence are load-bearing and both are pinned here, against
/// a real executor rather than the helper:
///
/// - **read-only** — a document the engine would execute as a write is refused, by its own
///   diagnosis, and nothing is written by it;
/// - **as the caller** — two principals running the *same* hook must not see the same rows. The
///   fixture is built so that a bridge running under any single fixed identity (a `run_as` ceiling,
///   the anonymous path, the first caller's context reused) fails it.
mod before_mutation_read_bridge {
    use std::{
        collections::HashMap,
        sync::{Arc, Mutex},
    };

    use async_trait::async_trait;
    use chrono::Utc;

    use super::*;
    use crate::{
        backend::WhereClause,
        schema::{
            ArgumentDefinition, AutoParams, CursorType, FieldType, InputFieldDefinition,
            InputObjectDefinition, MutationDefinition, MutationOperation, QueryDefinition,
        },
        security::{
            BeforeMutationGate, BeforeMutationOutcome, BeforeMutationRequest, DefaultRLSPolicy,
            SecurityContext,
        },
    };

    /// An adapter whose **reads answer with the filter they were given**.
    ///
    /// `execute_with_projection` returns one row echoing the `author_id` the RLS
    /// policy put in the WHERE clause, so "what did this hook see?" is a fact about
    /// the identity the read ran under, not about the fixture. Writes are logged by
    /// function name, so a refused write is provable by absence.
    struct ReadEchoAdapter {
        writes: Mutex<Vec<String>>,
    }

    impl ReadEchoAdapter {
        fn new() -> Self {
            Self {
                writes: Mutex::new(Vec::new()),
            }
        }

        fn writes(&self) -> Vec<String> {
            self.writes.lock().unwrap().clone()
        }
    }

    /// The `author_id` value the RLS policy AND-ed into this read's WHERE clause.
    ///
    /// `None` when the read carried no owner filter at all — which is what an
    /// anonymous read looks like, and is therefore a distinguishable answer rather
    /// than an indistinguishable empty one.
    fn owner_filter(clause: Option<&WhereClause>) -> Option<String> {
        match clause? {
            WhereClause::Field { path, value, .. }
                if path.last().map(String::as_str) == Some("author_id") =>
            {
                value.as_str().map(ToString::to_string)
            },
            WhereClause::And(parts) | WhereClause::Or(parts) => {
                parts.iter().find_map(|part| owner_filter(Some(part)))
            },
            _ => None,
        }
    }

    #[async_trait]
    impl DatabaseAdapter for ReadEchoAdapter {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![JsonbValue::new(serde_json::json!({
                "id": owner_filter(where_clause).unwrap_or_else(|| "anonymous".to_string()),
            }))])
        }

        async fn execute_where_query(
            &self,
            view: &str,
            where_clause: Option<&WhereClause>,
            limit: Option<u32>,
            offset: Option<u32>,
            order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            self.execute_with_projection(view, None, where_clause, limit, offset, order_by)
                .await
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl ReadEchoAdapter {
        async fn execute_function_call(
            &self,
            function_name: &str,
            _args: &[serde_json::Value],
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            self.writes.lock().unwrap().push(function_name.to_string());
            let mut row = std::collections::HashMap::new();
            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert("entity".to_string(), json!({ "id": "1" }));
            row.insert("entity_type".to_string(), json!("User"));
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>> {
            let rows = self.execute_function_call(function_name, args).await?;
            if let Err(refused) = gate(&rows) {
                // The call above logged it; the refusal takes it back.
                self.writes.lock().unwrap().pop();
                return Err(refused);
            }
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for ReadEchoAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// `guarded(input: CreateUserInput!)` to write, `users` to read.
    fn schema_with_a_readable_query() -> CompiledSchema {
        let mut schema = CompiledSchema::new();
        schema.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            fields:      vec![InputFieldDefinition::new("name", "String!")],
            description: None,
            metadata:    None,
        });
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_guarded".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_guarded".to_string(),
            },
            arguments: vec![ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Input("CreateUserInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("guarded", "User")
        });
        schema.queries.push(QueryDefinition {
            function: None,

            requires_actor:      Vec::new(),
            returns_count:       false,
            name:                "users".to_string(),
            return_type:         "User".to_string(),
            returns_list:        true,
            nullable:            false,
            arguments:           Vec::new(),
            sql_source:          Some("v_user".to_string()),
            description:         None,
            auto_params:         AutoParams::all(),
            deprecation:         None,
            jsonb_column:        "data".to_string(),
            relay:               false,
            relay_cursor_column: None,
            relay_cursor_type:   CursorType::default(),
            inject_params:       indexmap::IndexMap::default(),
            read_routing:        crate::backend::types::ReadRouting::default(),
            cache_ttl_seconds:   None,
            additional_views:    vec![],
            requires_role:       None,
            rest_path:           None,
            rest_method:         None,
            rest_stream:         false,
            native_columns:      HashMap::new(),
            pagination_order:    Some(crate::schema::PaginationOrder::JsonIdentity),
        });
        schema.build_indexes();
        schema
    }

    /// A gate that issues one document through the request's read bridge and
    /// aborts with what came back, so the read's outcome reaches the assertion
    /// through the engine's own refusal path.
    struct ReadsThroughTheBridge {
        document: &'static str,
    }

    #[async_trait]
    impl BeforeMutationGate for ReadsThroughTheBridge {
        async fn before_mutation(
            &self,
            request: &BeforeMutationRequest<'_>,
        ) -> Result<BeforeMutationOutcome> {
            let reader = request.reader.as_ref().ok_or_else(|| FraiseQLError::Internal {
                message: "the engine must hand every adjudicated write a read bridge".to_string(),
                source:  None,
            })?;
            match reader.query(self.document, None).await {
                Ok(value) => Ok(BeforeMutationOutcome::Abort {
                    reason: format!("read: {value}"),
                }),
                Err(error) => Err(error),
            }
        }
    }

    fn executor_reading(document: &'static str) -> (Executor, Arc<ReadEchoAdapter>) {
        let adapter = Arc::new(ReadEchoAdapter::new());
        let gate: Arc<dyn BeforeMutationGate> = Arc::new(ReadsThroughTheBridge { document });
        let executor = Executor::with_config(
            schema_with_a_readable_query(),
            Arc::clone(&adapter),
            RuntimeConfig::default()
                .with_before_mutation_gate(gate)
                .with_rls_policy(Arc::new(DefaultRLSPolicy::new().with_single_tenant())),
        );
        (executor, adapter)
    }

    fn principal(user: &str) -> SecurityContext {
        SecurityContext {
            user_id:          user.into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::default(),
            request_id:       format!("req-1328-{user}"),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    const WRITE: &str = r#"mutation { guarded(input: { name: "G" }) { id } }"#;

    // ── Cycle 1: the bridge is read-only ─────────────────────────────────

    /// A hook that issues a **mutation** through the bridge is refused, by name.
    ///
    /// Asserted on the refusal's own diagnosis — the `Authorization` variant and
    /// its `before_mutation_read` action — and not merely on "the request failed".
    /// Every other way this document could die (the gate aborting, the mutation
    /// being unknown, the write erroring) produces a *different* error, so a pass
    /// here cannot come from a downstream check.
    #[tokio::test]
    async fn a_hook_may_not_write_through_the_read_bridge() {
        let (executor, adapter) =
            executor_reading(r#"mutation { guarded(input: { name: "SNEAK" }) { id } }"#);

        let err = executor
            .execute_with_security(WRITE, None, &principal("u1"))
            .await
            .expect_err("a hook that writes through the read bridge must be refused");

        match &err {
            FraiseQLError::Authorization {
                message, action, ..
            } => {
                assert_eq!(
                    action.as_deref(),
                    Some("before_mutation_read"),
                    "the refusal must name itself: {err:?}"
                );
                assert!(message.contains("read-only"), "the refusal must say why: {message}");
            },
            other => panic!("expected the read bridge's own refusal, got {other:?}"),
        }
        assert!(
            adapter.writes().is_empty(),
            "neither the adjudicated write nor the hook's may run: {:?}",
            adapter.writes()
        );
    }

    /// The counterweight: the same bridge, the same fixture, a **query** document —
    /// it must succeed. Without this, the refusal above would also pass on a bridge
    /// that refuses everything.
    #[tokio::test]
    async fn a_hook_may_read_through_the_bridge() {
        let (executor, _adapter) = executor_reading("{ users { id } }");

        let err = executor
            .execute_with_security(WRITE, None, &principal("u1"))
            .await
            .expect_err("the fixture's gate always aborts, carrying what it read");

        assert!(
            err.to_string().contains("read: "),
            "a read document must reach the executor and answer: {err}"
        );
    }

    // ── Cycle 2: the read runs as the caller ─────────────────────────────

    /// Two principals, the same hook, the same document — each must see only what
    /// its own identity can.
    ///
    /// The adapter echoes the RLS owner filter the read carried, so the two answers
    /// differ **only** if the bridge ran under each caller's own context. A bridge
    /// pinned to one identity — a `run_as` ceiling, the anonymous path, or the
    /// context captured when the gate was installed — returns the same string twice
    /// and fails.
    #[tokio::test]
    async fn each_caller_reads_as_itself() {
        let (executor, _adapter) = executor_reading("{ users { id } }");

        let first = executor
            .execute_with_security(WRITE, None, &principal("alice"))
            .await
            .expect_err("the gate aborts with what it read")
            .to_string();
        let second = executor
            .execute_with_security(WRITE, None, &principal("bob"))
            .await
            .expect_err("the gate aborts with what it read")
            .to_string();

        assert!(
            first.contains("alice"),
            "alice's hook must read under alice's identity: {first}"
        );
        assert!(second.contains("bob"), "bob's hook must read under bob's identity: {second}");
        assert_ne!(first, second, "two principals must not read the same rows");
    }

    /// An anonymous write's hook reads anonymously — it is not promoted to a
    /// standing identity to make the read work.
    ///
    /// Under this fixture's RLS policy that means the read **fails closed**, which
    /// is exactly what an anonymous `/graphql` read of the same field does (#784).
    /// The assertion is on which failure it is: not the bridge's own read-only
    /// refusal (that would mean the bridge refuses everything, and
    /// `a_hook_may_read_through_the_bridge` would be passing for the wrong reason),
    /// and above all **not** an abort carrying rows — a hook that gets data here
    /// has been handed an identity its caller does not have.
    #[tokio::test]
    async fn an_anonymous_write_is_not_promoted_to_read() {
        let (executor, _adapter) = executor_reading("{ users { id } }");

        let err = executor.execute(WRITE, None).await.expect_err("the read cannot succeed");

        assert!(
            !err.to_string().contains("read: "),
            "an anonymous hook must not read rows its caller could not: {err}"
        );
        match &err {
            FraiseQLError::Validation { message, .. } => assert!(
                message.contains("users"),
                "the read must fail closed on the field it asked for: {message}"
            ),
            other => panic!("expected the anonymous read to fail closed, got {other:?}"),
        }
    }
}

// ── mod rest_write_body: #1331 + #1352 — a REST write carries the body it was given,
//    and both arms face the same gate ───────────────────────────────────────────────
//
// #1331: `execute_mutation_with_security` reached the engine by re-serialising its
// arguments into a GraphQL document with `format!("{k}: {v}")`. `Display` on a
// `serde_json::Value` emits JSON, and JSON quotes object keys where GraphQL does not, so
// any argument that *is* or *contains* an object produced a document the parser refused.
// Under the JSONB `data`-column model a nested object is the ordinary body shape.
//
// #1352: the anonymous arm passes an **empty** selection set, and an empty selection set
// is the permissive shape — `project_entity` returns the whole entity and
// `selection_set_selects_gated_field` is false, so the field authorizer is never
// consulted. An unauthenticated caller was served a gated field that an authenticated
// one is refused.
mod rest_write_body {
    use std::{
        collections::HashMap,
        sync::{Arc, Mutex},
    };

    use async_trait::async_trait;
    use chrono::Utc;

    use super::*;
    use crate::{
        graphql::FieldSelection,
        schema::{
            ArgumentDefinition, FieldDefinition, FieldDenyPolicy, FieldType, InputFieldDefinition,
            InputObjectDefinition, MutationDefinition, MutationOperation, TypeDefinition,
        },
        security::{FieldAuthorizer, FieldAuthzDecision, FieldAuthzRequest, SecurityContext},
    };

    /// Records the positional arguments each SQL function was actually bound.
    ///
    /// The assertion that matters is not "no parse error" but "the nested value arrived
    /// **intact** at the function": a fix that reached the engine while flattening or
    /// stringifying the object would still be wrong.
    struct ArgLog {
        calls:  Mutex<Vec<(String, Vec<serde_json::Value>)>>,
        entity: serde_json::Value,
    }

    impl ArgLog {
        fn new() -> Self {
            Self::returning(serde_json::json!({ "id": "1", "name": "G", "email": "g@x.tld" }))
        }

        /// The `entity` the `mutation_response` row carries back.
        fn returning(entity: serde_json::Value) -> Self {
            Self {
                calls: Mutex::new(Vec::new()),
                entity,
            }
        }

        fn functions(&self) -> Vec<String> {
            self.calls.lock().unwrap().iter().map(|(n, _)| n.clone()).collect()
        }

        fn args_for(&self, function: &str) -> Vec<serde_json::Value> {
            self.calls
                .lock()
                .unwrap()
                .iter()
                .find(|(n, _)| n == function)
                .map(|(_, a)| a.clone())
                .unwrap_or_default()
        }
    }

    #[async_trait]
    impl DatabaseAdapter for ArgLog {
        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl ArgLog {
        async fn execute_function_call(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            use serde_json::json;
            self.calls.lock().unwrap().push((function_name.to_string(), args.to_vec()));
            let mut row = HashMap::new();
            row.insert("succeeded".to_string(), json!(true));
            row.insert("state_changed".to_string(), json!(true));
            row.insert("entity".to_string(), self.entity.clone());
            // No `entity_type`: this double serves mutations of many return types, and a stamp
            // must name the one each returns (ruling AA 1). Unstamped, it resolves to it.
            row.insert("message".to_string(), json!(""));
            Ok(vec![row])
        }

        async fn execute_function_call_with_changelog(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
            _changelog: Option<&ChangeLogWrite<'_>>,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            self.execute_function_call(function_name, args).await
        }

        /// The commit gate (#1353) — see `field_authz::GatedEntityAdapter` for why a
        /// double on a policy-gated schema has to implement this rather than inherit
        /// the refusing default.
        async fn execute_function_call_gated(
            &self,
            function_name: &str,
            args: &[serde_json::Value],
            session_vars: &[(&str, &str)],
            changelog: Option<&ChangeLogWrite<'_>>,
            gate: fraiseql_db::MutationRowGate<'_>,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            let rows = self
                .execute_function_call_with_changelog(function_name, args, session_vars, changelog)
                .await?;
            gate(&rows)?;
            Ok(rows)
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for ArgLog {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            self.execute_function_call_gated(
                request.function,
                request.args,
                request.session_vars,
                request.changelog,
                gate,
            )
            .await
        }
    }

    /// `createUser(input: CreateUserInput!)` — the nested shape, and
    /// `patchUser(id: ID!, input: CreateUserInput!)` for the by-ids bulk path, which
    /// merges the row identity into the body under a declared argument.
    ///
    /// `gate_email` declares `User.email` policy-gated (#423), which is what #1352 turns on.
    fn schema(gate_email: bool) -> CompiledSchema {
        let mut s = CompiledSchema::new();
        s.input_types.push(InputObjectDefinition {
            name:        "CreateUserInput".to_string(),
            fields:      vec![
                InputFieldDefinition::new("name", "String!"),
                InputFieldDefinition::new("email", "String!"),
            ],
            description: None,
            metadata:    None,
        });

        let input_arg = || ArgumentDefinition {
            name:          "input".to_string(),
            arg_type:      FieldType::Input("CreateUserInput".to_string()),
            nullable:      false,
            default_value: None,
            description:   None,
            deprecation:   None,
        };

        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_user".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_create_user".to_string(),
            },
            arguments: vec![input_arg()],
            ..MutationDefinition::new("createUser", "User")
        });

        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_patch_user".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_patch_user".to_string(),
            },
            arguments: vec![
                ArgumentDefinition {
                    name:          "id".to_string(),
                    arg_type:      FieldType::Id,
                    nullable:      false,
                    default_value: None,
                    description:   None,
                    deprecation:   None,
                },
                input_arg(),
            ],
            ..MutationDefinition::new("patchUser", "User")
        });

        // A flat-scalar mutation: the positive twin's subject. It round-trips **today**,
        // which is exactly why a nested-only test proves nothing on its own.
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_rename_user".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_rename_user".to_string(),
            },
            arguments: vec![ArgumentDefinition {
                name:          "name".to_string(),
                arg_type:      FieldType::String,
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("renameUser", "User")
        });

        // Declares a return type that is not among `s.types`, so
        // `mutation_return_selections` takes its envelope fallback.
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_envelope_write".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_envelope_write".to_string(),
            },
            arguments: vec![ArgumentDefinition {
                name:          "name".to_string(),
                arg_type:      FieldType::String,
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("envelopeWrite", "MutationResponse")
        });

        // A return type whose only field is an **object**: there is no scalar to select,
        // so the helper must fall back rather than hand back an empty (permissive) set.
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_object_only".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_object_only".to_string(),
            },
            ..MutationDefinition::new("objectOnlyWrite", "ObjectOnly")
        });
        let mut object_only = TypeDefinition::new("ObjectOnly", "v_object_only");
        object_only.fields = vec![FieldDefinition::nullable(
            "owner",
            FieldType::Object("User".to_string()),
        )];
        s.types.push(object_only);

        let mut user = TypeDefinition::new("User", "v_user");
        let email = FieldDefinition::nullable("email", FieldType::String);
        user.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("name", FieldType::String),
            if gate_email {
                email.with_authorize(true)
            } else {
                email
            },
        ];
        s.types.push(user);
        s.build_indexes();
        s
    }

    fn executor(gate_email: bool) -> (Executor, Arc<ArgLog>) {
        let adapter = Arc::new(ArgLog::new());
        let ex = Executor::with_config(
            schema(gate_email),
            Arc::clone(&adapter),
            RuntimeConfig::default(),
        );
        (ex, adapter)
    }

    fn principal() -> SecurityContext {
        SecurityContext {
            user_id:          "u1".into(),
            roles:            vec![],
            tenant_id:        None,
            scopes:           vec![],
            attributes:       HashMap::default(),
            request_id:       "req-1331".to_string(),
            ip_address:       None,
            expires_at:       Utc::now() + chrono::Duration::hours(1),
            authenticated_at: Utc::now(),
            issuer:           None,
            audience:         None,
            email:            None,
            display_name:     None,
        }
    }

    fn nested_body() -> serde_json::Value {
        serde_json::json!({ "input": { "name": "G", "email": "g@x.tld" } })
    }

    // ── #1331: the three callers of `execute_mutation_with_security` ──────────────

    /// Caller 1 of 3 — `routes/rest/handler/mutation.rs:597`, the authenticated arm.
    #[tokio::test]
    async fn a_nested_body_reaches_the_function_through_the_authenticated_write() {
        let (ex, adapter) = executor(false);

        ex.execute_mutation_with_security("createUser", &nested_body(), Some(&principal()))
            .await
            .expect("an authenticated REST write must carry a nested body to the engine");

        assert_eq!(
            adapter.args_for("fn_create_user"),
            vec![serde_json::json!("G"), serde_json::json!("g@x.tld")],
            "the nested object's values must arrive intact, not stringified"
        );
    }

    /// Caller 2 of 3 — `routes/rest/bulk/mod.rs:121`, via `execute_mutation_batch`.
    ///
    /// A single red on the shared helper would pass over a fix that only reached one
    /// caller, so each of the three is asserted separately.
    #[tokio::test]
    async fn a_nested_body_reaches_the_function_through_the_batch_write() {
        let (ex, adapter) = executor(false);

        let result = ex
            .execute_mutation_batch(
                "createUser",
                &[nested_body(), nested_body()],
                Some(&principal()),
            )
            .await
            .expect("a bulk REST write must carry a nested body to the engine");

        assert_eq!(result.affected_rows, 2, "both items must run");
        assert_eq!(
            adapter.functions(),
            vec!["fn_create_user".to_string(), "fn_create_user".to_string()],
            "one call per item"
        );
        assert_eq!(
            adapter.args_for("fn_create_user"),
            vec![serde_json::json!("G"), serde_json::json!("g@x.tld")],
        );
    }

    /// Caller 3 of 3 — `routes/rest/bulk/mod.rs:313`, via `execute_bulk_by_ids`.
    #[tokio::test]
    async fn a_nested_body_reaches_the_function_through_the_by_ids_write() {
        let (ex, adapter) = executor(false);
        let body = serde_json::json!({ "input": { "name": "G", "email": "g@x.tld" } });

        let result = ex
            .execute_bulk_by_ids(
                "patchUser",
                "id",
                &[serde_json::json!("row-1")],
                Some(&body),
                Some(&principal()),
            )
            .await
            .expect("a by-ids REST write must carry a nested body to the engine");

        assert_eq!(result.affected_rows, 1);
        // A two-argument mutation binds `input` as an **object**, where the
        // single-argument `createUser` above flattens it to positional scalars. Both
        // shapes are asserted, because #1331 was a failure to represent the object at
        // all: before the fix this call never reached the function, so `args` was empty.
        let args = adapter.args_for("fn_patch_user");
        assert!(
            args.contains(&serde_json::json!({ "name": "G", "email": "g@x.tld" })),
            "the nested object must reach the function intact: {args:?}"
        );
        assert!(
            args.contains(&serde_json::json!("row-1")),
            "and the row identity must too: {args:?}"
        );
    }

    // ── the positive twins: these pass TODAY, and must keep passing ───────────────

    /// A flat-scalar body round-trips today. Without this twin, the nested tests above
    /// could be made green by a change that broke the shape REST actually sends most
    /// often, and nothing would say so.
    #[tokio::test]
    async fn a_flat_scalar_body_still_reaches_the_function_when_authenticated() {
        let (ex, adapter) = executor(false);

        ex.execute_mutation_with_security(
            "renameUser",
            &serde_json::json!({ "name": "G" }),
            Some(&principal()),
        )
        .await
        .expect("a flat body must keep working");

        assert_eq!(adapter.args_for("fn_rename_user"), vec![serde_json::json!("G")]);
    }

    // ── #1352 + #423: both arms face the same gate ───────────────────────────────

    struct AllowAll;
    impl FieldAuthorizer for AllowAll {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            Ok(FieldAuthzDecision::Allow)
        }
    }

    struct MaskAll;
    impl FieldAuthorizer for MaskAll {
        fn authorize_field(&self, _r: &FieldAuthzRequest<'_>) -> Result<FieldAuthzDecision> {
            Ok(FieldAuthzDecision::Deny {
                code:    "not_owner".into(),
                on_deny: FieldDenyPolicy::Mask,
            })
        }
    }

    fn gated_executor(authorizer: Arc<dyn FieldAuthorizer>) -> Executor {
        Executor::with_config(
            schema(true),
            Arc::new(ArgLog::new()),
            RuntimeConfig::default().with_field_authorizer(authorizer),
        )
    }

    /// âš  **This is the test that must redden if the selection set is simplified to
    /// `&[]`.** `selection_set_selects_gated_field` is false for an empty set, so
    /// `enforce_mutation_field_authz` short-circuits with zero authorizer calls and
    /// `project_entity` hands back the whole entity — `email` would come back in full
    /// instead of masked. Prove that by reverting, not by reading.
    #[tokio::test]
    async fn an_authenticated_write_masks_a_gated_field_the_authorizer_denies() {
        let ex = gated_executor(Arc::new(MaskAll));

        let res = ex
            .execute_mutation_with_security("createUser", &nested_body(), Some(&principal()))
            .await
            .expect("a masked field is a success, not a refusal");

        let payload = &res["data"]["createUser"];
        assert_eq!(payload["name"], "G", "ungated fields are still returned");
        assert!(payload["email"].is_null(), "the gated field must be masked: {payload}");
    }

    /// The positive twin, and the reason the test above proves something: with an
    /// **accepting** authorizer the same field comes back in full. Without this, a change
    /// that dropped `email` entirely would leave the masking test green.
    #[tokio::test]
    async fn an_authenticated_write_returns_a_gated_field_the_authorizer_allows() {
        let ex = gated_executor(Arc::new(AllowAll));

        let res = ex
            .execute_mutation_with_security("createUser", &nested_body(), Some(&principal()))
            .await
            .expect("an allowed field is returned");

        assert_eq!(res["data"]["createUser"]["email"], "g@x.tld");
    }

    /// #1352: the anonymous arm. Asserted on the **refusal**, not merely on the field's
    /// absence — a test that only checked `email` was missing would also pass if the
    /// field were dropped for some unrelated reason.
    ///
    /// The authorizer here *accepts*, so the refusal cannot be its answer: it is the
    /// fail-closed "gated field selected with no authenticated principal" rule.
    #[tokio::test]
    async fn an_anonymous_write_is_refused_a_gated_field() {
        let ex = gated_executor(Arc::new(AllowAll));

        let err = ex
            .execute_mutation_with_security("createUser", &nested_body(), None)
            .await
            .expect_err("an anonymous write must not be served a gated field");

        match err {
            FraiseQLError::Authorization {
                ref resource,
                ref message,
                ..
            } => {
                assert_eq!(resource.as_deref(), Some("User"), "{err:?}");
                assert!(
                    message.contains("not authenticated"),
                    "the refusal must be about the missing principal: {message}"
                );
            },
            other => panic!("expected a fail-closed Authorization refusal, got {other:?}"),
        }
        assert!(
            !format!("{err:?}").contains("g@x.tld"),
            "and the refusal must not leak the value it withheld"
        );
    }

    /// The discriminating pair, stated as one assertion: the bug was that the
    /// **anonymous** caller was served a field the **authenticated** one is refused.
    /// Whatever the gate decides, anonymous must never see more.
    #[tokio::test]
    async fn the_anonymous_arm_is_never_served_more_than_the_authenticated_one() {
        let authenticated = gated_executor(Arc::new(MaskAll))
            .execute_mutation_with_security("createUser", &nested_body(), Some(&principal()))
            .await
            .expect("authenticated write succeeds with the field masked");
        let anonymous = gated_executor(Arc::new(MaskAll))
            .execute_mutation_with_security("createUser", &nested_body(), None)
            .await;

        assert!(authenticated["data"]["createUser"]["email"].is_null(), "authenticated: masked");
        assert!(anonymous.is_err(), "anonymous: refused outright, never served the value");
    }

    /// The fallback's intent: a mutation whose declared return type is not a known object
    /// type still answers with the `app.mutation_response` envelope's own field names.
    ///
    /// This is what keeps `mutation_return_selections` from ever returning an empty set —
    /// and an empty set is the permissive shape this whole phase is about.
    #[tokio::test]
    async fn a_mutation_returning_the_envelope_still_answers_status_entity_id_message() {
        // `internal_note` is the discriminator. Without it this test would pass under an
        // empty selection set too — `project_entity` returns the whole entity, which
        // happens to be exactly the envelope — and the pin would be decorative. The
        // fourth key is a field the fallback must **not** name, so the test fails if the
        // fallback is ever replaced by `&[]`.
        let adapter = Arc::new(ArgLog::returning(serde_json::json!({
            "status": "ok", "entity_id": "42", "message": "done",
            "internal_note": "do not ship"
        })));
        let ex =
            Executor::with_config(schema(false), Arc::clone(&adapter), RuntimeConfig::default());

        let res = ex
            .execute_mutation_with_security(
                "envelopeWrite",
                &serde_json::json!({ "name": "G" }),
                Some(&principal()),
            )
            .await
            .expect("a schema that genuinely returns the envelope keeps working");

        let payload = &res["data"]["envelopeWrite"];
        assert_eq!(payload["status"], "ok", "{payload}");
        assert_eq!(payload["entity_id"], "42", "{payload}");
        assert_eq!(payload["message"], "done", "{payload}");
        assert!(
            payload.get("internal_note").is_none(),
            "the fallback names three fields; it must not return the whole entity: {payload}"
        );
    }

    /// The property **every** transport now depends on, pinned on the helper itself:
    /// `mutation_return_selections` never hands back an empty set.
    ///
    /// gRPC's own copy of this helper ended in `unwrap_or_default()` and so returned `&[]`
    /// for exactly these inputs, which is the permissive shape (#1352). Both transports
    /// share this function now, so this is the one place the property has to hold.
    #[test]
    fn the_selection_set_is_never_empty() {
        const ENVELOPE: [&str; 3] = ["status", "entity_id", "message"];

        let s = schema(false);
        let names =
            |sels: Vec<FieldSelection>| sels.into_iter().map(|f| f.name).collect::<Vec<_>>();

        assert_eq!(
            names(crate::runtime::mutation_return_selections(&s, "createUser")),
            vec!["id", "name", "email"],
            "a normal return type names its scalar fields"
        );
        assert_eq!(
            names(crate::runtime::mutation_return_selections(&s, "noSuchMutation")),
            ENVELOPE,
            "an unknown mutation falls back rather than returning an empty set"
        );
        assert_eq!(
            names(crate::runtime::mutation_return_selections(&s, "objectOnlyWrite")),
            ENVELOPE,
            "a return type with no scalar field falls back rather than returning an empty set"
        );
        assert_eq!(
            names(crate::runtime::mutation_return_selections(&s, "envelopeWrite")),
            ENVELOPE,
            "an undeclared return type falls back"
        );
    }

    /// The same twin on the batch path.
    #[tokio::test]
    async fn a_flat_scalar_body_still_reaches_the_function_through_the_batch_write() {
        let (ex, adapter) = executor(false);

        ex.execute_mutation_batch(
            "renameUser",
            &[serde_json::json!({ "name": "G" })],
            Some(&principal()),
        )
        .await
        .expect("a flat body must keep working on the batch path");

        assert_eq!(adapter.args_for("fn_rename_user"), vec![serde_json::json!("G")]);
    }
}

// ── mod write_selections: the non-empty invariant at the write entries (S2) ───
mod write_selections {
    use crate::{error::FraiseQLError, graphql::FieldSelection, runtime::WriteSelections};

    #[test]
    fn an_empty_selection_set_is_refused() {
        let err = WriteSelections::new(&[])
            .expect_err("an empty selection set is the permissive shape, not a neutral one");
        assert!(matches!(err, FraiseQLError::Validation { .. }), "{err:?}");
    }

    #[test]
    fn a_non_empty_selection_set_is_adopted_unchanged() {
        let set = vec![FieldSelection {
            name:          "id".to_string(),
            alias:         None,
            arguments:     vec![],
            nested_fields: vec![],
            directives:    vec![],
        }];
        let ws = WriteSelections::new(&set).expect("one field is not empty");
        assert_eq!(ws.as_slice().len(), 1);
        assert_eq!(ws.as_slice()[0].name, "id");
    }
}

// ── mod enum_membership: the wiring, not the facility (#1362) ─────────────────
//
// `argument_value_validation_tests` proves the adjudication answers correctly when
// it is called. These prove it IS called — through `Executor::execute`, against the
// chokepoint every transport that writes converges on. A facility with no installer
// is the shape of #1344, and a unit test on the function alone cannot tell the two
// apart: it passes whether or not a single call site exists.
//
// The discriminator is the message. `MockAdapter::new(vec![])` answers every write
// with "no rows", so a refusal that names the enum can only have come from before
// the database call — and the accepted-member case asserts it reaches "no rows",
// which is what keeps this from passing by refusing everything.
mod enum_membership {
    use super::*;
    use crate::schema::{
        ArgumentDefinition, EnumDefinition, EnumValueDefinition, FieldType, InputFieldDefinition,
        InputObjectDefinition, MutationDefinition, MutationOperation,
    };

    /// `createOrder(input: CreateOrderInput)` over an `OrderStatus` of three members.
    fn schema() -> CompiledSchema {
        let mut schema = CompiledSchema::new();
        schema.enums.push(
            EnumDefinition::new("OrderStatus")
                .with_value(EnumValueDefinition::new("PENDING"))
                .with_value(EnumValueDefinition::new("SHIPPED"))
                .with_value(EnumValueDefinition::new("CANCELLED")),
        );
        schema.input_types.push(
            InputObjectDefinition::new("CreateOrderInput")
                .with_field(InputFieldDefinition::new("reference", "String"))
                .with_field(InputFieldDefinition::new("status", "OrderStatus")),
        );
        schema.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_order".to_string()),
            operation: MutationOperation::Insert {
                table: "fn_create_order".to_string(),
            },
            // The compiler emits an input-type reference as `Object`, never `Input`.
            arguments: vec![ArgumentDefinition {
                name:          "input".to_string(),
                arg_type:      FieldType::Object("CreateOrderInput".to_string()),
                nullable:      false,
                default_value: None,
                description:   None,
                deprecation:   None,
            }],
            ..MutationDefinition::new("createOrder", "Order")
        });
        schema.build_indexes();
        schema
    }

    fn executor() -> Executor {
        Executor::new(schema(), Arc::new(MockAdapter::new(vec![])))
    }

    /// The finding, through the mounted path: an inline enum literal that names no
    /// member is refused before the write.
    #[tokio::test]
    async fn an_inline_non_member_literal_is_refused_before_the_database_call() {
        let err = executor()
            .execute(
                r#"mutation { createOrder(input: {reference: "r-1", status: BANANA}) { id } }"#,
                None,
            )
            .await
            .expect_err("a value that is not a member of OrderStatus must not reach the database");
        let msg = err.to_string();
        assert!(msg.contains("OrderStatus"), "the refusal must name the enum: {msg}");
        assert!(
            !msg.contains("no rows"),
            "reaching 'no rows' means the write was dispatched and nothing adjudicated the \
             enum: {msg}"
        );
    }

    /// The same value supplied as a variable. Both spellings reach SQL identically,
    /// so both have to be adjudicated identically.
    #[tokio::test]
    async fn a_non_member_supplied_by_variable_is_refused_before_the_database_call() {
        let vars = serde_json::json!({"input": {"reference": "r-1", "status": "BANANA"}});
        let err = executor()
            .execute(
                "mutation Create($input: CreateOrderInput!) { createOrder(input: $input) { id } }",
                Some(&vars),
            )
            .await
            .expect_err("a non-member supplied by variable must not reach the database");
        let msg = err.to_string();
        assert!(msg.contains("OrderStatus"), "the refusal must name the enum: {msg}");
        assert!(!msg.contains("no rows"), "the write was dispatched: {msg}");
    }

    /// The counterweight. Without it this module would pass by refusing everything,
    /// which is the failure mode a refusal-only suite cannot see.
    #[tokio::test]
    async fn a_declared_member_still_reaches_the_database() {
        let vars = serde_json::json!({"input": {"reference": "r-1", "status": "SHIPPED"}});
        let err = executor()
            .execute(
                "mutation Create($input: CreateOrderInput!) { createOrder(input: $input) { id } }",
                Some(&vars),
            )
            .await
            .expect_err("the empty mock adapter answers every write with 'no rows'");
        let msg = err.to_string();
        assert!(
            msg.contains("no rows"),
            "a declared member must be dispatched, not refused — got: {msg}"
        );
        assert!(
            !msg.contains("OrderStatus"),
            "a declared member must not be refused as a non-member: {msg}"
        );
    }
}

// ── AA 6 (rulings AD 3, AD 4): a dry run commits nothing, and nothing follows it ──
//
// A dry run runs the function and rolls back. What follows a commit — the fact-table
// version bump, view / entity / response-cache invalidation, the `mutation.executed` audit
// event — must not follow it: nothing was written. And the cache wrapper, which every
// server-side adapter is, must pass the dry run through rather than refuse it.
mod dry_run {
    use std::{
        collections::HashMap,
        sync::atomic::{AtomicUsize, Ordering},
    };

    use async_trait::async_trait;
    use serde_json::json;

    use super::*;
    use crate::{
        backend::types::{DatabaseType, PoolMetrics, sql_hints::OrderByClause},
        schema::{FieldDefinition, FieldType, MutationDefinition, TypeDefinition},
    };

    /// A writer whose dry run returns one successful `Post` row, and which counts what the
    /// runner does after it.
    #[derive(Default)]
    pub(super) struct DryRunAdapter {
        dry_runs:     AtomicUsize,
        bumps:        AtomicUsize,
        invalidation: AtomicUsize,
    }

    fn success_row() -> HashMap<String, serde_json::Value> {
        HashMap::from([
            ("succeeded".to_string(), json!(true)),
            ("state_changed".to_string(), json!(true)),
            ("entity".to_string(), json!({"id": "p1", "title": "Hello"})),
            ("entity_type".to_string(), json!("Post")),
            ("message".to_string(), json!("")),
        ])
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait]
    impl DatabaseAdapter for DryRunAdapter {
        async fn invalidate_views(&self, views: &[fraiseql_db::ViewName]) -> Result<u64> {
            self.invalidation.fetch_add(1, Ordering::SeqCst);
            Ok(views.len() as u64)
        }

        async fn execute_with_projection(
            &self,
            _view: &str,
            _projection: Option<&crate::schema::SqlProjectionHint>,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn execute_where_query(
            &self,
            _view: &str,
            _where_clause: Option<&WhereClause>,
            _limit: Option<u32>,
            _offset: Option<u32>,
            _order_by: Option<&[OrderByClause]>,
        ) -> Result<Vec<JsonbValue>> {
            Ok(vec![])
        }

        async fn health_check(&self) -> Result<()> {
            Ok(())
        }

        fn database_type(&self) -> DatabaseType {
            DatabaseType::PostgreSQL
        }

        fn pool_metrics(&self) -> PoolMetrics {
            PoolMetrics {
                total_connections:  1,
                active_connections: 0,
                idle_connections:   1,
                waiting_requests:   0,
            }
        }

        async fn execute_raw_query(
            &self,
            _sql: &str,
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }

        async fn execute_parameterized_aggregate(
            &self,
            _sql: &str,
            _params: &[serde_json::Value],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            Ok(vec![])
        }
    }

    // The writes this double answers, called by its `Writer` impl below.
    impl DryRunAdapter {
        async fn execute_function_call_dry_run(
            &self,
            _function_name: &str,
            _args: &[serde_json::Value],
            _session_vars: &[(&str, &str)],
        ) -> Result<Vec<HashMap<String, serde_json::Value>>> {
            self.dry_runs.fetch_add(1, Ordering::SeqCst);
            Ok(vec![success_row()])
        }
    }

    // async_trait: dyn-dispatch required; remove when RTN + Send is stable (RFC 3425)
    #[async_trait::async_trait]
    impl crate::backend::traits::Writer for DryRunAdapter {
        async fn execute_write(
            &self,
            request: &crate::backend::traits::WriteRequest<'_>,
            gate: crate::backend::traits::MutationRowGate<'_>,
        ) -> std::result::Result<
            Vec<std::collections::HashMap<String, serde_json::Value>>,
            crate::error::FraiseQLError,
        > {
            // Only the dry run answers; a commit is not what these tests are about.
            if request.mode != crate::backend::traits::WriteMode::DryRun {
                return Err(crate::error::FraiseQLError::Unsupported {
                    message: "DryRunAdapter answers only dry runs".to_string(),
                });
            }
            let rows = self
                .execute_function_call_dry_run(request.function, request.args, request.session_vars)
                .await?;
            gate(&rows)?;
            Ok(rows)
        }

        async fn bump_fact_table_versions(&self, _tables: &[String]) -> Result<()> {
            self.bumps.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    /// `createPost: Post`, invalidating `v_post` and the fact table `tf_posts`.
    pub(super) fn schema() -> CompiledSchema {
        let mut s = CompiledSchema::new();
        s.mutations.push(MutationDefinition {
            sql_source: Some("fn_create_post".to_string()),
            invalidates_views: vec!["v_post".to_string()],
            invalidates_fact_tables: vec!["tf_posts".to_string()],
            ..MutationDefinition::new("createPost", "Post")
        });
        let mut post = TypeDefinition::new("Post", "v_post");
        post.fields = vec![
            FieldDefinition::new("id", FieldType::Id),
            FieldDefinition::nullable("title", FieldType::String),
        ];
        s.types.push(post);
        s.build_indexes();
        s
    }

    #[tokio::test]
    async fn nothing_that_follows_a_commit_follows_a_dry_run() {
        let adapter = Arc::new(DryRunAdapter::default());
        let config = RuntimeConfig {
            dry_run_mutations: true,
            ..RuntimeConfig::default()
        };
        let res = Executor::with_config(schema(), Arc::clone(&adapter), config)
            .execute("mutation { createPost { id title } }", None)
            .await
            .expect("the dry run answers as the write would");
        assert_eq!(res["data"]["createPost"]["id"], "p1");
        assert_eq!(adapter.dry_runs.load(Ordering::SeqCst), 1);
        assert_eq!(
            adapter.bumps.load(Ordering::SeqCst),
            0,
            "no fact table moved: nothing committed"
        );
        assert_eq!(
            adapter.invalidation.load(Ordering::SeqCst),
            0,
            "no cache holds anything the dry run changed"
        );
    }

    #[tokio::test]
    async fn the_cache_wrapper_passes_a_dry_run_through() {
        let cached = crate::cache::CachedDatabaseAdapter::new(
            DryRunAdapter::default(),
            crate::cache::QueryResultCache::new(crate::cache::CacheConfig::enabled()),
            "1.0.0".to_string(),
        );
        let request = crate::backend::WriteRequest::new("fn_create_post", &[])
            .with_mode(crate::backend::WriteMode::DryRun);
        let rows = crate::backend::Writer::execute_write(&cached, &request, &|_| Ok(()))
            .await
            .expect("a dry run reaches the wrapped writer");
        assert_eq!(rows.len(), 1);
    }
}