udb 0.4.25

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
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
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::collections::{BTreeSet, HashMap};
use std::sync::{Mutex, OnceLock};

use crate::backend::BackendKind;
use crate::generation::sql::{
    qi, resolve_project_column, resolve_tenant_column, table_requires_tenant_column,
};
use crate::generation::{CatalogManifest, ManifestTable};
use crate::ir::{
    ComparisonOp, ConflictStrategy, LogicalDelete, LogicalFilter, LogicalPagination,
    LogicalProjection, LogicalRead, LogicalRecord, LogicalSort, LogicalValue, LogicalWrite,
    SortDirection,
};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RequestContext {
    pub tenant_id: String,
    pub user_id: String,
    pub correlation_id: String,
    pub purpose: String,
    pub scopes: Vec<String>,
    /// Optional project namespace. Empty = single-project mode.
    pub project_id: String,
    /// Read consistency hint from `x-udb-consistency`.
    ///
    /// Supported values are `strong`, `bounded_staleness`, and `eventual`.
    /// Empty means the runtime default, currently replica-eligible reads.
    #[serde(default)]
    pub consistency: String,
    /// Optional per-request maximum replica lag from `x-udb-max-replica-lag-ms`.
    /// A value of 0 means use the runtime default.
    #[serde(default)]
    pub max_replica_lag_ms: u64,
    /// Optional client-side catalog version from `x-udb-client-catalog-version`.
    /// Service authorization enforces this against the active catalog.
    #[serde(default)]
    pub client_catalog_version: String,
    /// Optional explicit backend target from `x-udb-target-backend`.
    #[serde(default)]
    pub target_backend: String,
    /// Optional explicit backend instance from `x-udb-target-instance`.
    #[serde(default)]
    pub target_instance: String,
    /// Routing policy hint from `x-udb-routing-policy`.
    #[serde(default)]
    pub routing_policy: String,
    /// Force reads to the primary/write backend.
    #[serde(default)]
    pub primary_read: bool,
    /// Permit eventually consistent read routing when the backend supports it.
    #[serde(default)]
    pub eventual_consistency_allowed: bool,
    /// JSON-encoded ReadFence supplied by SDKs/readers for read-your-writes.
    #[serde(default)]
    pub read_fence_json: String,
    /// mTLS/JWT service identity of the caller (`x-service-identity` /
    /// cert SAN). Emitted to the backend as `app.current_service_identity`
    /// so RLS policies / audit triggers can attribute the connection.
    #[serde(default)]
    pub service_identity: String,
    /// Stable id of the authorization decision that admitted this request.
    /// Emitted to the backend as `app.current_decision_id` so row-level
    /// audit records can be joined back to the broker's decision audit.
    #[serde(default)]
    pub decision_id: String,
}

impl RequestContext {
    pub fn requires_primary_read(&self) -> bool {
        if self.primary_read {
            return true;
        }
        matches!(
            self.consistency
                .to_ascii_lowercase()
                .replace('-', "_")
                .as_str(),
            "strong" | "primary" | "linearizable" | "read_your_writes"
        )
    }

    pub fn replica_lag_override(&self) -> Option<std::time::Duration> {
        (self.max_replica_lag_ms > 0)
            .then(|| std::time::Duration::from_millis(self.max_replica_lag_ms))
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct SelectPlanRequest {
    pub context: RequestContext,
    pub message_type: String,
    pub filter: Value,
    pub fields: Vec<String>,
    pub limit: i32,
    pub sort: Vec<SortSpec>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct UpsertPlanRequest {
    pub context: RequestContext,
    pub message_type: String,
    pub record: Value,
    pub conflict_fields: Vec<String>,
    pub return_record: bool,
    pub bypass_cache_write: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct DeletePlanRequest {
    pub context: RequestContext,
    pub message_type: String,
    pub filter: Value,
}

/// Planner input for the partial-update verb: SET the named `changes` columns
/// and/or apply atomic `increments` on the rows matched by `filter`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct UpdatePlanRequest {
    pub context: RequestContext,
    pub message_type: String,
    pub filter: Value,
    /// Columns to SET (proto field or physical column names; JSON null ⇒ SQL NULL).
    pub changes: Value,
    /// Atomic `col = col + delta` deltas applied in the same statement.
    pub increments: Vec<(String, f64)>,
    pub return_record: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CachePolicyRequest {
    pub message_type: String,
    pub operation: String,
    pub bypass_read: bool,
    pub bypass_write: bool,
    pub ttl_seconds: i32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct VectorSearchPlanRequest {
    pub context: RequestContext,
    pub collection: String,
    pub vector_dimension: usize,
    pub filter: Value,
    pub limit: i32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct VectorUpsertPlanRequest {
    pub context: RequestContext,
    pub collection: String,
    pub point_dimensions: Vec<usize>,
    pub payloads: Vec<Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct VectorQueryPlan {
    pub collection: String,
    pub backend: String,
    pub expected_dimension: i32,
    pub filter_fields: Vec<String>,
    pub errors: Vec<String>,
}

impl VectorQueryPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct VectorUpsertPlan {
    pub collection: String,
    pub backend: String,
    pub expected_dimension: i32,
    pub point_count: usize,
    pub payload_fields: Vec<String>,
    pub errors: Vec<String>,
}

impl VectorUpsertPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ObjectAccessRequest {
    pub context: RequestContext,
    pub bucket: String,
    pub object_key: String,
    pub method: String,
    pub presigned: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ObjectStreamPlanRequest {
    pub context: RequestContext,
    pub bucket: String,
    pub object_key: String,
    pub method: String,
    pub chunk_count: usize,
    pub final_chunk_seen: bool,
    pub content_type: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ObjectAccessDecision {
    pub allowed: bool,
    pub resource_uri: String,
    pub pii: bool,
    pub errors: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ObjectStreamPlan {
    pub allowed: bool,
    pub resource_uri: String,
    pub backend: String,
    pub method: String,
    pub requires_server_side_encryption: bool,
    pub errors: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct AuditEvent {
    pub event_type: String,
    pub tenant_id: String,
    pub user_id: String,
    pub correlation_id: String,
    pub purpose: String,
    pub resource_uri: String,
    pub checksum_sha256: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CachePolicyPlan {
    pub backend: String,
    pub key_pattern: String,
    pub ttl_seconds: i32,
    pub read_through: bool,
    pub write_through: bool,
    pub bypass_read: bool,
    pub bypass_write: bool,
    pub invalidates_on_mutation: bool,
    pub errors: Vec<String>,
}

impl CachePolicyPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SqlOperationPlan {
    pub operation: String,
    pub resource_uri: String,
    pub sql: String,
    pub parameter_columns: Vec<String>,
    pub selected_columns: Vec<String>,
    pub conflict_columns: Vec<String>,
    pub filter_columns: Vec<String>,
    pub cache_policy: CachePolicyPlan,
    pub audit_event_type: String,
    pub errors: Vec<String>,
}

impl SqlOperationPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct TransactionMutation {
    pub operation: String,
    pub message_type: String,
    pub record: Value,
    pub filter: Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct TransactionPlanRequest {
    pub context: RequestContext,
    pub tx_id: String,
    pub mutations: Vec<TransactionMutation>,
    pub commit: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct TransactionPlan {
    pub tx_id: String,
    pub state: String,
    pub mutation_count: usize,
    pub mutation_plans: Vec<SqlOperationPlan>,
    pub errors: Vec<String>,
}

impl TransactionPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct GenericDispatchRequest {
    pub context: RequestContext,
    pub store_kind: String,
    pub resource_name: String,
    pub operation: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct GenericDispatchPlan {
    pub store_kind: String,
    pub backend: String,
    pub resource_uri: String,
    pub dsn_env_key: String,
    pub operation: String,
    pub errors: Vec<String>,
}

impl GenericDispatchPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SortSpec {
    pub field: String,
    pub descending: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct QueryPlan {
    pub resource_uri: String,
    pub schema: String,
    pub table: String,
    pub selected_columns: Vec<String>,
    pub filter_columns: Vec<String>,
    pub sort_columns: Vec<String>,
    pub tenant_column: String,
    pub masked_columns: Vec<String>,
    pub cache_key_pattern: String,
    pub sql: String,
    pub parameter_columns: Vec<String>,
    pub errors: Vec<String>,
}

impl QueryPlan {
    pub fn passed(&self) -> bool {
        self.errors.is_empty()
    }
}

/// Compose the single deterministic cache key for `build_select_query_plan`.
///
/// The key encodes EVERY input that can influence the emitted SQL / `QueryPlan`,
/// so two requests collide on the key only when they would build a byte-identical
/// plan. Composition (in order):
///   1. `manifest.checksum_sha256` FIRST — the catalog version. Any schema reload
///      changes the checksum, so a manifest change can never reuse a prior plan
///      (the checksum is a strict prefix of the key, mirroring `manifest_index.rs`).
///      When the checksum is empty we fall back to the `ptr:{:p}:{len}` discriminator
///      that `manifest_index.rs:31` uses so an unchecksummed manifest is never
///      conflated with another.
///   2. `message_type` — selects the table/columns/security.
///   3. canonical filter JSON — `serde_json::Map` is a `BTreeMap` here
///      (no `preserve_order` feature), so `to_string()` is key-order-stable.
///   4. `fields` in request order — order is preserved into `selected_columns`,
///      so it is part of the output identity and must NOT be reordered.
///   5. sort specs (field + direction, in order).
///   6. `limit`.
///   7. planning-affecting `RequestContext` bits: effective SQL backend
///      (`target_backend` drives `effective_sql_backend`, which selects the SQL
///      dialect), `tenant_id`, `project_id`, `purpose`, and the sorted `scopes`
///      (scope order does not affect output, so it is normalized for hit-rate).
fn select_plan_cache_key(manifest: &CatalogManifest, request: &SelectPlanRequest) -> String {
    let manifest_key = if manifest.checksum_sha256.is_empty() {
        format!("ptr:{:p}:{}", manifest, manifest.tables.len())
    } else {
        manifest.checksum_sha256.clone()
    };
    let ctx = &request.context;
    let backend = effective_sql_backend(ctx);
    let mut scopes = ctx.scopes.clone();
    scopes.sort();
    let sort_key = request
        .sort
        .iter()
        .map(|sort| format!("{}:{}", sort.field, sort.descending))
        .collect::<Vec<_>>()
        .join(",");
    format!(
        "{ck}\u{1f}msg={msg}\u{1f}flt={flt}\u{1f}fields={fields}\u{1f}sort={sort}\u{1f}limit={limit}\u{1f}backend={backend:?}\u{1f}tenant={tenant}\u{1f}project={project}\u{1f}purpose={purpose}\u{1f}scopes={scopes}",
        ck = manifest_key,
        msg = request.message_type,
        flt = request.filter,
        fields = request.fields.join(","),
        sort = sort_key,
        limit = request.limit,
        tenant = ctx.tenant_id,
        project = ctx.project_id,
        purpose = ctx.purpose,
        scopes = scopes.join(","),
    )
}

/// Build the IR→SQL read plan for a typed Select, with a transparent, bounded,
/// process-global memoization (#136 pattern, see `select_plan_cache_key` and
/// `manifest_index.rs`). Identical inputs (including the manifest checksum) return
/// a byte-identical `QueryPlan` cloned from the cache; the planning output is
/// unchanged for every input. On a miss it builds exactly as before, caches, and
/// returns. Because `manifest.checksum_sha256` is the key prefix, a manifest
/// change always produces a fresh key and can never serve a stale plan.
pub fn build_select_query_plan(
    manifest: &CatalogManifest,
    request: &SelectPlanRequest,
) -> QueryPlan {
    static PLAN_CACHE: OnceLock<Mutex<HashMap<String, QueryPlan>>> = OnceLock::new();
    let cache_key = select_plan_cache_key(manifest, request);
    let cache = PLAN_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    if let Ok(guard) = cache.lock()
        && let Some(plan) = guard.get(&cache_key)
    {
        return plan.clone();
    }
    let plan = build_select_query_plan_uncached(manifest, request);
    if let Ok(mut guard) = cache.lock() {
        // Bound the process-global cache. The manifest checksum is part of every
        // key, so without a cap the map grows unbounded across schema reloads.
        // When a new key would exceed the cap, drop the whole cache and rebuild
        // lazily (rebuilding one plan is cheap) — #136.
        const PLAN_CACHE_CAP: usize = 512;
        if guard.len() >= PLAN_CACHE_CAP && !guard.contains_key(&cache_key) {
            guard.clear();
        }
        guard.entry(cache_key).or_insert_with(|| plan.clone());
    }
    plan
}

/// Convert the data-plane Select planner input into the canonical neutral read
/// shape. This is the 2.4 merge seam: the data-plane wrapper still owns its
/// value-adds (context/scope checks, PII projection exclusion, tenant/project
/// isolation, cache/audit metadata), while the emitted read can be compiled by
/// the shared IR compilers once live SQL equivalence is proven.
pub(crate) fn build_select_logical_read(
    manifest: &CatalogManifest,
    request: &SelectPlanRequest,
) -> Result<LogicalRead, Vec<String>> {
    let table = resolve_table_for_message(manifest, &request.message_type)
        .map_err(|error| vec![error.to_string()])?;

    let mut errors = Vec::new();
    if request.context.tenant_id.trim().is_empty() {
        errors.push("tenant_id is required".to_string());
    }
    if request.context.purpose.trim().is_empty() {
        errors.push("purpose is required".to_string());
    }
    if !has_scope(&request.context, "udb:read") {
        errors.push("scope udb:read is required".to_string());
    }

    let allowed = allowed_columns(table);
    let resolver = column_resolver(table);
    let filter_json = normalize_filter_keys(&resolver, &request.filter);
    // Validate fields (incl. unknowns nested inside $or) via the broad scan, then
    // use the MANDATORY set for isolation (X-4) — the broad set counts a column
    // inside an $or branch, which does not isolate.
    let _ = filter_columns(&filter_json, &allowed, &mut errors);
    let mandatory_columns = mandatory_and_columns(&filter_json, &allowed);
    let tenant = tenant_column(table);
    if tenant.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !mandatory_columns.contains(&tenant) {
        errors.push(format!("tenant isolation requires filter on {}", tenant));
    }
    let project = project_column(table);
    if !project.is_empty() && !mandatory_columns.contains(&project) {
        errors.push(format!("project isolation requires filter on {}", project));
    }

    let selected_columns = if request.fields.is_empty() {
        table
            .columns
            .iter()
            .filter(|column| !column.security.is_pii && !column.security.is_encrypted)
            .map(|column| column.column_name.clone())
            .collect::<Vec<_>>()
    } else {
        request
            .fields
            .iter()
            .map(|field| {
                let column = resolve_column(&resolver, field);
                if !allowed.contains(&column) {
                    errors.push(format!("unknown selected field {}", column));
                }
                column
            })
            .collect::<Vec<_>>()
    };

    let sort = request
        .sort
        .iter()
        .map(|sort| {
            let column = resolve_column(&resolver, &sort.field);
            if !allowed.contains(&column) {
                errors.push(format!("unknown sort field {}", column));
            }
            LogicalSort {
                field: column,
                direction: if sort.descending {
                    SortDirection::Desc
                } else {
                    SortDirection::Asc
                },
                nulls: Default::default(),
            }
        })
        .collect::<Vec<_>>();

    let filter = logical_filter_from_planner_json(&filter_json, &allowed, &mut errors);
    if !errors.is_empty() {
        return Err(errors);
    }

    const MAX_QUERY_LIMIT: i32 = 100_000;
    let pagination = (request.limit > 0).then(|| LogicalPagination {
        limit: Some(request.limit.min(MAX_QUERY_LIMIT) as u32),
        ..Default::default()
    });

    Ok(LogicalRead {
        message_type: request.message_type.clone(),
        filter,
        projection: Some(LogicalProjection::fields(selected_columns)),
        sort,
        include: Vec::new(),
        pagination,
    })
}

fn build_select_query_plan_uncached(
    manifest: &CatalogManifest,
    request: &SelectPlanRequest,
) -> QueryPlan {
    let table = match resolve_table_for_message(manifest, &request.message_type) {
        Ok(table) => table,
        Err(error) => {
            return QueryPlan {
                errors: vec![error.to_string()],
                ..QueryPlan::default()
            };
        }
    };

    let mut errors = Vec::new();
    if request.context.tenant_id.trim().is_empty() {
        errors.push("tenant_id is required".to_string());
    }
    if request.context.purpose.trim().is_empty() {
        errors.push("purpose is required".to_string());
    }
    if !has_scope(&request.context, "udb:read") {
        errors.push("scope udb:read is required".to_string());
    }

    let allowed = allowed_columns(table);
    // #117: resolve proto `field_name` aliases to physical `column_name`s before
    // validation/emission, so a column override (`field_name != column_name`)
    // doesn't reject a valid request or build SQL against the wrong column.
    let resolver = column_resolver(table);
    let filter = normalize_filter_keys(&resolver, &request.filter);
    let selected_columns = if request.fields.is_empty() {
        table
            .columns
            .iter()
            // Exclude PII and encrypted columns from the implicit SELECT *.
            // Callers must explicitly request PII fields; mask_in_logs controls
            // log redaction only, not access control.
            .filter(|column| !column.security.is_pii && !column.security.is_encrypted)
            .map(|column| column.column_name.clone())
            .collect::<Vec<_>>()
    } else {
        request
            .fields
            .iter()
            .map(|field| resolve_column(&resolver, field))
            .inspect(|field| {
                if !allowed.contains(field) {
                    errors.push(format!("unknown selected field {}", field));
                }
            })
            .collect::<Vec<_>>()
    };

    let mut parameter_columns = Vec::new();
    let backend_kind = effective_sql_backend(&request.context);
    let encrypted = encrypted_filter_columns(table);
    let compiled_filter = compile_filter_predicates(
        &filter,
        &allowed,
        &encrypted,
        &mut errors,
        &mut parameter_columns,
        1,
        &backend_kind,
    );
    let filter_columns = filter_columns(&filter, &allowed, &mut errors);
    let mandatory_columns = mandatory_and_columns(&filter, &allowed);
    let sort_columns = request
        .sort
        .iter()
        .map(|sort| resolve_column(&resolver, &sort.field))
        .inspect(|field| {
            if !allowed.contains(field) {
                errors.push(format!("unknown sort field {}", field));
            }
        })
        .collect::<Vec<_>>();
    let tenant_column = tenant_column(table);
    if tenant_column.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !mandatory_columns.contains(&tenant_column) {
        errors.push(format!(
            "tenant isolation requires filter on {}",
            tenant_column
        ));
    }
    // Project isolation (mirrors tenant): when the table declares a project key,
    // the read must filter on it so a query cannot span projects.
    let project_column = project_column(table);
    if !project_column.is_empty() && !mandatory_columns.contains(&project_column) {
        errors.push(format!(
            "project isolation requires filter on {}",
            project_column
        ));
    }

    let mut sql = format!(
        "SELECT {} FROM {}.{}",
        if selected_columns.is_empty() {
            "*".to_string()
        } else {
            quote_list(&selected_columns)
        },
        qi(&table.schema),
        qi(&table.table)
    );
    if !compiled_filter.sql.is_empty() {
        sql.push_str(" WHERE ");
        sql.push_str(&compiled_filter.sql);
    }
    if !request.sort.is_empty() {
        sql.push_str(" ORDER BY ");
        sql.push_str(
            &request
                .sort
                .iter()
                .map(|sort| {
                    format!(
                        "{} {}",
                        qi(&resolve_column(&resolver, &sort.field)),
                        if sort.descending { "DESC" } else { "ASC" }
                    )
                })
                .collect::<Vec<_>>()
                .join(", "),
        );
    }
    // Cap LIMIT to prevent DoS via arbitrarily large result sets.
    // Callers that need full table scans should use pagination or streaming.
    const MAX_QUERY_LIMIT: i32 = 100_000;
    if request.limit > 0 {
        sql.push_str(&format!(" LIMIT {}", request.limit.min(MAX_QUERY_LIMIT)));
    }

    QueryPlan {
        resource_uri: format!("sql://{}/{}", table.schema, table.table),
        schema: table.schema.clone(),
        table: table.table.clone(),
        selected_columns,
        filter_columns,
        sort_columns,
        tenant_column,
        masked_columns: masked_columns(table),
        cache_key_pattern: cache_key_pattern(manifest, table),
        sql,
        parameter_columns,
        errors,
    }
}

pub fn build_upsert_plan(
    manifest: &CatalogManifest,
    request: &UpsertPlanRequest,
) -> SqlOperationPlan {
    let table = match resolve_table_for_message(manifest, &request.message_type) {
        Ok(table) => table,
        Err(error) => {
            return SqlOperationPlan {
                operation: "upsert".to_string(),
                errors: vec![error.to_string()],
                ..SqlOperationPlan::default()
            };
        }
    };

    let mut errors = validate_write_context(&request.context);
    let allowed = allowed_columns(table);
    // #117: resolve proto `field_name` aliases (record keys, conflict fields) to
    // physical `column_name`s. Idempotent on already-physical names; the runtime
    // applies the same `normalize_record_keys` before binding values.
    let resolver = column_resolver(table);
    let Some(record) = request.record.as_object() else {
        return SqlOperationPlan {
            operation: "upsert".to_string(),
            resource_uri: format!("sql://{}/{}", table.schema, table.table),
            errors: vec!["record must be a JSON object".to_string()],
            ..SqlOperationPlan::default()
        };
    };

    let mut parameter_columns = Vec::new();
    for key in record.keys() {
        let column = resolve_column(&resolver, key);
        if !allowed.contains(&column) {
            errors.push(format!("unknown record field {}", key));
        } else if !is_server_owned_column(table, &column) {
            parameter_columns.push(column);
        }
    }
    parameter_columns.sort();
    parameter_columns.dedup();

    let tenant = tenant_column(table);
    if tenant.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !parameter_columns.contains(&tenant) {
        errors.push(format!("tenant isolation requires record field {}", tenant));
    }
    // Look up the tenant value case-insensitively: `record.get(&tenant)` uses the
    // lowercase manifest column name, but JSON keys arrive in original case, so a
    // `{"TenantId": …}` payload would miss the lookup and SKIP this mismatch check
    // — letting a foreign tenant_id through. Match any key whose lowercase equals
    // the tenant column.
    if !tenant.is_empty()
        && let Some(tenant_value) = record
            .iter()
            .find(|(key, _)| resolve_column(&resolver, key) == tenant)
            .and_then(|(_, value)| value.as_str())
        && tenant_value != request.context.tenant_id
    {
        errors.push("record tenant_id must match RequestContext.tenant_id".to_string());
    }

    // Project isolation (mirrors tenant). When the request carries a project_id
    // and the table has a project key, the record must include it and the value
    // must match the request context — preventing cross-project upserts. Gated on
    // a non-empty context project_id so single-project deployments are unaffected.
    let project = project_column(table);
    if !project.is_empty() && !request.context.project_id.is_empty() {
        if !parameter_columns.contains(&project) {
            errors.push(format!(
                "project isolation requires record field {}",
                project
            ));
        }
        if let Some(project_value) = record
            .iter()
            .find(|(key, _)| resolve_column(&resolver, key) == project)
            .and_then(|(_, value)| value.as_str())
            && project_value != request.context.project_id
        {
            errors.push("record project_id must match RequestContext.project_id".to_string());
        }
    }

    let conflict_columns = if request.conflict_fields.is_empty() {
        table.primary_key.clone()
    } else {
        request
            .conflict_fields
            .iter()
            .map(|field| resolve_column(&resolver, field))
            .collect::<Vec<_>>()
    };
    if conflict_columns.is_empty() {
        errors.push("upsert requires conflict_fields or a manifest primary key".to_string());
    }
    for column in &conflict_columns {
        if !allowed.contains(column) {
            errors.push(format!("unknown conflict field {}", column));
        }
    }
    if !conflict_columns.is_empty() && !conflict_target_is_unique(table, &conflict_columns) {
        errors.push(
            "conflict_fields must match the primary key or a declared unique index".to_string(),
        );
    }

    let update_columns = parameter_columns
        .iter()
        .filter(|column| {
            !conflict_columns.contains(column) && !is_update_excluded_column(table, column)
        })
        .cloned()
        .collect::<Vec<_>>();
    let values = (1..=parameter_columns.len())
        .map(|idx| format!("${idx}"))
        .collect::<Vec<_>>()
        .join(", ");
    let assignments = update_columns
        .iter()
        .map(|column| format!("{} = EXCLUDED.{}", qi(column), qi(column)))
        .collect::<Vec<_>>()
        .join(", ");
    let on_conflict = if update_columns.is_empty() {
        "DO NOTHING".to_string()
    } else {
        format!("DO UPDATE SET {assignments}")
    };
    let returning = if request.return_record {
        " RETURNING *"
    } else {
        ""
    };
    let sql = format!(
        "INSERT INTO {}.{} ({}) VALUES ({}) ON CONFLICT ({}) {}{}",
        qi(&table.schema),
        qi(&table.table),
        quote_list(&parameter_columns),
        values,
        quote_list(&conflict_columns),
        on_conflict,
        returning
    );

    SqlOperationPlan {
        operation: "upsert".to_string(),
        resource_uri: format!("sql://{}/{}", table.schema, table.table),
        sql,
        parameter_columns,
        conflict_columns,
        cache_policy: build_cache_policy_plan(
            manifest,
            &CachePolicyRequest {
                message_type: request.message_type.clone(),
                operation: "upsert".to_string(),
                bypass_write: request.bypass_cache_write,
                ..CachePolicyRequest::default()
            },
        ),
        audit_event_type: "udb.sql.upsert".to_string(),
        errors,
        ..SqlOperationPlan::default()
    }
}

/// Convert the data-plane Upsert planner input into a neutral write while
/// preserving the wrapper's validation boundary (scope, tenant/project binding,
/// server-owned column exclusion, conflict uniqueness, and return shape).
pub(crate) fn build_upsert_logical_write(
    manifest: &CatalogManifest,
    request: &UpsertPlanRequest,
) -> Result<LogicalWrite, Vec<String>> {
    let table = resolve_table_for_message(manifest, &request.message_type)
        .map_err(|error| vec![error.to_string()])?;

    let mut errors = validate_write_context(&request.context);
    let allowed = allowed_columns(table);
    let resolver = column_resolver(table);
    let Some(record) = request.record.as_object() else {
        return Err(vec!["record must be a JSON object".to_string()]);
    };

    let mut logical_record: LogicalRecord = BTreeMap::new();
    for (key, value) in record {
        let column = resolve_column(&resolver, key);
        if !allowed.contains(&column) {
            errors.push(format!("unknown record field {}", key));
        } else if !is_server_owned_column(table, &column) {
            logical_record.insert(column, logical_value_from_json(value));
        }
    }
    if logical_record.is_empty() {
        errors.push("upsert requires at least one client-writable record field".to_string());
    }

    let record_columns = logical_record.keys().cloned().collect::<Vec<_>>();
    let tenant = tenant_column(table);
    if tenant.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !record_columns.contains(&tenant) {
        errors.push(format!("tenant isolation requires record field {}", tenant));
    }
    if !tenant.is_empty()
        && let Some(LogicalValue::String(tenant_value)) = logical_record.get(&tenant)
        && tenant_value != &request.context.tenant_id
    {
        errors.push("record tenant_id must match RequestContext.tenant_id".to_string());
    }

    let project = project_column(table);
    if !project.is_empty() && !request.context.project_id.is_empty() {
        if !record_columns.contains(&project) {
            errors.push(format!(
                "project isolation requires record field {}",
                project
            ));
        }
        if let Some(LogicalValue::String(project_value)) = logical_record.get(&project)
            && project_value != &request.context.project_id
        {
            errors.push("record project_id must match RequestContext.project_id".to_string());
        }
    }

    let conflict_columns = if request.conflict_fields.is_empty() {
        table.primary_key.clone()
    } else {
        request
            .conflict_fields
            .iter()
            .map(|field| resolve_column(&resolver, field))
            .collect::<Vec<_>>()
    };
    if conflict_columns.is_empty() {
        errors.push("upsert requires conflict_fields or a manifest primary key".to_string());
    }
    for column in &conflict_columns {
        if !allowed.contains(column) {
            errors.push(format!("unknown conflict field {}", column));
        }
    }
    if !conflict_columns.is_empty() && !conflict_target_is_unique(table, &conflict_columns) {
        errors.push(
            "conflict_fields must match the primary key or a declared unique index".to_string(),
        );
    }

    let update_columns = record_columns
        .iter()
        .filter(|column| {
            !conflict_columns.contains(column) && !is_update_excluded_column(table, column)
        })
        .cloned()
        .collect::<Vec<_>>();
    let uses_primary_conflict =
        request.conflict_fields.is_empty() || conflict_columns == table.primary_key;
    let conflict = if update_columns.is_empty() {
        if !uses_primary_conflict {
            errors.push(
                "neutral IR cannot represent alternate-unique ON CONFLICT DO NOTHING yet"
                    .to_string(),
            );
        }
        ConflictStrategy::Ignore
    } else if uses_primary_conflict {
        ConflictStrategy::update(update_columns)
    } else {
        ConflictStrategy::update_on(update_columns, conflict_columns.clone())
    };

    if !errors.is_empty() {
        return Err(errors);
    }

    let return_fields = if request.return_record {
        table
            .columns
            .iter()
            .map(|column| column.column_name.clone())
            .collect()
    } else {
        Vec::new()
    };

    Ok(LogicalWrite {
        message_type: request.message_type.clone(),
        records: vec![logical_record],
        conflict,
        return_fields,
    })
}

pub fn build_delete_plan(
    manifest: &CatalogManifest,
    request: &DeletePlanRequest,
) -> SqlOperationPlan {
    let table = match resolve_table_for_message(manifest, &request.message_type) {
        Ok(table) => table,
        Err(error) => {
            return SqlOperationPlan {
                operation: "delete".to_string(),
                errors: vec![error.to_string()],
                ..SqlOperationPlan::default()
            };
        }
    };

    let mut errors = validate_write_context(&request.context);
    let allowed = allowed_columns(table);
    // #117: resolve proto `field_name` aliases in the delete filter.
    let resolver = column_resolver(table);
    let filter = normalize_filter_keys(&resolver, &request.filter);
    let mut parameter_columns = Vec::new();
    let backend_kind = effective_sql_backend(&request.context);
    let encrypted = encrypted_filter_columns(table);
    let compiled = compile_filter_predicates(
        &filter,
        &allowed,
        &encrypted,
        &mut errors,
        &mut parameter_columns,
        1,
        &backend_kind,
    );
    let filter_columns = filter_columns(&filter, &allowed, &mut errors);
    let mandatory_columns = mandatory_and_columns(&filter, &allowed);
    let tenant = tenant_column(table);
    if tenant.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !mandatory_columns.contains(&tenant) {
        errors.push(format!("tenant isolation requires filter on {}", tenant));
    }
    let project = project_column(table);
    if !project.is_empty() && !mandatory_columns.contains(&project) {
        errors.push(format!("project isolation requires filter on {}", project));
    }
    if compiled.sql.is_empty() {
        errors.push("delete requires at least one safe filter predicate".to_string());
    }
    let sql = format!(
        "DELETE FROM {}.{} WHERE {}",
        qi(&table.schema),
        qi(&table.table),
        if compiled.sql.is_empty() {
            "FALSE".to_string()
        } else {
            compiled.sql
        }
    );

    SqlOperationPlan {
        operation: "delete".to_string(),
        resource_uri: format!("sql://{}/{}", table.schema, table.table),
        sql,
        parameter_columns,
        filter_columns,
        cache_policy: build_cache_policy_plan(
            manifest,
            &CachePolicyRequest {
                message_type: request.message_type.clone(),
                operation: "delete".to_string(),
                ..CachePolicyRequest::default()
            },
        ),
        audit_event_type: "udb.sql.delete".to_string(),
        errors,
        ..SqlOperationPlan::default()
    }
}

/// Compile the partial-update verb: `UPDATE s.t SET a=$1[, cnt=cnt+$2] WHERE …`.
/// SET parameters come FIRST ($1..$k in `parameter_columns` order: changes then
/// increments), the filter predicate's parameters start at $k+1 — the executor
/// binds `changes ++ increments ++ filter` values in exactly that order. Shares
/// every safety property with the delete plan: field-name aliasing, tenant AND
/// project isolation on the MANDATORY column set, safe-predicate requirement,
/// and the encrypted-filter posture of `compile_filter_predicates`. Isolation
/// and primary-key columns are IMMUTABLE through this verb (identity changes
/// belong to Upsert), and increment columns must not also appear in `changes`.
pub fn build_update_plan(
    manifest: &CatalogManifest,
    request: &UpdatePlanRequest,
) -> SqlOperationPlan {
    let table = match resolve_table_for_message(manifest, &request.message_type) {
        Ok(table) => table,
        Err(error) => {
            return SqlOperationPlan {
                operation: "update".to_string(),
                errors: vec![error.to_string()],
                ..SqlOperationPlan::default()
            };
        }
    };

    let mut errors = validate_write_context(&request.context);
    let allowed = allowed_columns(table);
    let resolver = column_resolver(table);
    let filter = normalize_filter_keys(&resolver, &request.filter);

    // ── SET clause: changes (typed binds by column) then increments ──────────
    let tenant = tenant_column(table);
    let project = project_column(table);
    let immutable: BTreeSet<String> = table
        .primary_key
        .iter()
        .cloned()
        .chain([tenant.clone(), project.clone()])
        .filter(|column| !column.is_empty())
        .collect();
    let mut set_fragments: Vec<String> = Vec::new();
    let mut parameter_columns: Vec<String> = Vec::new();
    let mut next_param = 1usize;
    // NORMALIZE-then-SORT: the executor rebuilds the bind-value order from the
    // normalized physical column names (BTreeMap iteration), so the plan must
    // order SET parameters by the NORMALIZED name — sorting raw keys would
    // diverge whenever a field alias sorts differently from its column.
    for (normalized, key) in normalized_update_changes(&request.changes, &resolver, &mut errors) {
        if !allowed.contains(&normalized) {
            errors.push(format!("unknown update column {key}"));
            continue;
        }
        if immutable.contains(&normalized) {
            errors.push(format!(
                "column {normalized} is immutable through Update (primary key / tenant / project); use Upsert for identity changes"
            ));
            continue;
        }
        set_fragments.push(format!("{} = ${next_param}", qi(&normalized)));
        parameter_columns.push(normalized);
        next_param += 1;
    }
    let change_columns: BTreeSet<String> = parameter_columns.iter().cloned().collect();
    for (column, _delta) in &request.increments {
        let normalized = resolver
            .get(&column.to_ascii_lowercase())
            .cloned()
            .unwrap_or_else(|| column.to_ascii_lowercase());
        if !allowed.contains(&normalized) {
            errors.push(format!("unknown increment column {column}"));
            continue;
        }
        if immutable.contains(&normalized) {
            errors.push(format!("column {normalized} is immutable through Update"));
            continue;
        }
        if change_columns.contains(&normalized) {
            errors.push(format!(
                "column {normalized} appears in both changes and increments"
            ));
            continue;
        }
        set_fragments.push(format!(
            "{col} = {col} + ${next_param}",
            col = qi(&normalized)
        ));
        parameter_columns.push(normalized);
        next_param += 1;
    }
    if set_fragments.is_empty() {
        errors.push("update requires at least one change or increment".to_string());
    }

    // ── WHERE clause: identical machinery + isolation posture to delete ──────
    let backend_kind = effective_sql_backend(&request.context);
    let encrypted = encrypted_filter_columns(table);
    let compiled = compile_filter_predicates(
        &filter,
        &allowed,
        &encrypted,
        &mut errors,
        &mut parameter_columns,
        next_param,
        &backend_kind,
    );
    let filter_columns = filter_columns(&filter, &allowed, &mut errors);
    let mandatory_columns = mandatory_and_columns(&filter, &allowed);
    if tenant.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !mandatory_columns.contains(&tenant) {
        errors.push(format!("tenant isolation requires filter on {}", tenant));
    }
    if !project.is_empty() && !mandatory_columns.contains(&project) {
        errors.push(format!("project isolation requires filter on {}", project));
    }
    if compiled.sql.is_empty() {
        errors.push("update requires at least one safe filter predicate".to_string());
    }

    let sql = format!(
        "UPDATE {}.{} SET {} WHERE {}{}",
        qi(&table.schema),
        qi(&table.table),
        set_fragments.join(", "),
        if compiled.sql.is_empty() {
            "FALSE".to_string()
        } else {
            compiled.sql
        },
        if request.return_record {
            " RETURNING *"
        } else {
            ""
        },
    );

    SqlOperationPlan {
        operation: "update".to_string(),
        resource_uri: format!("sql://{}/{}", table.schema, table.table),
        sql,
        parameter_columns,
        filter_columns,
        cache_policy: build_cache_policy_plan(
            manifest,
            &CachePolicyRequest {
                message_type: request.message_type.clone(),
                operation: "update".to_string(),
                ..CachePolicyRequest::default()
            },
        ),
        audit_event_type: "udb.sql.update".to_string(),
        errors,
        ..SqlOperationPlan::default()
    }
}

/// Normalize an Update `changes` object into `(physical_column, raw_key)`
/// pairs SORTED by physical column — the shared ordering contract between
/// [`build_update_plan`] (which numbers the SET parameters) and the executor
/// (which binds the values). Duplicate normalizations (a field alias and its
/// physical column both present) are an error, not a silent overwrite.
pub fn normalized_update_changes(
    changes: &Value,
    resolver: &std::collections::HashMap<String, String>,
    errors: &mut Vec<String>,
) -> Vec<(String, String)> {
    let mut out: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
    match changes {
        Value::Object(map) => {
            for key in map.keys() {
                let normalized = resolver
                    .get(&key.to_ascii_lowercase())
                    .cloned()
                    .unwrap_or_else(|| key.to_ascii_lowercase());
                if let Some(previous) = out.insert(normalized.clone(), key.clone()) {
                    errors.push(format!(
                        "update changes name column {normalized} twice ({previous} and {key})"
                    ));
                }
            }
        }
        Value::Null => {}
        _ => errors.push("update changes must be a JSON object of column -> value".to_string()),
    }
    out.into_iter().collect()
}

/// Convert the data-plane Delete planner input into the canonical neutral
/// delete shape. The bridge keeps the data-plane tenant/project/scope checks and
/// refuses unbounded or planner-only Postgres filters rather than downgrading
/// them to a broader delete.
pub(crate) fn build_delete_logical_delete(
    manifest: &CatalogManifest,
    request: &DeletePlanRequest,
) -> Result<LogicalDelete, Vec<String>> {
    let table = resolve_table_for_message(manifest, &request.message_type)
        .map_err(|error| vec![error.to_string()])?;

    let mut errors = validate_write_context(&request.context);
    let allowed = allowed_columns(table);
    let resolver = column_resolver(table);
    let filter_json = normalize_filter_keys(&resolver, &request.filter);
    // Validate fields (incl. unknowns nested inside $or) via the broad scan, then
    // use the MANDATORY set for isolation (X-4) — the broad set counts a column
    // inside an $or branch, which does not isolate.
    let _ = filter_columns(&filter_json, &allowed, &mut errors);
    let mandatory_columns = mandatory_and_columns(&filter_json, &allowed);

    let tenant = tenant_column(table);
    if tenant.is_empty() {
        if table_requires_tenant_column(table) {
            errors.push(unresolved_tenant_column_error(table));
        }
    } else if !mandatory_columns.contains(&tenant) {
        errors.push(format!("tenant isolation requires filter on {}", tenant));
    }
    let project = project_column(table);
    if !project.is_empty() && !mandatory_columns.contains(&project) {
        errors.push(format!("project isolation requires filter on {}", project));
    }

    let filter = logical_filter_from_planner_json(&filter_json, &allowed, &mut errors);
    if filter.is_none() {
        errors.push("delete requires at least one safe filter predicate".to_string());
    }
    if !errors.is_empty() {
        return Err(errors);
    }

    Ok(LogicalDelete {
        message_type: request.message_type.clone(),
        filter: filter.expect("checked above"),
        return_fields: Vec::new(),
    })
}

pub fn build_transaction_plan(
    manifest: &CatalogManifest,
    request: &TransactionPlanRequest,
) -> TransactionPlan {
    let mut errors = validate_stream_context(&request.context);
    if request.tx_id.trim().is_empty() {
        errors.push("tx_id is required".to_string());
    }
    if request.mutations.is_empty() {
        errors.push("transaction stream requires at least one mutation".to_string());
    }

    let mut mutation_plans = Vec::new();
    for mutation in &request.mutations {
        match mutation.operation.as_str() {
            "upsert" => mutation_plans.push(build_upsert_plan(
                manifest,
                &UpsertPlanRequest {
                    context: request.context.clone(),
                    message_type: mutation.message_type.clone(),
                    record: mutation.record.clone(),
                    ..UpsertPlanRequest::default()
                },
            )),
            "delete" => mutation_plans.push(build_delete_plan(
                manifest,
                &DeletePlanRequest {
                    context: request.context.clone(),
                    message_type: mutation.message_type.clone(),
                    filter: mutation.filter.clone(),
                },
            )),
            other => errors.push(format!("unsupported transaction mutation op {}", other)),
        }
    }
    for plan in &mutation_plans {
        errors.extend(plan.errors.iter().cloned());
    }

    TransactionPlan {
        tx_id: request.tx_id.clone(),
        state: if errors.is_empty() {
            if request.commit {
                "TX_STATE_COMMITTED".to_string()
            } else {
                "TX_STATE_OPEN".to_string()
            }
        } else {
            "TX_STATE_ERROR".to_string()
        },
        mutation_count: mutation_plans.len(),
        mutation_plans,
        errors,
    }
}

pub fn build_cache_policy_plan(
    manifest: &CatalogManifest,
    request: &CachePolicyRequest,
) -> CachePolicyPlan {
    let table = match resolve_table_for_message(manifest, &request.message_type) {
        Ok(table) => table,
        Err(error) => {
            return CachePolicyPlan {
                errors: vec![error.to_string()],
                ..CachePolicyPlan::default()
            };
        }
    };
    let Some(store) = manifest.stores.iter().find(|store| {
        store.store_kind == "cache"
            && store.owner_schema == table.schema
            && store.owner_table == table.table
    }) else {
        return CachePolicyPlan::default();
    };

    CachePolicyPlan {
        backend: store.backend.clone(),
        key_pattern: store_option(store, "key_pattern"),
        ttl_seconds: if request.ttl_seconds > 0 {
            request.ttl_seconds
        } else {
            store_option_i32(store, "ttl_seconds")
        },
        read_through: store_option_bool(store, "read_through") && !request.bypass_read,
        write_through: store_option_bool(store, "write_through") && !request.bypass_write,
        bypass_read: request.bypass_read,
        bypass_write: request.bypass_write,
        invalidates_on_mutation: matches!(request.operation.as_str(), "upsert" | "delete"),
        ..CachePolicyPlan::default()
    }
}

pub fn build_vector_search_plan(
    manifest: &CatalogManifest,
    request: &VectorSearchPlanRequest,
) -> VectorQueryPlan {
    let mut errors = Vec::new();
    if request.context.tenant_id.trim().is_empty() {
        errors.push("tenant_id is required".to_string());
    }
    if !has_scope(&request.context, "udb:vector:read") {
        errors.push("scope udb:vector:read is required".to_string());
    }

    let Some(store) = manifest
        .stores
        .iter()
        .find(|store| store.store_kind == "vector" && store.resource_name == request.collection)
    else {
        return VectorQueryPlan {
            collection: request.collection.clone(),
            errors: vec![format!("unknown vector collection {}", request.collection)],
            ..VectorQueryPlan::default()
        };
    };

    let expected_dimension = store
        .options
        .iter()
        .find(|option| option.key == "dimension")
        .and_then(|option| option.value.parse::<i32>().ok())
        .unwrap_or_default();
    if expected_dimension > 0 && request.vector_dimension as i32 != expected_dimension {
        errors.push(format!(
            "vector dimension mismatch: got {}, expected {}",
            request.vector_dimension, expected_dimension
        ));
    }

    VectorQueryPlan {
        collection: request.collection.clone(),
        backend: store.backend.clone(),
        expected_dimension,
        filter_fields: vector_filter_fields(&request.filter, &mut errors),
        errors,
    }
}

pub fn build_vector_upsert_plan(
    manifest: &CatalogManifest,
    request: &VectorUpsertPlanRequest,
) -> VectorUpsertPlan {
    let mut errors = Vec::new();
    if request.context.tenant_id.trim().is_empty() {
        errors.push("tenant_id is required".to_string());
    }
    if !has_scope(&request.context, "udb:vector:write") {
        errors.push("scope udb:vector:write is required".to_string());
    }
    if request.point_dimensions.is_empty() {
        errors.push("at least one vector point is required".to_string());
    }

    let Some(store) = manifest
        .stores
        .iter()
        .find(|store| store.store_kind == "vector" && store.resource_name == request.collection)
    else {
        return VectorUpsertPlan {
            collection: request.collection.clone(),
            errors: vec![format!("unknown vector collection {}", request.collection)],
            ..VectorUpsertPlan::default()
        };
    };

    let expected_dimension = store_option_i32(store, "dimension");
    for (idx, dimension) in request.point_dimensions.iter().enumerate() {
        if expected_dimension > 0 && *dimension as i32 != expected_dimension {
            errors.push(format!(
                "vector point {} dimension mismatch: got {}, expected {}",
                idx, dimension, expected_dimension
            ));
        }
    }
    let mut payload_fields = Vec::new();
    for payload in &request.payloads {
        collect_payload_fields(payload, &mut payload_fields);
    }
    payload_fields.sort();
    payload_fields.dedup();

    VectorUpsertPlan {
        collection: request.collection.clone(),
        backend: store.backend.clone(),
        expected_dimension,
        point_count: request.point_dimensions.len(),
        payload_fields,
        errors,
    }
}

pub fn evaluate_object_access(
    manifest: &CatalogManifest,
    request: &ObjectAccessRequest,
) -> ObjectAccessDecision {
    let mut errors = Vec::new();
    if request.context.tenant_id.trim().is_empty() {
        errors.push("tenant_id is required".to_string());
    }
    if request.presigned && !has_scope(&request.context, "udb:object:presign") {
        errors.push("scope udb:object:presign is required".to_string());
    }
    let method = request.method.to_ascii_uppercase();
    if !matches!(method.as_str(), "GET" | "PUT") {
        errors.push("object access method must be GET or PUT".to_string());
    }

    let Some(store) = manifest.stores.iter().find(|store| {
        matches!(store.store_kind.as_str(), "object" | "blob" | "storage")
            && store.resource_name == request.bucket
    }) else {
        return ObjectAccessDecision {
            resource_uri: format!("object://{}", request.bucket),
            errors: vec![format!("unknown object bucket {}", request.bucket)],
            ..ObjectAccessDecision::default()
        };
    };

    if request.presigned {
        let allowed_by_annotation = match method.as_str() {
            "GET" => store_option_bool(store, "presigned_read"),
            "PUT" => store_option_bool(store, "presigned_write"),
            _ => false,
        };
        if !allowed_by_annotation {
            errors.push(format!(
                "presigned {} is not enabled for bucket {}",
                method, request.bucket
            ));
        }
    }

    let column_name = store
        .options
        .iter()
        .find(|option| option.key == "column_name")
        .map(|option| option.value.as_str())
        .unwrap_or_default();
    let pii = manifest
        .table(&store.owner_schema, &store.owner_table)
        .and_then(|table| {
            table
                .columns
                .iter()
                .find(|column| column.column_name == column_name)
        })
        .map(|column| column.security.is_pii || column.security.is_encrypted)
        .unwrap_or(false);

    if pii
        && !matches!(
            request.context.purpose.as_str(),
            "export" | "verification" | "audit"
        )
        && !has_scope(&request.context, "udb:object:pii")
    {
        errors.push(
            "PII object access requires export, verification, audit, or udb:object:pii scope"
                .to_string(),
        );
    }

    ObjectAccessDecision {
        allowed: errors.is_empty(),
        resource_uri: format!(
            "object://{}/{}",
            request.bucket,
            request.object_key.trim_start_matches('/')
        ),
        pii,
        errors,
    }
}

pub fn build_object_stream_plan(
    manifest: &CatalogManifest,
    request: &ObjectStreamPlanRequest,
) -> ObjectStreamPlan {
    let mut decision = evaluate_object_access(
        manifest,
        &ObjectAccessRequest {
            context: request.context.clone(),
            bucket: request.bucket.clone(),
            object_key: request.object_key.clone(),
            method: request.method.clone(),
            presigned: false,
        },
    );
    if !has_scope(&request.context, "udb:stream") {
        decision
            .errors
            .push("scope udb:stream is required".to_string());
    }
    if request.object_key.trim().is_empty() {
        decision.errors.push("object_key is required".to_string());
    }
    if request.method.eq_ignore_ascii_case("PUT") {
        if request.chunk_count == 0 {
            decision
                .errors
                .push("PUT stream requires at least one chunk".to_string());
        }
        if !request.final_chunk_seen {
            decision
                .errors
                .push("PUT stream must end with final_chunk=true".to_string());
        }
    }

    let store = manifest.stores.iter().find(|store| {
        matches!(store.store_kind.as_str(), "object" | "blob" | "storage")
            && store.resource_name == request.bucket
    });
    ObjectStreamPlan {
        allowed: decision.errors.is_empty(),
        resource_uri: decision.resource_uri,
        backend: store.map(|store| store.backend.clone()).unwrap_or_default(),
        method: request.method.to_ascii_uppercase(),
        requires_server_side_encryption: store
            .map(|store| store_option_bool(store, "server_side_encryption"))
            .unwrap_or(false),
        errors: decision.errors,
    }
}

pub fn build_audit_event(
    context: &RequestContext,
    event_type: &str,
    resource_uri: &str,
    checksum_sha256: &str,
) -> AuditEvent {
    AuditEvent {
        event_type: event_type.to_string(),
        tenant_id: context.tenant_id.clone(),
        user_id: context.user_id.clone(),
        correlation_id: context.correlation_id.clone(),
        purpose: context.purpose.clone(),
        resource_uri: resource_uri.to_string(),
        checksum_sha256: checksum_sha256.to_string(),
    }
}

pub fn build_generic_dispatch_plan(
    manifest: &CatalogManifest,
    request: &GenericDispatchRequest,
) -> GenericDispatchPlan {
    let mut errors = Vec::new();
    if request.context.tenant_id.trim().is_empty() {
        errors.push("tenant_id is required".to_string());
    }
    if request.context.purpose.trim().is_empty() {
        errors.push("purpose is required".to_string());
    }
    if !has_scope(&request.context, "udb:dispatch") {
        errors.push("scope udb:dispatch is required".to_string());
    }

    let store_kind = normalize_store_kind(&request.store_kind);
    let Some(store) = manifest.stores.iter().find(|store| {
        normalize_store_kind(&store.store_kind) == store_kind
            && (store.resource_name == request.resource_name
                || store.logical_name == request.resource_name)
    }) else {
        return GenericDispatchPlan {
            store_kind,
            operation: request.operation.clone(),
            errors: vec![format!(
                "unknown {} resource {}",
                request.store_kind, request.resource_name
            )],
            ..GenericDispatchPlan::default()
        };
    };

    GenericDispatchPlan {
        store_kind,
        backend: store.backend.clone(),
        resource_uri: format!(
            "{}://{}",
            normalize_store_kind(&store.store_kind),
            if store.namespace.trim().is_empty() {
                store.resource_name.clone()
            } else {
                format!("{}/{}", store.namespace, store.resource_name)
            }
        ),
        dsn_env_key: store.dsn_env_key.clone(),
        operation: request.operation.clone(),
        errors,
    }
}

// `table_for_message` moved to `crate::generation::manifest_index` so the
// WASM-portable `udb-portable` crate can resolve `crate::broker::table_for_message`
// (the one broker fn the IR→SQL compilers call) without this native module.
// Re-exported here so server call-sites (`crate::broker::table_for_message`,
// `crate::planning::broker::table_for_message`) are unchanged.
pub use crate::generation::manifest_index::{
    TableLookup, TableLookupError, describe_table_lookup_miss, resolve_table_for_message,
    table_for_message, table_lookup,
};

fn filter_columns(
    value: &Value,
    allowed: &BTreeSet<String>,
    errors: &mut Vec<String>,
) -> Vec<String> {
    let mut out = Vec::new();
    collect_filter_columns(value, allowed, errors, &mut out);
    out.sort();
    out.dedup();
    out
}

fn collect_filter_columns(
    value: &Value,
    allowed: &BTreeSet<String>,
    errors: &mut Vec<String>,
    out: &mut Vec<String>,
) {
    match value {
        Value::Object(map) => {
            for (key, nested) in map {
                let normalized = key.to_ascii_lowercase();
                if matches!(normalized.as_str(), "$raw" | "raw" | "sql" | "where_sql") {
                    errors.push(format!("raw SQL filter key '{}' is not allowed", key));
                    continue;
                }
                if matches!(normalized.as_str(), "$and" | "$or" | "and" | "or") {
                    collect_filter_columns(nested, allowed, errors, out);
                    continue;
                }
                if allowed.contains(&normalized) {
                    out.push(normalized);
                    collect_filter_columns(nested, allowed, errors, out);
                } else if !is_operator(&normalized) {
                    errors.push(format!("unknown filter field {}", key));
                }
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_filter_columns(item, allowed, errors, out);
            }
        }
        _ => {}
    }
}

/// Columns that constrain EVERY row a read returns or a delete affects — i.e.
/// those in the top-level AND context, descending through `$and` but NOT `$or`.
///
/// Tenant/project isolation MUST check this set, not the broad `filter_columns`
/// (which collects a column appearing anywhere, including inside an `$or`
/// branch). A predicate inside `$or` does not isolate — `{"$or":[{tenant_id:a},
/// {status:open}]}` returns rows that satisfy EITHER arm, so it can leak rows of
/// other tenants while still "mentioning" `tenant_id` (X-4).
fn mandatory_and_columns(value: &Value, allowed: &BTreeSet<String>) -> Vec<String> {
    let mut out = Vec::new();
    collect_mandatory_and_columns(value, allowed, &mut out);
    out.sort();
    out.dedup();
    out
}

fn collect_mandatory_and_columns(value: &Value, allowed: &BTreeSet<String>, out: &mut Vec<String>) {
    match value {
        Value::Object(map) => {
            for (key, nested) in map {
                let normalized = key.to_ascii_lowercase();
                if matches!(normalized.as_str(), "$and" | "and") {
                    // Every arm of an AND constrains every row → still mandatory.
                    collect_mandatory_and_columns(nested, allowed, out);
                } else if matches!(normalized.as_str(), "$or" | "or") {
                    // An OR arm does NOT constrain every row → not mandatory. Skip.
                    continue;
                } else if allowed.contains(&normalized) {
                    out.push(normalized);
                }
            }
        }
        Value::Array(items) => {
            // Reached only as an `$and`'s array value → every item is mandatory.
            for item in items {
                collect_mandatory_and_columns(item, allowed, out);
            }
        }
        _ => {}
    }
}

fn is_operator(value: &str) -> bool {
    matches!(
        value,
        "$eq" | "$ne" | "$gt" | "$gte" | "$lt" | "$lte" | "$in" | "$like" | "$is_null"
            // GAP 6: PostgreSQL-specific operators
            | "$not_null" | "$ilike" | "$contains" | "$contained_by"
            | "$has_key" | "$overlaps" | "$matches"
    )
}

fn tenant_column(table: &ManifestTable) -> String {
    resolve_tenant_column(table).unwrap_or_default().to_string()
}

/// Resolve the project-isolation column for a table: the proto-declared
/// `project_column: true` designator first (authoritative), else the well-known
/// `project_id` name. Mirrors [`tenant_column`]. Empty when the table has no
/// project key.
fn project_column(table: &ManifestTable) -> String {
    resolve_project_column(table)
        .unwrap_or_default()
        .to_string()
}

fn unresolved_tenant_column_error(table: &ManifestTable) -> String {
    format!(
        "tenant-scoped table {}.{} has no resolvable tenant column",
        table.schema, table.table
    )
}

fn masked_columns(table: &ManifestTable) -> Vec<String> {
    table
        .columns
        .iter()
        .filter(|column| column.security.is_pii || column.security.mask_in_logs)
        .map(|column| column.column_name.clone())
        .collect()
}

fn cache_key_pattern(manifest: &CatalogManifest, table: &ManifestTable) -> String {
    manifest
        .stores
        .iter()
        .find(|store| {
            store.store_kind == "cache"
                && store.owner_schema == table.schema
                && store.owner_table == table.table
        })
        .and_then(|store| {
            store
                .options
                .iter()
                .find(|option| option.key == "key_pattern")
                .map(|option| option.value.clone())
        })
        .unwrap_or_default()
}

fn has_scope(context: &RequestContext, required: &str) -> bool {
    context
        .scopes
        .iter()
        .any(|scope| scope == required || scope == "udb:*" || scope == "*")
}

fn vector_filter_fields(value: &Value, errors: &mut Vec<String>) -> Vec<String> {
    let mut fields = Vec::new();
    collect_vector_filter_fields(value, errors, &mut fields);
    fields.sort();
    fields.dedup();
    fields
}

fn collect_vector_filter_fields(value: &Value, errors: &mut Vec<String>, out: &mut Vec<String>) {
    match value {
        Value::Object(map) => {
            for (key, nested) in map {
                let normalized = key.to_ascii_lowercase();
                if matches!(normalized.as_str(), "$raw" | "raw" | "sql" | "where_sql") {
                    errors.push(format!("raw vector filter key '{}' is not allowed", key));
                    continue;
                }
                if !normalized.starts_with('$') {
                    out.push(normalized);
                }
                collect_vector_filter_fields(nested, errors, out);
            }
        }
        Value::Array(items) => {
            for item in items {
                collect_vector_filter_fields(item, errors, out);
            }
        }
        _ => {}
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct CompiledFilter {
    sql: String,
    next_param: usize,
}

fn compile_filter_predicates(
    value: &Value,
    allowed: &BTreeSet<String>,
    encrypted: &std::collections::BTreeMap<String, String>,
    errors: &mut Vec<String>,
    parameter_columns: &mut Vec<String>,
    start_param: usize,
    backend_kind: &BackendKind,
) -> CompiledFilter {
    match value {
        Value::Object(map) => {
            let mut parts = Vec::new();
            let mut next_param = start_param;
            for (key, nested) in map {
                let normalized = key.to_ascii_lowercase();
                if matches!(normalized.as_str(), "$raw" | "raw" | "sql" | "where_sql") {
                    errors.push(format!("raw SQL filter key '{}' is not allowed", key));
                    continue;
                }
                if matches!(normalized.as_str(), "$and" | "and" | "$or" | "or") {
                    let joiner = if normalized.contains("or") {
                        " OR "
                    } else {
                        " AND "
                    };
                    let compiled = compile_filter_group(
                        nested,
                        allowed,
                        encrypted,
                        errors,
                        parameter_columns,
                        next_param,
                        joiner,
                        backend_kind,
                    );
                    next_param = compiled.next_param;
                    if !compiled.sql.is_empty() {
                        parts.push(format!("({})", compiled.sql));
                    }
                    continue;
                }
                if !allowed.contains(&normalized) {
                    if !is_operator(&normalized) {
                        errors.push(format!("unknown filter field {}", key));
                    }
                    continue;
                }
                // W2: FAIL CLOSED on encrypted columns — AEAD ciphertext is
                // randomized, so this predicate silently matches nothing.
                if let Some(index_column) = encrypted.get(&normalized) {
                    if index_column.is_empty() {
                        errors.push(format!(
                            "filter on encrypted column \"{normalized}\" cannot match (AEAD \
                             ciphertext is randomized); declare a blind-index column to make \
                             this column filterable"
                        ));
                    } else {
                        errors.push(format!(
                            "filter on encrypted column \"{normalized}\" cannot match (AEAD \
                             ciphertext is randomized); filter on \"{index_column}\" (its blind \
                             index) instead"
                        ));
                    }
                    continue;
                }
                let compiled = compile_column_predicate(
                    &normalized,
                    nested,
                    errors,
                    parameter_columns,
                    next_param,
                    backend_kind,
                );
                next_param = compiled.next_param;
                if !compiled.sql.is_empty() {
                    parts.push(compiled.sql);
                }
            }
            CompiledFilter {
                sql: if parts.len() > 1 {
                    format!("({})", parts.join(" AND "))
                } else {
                    parts.join(" AND ")
                },
                next_param,
            }
        }
        _ => CompiledFilter {
            sql: String::new(),
            next_param: start_param,
        },
    }
}

fn compile_filter_group(
    value: &Value,
    allowed: &BTreeSet<String>,
    encrypted: &std::collections::BTreeMap<String, String>,
    errors: &mut Vec<String>,
    parameter_columns: &mut Vec<String>,
    start_param: usize,
    joiner: &str,
    backend_kind: &BackendKind,
) -> CompiledFilter {
    let mut parts = Vec::new();
    let mut next_param = start_param;
    if let Value::Array(items) = value {
        for item in items {
            let compiled = compile_filter_predicates(
                item,
                allowed,
                encrypted,
                errors,
                parameter_columns,
                next_param,
                backend_kind,
            );
            next_param = compiled.next_param;
            if !compiled.sql.is_empty() {
                parts.push(compiled.sql);
            }
        }
    } else {
        errors.push("logical filter operator requires an array".to_string());
    }
    CompiledFilter {
        sql: parts.join(joiner),
        next_param,
    }
}

fn compile_column_predicate(
    column: &str,
    value: &Value,
    errors: &mut Vec<String>,
    parameter_columns: &mut Vec<String>,
    start_param: usize,
    backend_kind: &BackendKind,
) -> CompiledFilter {
    if let Value::Object(map) = value {
        let mut parts = Vec::new();
        let mut next_param = start_param;
        for (op, op_value) in map {
            let Some(sql_op) = sql_operator(op) else {
                errors.push(format!("unsupported filter operator {}", op));
                continue;
            };
            // Operators that need no bound parameter
            if sql_op == "IS NULL" {
                parts.push(format!("{} IS NULL", qi(column)));
                continue;
            }
            if sql_op == "IS NOT NULL" {
                parts.push(format!("{} IS NOT NULL", qi(column)));
                continue;
            }
            if sql_op == "IN" {
                if !op_value.is_array() {
                    errors.push(format!("$in filter on {} requires an array value", column));
                    continue;
                }
                // PostgreSQL: col = ANY($N) where $N is bound as a text array
                parameter_columns.push(column.to_string());
                parts.push(format!("{} = ANY(${})", qi(column), next_param));
                next_param += 1;
                continue;
            }
            if matches!(sql_op, "@>" | "<@" | "?" | "@@" | "&&")
                && !matches!(backend_kind, &BackendKind::Postgres)
            {
                errors.push(format!(
                    "filter operator '{}' on column '{}' is PostgreSQL-only and cannot be used with backend '{}'",
                    sql_op,
                    column,
                    backend_kind.as_str()
                ));
                continue;
            }
            // GAP 6: JSONB containment / array overlap — bind value as JSONB/array cast
            if matches!(sql_op, "@>" | "<@") {
                parameter_columns.push(column.to_string());
                parts.push(format!("{} {} ${}::jsonb", qi(column), sql_op, next_param));
                next_param += 1;
                continue;
            }
            // GAP 6: JSONB key-exists operator takes a text key, no cast needed
            if sql_op == "?" {
                parameter_columns.push(column.to_string());
                parts.push(format!("{} ? ${}", qi(column), next_param));
                next_param += 1;
                continue;
            }
            // GAP 6: tsvector @@ operator — wrap RHS with to_tsquery
            if sql_op == "@@" {
                parameter_columns.push(column.to_string());
                parts.push(format!(
                    "{} @@ to_tsquery('simple', ${})",
                    qi(column),
                    next_param
                ));
                next_param += 1;
                continue;
            }
            // `$overlaps` (`&&`) is the Postgres array-overlap operator: it needs a
            // matching array cast on the bound parameter, which the planner cannot
            // synthesize without the column's element type. The generic `col && $N`
            // fallthrough below would bind text and fail at execution
            // ("operator does not exist: <type> && text"), so reject it here with a
            // clear message rather than emitting invalid SQL.
            if sql_op == "&&" {
                errors.push(format!(
                    "$overlaps on column '{}' is not supported (array-overlap requires a typed \
                     array cast); use $contains/$contained_by (@>/<@) for JSONB columns",
                    column
                ));
                continue;
            }
            // GAP 29: Guard against leading-wildcard full-table-scans via $like/$ilike.
            // A pattern beginning with '%' or '_' forces a sequential scan on every
            // row; B-tree indexes cannot be used. Reject such patterns at the query
            // planner layer so DoS via sequential scan is not possible.
            if matches!(sql_op, "LIKE" | "ILIKE")
                && let Value::String(pattern) = op_value
            {
                let guard_pattern = unescape_like_pattern(pattern);
                if guard_pattern.starts_with('%') || guard_pattern.starts_with('_') {
                    errors.push(format!(
                        "$like/$ilike on column '{}' starts with a wildcard — \
                         this forces a full sequential scan; use a full-text search \
                         index ($matches) or add a trigram GIN index instead",
                        column
                    ));
                    continue;
                }
                if pattern.len() > 256 {
                    errors.push(format!(
                        "$like/$ilike pattern on column '{}' exceeds 256 characters",
                        column
                    ));
                    continue;
                }
            }
            parameter_columns.push(column.to_string());
            if matches!(sql_op, "LIKE" | "ILIKE") {
                parts.push(format!(
                    "{} {} ${} ESCAPE '\\'",
                    qi(column),
                    sql_op,
                    next_param
                ));
            } else {
                parts.push(format!("{} {} ${}", qi(column), sql_op, next_param));
            }
            next_param += 1;
        }
        CompiledFilter {
            sql: parts.join(" AND "),
            next_param,
        }
    } else {
        parameter_columns.push(column.to_string());
        CompiledFilter {
            sql: format!("{} = ${}", qi(column), start_param),
            next_param: start_param + 1,
        }
    }
}

fn effective_sql_backend(context: &RequestContext) -> BackendKind {
    if context.target_backend.trim().is_empty() {
        return BackendKind::Postgres;
    }
    BackendKind::from_store_kind("sql", &context.target_backend).unwrap_or(BackendKind::Postgres)
}

fn unescape_like_pattern(pattern: &str) -> String {
    let mut out = String::with_capacity(pattern.len());
    let mut chars = pattern.chars();
    while let Some(ch) = chars.next() {
        if ch == '\\'
            && let Some(next) = chars.next()
        {
            out.push(next);
            continue;
        }
        out.push(ch);
    }
    out
}

fn logical_value_from_json(value: &Value) -> LogicalValue {
    match value {
        Value::Null => LogicalValue::Null,
        Value::Bool(v) => LogicalValue::Bool(*v),
        Value::Number(n) => n
            .as_i64()
            .map(LogicalValue::Int)
            .or_else(|| n.as_f64().map(LogicalValue::Float))
            .unwrap_or_else(|| LogicalValue::Json(value.clone())),
        Value::String(v) => LogicalValue::String(v.clone()),
        Value::Array(values) => LogicalValue::Array(
            values
                .iter()
                .map(logical_value_from_json)
                .collect::<Vec<_>>(),
        ),
        Value::Object(_) => LogicalValue::Json(value.clone()),
    }
}

fn logical_filter_from_planner_json(
    value: &Value,
    allowed: &BTreeSet<String>,
    errors: &mut Vec<String>,
) -> Option<LogicalFilter> {
    let Value::Object(map) = value else {
        return None;
    };
    let mut clauses = Vec::new();
    for (key, nested) in map {
        let normalized = key.to_ascii_lowercase();
        if matches!(normalized.as_str(), "$raw" | "raw" | "sql" | "where_sql") {
            errors.push(format!("raw SQL filter key '{}' is not allowed", key));
            continue;
        }
        if matches!(normalized.as_str(), "$and" | "and" | "$or" | "or") {
            let Some(items) = nested.as_array() else {
                errors.push("logical filter operator requires an array".to_string());
                continue;
            };
            let mut branches = Vec::new();
            for item in items {
                if let Some(branch) = logical_filter_from_planner_json(item, allowed, errors) {
                    branches.push(branch);
                }
            }
            clauses.push(if normalized.contains("or") {
                LogicalFilter::Or(branches)
            } else {
                LogicalFilter::And(branches)
            });
            continue;
        }
        if !allowed.contains(&normalized) {
            if !is_operator(&normalized) {
                errors.push(format!("unknown filter field {}", key));
            }
            continue;
        }
        if let Some(clause) = logical_column_filter_from_json(&normalized, nested, errors) {
            clauses.push(clause);
        }
    }

    match clauses.len() {
        0 => None,
        1 => clauses.into_iter().next(),
        _ => Some(LogicalFilter::And(clauses)),
    }
}

fn logical_column_filter_from_json(
    column: &str,
    value: &Value,
    errors: &mut Vec<String>,
) -> Option<LogicalFilter> {
    let Value::Object(map) = value else {
        return Some(LogicalFilter::Comparison {
            field: column.to_string(),
            op: ComparisonOp::Eq,
            value: logical_value_from_json(value),
        });
    };

    let mut clauses = Vec::new();
    for (op, op_value) in map {
        let normalized = op.to_ascii_lowercase();
        match normalized.as_str() {
            "$eq" | "=" => clauses.push(LogicalFilter::Comparison {
                field: column.to_string(),
                op: ComparisonOp::Eq,
                value: logical_value_from_json(op_value),
            }),
            "$ne" | "!=" => clauses.push(LogicalFilter::Comparison {
                field: column.to_string(),
                op: ComparisonOp::Ne,
                value: logical_value_from_json(op_value),
            }),
            "$gt" | ">" => clauses.push(LogicalFilter::Comparison {
                field: column.to_string(),
                op: ComparisonOp::Gt,
                value: logical_value_from_json(op_value),
            }),
            "$gte" | ">=" => clauses.push(LogicalFilter::Comparison {
                field: column.to_string(),
                op: ComparisonOp::Ge,
                value: logical_value_from_json(op_value),
            }),
            "$lt" | "<" => clauses.push(LogicalFilter::Comparison {
                field: column.to_string(),
                op: ComparisonOp::Lt,
                value: logical_value_from_json(op_value),
            }),
            "$lte" | "<=" => clauses.push(LogicalFilter::Comparison {
                field: column.to_string(),
                op: ComparisonOp::Le,
                value: logical_value_from_json(op_value),
            }),
            "$like" | "like" | "$ilike" | "ilike" => {
                let Some(pattern) = op_value.as_str() else {
                    errors.push(format!(
                        "{} filter on {} requires a string value",
                        op, column
                    ));
                    continue;
                };
                let guard_pattern = unescape_like_pattern(pattern);
                if guard_pattern.starts_with('%') || guard_pattern.starts_with('_') {
                    errors.push(format!(
                        "$like/$ilike on column '{}' starts with a wildcard — \
                         this forces a full sequential scan; use a full-text search \
                         index ($matches) or add a trigram GIN index instead",
                        column
                    ));
                    continue;
                }
                if pattern.len() > 256 {
                    errors.push(format!(
                        "$like/$ilike pattern on column '{}' exceeds 256 characters",
                        column
                    ));
                    continue;
                }
                clauses.push(LogicalFilter::Comparison {
                    field: column.to_string(),
                    op: if normalized.contains("ilike") {
                        ComparisonOp::ILike
                    } else {
                        ComparisonOp::Like
                    },
                    value: LogicalValue::String(pattern.to_string()),
                });
            }
            "$in" | "in" => {
                let Some(values) = op_value.as_array() else {
                    errors.push(format!("$in filter on {} requires an array value", column));
                    continue;
                };
                clauses.push(LogicalFilter::InList {
                    field: column.to_string(),
                    values: values.iter().map(logical_value_from_json).collect(),
                });
            }
            "$is_null" | "is_null" => clauses.push(LogicalFilter::IsNull(column.to_string())),
            "$not_null" | "is_not_null" => clauses.push(LogicalFilter::Not(Box::new(
                LogicalFilter::IsNull(column.to_string()),
            ))),
            "$contains" | "contains" | "$contained_by" | "contained_by" | "$has_key"
            | "has_key" | "$overlaps" | "overlaps" | "$matches" | "matches" => {
                errors.push(format!(
                    "filter operator '{}' on column '{}' has no neutral IR equivalent yet",
                    op, column
                ));
            }
            _ => errors.push(format!("unsupported filter operator {}", op)),
        }
    }

    match clauses.len() {
        0 => None,
        1 => clauses.into_iter().next(),
        _ => Some(LogicalFilter::And(clauses)),
    }
}

// Phase I: broker.rs split into helper modules.
mod helpers;
pub(crate) use helpers::*;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generation::{
        ManifestColumn, ManifestColumnSecurity, ManifestIndex, ManifestTableSecurity,
    };
    use crate::ir::compile::{
        CompileContext, CompileOperation, CompiledRendering, compile_for_backend,
    };
    use serde_json::json;

    // X-4: a tenant predicate inside `$or` must NOT satisfy isolation, because an
    // OR arm does not constrain every returned row.
    #[test]
    fn mandatory_and_columns_excludes_or_branches() {
        let allowed: BTreeSet<String> = ["tenant_id", "status", "id"]
            .into_iter()
            .map(String::from)
            .collect();

        // Top-level AND context: tenant_id is mandatory.
        let top = json!({"tenant_id": "t1", "status": "open"});
        assert!(mandatory_and_columns(&top, &allowed).contains(&"tenant_id".to_string()));

        // tenant_id ANDed with an $or group: still mandatory.
        let anded = json!({"tenant_id": "t1", "$or": [{"status": "open"}, {"id": 1}]});
        assert!(mandatory_and_columns(&anded, &allowed).contains(&"tenant_id".to_string()));

        // tenant_id buried INSIDE an $or: NOT mandatory (the leak X-4 closes).
        let in_or = json!({"$or": [{"tenant_id": "t1"}, {"status": "open"}]});
        assert!(!mandatory_and_columns(&in_or, &allowed).contains(&"tenant_id".to_string()));

        // Nested $and inside the tree keeps its columns mandatory.
        let nested_and = json!({"$and": [{"tenant_id": "t1"}, {"status": "open"}]});
        assert!(mandatory_and_columns(&nested_and, &allowed).contains(&"tenant_id".to_string()));
    }

    fn test_column(name: &str) -> ManifestColumn {
        ManifestColumn {
            field_name: name.to_string(),
            column_name: name.to_string(),
            sql_type: "TEXT".to_string(),
            is_primary: name == "id",
            ..ManifestColumn::default()
        }
    }

    // ── W7: partial-update planner ───────────────────────────────────────────

    fn update_test_manifest() -> CatalogManifest {
        let mut attempts = test_column("login_attempts");
        attempts.sql_type = "INTEGER".to_string();
        let table = ManifestTable {
            columns: vec![
                test_column("id"),
                test_column("tenant_id"),
                test_column("status"),
                attempts,
            ],
            table_security: ManifestTableSecurity {
                tenant_column: "tenant_id".to_string(),
                ..ManifestTableSecurity::default()
            },
            ..ManifestTable::default()
        };
        test_manifest(table)
    }

    #[test]
    fn update_plan_compiles_set_increment_where_with_isolation() {
        let manifest = update_test_manifest();
        let plan = build_update_plan(
            &manifest,
            &UpdatePlanRequest {
                context: RequestContext {
                    tenant_id: "t1".to_string(),
                    purpose: "unit-test".to_string(),
                    scopes: vec!["udb:write".to_string()],
                    ..RequestContext::default()
                },
                message_type: "acme.test.v1.Widget".to_string(),
                filter: json!({"id": "w1", "tenant_id": "t1"}),
                changes: json!({"status": "closed"}),
                increments: vec![("login_attempts".to_string(), 1.0)],
                return_record: false,
            },
        );
        assert_eq!(plan.errors, Vec::<String>::new());
        // SET params first (changes sorted by column, then increments), filter after.
        assert!(
            plan.sql.starts_with(
                "UPDATE \"public\".\"widgets\" SET \"status\" = $1, \"login_attempts\" = \"login_attempts\" + $2 WHERE "
            ),
            "unexpected sql: {}",
            plan.sql
        );
        assert_eq!(
            plan.parameter_columns,
            ["status", "login_attempts", "id", "tenant_id"]
        );
        assert!(!plan.sql.contains("RETURNING"));
        assert_eq!(plan.operation, "update");
        assert_eq!(plan.audit_event_type, "udb.sql.update");
    }

    #[test]
    fn update_plan_return_record_appends_returning() {
        let manifest = update_test_manifest();
        let plan = build_update_plan(
            &manifest,
            &UpdatePlanRequest {
                context: RequestContext {
                    tenant_id: "t1".to_string(),
                    purpose: "unit-test".to_string(),
                    scopes: vec!["udb:write".to_string()],
                    ..RequestContext::default()
                },
                message_type: "acme.test.v1.Widget".to_string(),
                filter: json!({"id": "w1", "tenant_id": "t1"}),
                changes: json!({"status": "open"}),
                increments: Vec::new(),
                return_record: true,
            },
        );
        assert_eq!(plan.errors, Vec::<String>::new());
        assert!(plan.sql.ends_with(" RETURNING *"), "sql: {}", plan.sql);
    }

    #[test]
    fn update_plan_fail_closed_shapes() {
        let manifest = update_test_manifest();
        let base = UpdatePlanRequest {
            context: RequestContext {
                tenant_id: "t1".to_string(),
                purpose: "unit-test".to_string(),
                scopes: vec!["udb:write".to_string()],
                ..RequestContext::default()
            },
            message_type: "acme.test.v1.Widget".to_string(),
            filter: json!({"id": "w1", "tenant_id": "t1"}),
            changes: json!({"status": "x"}),
            increments: Vec::new(),
            return_record: false,
        };

        // Identity/isolation columns are immutable through Update.
        for immutable in ["id", "tenant_id"] {
            let plan = build_update_plan(
                &manifest,
                &UpdatePlanRequest {
                    changes: json!({ immutable: "nope" }),
                    ..base.clone()
                },
            );
            assert!(
                plan.errors.iter().any(|e| e.contains("immutable")),
                "{immutable}: {:?}",
                plan.errors
            );
        }

        // A column cannot be both set and incremented.
        let plan = build_update_plan(
            &manifest,
            &UpdatePlanRequest {
                changes: json!({"login_attempts": 5}),
                increments: vec![("login_attempts".to_string(), 1.0)],
                ..base.clone()
            },
        );
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("both changes and increments")),
            "{:?}",
            plan.errors
        );

        // Unknown columns and empty updates are rejected.
        let plan = build_update_plan(
            &manifest,
            &UpdatePlanRequest {
                changes: json!({"no_such_column": 1}),
                ..base.clone()
            },
        );
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("unknown update column")),
            "{:?}",
            plan.errors
        );
        let plan = build_update_plan(
            &manifest,
            &UpdatePlanRequest {
                changes: json!({}),
                ..base.clone()
            },
        );
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("at least one change or increment")),
            "{:?}",
            plan.errors
        );

        // X-4 posture carries over: tenant inside $or does NOT satisfy isolation.
        let plan = build_update_plan(
            &manifest,
            &UpdatePlanRequest {
                filter: json!({"$or": [{"tenant_id": "t1"}, {"id": "w1"}]}),
                ..base.clone()
            },
        );
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("tenant isolation requires filter on tenant_id")),
            "{:?}",
            plan.errors
        );
    }

    // W2 (tip 3 stage 1): equality on an encrypted column must FAIL CLOSED with
    // a typed error naming the blind-index sibling — never silently match
    // nothing. Applies at every depth of the filter tree and to every verb that
    // compiles filters (select/delete/update share the compiler).
    #[test]
    fn encrypted_filter_fails_closed_naming_blind_index() {
        let mut mobile = test_column("mobile_number");
        mobile.security = ManifestColumnSecurity {
            is_encrypted: true,
            ..ManifestColumnSecurity::default()
        };
        let mut mobile_idx = test_column("mobile_number_idx");
        mobile_idx.security = ManifestColumnSecurity {
            is_blind_index: true,
            ..ManifestColumnSecurity::default()
        };
        let mut ssn = test_column("ssn");
        ssn.security = ManifestColumnSecurity {
            is_encrypted: true,
            ..ManifestColumnSecurity::default()
        };
        let table = ManifestTable {
            columns: vec![
                test_column("id"),
                test_column("tenant_id"),
                mobile,
                mobile_idx,
                ssn,
            ],
            table_security: ManifestTableSecurity {
                tenant_column: "tenant_id".to_string(),
                ..ManifestTableSecurity::default()
            },
            ..ManifestTable::default()
        };
        let manifest = test_manifest(table);
        let request = |filter: Value| DeletePlanRequest {
            context: RequestContext {
                tenant_id: "t1".to_string(),
                purpose: "unit-test".to_string(),
                scopes: vec!["udb:write".to_string()],
                ..RequestContext::default()
            },
            message_type: "acme.test.v1.Widget".to_string(),
            filter,
        };

        // Top-level predicate on the encrypted column: typed error names the idx.
        let plan = build_delete_plan(
            &manifest,
            &request(json!({"tenant_id": "t1", "mobile_number": "+15550100"})),
        );
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("encrypted column \"mobile_number\"")
                    && e.contains("\"mobile_number_idx\"")),
            "{:?}",
            plan.errors
        );

        // Nested inside $or: still caught.
        let plan = build_delete_plan(
            &manifest,
            &request(json!({"tenant_id": "t1", "$or": [{"mobile_number": "x"}, {"id": "w1"}]})),
        );
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("encrypted column \"mobile_number\"")),
            "{:?}",
            plan.errors
        );

        // Encrypted column WITHOUT a blind index: generic guidance.
        let plan = build_delete_plan(&manifest, &request(json!({"tenant_id": "t1", "ssn": "x"})));
        assert!(
            plan.errors
                .iter()
                .any(|e| e.contains("encrypted column \"ssn\"")
                    && e.contains("declare a blind-index column")),
            "{:?}",
            plan.errors
        );

        // Filtering on the blind-index sibling itself is legal.
        let plan = build_delete_plan(
            &manifest,
            &request(json!({"tenant_id": "t1", "mobile_number_idx": "hmac-token"})),
        );
        assert!(
            !plan.errors.iter().any(|e| e.contains("encrypted column")),
            "{:?}",
            plan.errors
        );
    }

    fn test_manifest(mut table: ManifestTable) -> CatalogManifest {
        table.message_name = "acme.test.v1.Widget".to_string();
        table.schema = "public".to_string();
        table.table = "widgets".to_string();
        table.primary_key = vec!["id".to_string()];
        CatalogManifest {
            tables: vec![table],
            ..CatalogManifest::default()
        }
    }

    fn colliding_auth_catalog() -> CatalogManifest {
        let mut tables = Vec::new();
        for (package, schema) in [
            ("acme.authn.entity.v1", "acme_authn"),
            ("udb.core.authn.entity.v1", "udb_authn"),
        ] {
            for (message, physical) in [("OTP", "otps"), ("User", "users"), ("Session", "sessions")]
            {
                tables.push(ManifestTable {
                    message_name: message.to_string(),
                    proto_package: package.to_string(),
                    schema: schema.to_string(),
                    table: physical.to_string(),
                    primary_key: vec!["id".to_string()],
                    columns: vec![test_column("id"), test_column("status")],
                    ..ManifestTable::default()
                });
            }
        }
        CatalogManifest {
            checksum_sha256: "catalog-fqn-planner-acceptance".to_string(),
            tables,
            ..CatalogManifest::default()
        }
    }

    fn read_context() -> RequestContext {
        RequestContext {
            tenant_id: "tenant-a".to_string(),
            purpose: "test".to_string(),
            scopes: vec!["udb:read".to_string()],
            ..RequestContext::default()
        }
    }

    fn write_context() -> RequestContext {
        RequestContext {
            tenant_id: "tenant-a".to_string(),
            purpose: "test".to_string(),
            scopes: vec!["udb:write".to_string()],
            ..RequestContext::default()
        }
    }

    fn compile_pg_sql(
        manifest: &CatalogManifest,
        context: &RequestContext,
        op: CompileOperation<'_>,
    ) -> (String, Vec<LogicalValue>) {
        let compile_ctx = CompileContext::new(manifest)
            .with_tenant(&context.tenant_id)
            .with_project(&context.project_id);
        let rendering = compile_for_backend(&BackendKind::Postgres, op, &compile_ctx)
            .expect("Postgres compiler must be present in this build")
            .expect("data-plane bridge should compile for Postgres");
        match rendering {
            CompiledRendering::Sql {
                backend,
                statement,
                params,
            } => {
                assert_eq!(backend, BackendKind::Postgres);
                (statement, params)
            }
            other => panic!("expected Postgres SQL rendering, got {other:?}"),
        }
    }

    #[test]
    fn request_context_consistency_helpers() {
        let strong = RequestContext {
            consistency: "strong".to_string(),
            max_replica_lag_ms: 250,
            ..RequestContext::default()
        };
        assert!(strong.requires_primary_read());
        assert_eq!(
            strong.replica_lag_override(),
            Some(std::time::Duration::from_millis(250))
        );

        let eventual = RequestContext {
            consistency: "eventual".to_string(),
            ..RequestContext::default()
        };
        assert!(!eventual.requires_primary_read());
        assert_eq!(eventual.replica_lag_override(), None);
    }

    #[test]
    fn colliding_catalog_select_and_upsert_route_only_by_exact_fqn() {
        let manifest = colliding_auth_catalog();
        for (message_type, expected_schema) in [
            ("acme.authn.entity.v1.OTP", "acme_authn"),
            ("udb.core.authn.entity.v1.OTP", "udb_authn"),
        ] {
            let select = build_select_query_plan(
                &manifest,
                &SelectPlanRequest {
                    context: read_context(),
                    message_type: message_type.to_string(),
                    filter: json!({"status": "pending"}),
                    ..SelectPlanRequest::default()
                },
            );
            assert!(select.errors.is_empty(), "{:?}", select.errors);
            assert_eq!(select.schema, expected_schema);
            assert_eq!(select.table, "otps");

            let upsert = build_upsert_plan(
                &manifest,
                &UpsertPlanRequest {
                    context: write_context(),
                    message_type: message_type.to_string(),
                    record: json!({"id": "otp-1", "status": "pending"}),
                    ..UpsertPlanRequest::default()
                },
            );
            assert!(upsert.errors.is_empty(), "{:?}", upsert.errors);
            assert_eq!(upsert.resource_uri, format!("sql://{expected_schema}/otps"));
        }

        let ambiguous_select = build_select_query_plan(
            &manifest,
            &SelectPlanRequest {
                context: read_context(),
                message_type: "OTP".to_string(),
                ..SelectPlanRequest::default()
            },
        );
        assert!(
            ambiguous_select
                .errors
                .iter()
                .any(|error| error.contains("ambiguous message type 'OTP'")
                    && error.contains("acme.authn.entity.v1.OTP")
                    && error.contains("udb.core.authn.entity.v1.OTP")),
            "{:?}",
            ambiguous_select.errors
        );

        let ambiguous_upsert = build_upsert_plan(
            &manifest,
            &UpsertPlanRequest {
                context: write_context(),
                message_type: "OTP".to_string(),
                record: json!({"id": "otp-1"}),
                ..UpsertPlanRequest::default()
            },
        );
        assert!(
            ambiguous_upsert
                .errors
                .iter()
                .any(|error| error.contains("ambiguous message type 'OTP'")),
            "{:?}",
            ambiguous_upsert.errors
        );
        assert!(ambiguous_upsert.resource_uri.is_empty());
    }

    #[test]
    fn planner_resolves_system_tenant_column() {
        let mut tenant = test_column("_tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            enable_rls: true,
            columns: vec![test_column("id"), tenant, test_column("status")],
            ..ManifestTable::default()
        });

        let plan = build_select_query_plan(
            &manifest,
            &SelectPlanRequest {
                context: read_context(),
                message_type: "Widget".to_string(),
                filter: json!({"_tenant_id": "tenant-a"}),
                ..SelectPlanRequest::default()
            },
        );

        assert_eq!(plan.tenant_column, "_tenant_id");
        assert!(plan.errors.is_empty(), "{:?}", plan.errors);
    }

    #[test]
    fn planner_fails_closed_for_scoped_table_without_tenant_column() {
        let manifest = test_manifest(ManifestTable {
            enable_rls: true,
            table_security: ManifestTableSecurity {
                tenant_isolation_mode: "tenant".to_string(),
                ..ManifestTableSecurity::default()
            },
            columns: vec![test_column("id"), test_column("status")],
            ..ManifestTable::default()
        });

        let select = build_select_query_plan(
            &manifest,
            &SelectPlanRequest {
                context: read_context(),
                message_type: "Widget".to_string(),
                filter: json!({"status": "open"}),
                ..SelectPlanRequest::default()
            },
        );
        assert!(
            select
                .errors
                .iter()
                .any(|error| error.contains("no resolvable tenant column")),
            "{:?}",
            select.errors
        );

        let upsert = build_upsert_plan(
            &manifest,
            &UpsertPlanRequest {
                context: write_context(),
                message_type: "Widget".to_string(),
                record: json!({"id": "w1", "status": "open"}),
                ..UpsertPlanRequest::default()
            },
        );
        assert!(
            upsert
                .errors
                .iter()
                .any(|error| error.contains("no resolvable tenant column")),
            "{:?}",
            upsert.errors
        );

        let delete = build_delete_plan(
            &manifest,
            &DeletePlanRequest {
                context: write_context(),
                message_type: "Widget".to_string(),
                filter: json!({"status": "open"}),
            },
        );
        assert!(
            delete
                .errors
                .iter()
                .any(|error| error.contains("no resolvable tenant column")),
            "{:?}",
            delete.errors
        );
    }

    #[test]
    fn like_escape_clause_renders_single_backslash_character() {
        let manifest = CatalogManifest {
            tables: vec![ManifestTable {
                message_name: "Doc".to_string(),
                schema: "public".to_string(),
                table: "docs".to_string(),
                columns: vec![
                    ManifestColumn {
                        field_name: "tenant_id".to_string(),
                        column_name: "tenant_id".to_string(),
                        security: ManifestColumnSecurity::default(),
                        ..ManifestColumn::default()
                    },
                    ManifestColumn {
                        field_name: "name".to_string(),
                        column_name: "name".to_string(),
                        security: ManifestColumnSecurity::default(),
                        ..ManifestColumn::default()
                    },
                ],
                ..ManifestTable::default()
            }],
            ..CatalogManifest::default()
        };
        let request = SelectPlanRequest {
            context: RequestContext {
                tenant_id: "tenant-a".to_string(),
                purpose: "test".to_string(),
                scopes: vec!["udb:read".to_string()],
                ..RequestContext::default()
            },
            message_type: "Doc".to_string(),
            filter: json!({
                "tenant_id": "tenant-a",
                "name": {
                    "$like": "abc\\_%"
                }
            }),
            ..SelectPlanRequest::default()
        };

        let plan = build_select_query_plan(&manifest, &request);

        assert!(
            plan.errors.is_empty(),
            "unexpected planner errors: {:?}",
            plan.errors
        );
        assert!(
            plan.sql.contains("ESCAPE '\\'"),
            "rendered SQL should contain one backslash between quotes: {}",
            plan.sql
        );
        assert!(
            !plan.sql.contains("ESCAPE '\\\\'"),
            "rendered SQL should not contain two backslashes between quotes: {}",
            plan.sql
        );
    }

    #[test]
    fn select_planner_logical_read_preserves_wrapper_value_adds() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let mut email = test_column("email");
        email.security = ManifestColumnSecurity {
            is_pii: true,
            is_encrypted: true,
            mask_in_logs: true,
            ..ManifestColumnSecurity::default()
        };
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("status"), email],
            ..ManifestTable::default()
        });

        let read = build_select_logical_read(
            &manifest,
            &SelectPlanRequest {
                context: read_context(),
                message_type: "acme.test.v1.Widget".to_string(),
                filter: json!({
                    "tenant_id": "tenant-a",
                    "status": {"$in": ["open", "queued"]},
                }),
                sort: vec![SortSpec {
                    field: "status".to_string(),
                    descending: true,
                }],
                limit: 25,
                ..SelectPlanRequest::default()
            },
        )
        .expect("planner request should lower to neutral read");

        assert_eq!(read.message_type, "acme.test.v1.Widget");
        assert_eq!(
            read.projection.expect("projection").fields,
            vec!["id", "tenant_id", "status"],
            "implicit data-plane reads must keep excluding PII/encrypted columns"
        );
        assert_eq!(read.sort.len(), 1);
        assert_eq!(read.sort[0].field, "status");
        assert_eq!(read.sort[0].direction, SortDirection::Desc);
        assert_eq!(read.pagination.expect("limit").limit, Some(25));
        let mut fields = Vec::new();
        read.filter
            .as_ref()
            .expect("filter")
            .referenced_fields(&mut fields);
        fields.sort();
        assert_eq!(fields, vec!["status", "tenant_id"]);
    }

    #[test]
    fn select_planner_bridge_matches_postgres_compiler_for_safe_subset() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("status")],
            ..ManifestTable::default()
        });
        let context = read_context();
        let request = SelectPlanRequest {
            context: context.clone(),
            message_type: "acme.test.v1.Widget".to_string(),
            filter: json!({
                "tenant_id": "tenant-a",
                "status": "open",
            }),
            fields: vec![
                "id".to_string(),
                "tenant_id".to_string(),
                "status".to_string(),
            ],
            sort: vec![SortSpec {
                field: "status".to_string(),
                descending: true,
            }],
            limit: 10,
        };

        let legacy_plan = build_select_query_plan(&manifest, &request);
        assert!(legacy_plan.errors.is_empty(), "{:?}", legacy_plan.errors);
        let read = build_select_logical_read(&manifest, &request)
            .expect("data-plane Select should lower to neutral read");
        let (compiled_sql, compiled_params) =
            compile_pg_sql(&manifest, &context, CompileOperation::Read(&read));

        assert_eq!(legacy_plan.sql, compiled_sql);
        assert_eq!(
            legacy_plan.parameter_columns,
            vec!["tenant_id".to_string(), "status".to_string()]
        );
        assert_eq!(
            compiled_params,
            vec![
                LogicalValue::String("tenant-a".to_string()),
                LogicalValue::String("open".to_string())
            ]
        );
    }

    #[test]
    fn select_planner_logical_read_rejects_unrepresented_pg_only_ops() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("payload")],
            ..ManifestTable::default()
        });

        let errors = build_select_logical_read(
            &manifest,
            &SelectPlanRequest {
                context: read_context(),
                message_type: "acme.test.v1.Widget".to_string(),
                filter: json!({
                    "tenant_id": "tenant-a",
                    "payload": {"$contains": {"kind": "invoice"}},
                }),
                ..SelectPlanRequest::default()
            },
        )
        .expect_err("jsonb containment has no neutral filter equivalent yet");

        assert!(
            errors.iter().any(|error| error.contains(
                "filter operator '$contains' on column 'payload' has no neutral IR equivalent yet"
            )),
            "{errors:?}"
        );
    }

    #[test]
    fn upsert_planner_logical_write_preserves_wrapper_value_adds() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let mut status = test_column("status");
        status.field_name = "public_status".to_string();
        let mut created_at = test_column("created_at");
        created_at.exclude_from_insert = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![
                test_column("id"),
                tenant,
                test_column("code"),
                status,
                created_at,
            ],
            indexes: vec![ManifestIndex {
                name: "uniq_widget_code".to_string(),
                columns: vec!["code".to_string()],
                unique: true,
                ..ManifestIndex::default()
            }],
            ..ManifestTable::default()
        });

        let write = build_upsert_logical_write(
            &manifest,
            &UpsertPlanRequest {
                context: write_context(),
                message_type: "acme.test.v1.Widget".to_string(),
                record: json!({
                    "id": "w1",
                    "tenant_id": "tenant-a",
                    "code": "external-1",
                    "public_status": "open",
                    "created_at": "server-owned"
                }),
                conflict_fields: vec!["code".to_string()],
                return_record: true,
                ..UpsertPlanRequest::default()
            },
        )
        .expect("planner upsert should lower to neutral write");

        assert_eq!(write.records.len(), 1);
        let record = &write.records[0];
        assert_eq!(
            record.keys().cloned().collect::<Vec<_>>(),
            vec!["code", "id", "status", "tenant_id"],
            "server-owned columns are excluded and proto field aliases resolve to physical columns"
        );
        assert_eq!(
            write.conflict,
            ConflictStrategy::update_on(
                vec!["status".to_string(), "tenant_id".to_string()],
                vec!["code".to_string()]
            )
        );
        assert_eq!(
            write.return_fields,
            vec!["id", "tenant_id", "code", "status", "created_at"]
        );
    }

    #[test]
    fn upsert_planner_logical_write_rejects_unrepresented_alt_unique_do_nothing() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("code")],
            indexes: vec![ManifestIndex {
                name: "uniq_widget_tenant_code".to_string(),
                columns: vec!["tenant_id".to_string(), "code".to_string()],
                unique: true,
                ..ManifestIndex::default()
            }],
            ..ManifestTable::default()
        });

        let errors = build_upsert_logical_write(
            &manifest,
            &UpsertPlanRequest {
                context: write_context(),
                message_type: "acme.test.v1.Widget".to_string(),
                record: json!({
                    "tenant_id": "tenant-a",
                    "code": "external-1"
                }),
                conflict_fields: vec!["tenant_id".to_string(), "code".to_string()],
                ..UpsertPlanRequest::default()
            },
        )
        .expect_err("alternate-unique DO NOTHING is not represented by current IR");

        assert!(
            errors.iter().any(|error| error.contains(
                "neutral IR cannot represent alternate-unique ON CONFLICT DO NOTHING yet"
            )),
            "{errors:?}"
        );
    }

    #[test]
    fn upsert_planner_bridge_matches_postgres_compiler_for_safe_subset() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("status")],
            ..ManifestTable::default()
        });
        let context = write_context();
        let request = UpsertPlanRequest {
            context: context.clone(),
            message_type: "acme.test.v1.Widget".to_string(),
            record: json!({
                "id": "w1",
                "tenant_id": "tenant-a",
                "status": "open",
            }),
            return_record: false,
            ..UpsertPlanRequest::default()
        };

        let legacy_plan = build_upsert_plan(&manifest, &request);
        assert!(legacy_plan.errors.is_empty(), "{:?}", legacy_plan.errors);
        let write = build_upsert_logical_write(&manifest, &request)
            .expect("data-plane Upsert should lower to neutral write");
        let (compiled_sql, compiled_params) =
            compile_pg_sql(&manifest, &context, CompileOperation::Write(&write));

        assert_eq!(legacy_plan.sql, compiled_sql);
        assert_eq!(
            legacy_plan.parameter_columns,
            vec![
                "id".to_string(),
                "status".to_string(),
                "tenant_id".to_string()
            ]
        );
        assert_eq!(
            compiled_params,
            vec![
                LogicalValue::String("w1".to_string()),
                LogicalValue::String("open".to_string()),
                LogicalValue::String("tenant-a".to_string())
            ]
        );
    }

    #[test]
    fn delete_planner_logical_delete_preserves_wrapper_value_adds() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("status")],
            ..ManifestTable::default()
        });

        let delete = build_delete_logical_delete(
            &manifest,
            &DeletePlanRequest {
                context: write_context(),
                message_type: "acme.test.v1.Widget".to_string(),
                filter: json!({
                    "tenant_id": "tenant-a",
                    "status": {"$ne": "archived"}
                }),
            },
        )
        .expect("planner delete should lower to neutral delete");

        assert_eq!(delete.message_type, "acme.test.v1.Widget");
        let mut fields = Vec::new();
        delete.filter.referenced_fields(&mut fields);
        fields.sort();
        assert_eq!(fields, vec!["status", "tenant_id"]);
    }

    #[test]
    fn delete_planner_logical_delete_rejects_unrepresented_pg_only_ops() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("payload")],
            ..ManifestTable::default()
        });

        let errors = build_delete_logical_delete(
            &manifest,
            &DeletePlanRequest {
                context: write_context(),
                message_type: "acme.test.v1.Widget".to_string(),
                filter: json!({
                    "tenant_id": "tenant-a",
                    "payload": {"$contains": {"kind": "invoice"}}
                }),
            },
        )
        .expect_err("jsonb containment has no neutral filter equivalent yet");

        assert!(
            errors.iter().any(|error| error.contains(
                "filter operator '$contains' on column 'payload' has no neutral IR equivalent yet"
            )),
            "{errors:?}"
        );
    }

    #[test]
    fn delete_planner_bridge_matches_postgres_compiler_for_safe_subset() {
        let mut tenant = test_column("tenant_id");
        tenant.is_tenant_column = true;
        let manifest = test_manifest(ManifestTable {
            columns: vec![test_column("id"), tenant, test_column("status")],
            ..ManifestTable::default()
        });
        let context = write_context();
        let request = DeletePlanRequest {
            context: context.clone(),
            message_type: "acme.test.v1.Widget".to_string(),
            filter: json!({
                "tenant_id": "tenant-a",
                "status": "archived",
            }),
        };

        let legacy_plan = build_delete_plan(&manifest, &request);
        assert!(legacy_plan.errors.is_empty(), "{:?}", legacy_plan.errors);
        let delete = build_delete_logical_delete(&manifest, &request)
            .expect("data-plane Delete should lower to neutral delete");
        let (compiled_sql, compiled_params) =
            compile_pg_sql(&manifest, &context, CompileOperation::Delete(&delete));

        assert_eq!(legacy_plan.sql, compiled_sql);
        assert_eq!(
            legacy_plan.parameter_columns,
            vec!["tenant_id".to_string(), "status".to_string()]
        );
        assert_eq!(
            compiled_params,
            vec![
                LogicalValue::String("tenant-a".to_string()),
                LogicalValue::String("archived".to_string())
            ]
        );
    }
}