udb 0.4.28

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
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
//! `AuthzService` handler over an atomically-swappable [`AuthzSnapshot`], with
//! an optional Postgres-backed policy/role-binding/relationship store.

use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use arc_swap::ArcSwap;
use sha2::{Digest, Sha256};
use sqlx::{PgPool, Row};
use tonic::{Request, Response, Status};
use uuid::Uuid;

use crate::proto::udb::core::authz::entity::v1 as authz_entity_pb;
use crate::proto::udb::core::authz::services::v1 as authz_pb;
use authz_pb::authz_service_server::AuthzService;

use super::mappings::{
    authz_principal_to_runtime, decision_to_pb, effect_to_entity, entity_effect_to_runtime,
    page_response, policy_from_pg_row, policy_to_rule_pb, resource_to_runtime, scopes_to_db,
    timestamp_from_unix,
};
use super::now_unix;
use crate::ir::{
    ComparisonOp, ConflictStrategy, LogicalAssignment, LogicalDelete, LogicalFilter, LogicalRecord,
    LogicalUpdate, LogicalValue,
};
use crate::runtime::DataBrokerRuntime;
use crate::runtime::authz::Effect;
use crate::runtime::authz::{
    AuthzPolicy, AuthzQuery, AuthzSnapshot, Decision, PolicyEngine, Principal, RelationshipTuple,
    ResourceRef, RoleBinding,
};
use crate::runtime::channels::{ChannelManager, ChannelPermit, OperationChannel};
use crate::runtime::native_catalog::{NativeModel, native_model};
use crate::runtime::service::native_helpers::{
    native_next_page_token_for_total, native_offset_page_window,
};

use super::events::{self, AuthEvent, AuthEventSink, topics};

// Topic submodules: inherent `impl AuthzServiceImpl` blocks (+ helpers); the
// single `impl AuthzService` trait block below delegates to them.
mod audit;
mod tuples;

// Phase K: Authz Policy Governance. Pure logic in `governance_logic`; DB-backed
// handlers split across topic submodules (drafts, activation, simulation, store).
mod governance;
mod governance_activate;
mod governance_drafts;
mod governance_logic;
mod governance_sim;
mod governance_store;

fn authz_capability_status(
    operation: &'static str,
    capability_required: &'static str,
    message: &'static str,
) -> Status {
    crate::runtime::executor_utils::capability_status(
        "authz",
        operation,
        capability_required,
        message,
    )
}

fn authz_not_found_status(
    operation: &'static str,
    schema_code: &'static str,
    message: &'static str,
) -> Status {
    crate::runtime::executor_utils::schema_status(
        tonic::Code::NotFound,
        "authz",
        operation,
        schema_code,
        message,
    )
}

fn authz_internal_status(operation: impl Into<String>, message: impl Into<String>) -> Status {
    crate::runtime::executor_utils::internal_status("authz", operation, message)
}

/// The dev/bootstrap default-allow escape hatch (`UDB_ABAC_DEFAULT_ALLOW`). Read
/// when assembling the PG-warmed authorization snapshot so it SURVIVES reloads —
/// the broker's data plane reads this same cell. Production leaves it unset
/// (deny-by-default). Named `abac_*` for continuity with the documented env var.
fn abac_default_allow_env() -> bool {
    std::env::var("UDB_ABAC_DEFAULT_ALLOW")
        .ok()
        .map(|v| {
            matches!(
                v.trim().to_ascii_lowercase().as_str(),
                "1" | "true" | "yes" | "on"
            )
        })
        .unwrap_or(false)
}

fn governed_direct_mutation_status(rpc: &'static str, policy_decision_id: &'static str) -> Status {
    crate::runtime::executor_utils::policy_status(
        "authz_governed_direct_mutation",
        policy_decision_id,
        format!(
            "governed mode: direct {rpc} is disabled; create a policy draft and activate it (or use break-glass governance)"
        ),
    )
}

fn authz_attribution_policy_status(
    operation: &'static str,
    policy_decision_id: &'static str,
    message: &'static str,
) -> Status {
    crate::runtime::executor_utils::policy_status_with_code(
        tonic::Code::PermissionDenied,
        operation,
        policy_decision_id,
        message,
    )
}

fn created_by_caller_mismatch_status(operation: &'static str) -> Status {
    authz_attribution_policy_status(
        operation,
        "created_by_caller_mismatch",
        "created_by must match the authenticated caller",
    )
}

fn assigned_by_caller_mismatch_status() -> Status {
    authz_attribution_policy_status(
        "assign_role",
        "assigned_by_caller_mismatch",
        "assigned_by must match the authenticated caller",
    )
}

fn policy_bundle_signing_not_configured_status() -> Status {
    authz_capability_status(
        "policy_bundle_signing",
        "policy_bundle_signing_secret",
        "policy bundle signing is not configured; set UDB_POLICY_BUNDLE_SECRET \
                 (or UDB_SESSION_HASH_SECRET)",
    )
}

fn policy_rule_model() -> NativeModel {
    native_model(
        "udb.core.authz.entity.v1.PolicyRule",
        &[
            "policy_id",
            "subject",
            "domain",
            "object",
            "action",
            "effect",
            "condition",
            "description",
            "is_active",
            "created_by",
            "deleted_at",
            "tenant_id",
            "deleted_by",
            "project_id",
            "resource_type",
            "attributes_json",
        ],
    )
}

fn policy_tuple_model() -> NativeModel {
    native_model(
        "udb.core.authz.entity.v1.PolicyTuple",
        &[
            "tuple_kind",
            "subject",
            "domain",
            "object",
            "action",
            "effect",
            "condition",
            "tenant_id",
            "project_id",
        ],
    )
}

fn role_model() -> NativeModel {
    native_model(
        "udb.core.authz.entity.v1.Role",
        &[
            "role_id",
            "name",
            "description",
            "is_system",
            "is_active",
            "created_by",
            "deleted_at",
            "tenant_id",
            "deleted_by",
            "role_code",
            "domain",
            "project_id",
            "scope_type",
            "access_surface",
            "metadata_json",
        ],
    )
}

fn user_role_model() -> NativeModel {
    native_model(
        "udb.core.authz.entity.v1.UserRole",
        &[
            "user_role_id",
            "user_id",
            "role_id",
            "domain",
            "assigned_by",
            "expires_at",
            "created_by",
            "tenant_id",
        ],
    )
}

fn access_decision_audit_model() -> NativeModel {
    native_model(
        "udb.core.authz.entity.v1.AccessDecisionAudit",
        &[
            "decision_audit_id",
            "user_id",
            "domain",
            "object",
            "action",
            "effect",
            "decision_source",
            "matched_rule",
            "reason",
            "ip_address",
            "correlation_id",
            "decided_at",
            "tenant_id",
            // Phase L3 task4 expanded compliance columns.
            "decision_id",
            "policy_version",
            "relationship_version",
            "purpose",
            "scopes",
            "matched_policy_ids",
            "project_id",
            "actor_kind",
            "resource_type",
            "trace_id",
            "span_id",
            "user_agent_hash",
            "decision_input",
        ],
    )
}

/// Request context threaded into the access-decision audit (Phase L3 task4): the
/// source IP, correlation/trace ids, user-agent, declared purpose, and redacted
/// decision-input attributes — populated from `AccessContext` instead of the
/// empty strings the audit-write previously bound.
#[derive(Default, Clone)]
pub(super) struct AuditContext {
    pub source_ip: String,
    pub correlation_id: String,
    pub trace_id: String,
    pub span_id: String,
    pub user_agent: String,
    pub purpose: String,
    /// Redacted decision-input attributes as a JSON object string.
    pub decision_input: String,
}

impl AuditContext {
    /// Build from the request attributes/context map. Pulls IP, user-agent,
    /// correlation/trace ids out of the attribute bag (the broker merges
    /// `AccessContext` fields into `attributes`), masks/hashes the sensitive
    /// ones, and captures the remaining attributes as a redacted JSON blob.
    pub(super) fn from_attributes(
        attributes: &std::collections::BTreeMap<String, String>,
        purpose: &str,
    ) -> Self {
        let get = |k: &str| attributes.get(k).cloned().unwrap_or_default();
        let source_ip = {
            let raw = get("ip_address");
            let raw = if raw.is_empty() {
                get("source_ip")
            } else {
                raw
            };
            events::mask_source_ip(&raw)
        };
        let user_agent = events::hash_user_agent(&get("user_agent"));
        let correlation_id = {
            let c = get("correlation_id");
            if c.is_empty() {
                get("x-correlation-id")
            } else {
                c
            }
        };
        // Capture non-sensitive attributes as a redacted JSON object so the audit
        // row records WHAT was evaluated without leaking credentials.
        let mut input = serde_json::Map::new();
        for (k, v) in attributes {
            if matches!(
                k.as_str(),
                "ip_address" | "source_ip" | "user_agent" | "correlation_id" | "x-correlation-id"
            ) {
                continue;
            }
            input.insert(k.clone(), serde_json::Value::String(v.clone()));
        }
        let mut input_value = serde_json::Value::Object(input);
        events::redact_auth_payload(&mut input_value);
        Self {
            source_ip,
            correlation_id,
            trace_id: get("trace_id"),
            span_id: get("span_id"),
            user_agent,
            purpose: purpose.to_string(),
            decision_input: input_value.to_string(),
        }
    }
}

fn role_select_projection(model: &NativeModel) -> String {
    [
        model.text("role_id"),
        model.select("name"),
        model.text_or_empty("description"),
        model.select("is_system"),
        model.select("is_active"),
        model.text_or_empty("created_by"),
        model.text_or_empty_as("tenant_id", "tenant"),
        model.text_or_empty_as("project_id", "project"),
        model.text_or_empty("role_code"),
        model.text_or_empty("domain"),
        model.select("scope_type"),
        model.text_or_empty("access_surface"),
        model.json_text_as("metadata_json", "metadata_json"),
        model.text_or_empty("deleted_by"),
    ]
    .join(", ")
}

fn user_role_select_projection(model: &NativeModel) -> String {
    [
        model.text("user_role_id"),
        model.text("user_id"),
        model.text("role_id"),
        model.text_or_empty("domain"),
        model.text_or_empty("assigned_by"),
        model.timestamp_unix_as("expires_at", "expires_at_unix"),
        model.text_or_empty_as("tenant_id", "tenant"),
        model.text_or_empty("created_by"),
    ]
    .join(", ")
}

fn policy_rule_select_projection(model: &NativeModel) -> String {
    [
        model.text("policy_id"),
        model.text_or_empty("subject"),
        model.text_or_empty("domain"),
        model.text_or_empty("object"),
        model.text_or_empty("action"),
        model.select("effect"),
        model.text_or_empty("condition"),
        model.text_or_empty("description"),
        model.select("is_active"),
        model.text_or_empty("created_by"),
        model.text_or_empty("tenant_id"),
        model.text_or_empty("deleted_by"),
        model.text_or_empty("project_id"),
        model.text_or_empty("resource_type"),
        model.json_text_as("attributes_json", "attributes_json"),
    ]
    .join(", ")
}

fn stable_audit_user_uuid(principal: &Principal) -> Uuid {
    let subject = [
        principal.subject.as_str(),
        principal.user_id.as_str(),
        principal.principal_id.as_str(),
        principal.service_identity.as_str(),
    ]
    .into_iter()
    .find(|value| !value.trim().is_empty())
    .unwrap_or("anonymous");
    stable_uuid_from_subject(subject)
}

pub(super) fn stable_uuid_from_subject(subject: &str) -> Uuid {
    if let Ok(uuid) = Uuid::parse_str(subject) {
        return uuid;
    }
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(subject.as_bytes());
    let mut bytes = [0u8; 16];
    bytes.copy_from_slice(&digest[..16]);
    Uuid::from_bytes(bytes)
}

fn authz_invalid_fields<I, F, D>(message: impl Into<String>, fields: I) -> Status
where
    I: IntoIterator<Item = (F, D)>,
    F: Into<String>,
    D: Into<String>,
{
    crate::runtime::executor_utils::invalid_argument_fields(message, fields)
}

fn authz_required_field(
    message: &'static str,
    field: &'static str,
    description: &'static str,
) -> Status {
    authz_invalid_fields(message, [(field, description)])
}

pub(super) fn parse_uuid_field(field_name: &str, value: &str) -> Result<Uuid, Status> {
    Uuid::parse_str(value).map_err(|_| {
        authz_invalid_fields(
            format!("{field_name} must be a UUID"),
            [(field_name.to_string(), "must be a UUID")],
        )
    })
}

pub(super) fn timestamp_unix_field(
    field_name: &str,
    value: Option<prost_types::Timestamp>,
) -> Result<Option<i64>, Status> {
    let Some(value) = value else {
        return Ok(None);
    };
    if value.seconds <= 0 {
        return Err(authz_invalid_fields(
            format!("{field_name} must be a positive unix timestamp"),
            [(field_name.to_string(), "must be a positive unix timestamp")],
        ));
    }
    Ok(Some(value.seconds))
}

fn tenant_from_domain(tenant_id: &str, domain: &str) -> String {
    if !tenant_id.trim().is_empty() {
        tenant_id.to_string()
    } else if let Some((prefix, suffix)) = domain.split_once(':') {
        if matches!(prefix, "tenant" | "project" | "resource") && !suffix.trim().is_empty() {
            suffix.to_string()
        } else {
            domain.to_string()
        }
    } else {
        domain.to_string()
    }
}

fn tuple_condition_expired(condition: &str, now: u64) -> bool {
    if condition.trim().is_empty() {
        return false;
    }
    let Ok(value) = serde_json::from_str::<serde_json::Value>(condition) else {
        return false;
    };
    let Some(expires_at) = value
        .get("expires_at_unix")
        .and_then(serde_json::Value::as_i64)
    else {
        return false;
    };
    expires_at > 0 && (expires_at as u64) <= now
}

/// Item 81: enrich a `ResourceRef` with the concrete manifest schema/table/store
/// resolved from its message type, so policies can match on
/// `schema`/`table`/`backend` and audits record the real relation. Looks the
/// message type up in the native manifest; leaves the ref untouched when it is
/// already populated or the type is not a known native relation.
fn enrich_resource(resource: &mut ResourceRef) {
    if !resource.table.trim().is_empty() {
        return;
    }
    let key = if !resource.message_type.trim().is_empty() {
        resource.message_type.clone()
    } else {
        resource.resource_name.clone()
    };
    if key.trim().is_empty() {
        return;
    }
    if let Some((schema, table)) = crate::runtime::native_catalog::native_relation(&key) {
        resource.schema = schema;
        resource.table = table;
        if resource.backend.trim().is_empty() {
            resource.backend = "postgres".to_string();
        }
    }
}

fn role_scope_type_to_db(scope_type: i32) -> &'static str {
    match authz_entity_pb::RoleScopeType::try_from(scope_type).unwrap_or_default() {
        authz_entity_pb::RoleScopeType::Global => "GLOBAL",
        authz_entity_pb::RoleScopeType::Tenant => "TENANT",
        authz_entity_pb::RoleScopeType::Project => "PROJECT",
        authz_entity_pb::RoleScopeType::Resource => "RESOURCE",
        authz_entity_pb::RoleScopeType::External => "EXTERNAL",
        authz_entity_pb::RoleScopeType::Unspecified => "UNSPECIFIED",
    }
}

fn role_scope_type_from_db(value: &str) -> i32 {
    match value {
        "GLOBAL" | "ROLE_SCOPE_TYPE_GLOBAL" => authz_entity_pb::RoleScopeType::Global as i32,
        "TENANT" | "ROLE_SCOPE_TYPE_TENANT" => authz_entity_pb::RoleScopeType::Tenant as i32,
        "PROJECT" | "ROLE_SCOPE_TYPE_PROJECT" => authz_entity_pb::RoleScopeType::Project as i32,
        "RESOURCE" | "ROLE_SCOPE_TYPE_RESOURCE" => authz_entity_pb::RoleScopeType::Resource as i32,
        "EXTERNAL" | "ROLE_SCOPE_TYPE_EXTERNAL" => authz_entity_pb::RoleScopeType::External as i32,
        _ => authz_entity_pb::RoleScopeType::Unspecified as i32,
    }
}

fn effect_to_db(effect: Effect) -> &'static str {
    match effect {
        Effect::Allow => "ALLOW",
        Effect::Deny => "DENY",
    }
}

pub(super) fn effect_from_db(value: &str) -> i32 {
    match value {
        "ALLOW" | "allow" | "POLICY_EFFECT_ALLOW" => authz_entity_pb::PolicyEffect::Allow as i32,
        "DENY" | "deny" | "POLICY_EFFECT_DENY" => authz_entity_pb::PolicyEffect::Deny as i32,
        _ => authz_entity_pb::PolicyEffect::Unspecified as i32,
    }
}

/// Map a `roles` row to the `Role` entity. Timestamps are not read back
/// (left `None`); the durable columns carry the role's logical state.
fn role_from_row(row: &sqlx::postgres::PgRow) -> Result<authz_entity_pb::Role, Status> {
    let map =
        |e: sqlx::Error| authz_internal_status("decode_role", format!("decode role failed: {e}"));
    Ok(authz_entity_pb::Role {
        role_id: row.try_get("role_id").map_err(map)?,
        name: row.try_get("name").map_err(map)?,
        description: row.try_get("description").map_err(map)?,
        is_system: row.try_get("is_system").map_err(map)?,
        is_active: row.try_get("is_active").map_err(map)?,
        created_by: row.try_get("created_by").map_err(map)?,
        created_at: None,
        updated_at: None,
        deleted_at: None,
        tenant_id: row.try_get("tenant").map_err(map)?,
        deleted_by: row.try_get("deleted_by").map_err(map)?,
        role_code: row.try_get("role_code").map_err(map)?,
        domain: row.try_get("domain").map_err(map)?,
        project_id: row.try_get("project").map_err(map)?,
        scope_type: role_scope_type_from_db(&row.try_get::<String, _>("scope_type").map_err(map)?),
        access_surface: row.try_get("access_surface").map_err(map)?,
        metadata_json: row.try_get("metadata_json").map_err(map)?,
    })
}

/// Map a `user_roles` row to the `UserRole` entity.
fn user_role_from_row(row: &sqlx::postgres::PgRow) -> Result<authz_entity_pb::UserRole, Status> {
    let map = |e: sqlx::Error| {
        authz_internal_status("decode_user_role", format!("decode user role failed: {e}"))
    };
    Ok(authz_entity_pb::UserRole {
        user_role_id: row.try_get("user_role_id").map_err(map)?,
        user_id: row.try_get("user_id").map_err(map)?,
        role_id: row.try_get("role_id").map_err(map)?,
        domain: row.try_get("domain").map_err(map)?,
        assigned_by: row.try_get("assigned_by").map_err(map)?,
        assigned_at: None,
        expires_at: timestamp_from_unix(
            row.try_get::<i64, _>("expires_at_unix")
                .map_err(map)?
                .max(0) as u64,
        ),
        created_at: None,
        updated_at: None,
        created_by: row.try_get("created_by").map_err(map)?,
        tenant_id: row.try_get("tenant").map_err(map)?,
    })
}

/// Map a `policy_rules` row to the `PolicyRule` entity without going through
/// the evaluation snapshot. The snapshot intentionally drops management fields
/// such as description/deleted_by; admin read APIs must return the durable row.
fn policy_rule_from_row(
    row: &sqlx::postgres::PgRow,
) -> Result<authz_entity_pb::PolicyRule, Status> {
    let map = |e: sqlx::Error| {
        authz_internal_status(
            "decode_policy_rule",
            format!("decode policy rule failed: {e}"),
        )
    };
    Ok(authz_entity_pb::PolicyRule {
        policy_id: row.try_get("policy_id").map_err(map)?,
        subject: row.try_get("subject").map_err(map)?,
        domain: row.try_get("domain").map_err(map)?,
        object: row.try_get("object").map_err(map)?,
        action: row.try_get("action").map_err(map)?,
        effect: effect_from_db(&row.try_get::<String, _>("effect").map_err(map)?),
        condition: row.try_get("condition").map_err(map)?,
        description: row.try_get("description").map_err(map)?,
        is_active: row.try_get("is_active").map_err(map)?,
        created_by: row.try_get("created_by").map_err(map)?,
        created_at: None,
        updated_at: None,
        deleted_at: None,
        tenant_id: row.try_get("tenant_id").map_err(map)?,
        deleted_by: row.try_get("deleted_by").map_err(map)?,
        project_id: row.try_get("project_id").map_err(map)?,
        resource_type: row.try_get("resource_type").map_err(map)?,
        attributes_json: row.try_get("attributes_json").map_err(map)?,
    })
}

/// `AuthzService` handler over an atomically-swappable [`AuthzSnapshot`].
/// `Clone` is cheap (every field is an `Arc`/`Duration`/`Option<PgPool>`) and is
/// used to hand a detached executor to the Phase-9 canary evaluator task.
#[derive(Clone)]
pub struct AuthzServiceImpl {
    snapshot: Arc<ArcSwap<AuthzSnapshot>>,
    snapshot_loaded_at: Arc<Mutex<Option<Instant>>>,
    snapshot_ttl: Duration,
    pg_pool: Option<PgPool>,
    event_sink: Arc<dyn AuthEventSink>,
    /// Records authz metrics (deny count). Defaults to a no-op; production wires
    /// the broker's shared recorder via [`AuthzServiceImpl::with_metrics`].
    metrics: Arc<dyn crate::metrics::MetricsRecorder>,
    /// Per-tenant fair-admission manager (the SAME one the data/media planes use).
    /// The hot authz decision RPCs (`authorize`, `check_access`,
    /// `batch_check_permissions`) acquire a per-tenant `Admin` budget through this
    /// so one tenant flooding authz checks cannot starve others or exhaust the
    /// shared PG pool / snapshot path. `None` only in bare/test construction (no
    /// runtime wired) — production wires it via [`AuthzServiceImpl::with_channels`].
    channels: Option<ChannelManager>,
    /// Runtime handle used for native typed entity persistence. `pg_pool` remains
    /// for raw SQL paths that need joins, transactions, or conditional updates
    /// until the native substrate supports those shapes.
    runtime: Option<Arc<DataBrokerRuntime>>,
}

impl AuthzServiceImpl {
    /// Owning constructor over an in-memory snapshot. Production wires the
    /// service through [`AuthzServiceImpl::shared`] (a shared `ArcSwap` cell so
    /// reloads are visible across handlers); `new` is the convenience
    /// constructor used by the unit/integration tests, which exercise the
    /// service over a self-owned snapshot.
    #[cfg(test)]
    pub fn new(snapshot: AuthzSnapshot) -> Self {
        Self {
            snapshot: Arc::new(ArcSwap::from_pointee(snapshot)),
            snapshot_loaded_at: Arc::new(Mutex::new(Some(Instant::now()))),
            snapshot_ttl: authz_snapshot_ttl(),
            pg_pool: None,
            event_sink: events::noop_sink(),
            metrics: Arc::new(crate::metrics::NoopMetrics),
            channels: None,
            runtime: None,
        }
    }

    /// Share an externally-owned snapshot cell (so reloads are visible here).
    pub fn shared(snapshot: Arc<ArcSwap<AuthzSnapshot>>) -> Self {
        Self {
            snapshot,
            snapshot_loaded_at: Arc::new(Mutex::new(None)),
            snapshot_ttl: authz_snapshot_ttl(),
            pg_pool: None,
            event_sink: events::noop_sink(),
            metrics: Arc::new(crate::metrics::NoopMetrics),
            channels: None,
            runtime: None,
        }
    }

    /// Wire the broker's shared per-tenant fair-admission manager (mirror of
    /// `StorageServiceImpl::with_object`'s channel wiring). The parent builder
    /// (`build_auth_services`) passes `Some(runtime.channels().clone())`. `None`
    /// keeps the bare/test path admitting without a permit.
    pub(crate) fn with_channels(mut self, channels: Option<ChannelManager>) -> Self {
        self.channels = channels;
        self
    }

    pub(crate) fn with_runtime(mut self, runtime: Option<Arc<DataBrokerRuntime>>) -> Self {
        self.runtime = runtime;
        self
    }

    /// Per-tenant fair admission for the hot authz decision RPCs, keyed by the
    /// VALIDATED caller tenant (never an unverified body field). Acquires the
    /// `Admin` (control-plane) channel budget scoped to the tenant so one tenant
    /// cannot exhaust the shared PG pool / snapshot path with authz checks. The
    /// returned [`ChannelPermit`] MUST be held across the decision (drop =
    /// release). `None` channels (bare/test construction — no runtime wired) admit
    /// without a permit, since there is no shared admission budget to starve.
    ///
    /// On budget/concurrency exhaustion this returns the same
    /// `Status::resource_exhausted` backpressure the data plane returns.
    async fn admit(&self, tenant: &str) -> Result<Option<ChannelPermit>, Status> {
        let Some(channels) = self.channels.as_ref() else {
            return Ok(None);
        };
        let op = OperationChannel::Admin;
        // Local tenant hash for the metric label (the parent module's
        // `tenant_hash_label` is private to `service/mod.rs`); never logs the raw
        // tenant id.
        let tenant_hash = {
            use sha2::{Digest, Sha256};
            let digest = Sha256::digest(tenant.as_bytes());
            digest[..8]
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect::<String>()
        };
        match channels
            .acquire_fair_with_backpressure(op, Some(tenant), None, None, None, op.default_cost())
            .await
        {
            Ok(permit) => {
                self.metrics.record_fair_admission(
                    "default",
                    &tenant_hash,
                    "authz",
                    "default",
                    op.as_str(),
                    "accepted",
                );
                self.metrics.add_fair_cost(
                    "default",
                    &tenant_hash,
                    "authz",
                    "default",
                    op.as_str(),
                    f64::from(op.default_cost()),
                );
                Ok(Some(permit))
            }
            Err(err) => {
                self.metrics.inc_channel_rejected(op.as_str());
                self.metrics.record_fair_admission(
                    "default",
                    &tenant_hash,
                    "authz",
                    "default",
                    op.as_str(),
                    "rejected",
                );
                Err(err)
            }
        }
    }

    pub fn with_postgres(mut self, pool: Option<PgPool>) -> Self {
        let has_pool = pool.is_some();
        self.pg_pool = pool;
        // A durable Postgres pool is the source of truth. The constructor seeds
        // `snapshot_loaded_at = Some(now)` over the (possibly empty) in-memory
        // snapshot, which would otherwise be served as "fresh" for the whole TTL
        // and suppress the first load from Postgres. Force the next read to load
        // the real snapshot from PG.
        if has_pool {
            self.invalidate_snapshot_cache();
        }
        self
    }

    /// Invalidate the cached authz snapshot so the next `current_snapshot()`
    /// reloads from Postgres. Called after every authz mutation so the writing
    /// node enforces its own writes immediately (read-your-writes) instead of
    /// serving a stale snapshot until the TTL elapses.
    pub(super) fn invalidate_snapshot_cache(&self) {
        if let Ok(mut guard) = self.snapshot_loaded_at.lock() {
            *guard = None;
        }
    }

    /// The shared-snapshot reload TTL (used by the broker's boot/interval warmer
    /// to pace its reloads — auth_fix.md Block 1, Decision A).
    pub(crate) fn snapshot_ttl(&self) -> Duration {
        self.snapshot_ttl
    }

    /// Force a Postgres reload of the SHARED authz snapshot cell. The broker's
    /// startup eager-warm + interval warmer call this so the authn login path
    /// (which only reads the shared cell, never triggers a reload) sees role
    /// bindings on the very first login instead of the cold ABAC-only snapshot
    /// (auth_fix.md Block 1, Decision A). GAP-36 posture: `current_snapshot`
    /// only `store()`s on a successful load, so a reload error leaves the last
    /// good snapshot in place — we just log it, never blank the cell.
    pub(crate) async fn warm_shared_snapshot(&self) {
        self.invalidate_snapshot_cache();
        if let Err(err) = self.current_snapshot().await {
            tracing::warn!(
                error = %err,
                "authz snapshot warm reload failed; retaining last good snapshot"
            );
        }
    }

    pub(crate) fn with_event_sink(mut self, sink: Arc<dyn AuthEventSink>) -> Self {
        self.event_sink = sink;
        self
    }

    /// Attach the metrics recorder (the broker's shared recorder in production).
    /// Defaults to a no-op.
    pub(crate) fn with_metrics(
        mut self,
        metrics: Arc<dyn crate::metrics::MetricsRecorder>,
    ) -> Self {
        self.metrics = metrics;
        self
    }

    pub(super) async fn emit_event(&self, event: AuthEvent) {
        let topic = event.topic;
        if let Err(err) = self.event_sink.emit(event).await {
            tracing::warn!(topic, error = %err, "failed to publish authz event");
        }
    }

    pub(super) async fn decide_with_snapshot(
        &self,
        snapshot: &AuthzSnapshot,
        principal: &Principal,
        resource: &ResourceRef,
        action: &str,
        purpose: &str,
        attributes: &BTreeMap<String, String>,
    ) -> Decision {
        // Item 82: the service consumes the pluggable `PolicyEngine` seam (the
        // snapshot's impl drives the real Casbin enforcer in
        // `runtime::authz::casbin_engine`), so a future engine slots in here
        // without touching the service boundary.
        PolicyEngine::decide(
            snapshot,
            &AuthzQuery {
                principal,
                resource,
                action,
                purpose,
                attributes,
            },
        )
        .await
    }

    pub(super) fn policies_model(&self) -> NativeModel {
        policy_rule_model()
    }

    pub(super) fn relationship_tuples_model(&self) -> NativeModel {
        policy_tuple_model()
    }

    pub(super) fn roles_model(&self) -> NativeModel {
        role_model()
    }

    pub(super) fn user_roles_model(&self) -> NativeModel {
        user_role_model()
    }

    pub(super) fn audits_model(&self) -> NativeModel {
        access_decision_audit_model()
    }

    /// Resolve a role's stable `role_code` (falling back to `name`) for use as
    /// the grouping-tuple role token when binding a non-UUID principal. Returns
    /// `None` when the role is missing.
    pub(super) async fn role_code_for(
        &self,
        role_id: Uuid,
        domain: &str,
    ) -> Result<Option<String>, Status> {
        let pool = self.require_pool()?;
        let m = self.roles_model();
        let rel = m.relation.clone();
        let row = sqlx::query(&format!(
            "SELECT COALESCE(NULLIF({role_code}, ''), {name}) AS role FROM {rel} \
             WHERE {role_id} = $1::UUID AND {deleted_at} IS NULL AND ($2 = '' OR {domain_col} = $2) LIMIT 1",
            role_code = m.q("role_code"),
            name = m.q("name"),
            role_id = m.q("role_id"),
            deleted_at = m.q("deleted_at"),
            domain_col = m.q("domain"),
        ))
        .bind(role_id)
        .bind(domain)
        .fetch_optional(pool)
        .await
        .map_err(|err| {
            authz_internal_status("resolve_role_code", format!("resolve role code failed: {err}"))
        })?;
        Ok(row.and_then(|r| r.try_get::<String, _>("role").ok()))
    }

    /// Role/assignment/audit management is durable-only: fail closed when no
    /// Postgres pool is configured.
    pub(super) fn require_pool(&self) -> Result<&PgPool, Status> {
        self.pg_pool.as_ref().ok_or_else(|| {
            authz_capability_status(
                "postgres_auth_store",
                "postgres_auth_store",
                "this operation requires a Postgres-backed auth store (no PG pool configured)",
            )
        })
    }

    /// Best-effort access-decision audit write (items 84–86): records denies and
    /// audit-flagged allows into the proto-defined `access_decision_audits`
    /// table. Errors are logged, never surfaced — auditing must not block the
    /// decision path. The UUID `user_id` column accepts any principal subject by
    /// deriving a stable UUID from it (service/external identities aren't UUIDs).
    pub(super) async fn write_decision_audit(
        &self,
        principal: &Principal,
        resource: &ResourceRef,
        action: &str,
        decision: &Decision,
        ctx: &AuditContext,
    ) {
        // Phase 5: count every deny decision regardless of audit-sink/pool state
        // (this is the chokepoint all decision paths route through).
        if !decision.allowed {
            self.metrics.record_authz_deny();
        }
        if decision.allowed && !decision.audit_required {
            return;
        }
        let Some(runtime) = &self.runtime else {
            tracing::warn!(
                "skipping access-decision audit write: authz runtime handle is not wired"
            );
            return;
        };
        let user_uuid = stable_audit_user_uuid(principal);
        let effect = if decision.allowed { "ALLOW" } else { "DENY" };
        let source = if decision.matched_policy_ids.is_empty() {
            "NO_MATCH"
        } else if decision.allowed && decision.via_role {
            "ROLE_POLICY"
        } else {
            "DIRECT_POLICY"
        };
        let domain = if principal.project_id.trim().is_empty() {
            principal.tenant_id.clone()
        } else {
            principal.project_id.clone()
        };
        // Phase L3 task4: classify the actor and join the scope/policy lists.
        let actor_kind = if !principal.user_id.trim().is_empty() {
            "user"
        } else if !principal.service_identity.trim().is_empty() {
            "service"
        } else {
            "external"
        };
        let scopes = decision.required_scopes.join(",");
        let decision_input = serde_json::from_str(&ctx.decision_input)
            .unwrap_or_else(|_| serde_json::Value::String(ctx.decision_input.clone()));
        let mut record = LogicalRecord::new();
        record.insert(
            "decision_audit_id".to_string(),
            LogicalValue::String(Uuid::new_v4().to_string()),
        );
        record.insert(
            "user_id".to_string(),
            LogicalValue::String(user_uuid.to_string()),
        );
        record.insert("domain".to_string(), LogicalValue::String(domain));
        record.insert(
            "object".to_string(),
            LogicalValue::String(resource.resource_name.clone()),
        );
        record.insert(
            "action".to_string(),
            LogicalValue::String(action.to_string()),
        );
        record.insert(
            "effect".to_string(),
            LogicalValue::String(effect.to_string()),
        );
        record.insert(
            "decision_source".to_string(),
            LogicalValue::String(source.to_string()),
        );
        record.insert(
            "matched_rule".to_string(),
            LogicalValue::String(
                decision
                    .matched_policy_ids
                    .first()
                    .cloned()
                    .unwrap_or_default(),
            ),
        );
        record.insert(
            "reason".to_string(),
            LogicalValue::String(decision.deny_reason.clone()),
        );
        // Phase L3 task4: populate source IP + correlation id from AccessContext
        // instead of binding empty strings.
        record.insert(
            "ip_address".to_string(),
            LogicalValue::String(ctx.source_ip.clone()),
        );
        record.insert(
            "correlation_id".to_string(),
            LogicalValue::String(ctx.correlation_id.clone()),
        );
        record.insert(
            "tenant_id".to_string(),
            LogicalValue::String(principal.tenant_id.clone()),
        );
        record.insert(
            "decision_id".to_string(),
            LogicalValue::String(decision.decision_id.clone()),
        );
        record.insert(
            "policy_version".to_string(),
            LogicalValue::String(decision.policy_version.clone()),
        );
        record.insert(
            "relationship_version".to_string(),
            LogicalValue::String(decision.relationship_version.clone()),
        );
        record.insert(
            "purpose".to_string(),
            LogicalValue::String(ctx.purpose.clone()),
        );
        record.insert("scopes".to_string(), LogicalValue::String(scopes));
        record.insert(
            "matched_policy_ids".to_string(),
            LogicalValue::Array(
                decision
                    .matched_policy_ids
                    .iter()
                    .cloned()
                    .map(LogicalValue::String)
                    .collect(),
            ),
        );
        record.insert(
            "project_id".to_string(),
            LogicalValue::String(principal.project_id.clone()),
        );
        record.insert(
            "actor_kind".to_string(),
            LogicalValue::String(actor_kind.to_string()),
        );
        record.insert(
            "resource_type".to_string(),
            LogicalValue::String(resource.resource_type.clone()),
        );
        record.insert(
            "trace_id".to_string(),
            LogicalValue::String(ctx.trace_id.clone()),
        );
        record.insert(
            "span_id".to_string(),
            LogicalValue::String(ctx.span_id.clone()),
        );
        record.insert(
            "user_agent_hash".to_string(),
            LogicalValue::String(ctx.user_agent.clone()),
        );
        record.insert(
            "decision_input".to_string(),
            LogicalValue::Json(decision_input),
        );
        let audit_context = crate::RequestContext {
            tenant_id: principal.tenant_id.clone(),
            project_id: principal.project_id.clone(),
            ..crate::RequestContext::default()
        };
        let result = runtime
            .native_entity_write_for_service(
                "authz",
                &audit_context,
                "udb.core.authz.entity.v1.AccessDecisionAudit",
                record,
                ConflictStrategy::Error,
            )
            .await;
        if let Err(err) = result {
            tracing::warn!(error = %err, "failed to write access-decision audit");
        }

        // Phase L2: an ALLOW that the policy flagged `audit_required` is a
        // security-sensitive event in its own right (e.g. access to a regulated
        // resource that is permitted but must be reviewed). Publish it so the
        // compliance plane sees the audited-allow, distinct from the typed audit
        // row above. Denies already surface via `ACCESS_DENIED` at the decision
        // sites, so we only emit here for the allow+audit_required case.
        if decision.allowed && decision.audit_required {
            let actor = if principal.subject.trim().is_empty() {
                principal.principal_id.clone()
            } else {
                principal.subject.clone()
            };
            let correlation = if ctx.correlation_id.trim().is_empty() {
                format!("audit_allow:{}:{}", actor, resource.resource_name)
            } else {
                ctx.correlation_id.clone()
            };
            self.emit_event(
                AuthEvent::new(
                    topics::ACCESS_AUDIT_REQUIRED_ALLOW,
                    actor.clone(),
                    principal.tenant_id.clone(),
                    serde_json::json!({
                        "subject": actor.clone(),
                        "resource": resource.resource_name.clone(),
                        "action": action,
                        "purpose": ctx.purpose.clone(),
                        "matched_policy_ids": decision.matched_policy_ids.clone(),
                    }),
                )
                .with_correlation(correlation)
                .with_compliance(events::ComplianceEnvelope {
                    actor: actor.clone(),
                    actor_project: principal.project_id.clone(),
                    target_resource: resource.resource_name.clone(),
                    operation: action.to_string(),
                    outcome: "allow".to_string(),
                    reason_code: "audit_required_allow".to_string(),
                    decision_id: decision.decision_id.clone(),
                    policy_version: decision.policy_version.clone(),
                    relationship_version: decision.relationship_version.clone(),
                    trace_id: ctx.trace_id.clone(),
                    span_id: ctx.span_id.clone(),
                    ..events::ComplianceEnvelope::default()
                }),
            )
            .await;
        }
    }

    /// Native authz reads and mutations require a Postgres-backed store. There is
    /// no in-memory fallback, so a missing pool fails closed.
    pub(super) fn require_snapshot_fallback(&self) -> Result<(), Status> {
        Err(authz_capability_status(
            "snapshot_fallback",
            "postgres_auth_store",
            "native authz requires a Postgres-backed auth store",
        ))
    }

    async fn authz_revision_fingerprint(&self) -> Result<String, Status> {
        let Some(pool) = &self.pg_pool else {
            return Ok(String::new());
        };
        let m = self.authz_revisions_model();
        let rows = sqlx::query(&format!(
            "SELECT DISTINCT ON ({tenant_id}, {project_id}) \
                    {tenant_id}::TEXT AS tenant_id, COALESCE({project_id}, '') AS project_id, \
                    {policy_revision} AS policy_revision, \
                    {relationship_revision} AS relationship_revision, \
                    COALESCE({content_hash}, '') AS content_hash \
             FROM {rel} \
             ORDER BY {tenant_id}, {project_id}, {policy_revision} DESC, \
                      {relationship_revision} DESC, {changed_at} DESC",
            rel = m.relation.clone(),
            tenant_id = m.q("tenant_id"),
            project_id = m.q("project_id"),
            policy_revision = m.q("policy_revision"),
            relationship_revision = m.q("relationship_revision"),
            content_hash = m.q("content_hash"),
            changed_at = m.q("changed_at"),
        ))
        .fetch_all(pool)
        .await
        .map_err(|err| {
            authz_internal_status(
                "read_authz_revision_fence",
                format!("read authz revision fence failed: {err}"),
            )
        })?;

        let mut hasher = Sha256::new();
        for row in rows {
            let tenant_id: String = row.try_get("tenant_id").map_err(|err| {
                authz_internal_status(
                    "decode_authz_revision_fence",
                    format!("decode authz fence failed: {err}"),
                )
            })?;
            let project_id: String = row.try_get("project_id").map_err(|err| {
                authz_internal_status(
                    "decode_authz_revision_fence",
                    format!("decode authz fence failed: {err}"),
                )
            })?;
            let policy_revision: i64 = row.try_get("policy_revision").map_err(|err| {
                authz_internal_status(
                    "decode_authz_revision_fence",
                    format!("decode authz fence failed: {err}"),
                )
            })?;
            let relationship_revision: i64 =
                row.try_get("relationship_revision").map_err(|err| {
                    authz_internal_status(
                        "decode_authz_revision_fence",
                        format!("decode authz fence failed: {err}"),
                    )
                })?;
            let content_hash: String = row.try_get("content_hash").map_err(|err| {
                authz_internal_status(
                    "decode_authz_revision_fence",
                    format!("decode authz fence failed: {err}"),
                )
            })?;
            hasher.update(tenant_id.as_bytes());
            hasher.update([0]);
            hasher.update(project_id.as_bytes());
            hasher.update([0]);
            hasher.update(policy_revision.to_be_bytes());
            hasher.update(relationship_revision.to_be_bytes());
            hasher.update(content_hash.as_bytes());
            hasher.update([0xff]);
        }
        Ok(format!("{:x}", hasher.finalize()))
    }

    async fn load_snapshot_from_postgres(&self) -> Result<Option<AuthzSnapshot>, Status> {
        let Some(pool) = &self.pg_pool else {
            return Ok(None);
        };
        let policy = self.policies_model();
        let binding = self.user_roles_model();
        let role = self.roles_model();
        let tuple = self.relationship_tuples_model();

        let policy_rows = sqlx::query(&format!(
            "SELECT {policy_id_text} AS id, COALESCE(NULLIF({attributes_json}->>'priority', '')::INT, 0) AS priority, {is_active} AS enabled, {effect}, {tenant_id} AS tenant, COALESCE({project_id}, '') AS project, {subject}, \
                    COALESCE({attributes_json}->>'role', '') AS role, {action}, {object_col} AS resource, COALESCE({attributes_json}->>'purpose', '') AS purpose, \
                    COALESCE({attributes_json}->>'relationship', '') AS relationship, {attributes_json} AS conditions, COALESCE({attributes_json}->>'required_scopes', '') AS required_scopes \
             FROM {policy_rel} \
             WHERE {deleted_at} IS NULL AND {is_active} = TRUE \
             ORDER BY priority DESC, {policy_id} ASC",
            policy_rel = policy.relation.clone(),
            policy_id_text = format!("{}::TEXT", policy.q("policy_id")),
            policy_id = policy.q("policy_id"),
            attributes_json = policy.q("attributes_json"),
            is_active = policy.q("is_active"),
            effect = policy.q("effect"),
            tenant_id = policy.q("tenant_id"),
            project_id = policy.q("project_id"),
            subject = policy.q("subject"),
            action = policy.q("action"),
            object_col = policy.q("object"),
            deleted_at = policy.q("deleted_at"),
        ))
        .fetch_all(pool)
        .await
        .map_err(|err| {
            authz_internal_status(
                "load_authz_policies",
                format!("load authz policies failed: {err}"),
            )
        })?;

        let mut policies = Vec::with_capacity(policy_rows.len());
        for row in &policy_rows {
            policies.push(policy_from_pg_row(row).map_err(|err| {
                authz_internal_status(
                    "decode_authz_policy",
                    format!("decode authz policy failed: {err}"),
                )
            })?);
        }

        let binding_rows = sqlx::query(&format!(
            "SELECT ur.{user_id}::TEXT AS subject, COALESCE(NULLIF(r.{role_code}, ''), NULLIF(r.{name}, ''), ur.{role_id}::TEXT) AS role, ur.{tenant_id} AS tenant, COALESCE(r.{project_id}, '') AS project \
             FROM {binding_rel} ur \
             LEFT JOIN {role_rel} r ON r.{role_role_id} = ur.{role_id} \
             WHERE (ur.{expires_at} IS NULL OR ur.{expires_at} > NOW()) \
               AND r.{deleted_at} IS NULL \
               AND (r.{is_active} IS NULL OR r.{is_active} = TRUE)",
            binding_rel = binding.relation.clone(),
            role_rel = role.relation.clone(),
            user_id = binding.q("user_id"),
            role_id = binding.q("role_id"),
            tenant_id = binding.q("tenant_id"),
            expires_at = binding.q("expires_at"),
            role_role_id = role.q("role_id"),
            role_code = role.q("role_code"),
            name = role.q("name"),
            project_id = role.q("project_id"),
            deleted_at = role.q("deleted_at"),
            is_active = role.q("is_active"),
        ))
        .fetch_all(pool)
        .await
        .map_err(|err| {
            authz_internal_status(
                "load_role_bindings",
                format!("load role bindings failed: {err}"),
            )
        })?;
        let mut role_bindings = Vec::with_capacity(binding_rows.len());
        for row in binding_rows {
            role_bindings.push(RoleBinding {
                subject: row.try_get("subject").map_err(|err| {
                    authz_internal_status(
                        "decode_role_binding",
                        format!("decode role binding failed: {err}"),
                    )
                })?,
                role: row.try_get("role").map_err(|err| {
                    authz_internal_status(
                        "decode_role_binding",
                        format!("decode role binding failed: {err}"),
                    )
                })?,
                tenant: row.try_get("tenant").map_err(|err| {
                    authz_internal_status(
                        "decode_role_binding",
                        format!("decode role binding failed: {err}"),
                    )
                })?,
                project: row.try_get("project").map_err(|err| {
                    authz_internal_status(
                        "decode_role_binding",
                        format!("decode role binding failed: {err}"),
                    )
                })?,
            });
        }

        let grouping_rows = sqlx::query(&format!(
            "SELECT {subject}, {action} AS role, {tenant_id} AS tenant, COALESCE({project_id}, '') AS project, {condition} \
             FROM {tuple_rel} \
             WHERE {tuple_kind} = 'grouping'",
            tuple_rel = tuple.relation.clone(),
            subject = tuple.q("subject"),
            action = tuple.q("action"),
            tenant_id = tuple.q("tenant_id"),
            project_id = tuple.q("project_id"),
            condition = tuple.q("condition"),
            tuple_kind = tuple.q("tuple_kind"),
        ))
        .fetch_all(pool)
        .await
        .map_err(|err| {
            authz_internal_status(
                "load_grouping_tuples",
                format!("load grouping tuples failed: {err}"),
            )
        })?;
        let now = now_unix();
        for row in grouping_rows {
            let condition: String = row.try_get("condition").map_err(|err| {
                authz_internal_status(
                    "decode_grouping_tuple",
                    format!("decode grouping tuple failed: {err}"),
                )
            })?;
            if tuple_condition_expired(&condition, now) {
                continue;
            }
            role_bindings.push(RoleBinding {
                subject: row.try_get("subject").map_err(|err| {
                    authz_internal_status(
                        "decode_grouping_tuple",
                        format!("decode grouping tuple failed: {err}"),
                    )
                })?,
                role: row.try_get("role").map_err(|err| {
                    authz_internal_status(
                        "decode_grouping_tuple",
                        format!("decode grouping tuple failed: {err}"),
                    )
                })?,
                tenant: row.try_get("tenant").map_err(|err| {
                    authz_internal_status(
                        "decode_grouping_tuple",
                        format!("decode grouping tuple failed: {err}"),
                    )
                })?,
                project: row.try_get("project").map_err(|err| {
                    authz_internal_status(
                        "decode_grouping_tuple",
                        format!("decode grouping tuple failed: {err}"),
                    )
                })?,
            });
        }

        let tuple_rows = sqlx::query(&format!(
            "SELECT {subject}, {action} AS relation, {object_col}, {tenant_id} AS tenant, COALESCE({project_id}, '') AS project, {condition} FROM {tuple_rel} \
             WHERE {tuple_kind} = 'relationship'",
            tuple_rel = tuple.relation.clone(),
            subject = tuple.q("subject"),
            action = tuple.q("action"),
            object_col = tuple.q("object"),
            tenant_id = tuple.q("tenant_id"),
            project_id = tuple.q("project_id"),
            condition = tuple.q("condition"),
            tuple_kind = tuple.q("tuple_kind"),
        ))
        .fetch_all(pool)
        .await
        .map_err(|err| {
            authz_internal_status(
                "load_relationship_tuples",
                format!("load relationship tuples failed: {err}"),
            )
        })?;
        let mut tuples = Vec::with_capacity(tuple_rows.len());
        for row in tuple_rows {
            let condition: String = row.try_get("condition").map_err(|err| {
                authz_internal_status(
                    "decode_relationship_tuple",
                    format!("decode relationship tuple failed: {err}"),
                )
            })?;
            if tuple_condition_expired(&condition, now) {
                continue;
            }
            tuples.push(RelationshipTuple {
                subject: row.try_get("subject").map_err(|err| {
                    authz_internal_status(
                        "decode_relationship_tuple",
                        format!("decode relationship tuple failed: {err}"),
                    )
                })?,
                relation: row.try_get("relation").map_err(|err| {
                    authz_internal_status(
                        "decode_relationship_tuple",
                        format!("decode relationship tuple failed: {err}"),
                    )
                })?,
                object: row.try_get("object").map_err(|err| {
                    authz_internal_status(
                        "decode_relationship_tuple",
                        format!("decode relationship tuple failed: {err}"),
                    )
                })?,
                tenant: row.try_get("tenant").map_err(|err| {
                    authz_internal_status(
                        "decode_relationship_tuple",
                        format!("decode relationship tuple failed: {err}"),
                    )
                })?,
                project: row.try_get("project").map_err(|err| {
                    authz_internal_status(
                        "decode_relationship_tuple",
                        format!("decode relationship tuple failed: {err}"),
                    )
                })?,
            });
        }

        Ok(Some(AuthzSnapshot {
            // Content-addressed versions (not count-only): any in-place policy/
            // tuple edit changes the version even when the row count is unchanged,
            // so SDK-cached bundles and cross-node snapshot caches invalidate
            // correctly. See `policy_content_version` / `tuple_content_version`.
            version: policy_content_version(&policies),
            relationship_version: tuple_content_version(&tuples),
            policies,
            role_bindings,
            tuples,
            // The dev/bootstrap escape hatch must SURVIVE a PG warm: the broker's
            // data-plane authorize() reads this same PG-warmed cell, so if this were
            // hardcoded false, `UDB_ABAC_DEFAULT_ALLOW=true` would silently stop
            // working the moment the first reload replaced the initial snapshot.
            default_allow: abac_default_allow_env(),
        }))
    }

    pub(super) async fn current_snapshot(&self) -> Result<Arc<AuthzSnapshot>, Status> {
        let cached_is_fresh = self
            .snapshot_loaded_at
            .lock()
            .map(|guard| {
                guard
                    .map(|t| t.elapsed() < self.snapshot_ttl)
                    .unwrap_or(false)
            })
            .unwrap_or(false);
        if cached_is_fresh {
            return Ok(self.snapshot.load_full());
        }
        // H1: time the policy-snapshot (re)load so operators can alert on a slow
        // authz reload path. The histogram + recorder already exist; this is the
        // missing call site. Covers the real DB round-trip + decode in
        // `load_snapshot_from_postgres`.
        let reload_started = Instant::now();
        let revision_before = self.authz_revision_fingerprint().await?;
        let loaded = self.load_snapshot_from_postgres().await?;
        let revision_after = self.authz_revision_fingerprint().await?;
        self.metrics
            .observe_policy_reload_seconds(reload_started.elapsed().as_secs_f64());
        if revision_before != revision_after {
            return Err(crate::runtime::executor_utils::retryable_aborted_status(
                "authz",
                "snapshot reload revision",
                0,
                "authz revision changed while loading snapshot; retry snapshot load",
            ));
        }
        if let Some(snapshot) = loaded {
            self.snapshot.store(Arc::new(snapshot));
            if let Ok(mut guard) = self.snapshot_loaded_at.lock() {
                *guard = Some(Instant::now());
            }
            return Ok(self.snapshot.load_full());
        }
        self.require_snapshot_fallback()?;
        if let Ok(mut guard) = self.snapshot_loaded_at.lock() {
            *guard = Some(Instant::now());
        }
        Ok(self.snapshot.load_full())
    }
}

fn authz_snapshot_ttl() -> Duration {
    let secs = std::env::var("UDB_AUTHZ_SNAPSHOT_TTL_SECS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(5)
        .max(1);
    Duration::from_secs(secs)
}

#[tonic::async_trait]
impl AuthzService for AuthzServiceImpl {
    async fn authorize(
        &self,
        request: Request<authz_pb::AuthzRequest>,
    ) -> Result<Response<authz_pb::AuthzResponse>, Status> {
        let started = Instant::now();
        let req = request.into_inner();
        // 01.5.2.1 — capture the body-REQUESTED scopes BEFORE the claim-binding below
        // forces `principal.scopes` to the EFFECTIVE claim set, so the durable audit
        // can show requested-vs-effective (a scope the body asked for but the claim
        // did not grant is then observable).
        let requested_scopes = req
            .principal
            .as_ref()
            .map(|p| p.scopes.clone())
            .unwrap_or_default();
        let mut principal = req
            .principal
            .as_ref()
            .map(authz_principal_to_runtime)
            .unwrap_or_default();
        if principal.tenant_id.trim().is_empty() {
            principal.tenant_id = if req.tenant_id.trim().is_empty() {
                req.domain.clone()
            } else {
                req.tenant_id.clone()
            };
        }
        if principal.project_id.trim().is_empty() {
            principal.project_id = req.project_id.clone();
        }
        if principal.subject.trim().is_empty() {
            principal.subject = if !principal.user_id.trim().is_empty() {
                principal.user_id.clone()
            } else {
                principal.principal_id.clone()
            };
        }
        if principal.principal_id.trim().is_empty() {
            principal.principal_id = principal.subject.clone();
        }
        // Claim-binding (served path only): the decision must be evaluated as the
        // AUTHENTICATED caller, not as whatever principal the body claims. Seed the
        // principal from the verified claim and enforce the body tenant/project
        // matches the claim. A non-admin caller may NOT impersonate another
        // subject/tenant/project/scope set — those are forced to the claim and the
        // body `req.principal` is treated only as the asked-about TARGET. A genuine
        // cross-tenant admin may keep the body-derived principal to ask "can X do Y".
        // The in-process / loopback path (no claim) preserves the body-derived
        // behavior built above.
        if crate::runtime::service::method_security::claim_context_present() {
            let ctx = crate::runtime::service::method_security::current_claim_context();
            crate::runtime::service::method_security::enforce_body_tenant_matches_claim(
                &ctx,
                &req.tenant_id,
                &req.project_id,
            )?;
            if !ctx.is_cross_tenant_admin() {
                let base = ctx.to_principal();
                principal.subject = base.subject;
                principal.tenant_id = base.tenant_id;
                principal.project_id = base.project_id;
                principal.scopes = base.scopes;
                if principal.principal_id.trim().is_empty() {
                    principal.principal_id = principal.subject.clone();
                }
            }
        }
        let mut resource = req
            .resource
            .as_ref()
            .map(resource_to_runtime)
            .unwrap_or_default();
        enrich_resource(&mut resource);
        let mut attributes: BTreeMap<String, String> = req.attributes.into_iter().collect();
        if let Some(ctx) = req.context {
            attributes.extend(ctx.attributes.into_iter());
        }
        // Tier-0 #1: per-tenant fair admission keyed by the resolved caller
        // tenant. Held across the snapshot load + decision so a single tenant
        // flooding `Authorize` can't starve others / exhaust the PG pool.
        let _admit = self.admit(&principal.tenant_id).await?;
        let snap = self.current_snapshot().await?;
        let decision = self
            .decide_with_snapshot(
                &snap,
                &principal,
                &resource,
                &req.action,
                &req.purpose,
                &attributes,
            )
            .await;
        // Milestone 6: decision-evaluation latency.
        tracing::debug!(
            decision_id = %decision.decision_id,
            allowed = decision.allowed,
            action = %req.action,
            latency_us = started.elapsed().as_micros() as u64,
            "authz decision",
        );
        // 01.5.2.1 — fold the body-requested scopes into the audit attribute bag
        // (AFTER the decision, so the decision input is unchanged) so the durable
        // decision-audit row records what was REQUESTED next to what was EFFECTIVE.
        if !requested_scopes.is_empty() {
            attributes.insert("requested_scopes".to_string(), requested_scopes.join(","));
        }
        // Items 84–86: persist denies / audit-flagged allows to the proto audit table.
        let audit_ctx = AuditContext::from_attributes(&attributes, &req.purpose);
        self.write_decision_audit(&principal, &resource, &req.action, &decision, &audit_ctx)
            .await;
        // Publish a denial event so security dashboards (Kafka → Spark) see
        // deny rates in near-real-time, alongside the durable audit row.
        if !decision.allowed {
            let subject = if principal.user_id.trim().is_empty() {
                principal.subject.clone()
            } else {
                principal.user_id.clone()
            };
            self.emit_event(
                AuthEvent::new(
                    topics::ACCESS_DENIED,
                    subject.clone(),
                    principal.tenant_id.clone(),
                    serde_json::json!({
                        "user_id": principal.user_id.clone(),
                        "subject": subject.clone(),
                        "tenant_id": principal.tenant_id.clone(),
                        "resource": resource.resource_name.clone(),
                        "action": req.action.clone(),
                        "deny_reason": decision.deny_reason.clone(),
                        "decision_id": decision.decision_id.clone(),
                        // 01.5.2.1 — requested-vs-effective scope visibility on the
                        // deny event: the body-requested set vs the decision scopes.
                        "requested_scopes": requested_scopes.clone(),
                        "effective_scopes": principal.scopes.clone(),
                    }),
                )
                .with_correlation(if decision.decision_id.trim().is_empty() {
                    format!("deny:{}:{}", subject, resource.resource_name)
                } else {
                    decision.decision_id.clone()
                })
                .with_compliance(events::ComplianceEnvelope {
                    actor: subject.clone(),
                    actor_project: principal.project_id.clone(),
                    target_resource: resource.resource_name.clone(),
                    operation: req.action.clone(),
                    outcome: "deny".to_string(),
                    reason_code: if decision.deny_reason.trim().is_empty() {
                        "access_denied".to_string()
                    } else {
                        decision.deny_reason.clone()
                    },
                    decision_id: decision.decision_id.clone(),
                    policy_version: decision.policy_version.clone(),
                    relationship_version: decision.relationship_version.clone(),
                    source_ip: audit_ctx.source_ip.clone(),
                    trace_id: audit_ctx.trace_id.clone(),
                    span_id: audit_ctx.span_id.clone(),
                    ..events::ComplianceEnvelope::default()
                }),
            )
            .await;
        }
        Ok(Response::new(authz_pb::AuthzResponse {
            decision: Some(decision_to_pb(&decision)),
        }))
    }

    async fn put_role_binding(
        &self,
        request: Request<authz_pb::PutRoleBindingRequest>,
    ) -> Result<Response<authz_pb::AuthMutationResponse>, Status> {
        self.put_role_binding_impl(request).await
    }

    async fn put_relationship(
        &self,
        request: Request<authz_pb::PutRelationshipRequest>,
    ) -> Result<Response<authz_pb::AuthMutationResponse>, Status> {
        self.put_relationship_impl(request).await
    }

    async fn put_authz_policy(
        &self,
        request: Request<authz_pb::PutAuthzPolicyRequest>,
    ) -> Result<Response<authz_pb::AuthMutationResponse>, Status> {
        // K2.2: in governed mode a direct active mutation is rejected — callers
        // must go through the draft -> approve -> activate flow (or use a
        // break-glass governance RPC). Off by default so legacy deployments keep
        // the direct path.
        if governance::governed_mode_enabled() {
            return Err(governed_direct_mutation_status(
                "PutAuthzPolicy",
                "put_authz_policy_disabled",
            ));
        }
        let p = request.into_inner().policy.ok_or_else(|| {
            authz_required_field(
                "policy is required",
                "policy",
                "must include an authz policy",
            )
        })?;
        if p.id.trim().is_empty() {
            return Err(authz_required_field(
                "policy id is required",
                "policy.id",
                "must be a non-empty policy id",
            ));
        }
        // Reject unknown effect strings rather than silently defaulting to Allow:
        // a typo'd effect must never become a permissive policy.
        let effect = if p.effect.eq_ignore_ascii_case("deny") {
            Effect::Deny
        } else if p.effect.eq_ignore_ascii_case("allow") {
            Effect::Allow
        } else {
            return Err(authz_invalid_fields(
                format!(
                    "policy effect must be 'allow' or 'deny', got '{}'",
                    p.effect
                ),
                [("policy.effect", "must be either 'allow' or 'deny'")],
            ));
        };
        let policy = AuthzPolicy {
            id: p.id,
            priority: p.priority,
            enabled: p.enabled,
            effect,
            tenant: p.tenant,
            project: p.project,
            subject: p.subject,
            role: p.role,
            action: p.action,
            resource: p.resource,
            purpose: p.purpose,
            relationship: p.relationship,
            conditions: p.conditions.into_iter().collect(),
            required_scopes: p.required_scopes,
        };
        if self.pg_pool.is_some() {
            let runtime = self.runtime.as_ref().ok_or_else(|| {
                authz_capability_status(
                    "policy_persistence",
                    "runtime_native_entity_dispatch",
                    "native authz requires runtime-backed policy persistence",
                )
            })?;
            let policy_id = parse_uuid_field("policy.id", &policy.id)?;
            let mut attributes = serde_json::Map::new();
            for (key, value) in &policy.conditions {
                attributes.insert(key.clone(), serde_json::Value::String(value.clone()));
            }
            attributes.insert(
                "priority".to_string(),
                serde_json::Value::String(policy.priority.to_string()),
            );
            attributes.insert(
                "role".to_string(),
                serde_json::Value::String(policy.role.clone()),
            );
            attributes.insert(
                "purpose".to_string(),
                serde_json::Value::String(policy.purpose.clone()),
            );
            attributes.insert(
                "relationship".to_string(),
                serde_json::Value::String(policy.relationship.clone()),
            );
            attributes.insert(
                "required_scopes".to_string(),
                serde_json::Value::String(scopes_to_db(&policy.required_scopes)),
            );
            // P6.10 Wave 4: typed upsert on PK `policy_id` (was raw INSERT … ON
            // CONFLICT (policy_id) DO UPDATE). `condition`/`description` are
            // insert-only ('' literals, NOT in the update set); `domain` binds to
            // `policy.tenant` exactly as the raw `$3` reuse; attributes_json → JSONB.
            let mut record = LogicalRecord::new();
            record.insert(
                "policy_id".to_string(),
                LogicalValue::String(policy_id.to_string()),
            );
            record.insert(
                "subject".to_string(),
                LogicalValue::String(policy.subject.clone()),
            );
            record.insert(
                "domain".to_string(),
                LogicalValue::String(policy.tenant.clone()),
            );
            record.insert(
                "object".to_string(),
                LogicalValue::String(policy.resource.clone()),
            );
            record.insert(
                "action".to_string(),
                LogicalValue::String(policy.action.clone()),
            );
            record.insert(
                "effect".to_string(),
                LogicalValue::String(effect_to_db(policy.effect).to_string()),
            );
            record.insert("condition".to_string(), LogicalValue::String(String::new()));
            record.insert(
                "description".to_string(),
                LogicalValue::String(String::new()),
            );
            record.insert("is_active".to_string(), LogicalValue::Bool(policy.enabled));
            record.insert(
                "tenant_id".to_string(),
                LogicalValue::String(policy.tenant.clone()),
            );
            record.insert(
                "project_id".to_string(),
                LogicalValue::String(policy.project.clone()),
            );
            record.insert(
                "attributes_json".to_string(),
                LogicalValue::Json(serde_json::Value::Object(attributes)),
            );
            let context = crate::RequestContext {
                tenant_id: policy.tenant.clone(),
                project_id: policy.project.clone(),
                ..crate::RequestContext::default()
            };
            runtime
                .native_entity_write_for_service(
                    "authz",
                    &context,
                    "udb.core.authz.entity.v1.PolicyRule",
                    record,
                    ConflictStrategy::update(vec![
                        "subject".to_string(),
                        "domain".to_string(),
                        "object".to_string(),
                        "action".to_string(),
                        "effect".to_string(),
                        "is_active".to_string(),
                        "tenant_id".to_string(),
                        "project_id".to_string(),
                        "attributes_json".to_string(),
                    ]),
                )
                .await
                .map_err(|err| {
                    authz_internal_status(
                        "store_authz_policy",
                        format!("store authz policy failed: {err}"),
                    )
                })?;
            let _ = self
                .bump_authz_revision(
                    &policy.tenant,
                    &policy.project,
                    authz_entity_pb::AuthzChangeType::Policy,
                    "policy-put",
                    "",
                )
                .await;
        } else {
            self.require_snapshot_fallback()?;
        }
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::AuthMutationResponse {
            ok: true,
            message: "authz policy stored".to_string(),
        }))
    }

    async fn lint_authz_policies(
        &self,
        _request: Request<authz_pb::LintAuthzPoliciesRequest>,
    ) -> Result<Response<authz_pb::LintAuthzPoliciesResponse>, Status> {
        // Item 82: lint through the `PolicyEngine` seam — the snapshot's v2
        // linter covers the previous inline checks (empty/duplicate ids,
        // disabled rules, overly broad allows) plus shadowed allows, dangling
        // role refs, and duplicate relationship tuples.
        let snap = self.current_snapshot().await?;
        let findings = PolicyEngine::lint(snap.as_ref())
            .await
            .into_iter()
            .map(|f| format!("[{}] {}: {}", f.severity, f.category, f.message))
            .collect();
        Ok(Response::new(authz_pb::LintAuthzPoliciesResponse {
            findings,
        }))
    }

    // Snapshot-backed authz helpers. Role entity CRUD + audits remain DB-backed
    // surfaces for later milestones.

    async fn check_access(
        &self,
        request: Request<authz_pb::CheckAccessRequest>,
    ) -> Result<Response<authz_pb::CheckAccessResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(authz_required_field(
                "user_id is required",
                "user_id",
                "must be a non-empty user id",
            ));
        }
        if req.object.trim().is_empty() {
            return Err(authz_required_field(
                "object is required",
                "object",
                "must be a non-empty object",
            ));
        }
        if req.action.trim().is_empty() {
            return Err(authz_required_field(
                "action is required",
                "action",
                "must be a non-empty action",
            ));
        }

        let mut principal = req
            .principal
            .as_ref()
            .map(authz_principal_to_runtime)
            .unwrap_or_default();
        if principal.principal_id.trim().is_empty() {
            principal.principal_id = req.user_id.clone();
        }
        if principal.subject.trim().is_empty() {
            principal.subject = req.user_id.clone();
        }
        if principal.user_id.trim().is_empty() {
            principal.user_id = req.user_id.clone();
        }
        if principal.tenant_id.trim().is_empty() {
            principal.tenant_id = if req.tenant_id.trim().is_empty() {
                req.domain.clone()
            } else {
                req.tenant_id.clone()
            };
        }
        if principal.project_id.trim().is_empty() {
            principal.project_id = req.project_id.clone();
        }

        // Claim-binding (served path only): a non-admin caller may only ask the PDP
        // about THEMSELVES — force the evaluated principal's subject/tenant/project/
        // scopes to the verified claim so a tenant-A token cannot probe a tenant-B
        // user's access by supplying that user_id. A cross-tenant admin keeps the
        // body-derived "can user X do Y?" query. The in-process/loopback path (no
        // claim) preserves the body-derived behavior above.
        if crate::runtime::service::method_security::claim_context_present() {
            let ctx = crate::runtime::service::method_security::current_claim_context();
            crate::runtime::service::method_security::enforce_body_tenant_matches_claim(
                &ctx,
                &req.tenant_id,
                &req.project_id,
            )?;
            if !ctx.is_cross_tenant_admin() {
                let base = ctx.to_principal();
                principal.subject = base.subject;
                principal.user_id = base.user_id;
                principal.tenant_id = base.tenant_id;
                principal.project_id = base.project_id;
                principal.scopes = base.scopes;
                if principal.principal_id.trim().is_empty() {
                    principal.principal_id = principal.subject.clone();
                }
            }
        }

        let mut resource = req
            .resource
            .as_ref()
            .map(resource_to_runtime)
            .unwrap_or_default();
        if resource.resource_name.trim().is_empty() {
            resource.resource_name = req.object.clone();
        }
        if resource.message_type.trim().is_empty() {
            resource.message_type = req.object.clone();
        }
        enrich_resource(&mut resource);

        let mut attributes: BTreeMap<String, String> = req.attributes.into_iter().collect();
        if let Some(ctx) = req.context {
            attributes.extend(ctx.attributes.into_iter());
        }
        // Tier-0 #1: per-tenant fair admission keyed by the resolved caller
        // tenant, held across the snapshot load + decision (same backpressure the
        // data plane returns on exhaustion).
        let _admit = self.admit(&principal.tenant_id).await?;
        let snap = self.current_snapshot().await?;
        let decision = self
            .decide_with_snapshot(
                &snap,
                &principal,
                &resource,
                &req.action,
                &req.purpose,
                &attributes,
            )
            .await;
        let audit_ctx = AuditContext::from_attributes(&attributes, &req.purpose);
        self.write_decision_audit(&principal, &resource, &req.action, &decision, &audit_ctx)
            .await;
        Ok(Response::new(authz_pb::CheckAccessResponse {
            allowed: decision.allowed,
            effect: effect_to_entity(decision.effect),
            matched_rule: decision
                .matched_policy_ids
                .first()
                .cloned()
                .unwrap_or_default(),
            reason: decision.deny_reason.clone(),
            decision: Some(decision_to_pb(&decision)),
        }))
    }
    async fn create_role(
        &self,
        request: Request<authz_pb::CreateRoleRequest>,
    ) -> Result<Response<authz_pb::CreateRoleResponse>, Status> {
        governance::guard_governed_role_mutation("CreateRole")?;
        let req = request.into_inner();
        if req.name.trim().is_empty() {
            return Err(authz_required_field(
                "name is required",
                "name",
                "must be a non-empty role name",
            ));
        }
        let tenant_id = tenant_from_domain(&req.tenant_id, &req.domain);
        if tenant_id.trim().is_empty() {
            return Err(authz_invalid_fields(
                "tenant_id or domain is required",
                [
                    (
                        "tenant_id",
                        "must include tenant_id or a tenant/project/resource domain",
                    ),
                    (
                        "domain",
                        "must include tenant_id or a tenant/project/resource domain",
                    ),
                ],
            ));
        }
        // Bind `created_by` to the authenticated caller on the served path: derive
        // it from the claim subject when the body omits it, and forge-guard a
        // supplied value that disagrees with the caller's claim-derived UUID unless
        // the caller is a cross-tenant/governance admin acting on someone's behalf.
        let created_by = if crate::runtime::service::method_security::claim_context_present() {
            let ctx = crate::runtime::service::method_security::current_claim_context();
            let claim_id = stable_uuid_from_subject(&ctx.subject);
            if req.created_by.trim().is_empty() {
                claim_id
            } else {
                let supplied = parse_uuid_field("created_by", &req.created_by)?;
                if supplied != claim_id && !ctx.is_cross_tenant_admin() {
                    return Err(created_by_caller_mismatch_status("create_role"));
                }
                supplied
            }
        } else {
            if req.created_by.trim().is_empty() {
                return Err(authz_required_field(
                    "created_by is required",
                    "created_by",
                    "must be a non-empty creator id",
                ));
            }
            parse_uuid_field("created_by", &req.created_by)?
        };
        let runtime = self.runtime.as_ref().ok_or_else(|| {
            authz_capability_status(
                "role_persistence",
                "runtime_native_entity_dispatch",
                "native authz requires runtime-backed role persistence",
            )
        })?;
        let role_id = Uuid::new_v4().to_string();
        let metadata_json =
            serde_json::to_string(&req.metadata).unwrap_or_else(|_| "{}".to_string());
        // P6.10 Wave 1: typed native insert (was raw INSERT). `is_system=false`,
        // `is_active=true` literals preserved; `created_by` is a validated UUID
        // (so the old `NULLIF($4,'')` never fired); `metadata_json` binds as JSONB
        // via `LogicalValue::Json`.
        let mut record = LogicalRecord::new();
        record.insert("role_id".to_string(), LogicalValue::String(role_id.clone()));
        record.insert("name".to_string(), LogicalValue::String(req.name.clone()));
        record.insert(
            "description".to_string(),
            LogicalValue::String(req.description.clone()),
        );
        record.insert("is_system".to_string(), LogicalValue::Bool(false));
        record.insert("is_active".to_string(), LogicalValue::Bool(true));
        record.insert(
            "created_by".to_string(),
            LogicalValue::String(created_by.to_string()),
        );
        record.insert(
            "tenant_id".to_string(),
            LogicalValue::String(tenant_id.clone()),
        );
        record.insert(
            "project_id".to_string(),
            LogicalValue::String(req.project_id.clone()),
        );
        record.insert(
            "role_code".to_string(),
            LogicalValue::String(req.role_code.clone()),
        );
        record.insert(
            "domain".to_string(),
            LogicalValue::String(req.domain.clone()),
        );
        record.insert(
            "scope_type".to_string(),
            LogicalValue::String(role_scope_type_to_db(req.scope_type).to_string()),
        );
        record.insert(
            "access_surface".to_string(),
            LogicalValue::String(req.access_surface.clone()),
        );
        record.insert(
            "metadata_json".to_string(),
            LogicalValue::Json(
                serde_json::from_str(&metadata_json)
                    .unwrap_or_else(|_| serde_json::Value::Object(Default::default())),
            ),
        );
        let context = crate::RequestContext {
            tenant_id: tenant_id.clone(),
            project_id: req.project_id.clone(),
            ..crate::RequestContext::default()
        };
        runtime
            .native_entity_write_for_service(
                "authz",
                &context,
                "udb.core.authz.entity.v1.Role",
                record,
                ConflictStrategy::Error,
            )
            .await
            .map_err(|err| {
                crate::runtime::executor_utils::prefix_status("create role failed", err)
            })?;
        self.emit_event(
            AuthEvent::new(
                topics::ROLE_CREATED,
                role_id.clone(),
                tenant_id.clone(),
                serde_json::json!({
                    "role_id": role_id.clone(),
                    "role_code": req.role_code.clone(),
                    "tenant_id": tenant_id.clone(),
                    "project_id": req.project_id.clone(),
                    "created_by": req.created_by.clone(),
                }),
            )
            .with_correlation(format!("role_create:{role_id}"))
            .with_compliance(events::ComplianceEnvelope {
                actor: if req.created_by.trim().is_empty() {
                    created_by.to_string()
                } else {
                    req.created_by.clone()
                },
                actor_project: req.project_id.clone(),
                target_resource: format!("role:{role_id}"),
                operation: "role_create".to_string(),
                outcome: "success".to_string(),
                reason_code: "role_created".to_string(),
                ..events::ComplianceEnvelope::default()
            }),
        )
        .await;
        let _ = self
            .bump_authz_revision(
                &tenant_id,
                &req.project_id,
                authz_entity_pb::AuthzChangeType::Role,
                "role-created",
                &req.created_by,
            )
            .await;
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::CreateRoleResponse {
            role: Some(authz_entity_pb::Role {
                role_id,
                name: req.name,
                description: req.description,
                is_system: false,
                is_active: true,
                created_by: req.created_by,
                created_at: None,
                updated_at: None,
                deleted_at: None,
                tenant_id,
                deleted_by: String::new(),
                role_code: req.role_code,
                domain: req.domain,
                project_id: req.project_id,
                scope_type: req.scope_type,
                access_surface: req.access_surface,
                metadata_json,
            }),
        }))
    }
    async fn assign_role(
        &self,
        request: Request<authz_pb::AssignRoleRequest>,
    ) -> Result<Response<authz_pb::AssignRoleResponse>, Status> {
        governance::guard_governed_role_mutation("AssignRole")?;
        let req = request.into_inner();
        // K7 principal-kind parity: a binding identifies a principal by either a
        // UUID user_id (USER compat) or a non-UUID principal_id for service
        // accounts / workloads / groups / external subjects. The `user_roles`
        // table keys on a UUID column, so non-UUID principals are mapped to a
        // STABLE UUID derived from their canonical principal id (deterministic,
        // so the same principal always resolves to the same row). Groups may be
        // bound only through an explicit principal_id (IdP/SCIM mapping policy).
        use authz_entity_pb::PrincipalKind;
        let principal_kind = PrincipalKind::try_from(req.principal_kind).unwrap_or_default();
        let principal_ref = if !req.principal_id.trim().is_empty() {
            req.principal_id.clone()
        } else {
            req.user_id.clone()
        };
        if principal_ref.trim().is_empty() || req.role_id.trim().is_empty() {
            return Err(authz_invalid_fields(
                "user_id (or principal_id) and role_id are required",
                [
                    (
                        "user_id",
                        "must include user_id or principal_id for the role binding",
                    ),
                    (
                        "principal_id",
                        "must include user_id or principal_id for the role binding",
                    ),
                    ("role_id", "must be a non-empty role id"),
                ],
            ));
        }
        if matches!(principal_kind, PrincipalKind::Group) && req.principal_id.trim().is_empty() {
            return Err(authz_required_field(
                "group role bindings require an explicit principal_id (IdP/SCIM group mapping)",
                "principal_id",
                "must be explicit for group role bindings",
            ));
        }
        // Bind `assigned_by` to the authenticated caller on the served path (same
        // shape as create_role.created_by): derive from the claim subject when the
        // body omits it; forge-guard a supplied value that disagrees with the
        // caller's claim-derived UUID unless the caller is a cross-tenant admin.
        let assigned_by_uuid = if crate::runtime::service::method_security::claim_context_present()
        {
            let ctx = crate::runtime::service::method_security::current_claim_context();
            let claim_id = stable_uuid_from_subject(&ctx.subject);
            if req.assigned_by.trim().is_empty() {
                claim_id
            } else {
                let supplied = parse_uuid_field("assigned_by", &req.assigned_by)?;
                if supplied != claim_id && !ctx.is_cross_tenant_admin() {
                    return Err(assigned_by_caller_mismatch_status());
                }
                supplied
            }
        } else {
            if req.assigned_by.trim().is_empty() {
                return Err(authz_required_field(
                    "assigned_by is required",
                    "assigned_by",
                    "must be a non-empty assigner id",
                ));
            }
            parse_uuid_field("assigned_by", &req.assigned_by)?
        };
        // USER with a UUID keeps its UUID; every other kind (and non-UUID users)
        // gets a stable derived UUID so service/workload/group/external principals
        // are first-class without forcing them through a real user_id.
        let user_id = match principal_kind {
            PrincipalKind::User | PrincipalKind::Unspecified => {
                Uuid::parse_str(principal_ref.trim())
                    .unwrap_or_else(|_| stable_uuid_from_subject(principal_ref.trim()))
            }
            _ => stable_uuid_from_subject(principal_ref.trim()),
        };
        let role_id = parse_uuid_field("role_id", &req.role_id)?;
        let assigned_by = assigned_by_uuid;
        let expires_at_unix = timestamp_unix_field("expires_at", req.expires_at.clone())?;
        let tenant_id = tenant_from_domain(&req.tenant_id, &req.domain);
        if tenant_id.trim().is_empty() {
            return Err(authz_invalid_fields(
                "tenant_id or domain is required",
                [
                    (
                        "tenant_id",
                        "must include tenant_id or a tenant/project/resource domain",
                    ),
                    (
                        "domain",
                        "must include tenant_id or a tenant/project/resource domain",
                    ),
                ],
            ));
        }

        // Non-USER principals (service account / workload / group / external)
        // bind via a grouping tuple keyed on the LITERAL principal id so the
        // snapshot loader exposes the real subject string (a derived UUID in
        // user_roles would never match at decision time). USER (UUID) keeps the
        // user_roles path for backward compatibility.
        let is_literal_principal = matches!(
            principal_kind,
            PrincipalKind::ServiceAccount
                | PrincipalKind::Workload
                | PrincipalKind::Group
                | PrincipalKind::ExternalSubject
        ) || (matches!(
            principal_kind,
            PrincipalKind::Unspecified | PrincipalKind::User
        ) && Uuid::parse_str(principal_ref.trim()).is_err());
        if is_literal_principal {
            let role_code = self
                .role_code_for(role_id, &req.domain)
                .await?
                .unwrap_or_else(|| req.role_id.clone());
            let condition = serde_json::json!({
                "source": "assign_role",
                "principal_kind": req.principal_kind,
                "expires_at_unix": expires_at_unix.unwrap_or(0),
            })
            .to_string();
            // P6.10 Wave 4: typed grouping-tuple upsert on the composite unique
            // (tuple_kind,subject,domain,object,action,effect); only condition+tenant_id
            // update on conflict. domain and tenant_id both = tenant_id (raw `$3` reuse);
            // object/effect are insert literals ''.
            let runtime = self.runtime.as_ref().ok_or_else(|| {
                authz_capability_status(
                    "tuple_persistence",
                    "runtime_native_entity_dispatch",
                    "native authz requires runtime-backed tuple persistence",
                )
            })?;
            let mut record = LogicalRecord::new();
            record.insert(
                "tuple_kind".to_string(),
                LogicalValue::String("grouping".to_string()),
            );
            record.insert(
                "subject".to_string(),
                LogicalValue::String(principal_ref.trim().to_string()),
            );
            record.insert(
                "domain".to_string(),
                LogicalValue::String(tenant_id.clone()),
            );
            record.insert("object".to_string(), LogicalValue::String(String::new()));
            record.insert(
                "action".to_string(),
                LogicalValue::String(role_code.clone()),
            );
            record.insert("effect".to_string(), LogicalValue::String(String::new()));
            record.insert(
                "condition".to_string(),
                LogicalValue::String(condition.clone()),
            );
            record.insert(
                "tenant_id".to_string(),
                LogicalValue::String(tenant_id.clone()),
            );
            record.insert(
                "project_id".to_string(),
                LogicalValue::String(req.project_id.clone()),
            );
            let context = crate::RequestContext {
                tenant_id: tenant_id.clone(),
                project_id: req.project_id.clone(),
                ..crate::RequestContext::default()
            };
            runtime
                .native_entity_write_for_service(
                    "authz",
                    &context,
                    "udb.core.authz.entity.v1.PolicyTuple",
                    record,
                    ConflictStrategy::update_on(
                        vec!["condition".to_string(), "tenant_id".to_string()],
                        vec![
                            "tuple_kind".to_string(),
                            "subject".to_string(),
                            "domain".to_string(),
                            "object".to_string(),
                            "action".to_string(),
                            "effect".to_string(),
                        ],
                    ),
                )
                .await
                .map_err(|err| {
                    authz_internal_status(
                        "assign_role_principal",
                        format!("assign role (principal) failed: {err}"),
                    )
                })?;
            self.emit_event(
                AuthEvent::new(
                    topics::ROLE_ASSIGNED,
                    principal_ref.clone(),
                    tenant_id.clone(),
                    serde_json::json!({
                        "principal_id": principal_ref.clone(),
                        "principal_kind": req.principal_kind,
                        "role_id": req.role_id.clone(),
                        "role_code": role_code.clone(),
                        "tenant_id": tenant_id.clone(),
                        "domain": req.domain.clone(),
                        "assigned_by": req.assigned_by.clone(),
                    }),
                )
                .with_correlation(format!("role_assign:{principal_ref}:{}", req.role_id))
                .with_compliance(events::ComplianceEnvelope {
                    actor: if req.assigned_by.trim().is_empty() {
                        principal_ref.clone()
                    } else {
                        req.assigned_by.clone()
                    },
                    actor_project: req.project_id.clone(),
                    target_resource: principal_ref.clone(),
                    operation: "role_assign".to_string(),
                    outcome: "success".to_string(),
                    reason_code: "role_assigned".to_string(),
                    ..events::ComplianceEnvelope::default()
                }),
            )
            .await;
            let _ = self
                .bump_authz_revision(
                    &tenant_id,
                    &req.project_id,
                    authz_entity_pb::AuthzChangeType::RoleAssignment,
                    "role-assignment",
                    &req.assigned_by,
                )
                .await;
            self.invalidate_snapshot_cache();
            return Ok(Response::new(authz_pb::AssignRoleResponse {
                user_role: Some(authz_entity_pb::UserRole {
                    user_role_id: stable_uuid_from_subject(&format!(
                        "{principal_ref}:{}:{}",
                        req.role_id, req.domain
                    ))
                    .to_string(),
                    user_id: principal_ref,
                    role_id: req.role_id,
                    domain: req.domain,
                    assigned_by: req.assigned_by.clone(),
                    assigned_at: None,
                    expires_at: req.expires_at,
                    created_at: None,
                    updated_at: None,
                    created_by: req.assigned_by,
                    tenant_id,
                }),
            }));
        }

        let new_user_role_id = Uuid::new_v4().to_string();
        // P6.10 Wave 4: typed UserRole upsert on the composite unique
        // (user_id,role_id,domain) + RETURNING user_role_id (existing on conflict,
        // new on insert). The raw `CASE WHEN $8 <= 0 THEN NULL ELSE to_timestamp($8)`
        // expiry is computed here as a typed Timestamp (NULL when absent/non-positive).
        // `created_by` binds req.assigned_by verbatim (parity with the raw `$7`).
        let expires_value = match expires_at_unix {
            Some(seconds) if seconds > 0 => chrono::DateTime::from_timestamp(seconds, 0)
                .map(LogicalValue::Timestamp)
                .unwrap_or(LogicalValue::Null),
            _ => LogicalValue::Null,
        };
        let runtime = self.runtime.as_ref().ok_or_else(|| {
            authz_capability_status(
                "user_role_persistence",
                "runtime_native_entity_dispatch",
                "native authz requires runtime-backed user-role persistence",
            )
        })?;
        let mut record = LogicalRecord::new();
        record.insert(
            "user_role_id".to_string(),
            LogicalValue::String(new_user_role_id.clone()),
        );
        record.insert(
            "user_id".to_string(),
            LogicalValue::String(user_id.to_string()),
        );
        record.insert(
            "role_id".to_string(),
            LogicalValue::String(role_id.to_string()),
        );
        record.insert(
            "domain".to_string(),
            LogicalValue::String(req.domain.clone()),
        );
        record.insert(
            "assigned_by".to_string(),
            LogicalValue::String(assigned_by.to_string()),
        );
        record.insert(
            "tenant_id".to_string(),
            LogicalValue::String(tenant_id.clone()),
        );
        record.insert(
            "created_by".to_string(),
            LogicalValue::String(req.assigned_by.clone()),
        );
        record.insert("expires_at".to_string(), expires_value);
        let context = crate::RequestContext {
            tenant_id: tenant_id.clone(),
            project_id: req.project_id.clone(),
            ..crate::RequestContext::default()
        };
        let returned = runtime
            .native_entity_write_for_service_returning(
                "authz",
                &context,
                "udb.core.authz.entity.v1.UserRole",
                record,
                ConflictStrategy::update_on(
                    vec![
                        "assigned_by".to_string(),
                        "tenant_id".to_string(),
                        "created_by".to_string(),
                        "expires_at".to_string(),
                    ],
                    vec![
                        "user_id".to_string(),
                        "role_id".to_string(),
                        "domain".to_string(),
                    ],
                ),
                vec!["user_role_id".to_string()],
            )
            .await
            .map_err(|err| {
                authz_internal_status("assign_role", format!("assign role failed: {err}"))
            })?;
        let user_role_id = returned
            .first()
            .and_then(|r| r.get("user_role_id"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or(new_user_role_id);
        self.emit_event(
            AuthEvent::new(
                topics::ROLE_ASSIGNED,
                req.user_id.clone(),
                tenant_id.clone(),
                serde_json::json!({
                    "user_role_id": user_role_id.clone(),
                    "user_id": req.user_id.clone(),
                    "role_id": req.role_id.clone(),
                    "tenant_id": tenant_id.clone(),
                    "domain": req.domain.clone(),
                    "assigned_by": req.assigned_by.clone(),
                }),
            )
            .with_correlation(format!("role_assign:{}:{}", req.user_id, req.role_id))
            .with_compliance(events::ComplianceEnvelope {
                actor: if req.assigned_by.trim().is_empty() {
                    req.user_id.clone()
                } else {
                    req.assigned_by.clone()
                },
                actor_project: req.project_id.clone(),
                target_resource: req.user_id.clone(),
                operation: "role_assign".to_string(),
                outcome: "success".to_string(),
                reason_code: "role_assigned".to_string(),
                ..events::ComplianceEnvelope::default()
            }),
        )
        .await;
        // K2.1: role assignment bumps the active authz revision so cached bundles
        // invalidate (not only policy/tuple edits).
        let _ = self
            .bump_authz_revision(
                &tenant_id,
                &req.project_id,
                authz_entity_pb::AuthzChangeType::RoleAssignment,
                "role-assignment",
                &req.assigned_by,
            )
            .await;
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::AssignRoleResponse {
            user_role: Some(authz_entity_pb::UserRole {
                user_role_id,
                user_id: req.user_id,
                role_id: req.role_id,
                domain: req.domain,
                assigned_by: req.assigned_by.clone(),
                assigned_at: None,
                expires_at: req.expires_at,
                created_at: None,
                updated_at: None,
                created_by: req.assigned_by,
                tenant_id,
            }),
        }))
    }
    async fn create_policy_rule(
        &self,
        request: Request<authz_pb::CreatePolicyRuleRequest>,
    ) -> Result<Response<authz_pb::CreatePolicyRuleResponse>, Status> {
        // K2.2: governed mode disables direct active mutation (use the draft flow).
        if governance::governed_mode_enabled() {
            return Err(governed_direct_mutation_status(
                "CreatePolicyRule",
                "create_policy_rule_disabled",
            ));
        }
        let req = request.into_inner();
        if req.subject.trim().is_empty() {
            return Err(authz_required_field(
                "subject is required",
                "subject",
                "must be a non-empty policy subject",
            ));
        }
        if req.domain.trim().is_empty() {
            return Err(authz_required_field(
                "domain is required",
                "domain",
                "must be a non-empty policy domain",
            ));
        }
        if req.object.trim().is_empty() {
            return Err(authz_required_field(
                "object is required",
                "object",
                "must be a non-empty policy object",
            ));
        }
        if req.action.trim().is_empty() {
            return Err(authz_required_field(
                "action is required",
                "action",
                "must be a non-empty policy action",
            ));
        }
        // Bind `created_by` to the authenticated caller on the served path (same
        // shape as create_role.created_by): derive from the claim subject when the
        // body omits it; forge-guard a supplied mismatch unless cross-tenant admin.
        let created_by = if crate::runtime::service::method_security::claim_context_present() {
            let ctx = crate::runtime::service::method_security::current_claim_context();
            let claim_id = stable_uuid_from_subject(&ctx.subject);
            if req.created_by.trim().is_empty() {
                claim_id
            } else {
                let supplied = parse_uuid_field("created_by", &req.created_by)?;
                if supplied != claim_id && !ctx.is_cross_tenant_admin() {
                    return Err(created_by_caller_mismatch_status("create_policy_rule"));
                }
                supplied
            }
        } else {
            if req.created_by.trim().is_empty() {
                return Err(authz_required_field(
                    "created_by is required",
                    "created_by",
                    "must be a non-empty creator id",
                ));
            }
            parse_uuid_field("created_by", &req.created_by)?
        };
        let effect = entity_effect_to_runtime(req.effect)?;
        let policy = AuthzPolicy {
            id: Uuid::new_v4().to_string(),
            priority: 0,
            enabled: true,
            effect,
            tenant: if req.tenant_id.trim().is_empty() {
                req.domain.clone()
            } else {
                req.tenant_id.clone()
            },
            project: req.project_id.clone(),
            subject: req.subject.clone(),
            role: String::new(),
            action: req.action.clone(),
            resource: req.object.clone(),
            purpose: String::new(),
            relationship: String::new(),
            conditions: req.attributes.into_iter().collect(),
            required_scopes: Vec::new(),
        };
        let policy_rule = policy_to_rule_pb(&policy);
        if self.pg_pool.is_some() {
            let runtime = self.runtime.as_ref().ok_or_else(|| {
                authz_capability_status(
                    "policy_persistence",
                    "runtime_native_entity_dispatch",
                    "native authz requires runtime-backed policy persistence",
                )
            })?;
            let attributes = serde_json::to_value(&policy.conditions).map_err(|err| {
                authz_internal_status(
                    "encode_policy_conditions",
                    format!("encode policy conditions failed: {err}"),
                )
            })?;
            // P6.10 Wave 1: typed native insert (was raw INSERT). `is_active=TRUE`
            // literal preserved; `created_by` is a validated UUID; `attributes_json`
            // binds as JSONB via `LogicalValue::Json`. Column→value parity is exact:
            // domain=req.domain, object=policy.resource, tenant_id=policy.tenant.
            let mut record = LogicalRecord::new();
            record.insert(
                "policy_id".to_string(),
                LogicalValue::String(policy.id.clone()),
            );
            record.insert(
                "subject".to_string(),
                LogicalValue::String(policy.subject.clone()),
            );
            record.insert(
                "domain".to_string(),
                LogicalValue::String(req.domain.clone()),
            );
            record.insert(
                "object".to_string(),
                LogicalValue::String(policy.resource.clone()),
            );
            record.insert(
                "action".to_string(),
                LogicalValue::String(policy.action.clone()),
            );
            record.insert(
                "effect".to_string(),
                LogicalValue::String(effect_to_db(policy.effect).to_string()),
            );
            record.insert(
                "condition".to_string(),
                LogicalValue::String(req.condition.clone()),
            );
            record.insert(
                "description".to_string(),
                LogicalValue::String(req.description.clone()),
            );
            record.insert("is_active".to_string(), LogicalValue::Bool(true));
            record.insert(
                "created_by".to_string(),
                LogicalValue::String(created_by.to_string()),
            );
            record.insert(
                "tenant_id".to_string(),
                LogicalValue::String(policy.tenant.clone()),
            );
            record.insert(
                "project_id".to_string(),
                LogicalValue::String(policy.project.clone()),
            );
            record.insert(
                "resource_type".to_string(),
                LogicalValue::String(req.resource_type.clone()),
            );
            record.insert(
                "attributes_json".to_string(),
                LogicalValue::Json(attributes),
            );
            let context = crate::RequestContext {
                tenant_id: policy.tenant.clone(),
                // `GetPolicyRule`/`ListPolicyRules` read the authz control table
                // from the service Postgres pool. Store the caller's project_id in
                // the row, but do not use it for native-store placement here or a
                // project-scoped backend can receive the write while the served
                // read path checks the primary control table.
                project_id: String::new(),
                ..crate::RequestContext::default()
            };
            let returned = runtime
                .native_entity_write_for_service_returning(
                    "authz",
                    &context,
                    "udb.core.authz.entity.v1.PolicyRule",
                    record,
                    ConflictStrategy::Error,
                    vec!["policy_id".to_string()],
                )
                .await
                .map_err(|err| {
                    authz_internal_status(
                        "create_policy_rule",
                        format!("create policy rule failed: {err}"),
                    )
                })?;
            let created_policy_id = returned
                .first()
                .and_then(|r| r.get("policy_id"))
                .and_then(|v| v.as_str())
                .ok_or_else(|| {
                    authz_internal_status(
                        "create_policy_rule",
                        "create policy rule returned no persisted id",
                    )
                })?
                .to_string();
            if created_policy_id != policy.id {
                return Err(authz_internal_status(
                    "create_policy_rule",
                    "create policy rule returned mismatched policy_id",
                ));
            }
            let _ = self
                .bump_authz_revision(
                    &policy.tenant,
                    &policy.project,
                    authz_entity_pb::AuthzChangeType::Policy,
                    "policy-created",
                    &req.created_by,
                )
                .await;
        } else {
            self.require_snapshot_fallback()?;
        }
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::CreatePolicyRuleResponse {
            policy: Some(authz_entity_pb::PolicyRule {
                domain: req.domain,
                description: req.description,
                created_by: req.created_by,
                resource_type: req.resource_type,
                condition: req.condition,
                ..policy_rule
            }),
        }))
    }
    async fn list_user_permissions(
        &self,
        request: Request<authz_pb::ListUserPermissionsRequest>,
    ) -> Result<Response<authz_pb::ListUserPermissionsResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(authz_required_field(
                "user_id is required",
                "user_id",
                "must be a non-empty user id",
            ));
        }
        let snap = self.current_snapshot().await?;
        let mut roles = Vec::new();
        for binding in &snap.role_bindings {
            if binding.subject == req.user_id
                && (req.domain.trim().is_empty()
                    || binding.tenant == req.domain
                    || binding.project == req.domain)
                && !roles.contains(&binding.role)
            {
                roles.push(binding.role.clone());
            }
        }
        let mut permissions = Vec::new();
        for policy in &snap.policies {
            if !policy.enabled || policy.effect != Effect::Allow {
                continue;
            }
            let domain_matches = req.domain.trim().is_empty()
                || policy.tenant == req.domain
                || policy.project == req.domain;
            let subject_matches =
                policy.subject.is_empty() || policy.subject == "*" || policy.subject == req.user_id;
            let role_matches =
                !policy.role.trim().is_empty() && roles.iter().any(|r| r == &policy.role);
            if domain_matches && (subject_matches || role_matches) {
                permissions.push(authz_pb::EffectivePermission {
                    object: policy.resource.clone(),
                    action: policy.action.clone(),
                    via_role: if role_matches {
                        policy.role.clone()
                    } else {
                        String::new()
                    },
                    resource_type: String::new(),
                    domain: if policy.tenant.trim().is_empty() {
                        policy.project.clone()
                    } else {
                        policy.tenant.clone()
                    },
                });
            }
        }
        let page_window = native_offset_page_window(1, req.page_size, &req.page_token, 50);
        let total = permissions.len() as i64;
        let permissions = permissions
            .into_iter()
            .skip(page_window.offset)
            .take(page_window.limit)
            .collect();
        Ok(Response::new(authz_pb::ListUserPermissionsResponse {
            permissions,
            next_page_token: native_next_page_token_for_total(
                page_window.offset,
                page_window.limit,
                total,
            ),
        }))
    }
    async fn list_access_decision_audits(
        &self,
        request: Request<authz_pb::ListAccessDecisionAuditsRequest>,
    ) -> Result<Response<authz_pb::ListAccessDecisionAuditsResponse>, Status> {
        self.list_access_decision_audits_impl(request).await
    }
    async fn revoke_role(
        &self,
        request: Request<authz_pb::RevokeRoleRequest>,
    ) -> Result<Response<authz_pb::RevokeRoleResponse>, Status> {
        governance::guard_governed_role_mutation("RevokeRole")?;
        let req = request.into_inner();
        if req.user_role_id.trim().is_empty() {
            return Err(authz_required_field(
                "user_role_id is required",
                "user_role_id",
                "must be a non-empty user-role assignment id",
            ));
        }
        let user_role_id = parse_uuid_field("user_role_id", &req.user_role_id)?;
        let runtime = self.runtime.as_ref().ok_or_else(|| {
            authz_capability_status(
                "user_role_persistence",
                "runtime_native_entity_dispatch",
                "native authz requires runtime-backed user-role persistence",
            )
        })?;
        // P6.10 Wave 1: typed DELETE returning the tenant so the revocation can bump
        // the tenant-scoped authz revision (K2.1). project stays '' (raw literal).
        let op = LogicalDelete {
            message_type: "udb.core.authz.entity.v1.UserRole".to_string(),
            filter: LogicalFilter::Comparison {
                field: "user_role_id".to_string(),
                op: ComparisonOp::Eq,
                value: LogicalValue::String(user_role_id.to_string()),
            },
            return_fields: vec!["tenant_id".to_string()],
        };
        let context = crate::RequestContext::default();
        let deleted_rows = runtime
            .native_entity_delete_rows_for_service("authz", &context, op)
            .await
            .map_err(|err| {
                authz_internal_status("revoke_role", format!("revoke role failed: {err}"))
            })?;
        let revoked = !deleted_rows.is_empty();
        if let Some(row) = deleted_rows.first() {
            let tenant: String = row
                .get("tenant_id")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();
            let project = String::new();
            self.emit_event(
                AuthEvent::new(
                    topics::ROLE_REVOKED,
                    req.user_id.clone(),
                    tenant.clone(),
                    serde_json::json!({
                        "user_role_id": req.user_role_id.clone(),
                        "user_id": req.user_id.clone(),
                        "reason": req.reason.clone(),
                        "revoked_by": req.revoked_by.clone(),
                    }),
                )
                .with_correlation(format!("role_revoke:{}", req.user_role_id))
                .with_compliance(events::ComplianceEnvelope {
                    actor: if req.revoked_by.trim().is_empty() {
                        req.user_id.clone()
                    } else {
                        req.revoked_by.clone()
                    },
                    target_resource: req.user_id.clone(),
                    operation: "role_revoke".to_string(),
                    outcome: "success".to_string(),
                    reason_code: if req.reason.trim().is_empty() {
                        "role_revoked".to_string()
                    } else {
                        req.reason.clone()
                    },
                    ..events::ComplianceEnvelope::default()
                }),
            )
            .await;
            if !tenant.trim().is_empty() {
                let _ = self
                    .bump_authz_revision(
                        &tenant,
                        &project,
                        authz_entity_pb::AuthzChangeType::RoleAssignment,
                        "role-revoked",
                        &req.revoked_by,
                    )
                    .await;
            }
        }
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::RevokeRoleResponse { revoked }))
    }
    async fn list_user_roles(
        &self,
        request: Request<authz_pb::ListUserRolesRequest>,
    ) -> Result<Response<authz_pb::ListUserRolesResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(authz_required_field(
                "user_id is required",
                "user_id",
                "must be a non-empty user id",
            ));
        }
        let user_id = parse_uuid_field("user_id", &req.user_id)?;
        let pool = self.require_pool()?;
        let user_role_model = self.user_roles_model();
        let rel = user_role_model.relation.clone();
        let projection = user_role_select_projection(&user_role_model);
        let rows = sqlx::query(&format!(
            "SELECT {projection} \
             FROM {rel} \
             WHERE {user_id} = $1::UUID \
               AND ($2 = '' OR {domain_col} = $2) \
               AND (NOT $3 OR {expires_at} IS NULL OR {expires_at} > NOW())",
            user_id = user_role_model.q("user_id"),
            domain_col = user_role_model.q("domain"),
            expires_at = user_role_model.q("expires_at"),
        ))
        .bind(user_id)
        .bind(&req.domain)
        .bind(req.active_only)
        .fetch_all(pool)
        .await
        .map_err(|err| {
            authz_internal_status("list_user_roles", format!("list user roles failed: {err}"))
        })?;
        let mut user_roles = Vec::with_capacity(rows.len());
        for row in &rows {
            user_roles.push(user_role_from_row(row)?);
        }
        let page_window = native_offset_page_window(1, req.page_size, &req.page_token, 50);
        let total = user_roles.len() as i64;
        let user_roles = user_roles
            .into_iter()
            .skip(page_window.offset)
            .take(page_window.limit)
            .collect();
        Ok(Response::new(authz_pb::ListUserRolesResponse {
            user_roles,
            next_page_token: native_next_page_token_for_total(
                page_window.offset,
                page_window.limit,
                total,
            ),
        }))
    }
    async fn get_role(
        &self,
        request: Request<authz_pb::GetRoleRequest>,
    ) -> Result<Response<authz_pb::GetRoleResponse>, Status> {
        let req = request.into_inner();
        if req.role_id.trim().is_empty() && req.role_code.trim().is_empty() {
            return Err(authz_invalid_fields(
                "role_id or role_code is required",
                [
                    ("role_id", "must include role_id or role_code"),
                    ("role_code", "must include role_id or role_code"),
                ],
            ));
        }
        let role_id_filter = if req.role_id.trim().is_empty() {
            None
        } else {
            Some(parse_uuid_field("role_id", &req.role_id)?)
        };
        let pool = self.require_pool()?;
        let role_model = self.roles_model();
        let rel = role_model.relation.clone();
        let projection = role_select_projection(&role_model);
        let row = sqlx::query(&format!(
            "SELECT {projection} \
             FROM {rel} \
             WHERE {deleted_at} IS NULL \
               AND (($1::UUID IS NOT NULL AND {role_id} = $1) OR ($1::UUID IS NULL AND {role_code} = $2)) \
               AND ($3 = '' OR {domain_col} = $3) \
             LIMIT 1",
            role_id = role_model.q("role_id"),
            role_code = role_model.q("role_code"),
            domain_col = role_model.q("domain"),
            deleted_at = role_model.q("deleted_at"),
        ))
        .bind(role_id_filter)
        .bind(&req.role_code)
        .bind(&req.domain)
        .fetch_optional(pool)
        .await
        .map_err(|err| authz_internal_status("get_role", format!("get role failed: {err}")))?;
        match row {
            Some(row) => Ok(Response::new(authz_pb::GetRoleResponse {
                role: Some(role_from_row(&row)?),
            })),
            None => Err(authz_not_found_status(
                "get_role",
                "role_not_found",
                "role not found",
            )),
        }
    }
    async fn list_roles(
        &self,
        request: Request<authz_pb::ListRolesRequest>,
    ) -> Result<Response<authz_pb::ListRolesResponse>, Status> {
        let req = request.into_inner();
        let pool = self.require_pool()?;
        let role_model = self.roles_model();
        let rel = role_model.relation.clone();
        let projection = role_select_projection(&role_model);
        let rows = sqlx::query(&format!(
            "SELECT {projection} \
             FROM {rel} \
             WHERE {deleted_at} IS NULL \
               AND ($1 = '' OR {domain_col} = $1) \
               AND (NOT $2 OR {is_active} = TRUE) \
             ORDER BY {name} ASC",
            domain_col = role_model.q("domain"),
            is_active = role_model.q("is_active"),
            name = role_model.q("name"),
            deleted_at = role_model.q("deleted_at"),
        ))
        .bind(&req.domain)
        .bind(req.active_only)
        .fetch_all(pool)
        .await
        .map_err(|err| authz_internal_status("list_roles", format!("list roles failed: {err}")))?;
        let mut all = Vec::with_capacity(rows.len());
        for row in &rows {
            all.push(role_from_row(row)?);
        }
        let page = req.page.as_ref();
        let page_number = page.map(|p| p.page).filter(|p| *p > 0).unwrap_or(1) as usize;
        let page_size = page
            .map(|p| p.page_size)
            .filter(|s| *s > 0)
            .unwrap_or(all.len().max(1) as i32) as usize;
        let start = page_number.saturating_sub(1).saturating_mul(page_size);
        let total = all.len();
        let roles = all.into_iter().skip(start).take(page_size).collect();
        Ok(Response::new(authz_pb::ListRolesResponse {
            page: Some(page_response(total, page)),
            roles,
        }))
    }
    async fn batch_check_permissions(
        &self,
        request: Request<authz_pb::BatchCheckPermissionsRequest>,
    ) -> Result<Response<authz_pb::BatchCheckPermissionsResponse>, Status> {
        let req = request.into_inner();
        if req.user_id.trim().is_empty() {
            return Err(authz_required_field(
                "user_id is required",
                "user_id",
                "must be a non-empty user id",
            ));
        }
        let attributes: BTreeMap<String, String> = req
            .context
            .map(|ctx| ctx.attributes.into_iter().collect())
            .unwrap_or_default();
        let principal = Principal {
            principal_id: req.user_id.clone(),
            subject: req.user_id.clone(),
            user_id: req.user_id.clone(),
            tenant_id: req.domain.clone(),
            ..Default::default()
        };
        // Tier-0 #1: acquire ONE per-tenant fair-admission permit for the whole
        // batch (bounded cost) — not per-check — keyed by the resolved tenant.
        // Held across all checks in the batch (same backpressure on exhaustion).
        let _admit = self.admit(&principal.tenant_id).await?;
        let snap = self.current_snapshot().await?;
        let audit_ctx = AuditContext::from_attributes(&attributes, "");
        let mut results = std::collections::HashMap::new();
        for check in req.checks {
            let mut resource = ResourceRef {
                resource_name: check.object.clone(),
                message_type: check.object.clone(),
                ..Default::default()
            };
            enrich_resource(&mut resource);
            let decision = self
                .decide_with_snapshot(&snap, &principal, &resource, &check.action, "", &attributes)
                .await;
            self.write_decision_audit(&principal, &resource, &check.action, &decision, &audit_ctx)
                .await;
            results.insert(
                format!("{}:{}", check.object, check.action),
                decision.allowed,
            );
        }
        Ok(Response::new(authz_pb::BatchCheckPermissionsResponse {
            results,
        }))
    }
    async fn update_role(
        &self,
        request: Request<authz_pb::UpdateRoleRequest>,
    ) -> Result<Response<authz_pb::UpdateRoleResponse>, Status> {
        governance::guard_governed_role_mutation("UpdateRole")?;
        let req = request.into_inner();
        if req.role_id.trim().is_empty() {
            return Err(authz_required_field(
                "role_id is required",
                "role_id",
                "must be a non-empty role id",
            ));
        }
        let role_id = parse_uuid_field("role_id", &req.role_id)?;
        if req.updated_by.trim().is_empty() {
            return Err(authz_required_field(
                "updated_by is required",
                "updated_by",
                "must be a non-empty updater id",
            ));
        }
        let update_mask = crate::runtime::service::native_helpers::update_mask_path_set(
            req.update_mask.as_ref(),
            &["name", "description", "is_active"],
        )?;
        if update_mask
            .as_ref()
            .is_some_and(|paths| paths.contains("is_active"))
            && req.is_active.is_none()
        {
            return Err(authz_required_field(
                "is_active is required when present in update_mask",
                "is_active",
                "must be supplied when update_mask includes is_active",
            ));
        }
        let update_name = crate::runtime::service::native_helpers::update_mask_allows(
            &update_mask,
            "name",
            !req.name.trim().is_empty(),
        );
        let update_description = crate::runtime::service::native_helpers::update_mask_allows(
            &update_mask,
            "description",
            !req.description.trim().is_empty(),
        );
        let update_is_active = crate::runtime::service::native_helpers::update_mask_allows(
            &update_mask,
            "is_active",
            req.is_active.is_some(),
        );
        let pool = self.require_pool()?;
        let role_model = self.roles_model();
        let rel = role_model.relation.clone();
        let projection = role_select_projection(&role_model);
        let row = sqlx::query(&format!(
            "UPDATE {rel} SET \
               {name} = CASE WHEN $2 THEN $3 ELSE {name} END, \
               {description} = CASE WHEN $4 THEN $5 ELSE {description} END, \
               {is_active} = CASE WHEN $6 THEN $7 ELSE {is_active} END \
             WHERE {role_id} = $1::UUID AND {deleted_at} IS NULL \
             RETURNING {projection}",
            name = role_model.q("name"),
            description = role_model.q("description"),
            is_active = role_model.q("is_active"),
            role_id = role_model.q("role_id"),
            deleted_at = role_model.q("deleted_at"),
        ))
        .bind(role_id)
        .bind(update_name)
        .bind(&req.name)
        .bind(update_description)
        .bind(&req.description)
        .bind(update_is_active)
        .bind(req.is_active.unwrap_or(false))
        .fetch_optional(pool)
        .await
        .map_err(|err| {
            crate::runtime::executor_utils::sqlx_error_to_status("update role failed", &err)
        })?;
        let Some(row) = row else {
            return Err(authz_not_found_status(
                "update_role",
                "role_not_found",
                "role not found",
            ));
        };
        let role = role_from_row(&row)?;
        self.emit_event(
            AuthEvent::new(
                topics::ROLE_UPDATED,
                role.role_id.clone(),
                role.tenant_id.clone(),
                serde_json::json!({
                    "role_id": role.role_id.clone(),
                    "role_code": role.role_code.clone(),
                    "tenant_id": role.tenant_id.clone(),
                    "updated_by": req.updated_by.clone(),
                }),
            )
            .with_correlation(format!("role_update:{}", role.role_id))
            .with_compliance(events::ComplianceEnvelope {
                actor: if req.updated_by.trim().is_empty() {
                    role.role_id.clone()
                } else {
                    req.updated_by.clone()
                },
                actor_project: role.project_id.clone(),
                target_resource: format!("role:{}", role.role_id),
                operation: "role_update".to_string(),
                outcome: "success".to_string(),
                reason_code: "role_updated".to_string(),
                ..events::ComplianceEnvelope::default()
            }),
        )
        .await;
        let _ = self
            .bump_authz_revision(
                &role.tenant_id,
                &role.project_id,
                authz_entity_pb::AuthzChangeType::Role,
                "role-updated",
                &req.updated_by,
            )
            .await;
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::UpdateRoleResponse {
            role: Some(role),
        }))
    }
    async fn delete_role(
        &self,
        request: Request<authz_pb::DeleteRoleRequest>,
    ) -> Result<Response<authz_pb::DeleteRoleResponse>, Status> {
        governance::guard_governed_role_mutation("DeleteRole")?;
        let req = request.into_inner();
        if req.role_id.trim().is_empty() {
            return Err(authz_required_field(
                "role_id is required",
                "role_id",
                "must be a non-empty role id",
            ));
        }
        if req.deleted_by.trim().is_empty() {
            return Err(authz_required_field(
                "deleted_by is required",
                "deleted_by",
                "must be a non-empty deleter id",
            ));
        }
        let role_id = parse_uuid_field("role_id", &req.role_id)?;
        let deleted_by = parse_uuid_field("deleted_by", &req.deleted_by)?;
        let pool = self.require_pool()?;
        let role_model = self.roles_model();
        let role_rel = role_model.relation.clone();
        // Capture the role's tenant/project before the soft delete so the authz
        // revision bump is scoped correctly. (Scope read stays a raw read.)
        let scope_row = sqlx::query(&format!(
            "SELECT {tenant_id}::TEXT AS tenant, COALESCE({project_id}, '') AS project FROM {role_rel} WHERE {role_id} = $1::UUID",
            tenant_id = role_model.q("tenant_id"),
            project_id = role_model.q("project_id"),
            role_id = role_model.q("role_id"),
        ))
        .bind(role_id)
        .fetch_optional(pool)
        .await
        .map_err(|err| {
            authz_internal_status(
                "read_role_scope",
                format!("read role scope failed: {err}"),
            )
        })?;
        let (role_tenant, role_project) = scope_row
            .map(|r| {
                (
                    r.try_get::<String, _>("tenant").unwrap_or_default(),
                    r.try_get::<String, _>("project").unwrap_or_default(),
                )
            })
            .unwrap_or_default();
        let runtime = self.runtime.as_ref().ok_or_else(|| {
            authz_capability_status(
                "role_persistence",
                "runtime_native_entity_dispatch",
                "native authz requires runtime-backed role persistence",
            )
        })?;
        // P6.10 Wave 1: typed soft-delete (deleted_at=NOW, deleted_by, is_active=FALSE)
        // with the `deleted_at IS NULL` idempotency guard, then the typed cascade
        // delete of the role's user_role assignments.
        let mut assignments = std::collections::BTreeMap::new();
        assignments.insert("deleted_at".to_string(), LogicalAssignment::ServerNow);
        assignments.insert(
            "deleted_by".to_string(),
            LogicalAssignment::Set {
                value: LogicalValue::String(deleted_by.to_string()),
            },
        );
        assignments.insert(
            "is_active".to_string(),
            LogicalAssignment::Set {
                value: LogicalValue::Bool(false),
            },
        );
        let (affected, _) = runtime
            .native_entity_update_for_service(
                "authz",
                &crate::RequestContext::default(),
                LogicalUpdate {
                    message_type: "udb.core.authz.entity.v1.Role".to_string(),
                    filter: LogicalFilter::And(vec![
                        LogicalFilter::Comparison {
                            field: "role_id".to_string(),
                            op: ComparisonOp::Eq,
                            value: LogicalValue::String(role_id.to_string()),
                        },
                        LogicalFilter::IsNull("deleted_at".to_string()),
                    ]),
                    assignments,
                    return_fields: Vec::new(),
                    require_affected: false,
                },
            )
            .await
            .map_err(|err| {
                authz_internal_status("delete_role", format!("delete role failed: {err}"))
            })?;
        if affected > 0 {
            runtime
                .native_entity_delete_for_service(
                    "authz",
                    &crate::RequestContext::default(),
                    LogicalDelete {
                        message_type: "udb.core.authz.entity.v1.UserRole".to_string(),
                        filter: LogicalFilter::Comparison {
                            field: "role_id".to_string(),
                            op: ComparisonOp::Eq,
                            value: LogicalValue::String(role_id.to_string()),
                        },
                        return_fields: Vec::new(),
                    },
                )
                .await
                .map_err(|err| {
                    authz_internal_status(
                        "delete_role_assignments",
                        format!("delete role assignments failed: {err}"),
                    )
                })?;
        }
        if affected > 0 && !role_tenant.trim().is_empty() {
            let _ = self
                .bump_authz_revision(
                    &role_tenant,
                    &role_project,
                    authz_entity_pb::AuthzChangeType::Role,
                    "role-deleted",
                    &req.deleted_by,
                )
                .await;
        }
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::DeleteRoleResponse {
            deleted: affected > 0,
        }))
    }
    async fn get_policy_rule(
        &self,
        request: Request<authz_pb::GetPolicyRuleRequest>,
    ) -> Result<Response<authz_pb::GetPolicyRuleResponse>, Status> {
        let req = request.into_inner();
        if req.policy_id.trim().is_empty() {
            return Err(authz_required_field(
                "policy_id is required",
                "policy_id",
                "must be a non-empty policy id",
            ));
        }
        if let Some(pool) = &self.pg_pool {
            let policy_id = parse_uuid_field("policy_id", &req.policy_id)?;
            let policy_model = self.policies_model();
            let rel = policy_model.relation.clone();
            let projection = policy_rule_select_projection(&policy_model);
            let row = sqlx::query(&format!(
                "SELECT {projection} \
                 FROM {rel} \
                 WHERE {policy_id} = $1::UUID AND {deleted_at} IS NULL \
                 LIMIT 1",
                policy_id = policy_model.q("policy_id"),
                deleted_at = policy_model.q("deleted_at"),
            ))
            .bind(policy_id)
            .fetch_optional(pool)
            .await
            .map_err(|err| {
                authz_internal_status("get_policy_rule", format!("get policy rule failed: {err}"))
            })?;
            return match row {
                Some(row) => Ok(Response::new(authz_pb::GetPolicyRuleResponse {
                    policy: Some(policy_rule_from_row(&row)?),
                })),
                None => Err(authz_not_found_status(
                    "get_policy_rule",
                    "policy_rule_not_found",
                    "policy rule not found",
                )),
            };
        }
        let snap = self.current_snapshot().await?;
        let policy = snap
            .policies
            .iter()
            .find(|p| p.id == req.policy_id)
            .map(policy_to_rule_pb);
        Ok(Response::new(authz_pb::GetPolicyRuleResponse { policy }))
    }
    async fn list_policy_rules(
        &self,
        request: Request<authz_pb::ListPolicyRulesRequest>,
    ) -> Result<Response<authz_pb::ListPolicyRulesResponse>, Status> {
        let req = request.into_inner();
        if let Some(pool) = &self.pg_pool {
            let policy_model = self.policies_model();
            let rel = policy_model.relation.clone();
            let projection = policy_rule_select_projection(&policy_model);
            let rows = sqlx::query(&format!(
                "SELECT {projection} \
                 FROM {rel} \
                 WHERE {deleted_at} IS NULL \
                   AND ($1 = '' OR {domain_col} = $1 OR {tenant_id} = $1 OR {project_id} = $1) \
                   AND ($2 = '' OR {subject} = $2) \
                   AND ($3 = '' OR {object_col} = $3) \
                   AND (NOT $4 OR {is_active} = TRUE) \
                 ORDER BY {is_active} DESC, {policy_id} ASC",
                deleted_at = policy_model.q("deleted_at"),
                domain_col = policy_model.q("domain"),
                tenant_id = policy_model.q("tenant_id"),
                project_id = policy_model.q("project_id"),
                subject = policy_model.q("subject"),
                object_col = policy_model.q("object"),
                is_active = policy_model.q("is_active"),
                policy_id = policy_model.q("policy_id"),
            ))
            .bind(&req.domain)
            .bind(&req.subject)
            .bind(&req.object)
            .bind(req.active_only)
            .fetch_all(pool)
            .await
            .map_err(|err| {
                authz_internal_status(
                    "list_policy_rules",
                    format!("list policy rules failed: {err}"),
                )
            })?;
            let all = rows
                .iter()
                .map(policy_rule_from_row)
                .collect::<Result<Vec<_>, _>>()?;
            let page = req.page.as_ref();
            let page_number = page.map(|p| p.page).filter(|p| *p > 0).unwrap_or(1) as usize;
            let page_size = page
                .map(|p| p.page_size)
                .filter(|s| *s > 0)
                .unwrap_or(all.len().max(1) as i32) as usize;
            let start = page_number.saturating_sub(1).saturating_mul(page_size);
            let policies = all.into_iter().skip(start).take(page_size).collect();
            return Ok(Response::new(authz_pb::ListPolicyRulesResponse {
                page: Some(page_response(rows.len(), page)),
                policies,
            }));
        }
        let snap = self.current_snapshot().await?;
        let policies: Vec<_> = snap
            .policies
            .iter()
            .filter(|p| !req.active_only || p.enabled)
            .filter(|p| {
                req.domain.trim().is_empty() || p.tenant == req.domain || p.project == req.domain
            })
            .filter(|p| req.subject.trim().is_empty() || p.subject == req.subject)
            .filter(|p| req.object.trim().is_empty() || p.resource == req.object)
            .map(policy_to_rule_pb)
            .collect();
        Ok(Response::new(authz_pb::ListPolicyRulesResponse {
            page: Some(page_response(policies.len(), req.page.as_ref())),
            policies,
        }))
    }
    async fn delete_policy_rule(
        &self,
        request: Request<authz_pb::DeletePolicyRuleRequest>,
    ) -> Result<Response<authz_pb::DeletePolicyRuleResponse>, Status> {
        let req = request.into_inner();
        if req.policy_id.trim().is_empty() {
            return Err(authz_required_field(
                "policy_id is required",
                "policy_id",
                "must be a non-empty policy id",
            ));
        }
        let mut deleted = false;
        if self.pg_pool.is_some() {
            let runtime = self.runtime.as_ref().ok_or_else(|| {
                authz_capability_status(
                    "policy_persistence",
                    "runtime_native_entity_dispatch",
                    "native authz requires runtime-backed policy persistence",
                )
            })?;
            let policy_id = parse_uuid_field("policy_id", &req.policy_id)?;
            let deleted_by = if req.deleted_by.trim().is_empty() {
                None
            } else {
                Some(parse_uuid_field("deleted_by", &req.deleted_by)?)
            };
            // P6.10 Wave 1: typed conditional soft-delete (was raw UPDATE). The
            // `deleted_at IS NULL` guard preserves idempotency; `deleted_by` is NULL
            // when absent; `require_affected=false` (caller reports deleted=affected>0).
            let mut assignments = std::collections::BTreeMap::new();
            assignments.insert("deleted_at".to_string(), LogicalAssignment::ServerNow);
            assignments.insert(
                "deleted_by".to_string(),
                LogicalAssignment::Set {
                    value: match &deleted_by {
                        Some(u) => LogicalValue::String(u.to_string()),
                        None => LogicalValue::Null,
                    },
                },
            );
            assignments.insert(
                "is_active".to_string(),
                LogicalAssignment::Set {
                    value: LogicalValue::Bool(false),
                },
            );
            let op = LogicalUpdate {
                message_type: "udb.core.authz.entity.v1.PolicyRule".to_string(),
                filter: LogicalFilter::And(vec![
                    LogicalFilter::Comparison {
                        field: "policy_id".to_string(),
                        op: ComparisonOp::Eq,
                        value: LogicalValue::String(policy_id.to_string()),
                    },
                    LogicalFilter::IsNull("deleted_at".to_string()),
                ]),
                assignments,
                return_fields: Vec::new(),
                require_affected: false,
            };
            let context = crate::RequestContext::default();
            let (affected, _) = runtime
                .native_entity_update_for_service("authz", &context, op)
                .await
                .map_err(|err| {
                    authz_internal_status(
                        "delete_policy_rule",
                        format!("delete policy rule failed: {err}"),
                    )
                })?;
            deleted = affected > 0;
        } else {
            self.require_snapshot_fallback()?;
        }
        self.invalidate_snapshot_cache();
        Ok(Response::new(authz_pb::DeletePolicyRuleResponse {
            deleted,
        }))
    }

    /// Stage 2 (item 133): authorize through the same engine and, when allowed,
    /// mint a short-lived native-access contract (restricted role + scoped DSN +
    /// RLS session variables). The decision is always returned; the grant is
    /// present only on allow and only when native access is configured.
    async fn get_native_access(
        &self,
        request: Request<authz_pb::NativeAccessRequest>,
    ) -> Result<Response<authz_pb::NativeAccessResponse>, Status> {
        use crate::runtime::authz::native_access::NativeAccessConfig;

        let req = request.into_inner();
        // 01.5.1.1 — capture the body-REQUESTED scopes before the claim-binding /
        // narrow-only intersection below rewrites `principal.scopes` into the
        // EFFECTIVE set, so the grant audit can surface a narrowed/rejected scope
        // request distinct from what was actually granted.
        let requested_scopes = req.requested_scopes.clone();
        let mut principal = req
            .principal
            .as_ref()
            .map(authz_principal_to_runtime)
            .unwrap_or_default();
        if principal.tenant_id.trim().is_empty() {
            principal.tenant_id = req.tenant_id.clone();
        }
        if principal.project_id.trim().is_empty() {
            principal.project_id = req.project_id.clone();
        }
        // Claim-binding (served path only): seed the principal from the verified
        // claim so the minted native-access contract is scoped to the AUTHENTICATED
        // caller, not the body. `req.requested_scopes` may only NARROW the claim
        // scopes (intersection) — never widen them into a superset of the token.
        // `req.principal` stays a TARGET only for a genuine cross-tenant admin. The
        // in-process / loopback path (no claim) preserves the body-derived behavior.
        if crate::runtime::service::method_security::claim_context_present() {
            let ctx = crate::runtime::service::method_security::current_claim_context();
            crate::runtime::service::method_security::enforce_body_tenant_matches_claim(
                &ctx,
                &req.tenant_id,
                &req.project_id,
            )?;
            if !ctx.is_cross_tenant_admin() {
                let base = ctx.to_principal();
                principal.subject = base.subject;
                principal.user_id = base.user_id;
                principal.tenant_id = base.tenant_id;
                principal.project_id = base.project_id;
                principal.scopes = base.scopes;
            }
            // Intersect requested scopes with the claim scopes (narrow-only). When
            // the caller requests no specific scopes, keep the full claim set.
            if !req.requested_scopes.is_empty() {
                principal.scopes.retain(|scope| {
                    req.requested_scopes
                        .iter()
                        .any(|requested| requested == scope)
                });
            }
        } else if principal.scopes.is_empty() {
            principal.scopes = req.requested_scopes.clone();
        }
        if principal.subject.trim().is_empty() {
            principal.subject = if !principal.user_id.trim().is_empty() {
                principal.user_id.clone()
            } else {
                principal.principal_id.clone()
            };
        }
        if principal.principal_id.trim().is_empty() {
            principal.principal_id = principal.subject.clone();
        }
        if principal.tenant_id.trim().is_empty() {
            return Err(authz_required_field(
                "tenant_id is required",
                "tenant_id",
                "must be a non-empty tenant id",
            ));
        }

        let mut resource = req
            .resource
            .as_ref()
            .map(resource_to_runtime)
            .unwrap_or_default();
        if !req.backend.trim().is_empty() && resource.backend.trim().is_empty() {
            resource.backend = req.backend.clone();
        }
        enrich_resource(&mut resource);

        let mut attributes: BTreeMap<String, String> = req.attributes.into_iter().collect();
        if let Some(ctx) = req.context {
            attributes.extend(ctx.attributes.into_iter());
        }

        let snap = self.current_snapshot().await?;
        let decision = self
            .decide_with_snapshot(
                &snap,
                &principal,
                &resource,
                &req.action,
                &req.purpose,
                &attributes,
            )
            .await;
        let audit_ctx = AuditContext::from_attributes(&attributes, &req.purpose);
        self.write_decision_audit(&principal, &resource, &req.action, &decision, &audit_ctx)
            .await;

        let grant = NativeAccessConfig::from_env()
            .mint(
                &principal,
                &resource,
                &req.action,
                &req.purpose,
                &decision,
                now_unix() as i64,
            )
            .map(|g| authz_pb::NativeAccessGrant {
                dsn: g.dsn,
                role: g.role,
                backend: g.backend,
                database: g.database,
                schema: g.schema,
                session_variables: g.session_variables.into_iter().collect(),
                expires_at_unix: g.expires_at_unix,
                ttl_seconds: g.ttl_seconds,
            });

        // Audit the native-access grant outcome (security-sensitive). A grant is
        // only ISSUED when the decision allowed AND a DSN was minted; otherwise it
        // is DENIED. The DSN/role NEVER enter the event body (credential material).
        let actor = if principal.subject.trim().is_empty() {
            principal.principal_id.clone()
        } else {
            principal.subject.clone()
        };
        let correlation = if audit_ctx.correlation_id.trim().is_empty() {
            format!("native_access:{}:{}", actor, resource.resource_name)
        } else {
            audit_ctx.correlation_id.clone()
        };
        let issued = decision.allowed && grant.is_some();
        let (grant_topic, grant_op, grant_outcome, grant_reason) = if issued {
            (
                topics::NATIVE_ACCESS_GRANT_ISSUED,
                "native_access_grant",
                "allow",
                "grant_issued".to_string(),
            )
        } else {
            (
                topics::NATIVE_ACCESS_GRANT_DENIED,
                "native_access_grant",
                "deny",
                if decision.deny_reason.trim().is_empty() {
                    "no_grant_minted".to_string()
                } else {
                    decision.deny_reason.clone()
                },
            )
        };
        self.emit_event(
            AuthEvent::new(
                grant_topic,
                actor.clone(),
                principal.tenant_id.clone(),
                serde_json::json!({
                    "subject": actor.clone(),
                    "resource": resource.resource_name.clone(),
                    "backend": resource.backend.clone(),
                    "action": req.action.clone(),
                    "purpose": req.purpose.clone(),
                    "allowed": decision.allowed,
                    "granted": issued,
                    // 01.5.1.1 — requested-vs-effective scope visibility: the raw
                    // body-requested set next to the narrowed set actually granted.
                    "requested_scopes": requested_scopes.clone(),
                    "effective_scopes": principal.scopes.clone(),
                }),
            )
            .with_correlation(correlation)
            .with_compliance(events::ComplianceEnvelope {
                actor: actor.clone(),
                actor_project: principal.project_id.clone(),
                target_resource: resource.resource_name.clone(),
                operation: grant_op.to_string(),
                outcome: grant_outcome.to_string(),
                reason_code: grant_reason,
                decision_id: decision.decision_id.clone(),
                policy_version: decision.policy_version.clone(),
                relationship_version: decision.relationship_version.clone(),
                ..events::ComplianceEnvelope::default()
            }),
        )
        .await;

        Ok(Response::new(authz_pb::NativeAccessResponse {
            decision: Some(decision_to_pb(&decision)),
            grant,
        }))
    }

    /// Stage 2 (item 139): return a signed, tenant-scoped projection of the live
    /// authorization snapshot so SDKs can cache it and answer `can()` locally.
    async fn get_policy_bundle(
        &self,
        request: Request<authz_pb::PolicyBundleRequest>,
    ) -> Result<Response<authz_pb::PolicyBundleResponse>, Status> {
        use crate::runtime::authz::bundle::PolicyBundleConfig;

        let req = request.into_inner();
        // A bundle is always tenant-scoped; an empty tenant must not fall through
        // to "all tenants" (that would sign + return every tenant's policies).
        if req.tenant_id.trim().is_empty() {
            return Err(authz_required_field(
                "tenant_id is required for a policy bundle",
                "tenant_id",
                "must be a non-empty tenant id for a policy bundle",
            ));
        }
        let cfg = PolicyBundleConfig::from_env();
        if !cfg.enabled() {
            return Err(policy_bundle_signing_not_configured_status());
        }
        let snap = self.current_snapshot().await?;
        let tenant = if req.tenant_id.trim().is_empty() {
            req.domain.clone()
        } else {
            req.tenant_id.clone()
        };
        // Item 82: signing goes through the `PolicyEngine` seam (the snapshot's
        // impl forwards to `PolicyBundleConfig::sign`).
        let now = now_unix() as i64;
        let signed = PolicyEngine::bundle(snap.as_ref(), &cfg, &tenant, &req.project_id, now)
            .await
            .ok_or_else(|| {
                authz_internal_status("sign_policy_bundle", "failed to sign policy bundle")
            })?;

        // Audit the bundle issuance (security-sensitive). Only the bundle metadata
        // (key id, versions) is recorded — never the signed bundle bytes.
        // `PolicyBundleRequest` is a server-only RPC carrying no principal, so the
        // requesting tenant is the audited actor.
        let bundle_actor = format!("tenant:{tenant}");
        self.emit_event(
            AuthEvent::new(
                topics::POLICY_BUNDLE_ISSUED,
                format!("{tenant}/{}", req.project_id),
                tenant.clone(),
                serde_json::json!({
                    "tenant_id": tenant.clone(),
                    "project_id": req.project_id.clone(),
                    "key_id": signed.key_id.clone(),
                    "policy_version": signed.policy_version.clone(),
                    "relationship_version": signed.relationship_version.clone(),
                }),
            )
            .with_correlation(format!("policy_bundle:{tenant}/{}", req.project_id))
            .with_compliance(events::ComplianceEnvelope {
                actor: bundle_actor,
                target_resource: format!("policy_bundle:{tenant}/{}", req.project_id),
                operation: "policy_bundle_issue".to_string(),
                outcome: "success".to_string(),
                reason_code: "bundle_signed".to_string(),
                policy_version: signed.policy_version.clone(),
                relationship_version: signed.relationship_version.clone(),
                ..events::ComplianceEnvelope::default()
            }),
        )
        .await;

        Ok(Response::new(authz_pb::PolicyBundleResponse {
            bundle: Some(authz_pb::SignedPolicyBundle {
                bundle: signed.bundle,
                signature: signed.signature,
                key_id: signed.key_id,
                algorithm: signed.algorithm,
                policy_version: signed.policy_version,
                relationship_version: signed.relationship_version,
                issued_at_unix: signed.issued_at_unix,
                expires_at_unix: signed.expires_at_unix,
                ttl_seconds: signed.ttl_seconds,
            }),
        }))
    }

    // ── Phase K: Authz Policy Governance — delegate to topic submodules ──────

    async fn create_policy_draft(
        &self,
        request: Request<authz_pb::CreatePolicyDraftRequest>,
    ) -> Result<Response<authz_pb::PolicyDraftResponse>, Status> {
        self.create_policy_draft_impl(request).await
    }

    async fn update_policy_draft(
        &self,
        request: Request<authz_pb::UpdatePolicyDraftRequest>,
    ) -> Result<Response<authz_pb::PolicyDraftResponse>, Status> {
        self.update_policy_draft_impl(request).await
    }

    async fn diff_policy_draft(
        &self,
        request: Request<authz_pb::DiffPolicyDraftRequest>,
    ) -> Result<Response<authz_pb::DiffPolicyDraftResponse>, Status> {
        self.diff_policy_draft_impl(request).await
    }

    async fn submit_policy_draft(
        &self,
        request: Request<authz_pb::SubmitPolicyDraftRequest>,
    ) -> Result<Response<authz_pb::PolicyDraftResponse>, Status> {
        self.submit_policy_draft_impl(request).await
    }

    async fn approve_policy_draft(
        &self,
        request: Request<authz_pb::ApprovePolicyDraftRequest>,
    ) -> Result<Response<authz_pb::PolicyApprovalResponse>, Status> {
        self.approve_policy_draft_impl(request).await
    }

    async fn reject_policy_draft(
        &self,
        request: Request<authz_pb::RejectPolicyDraftRequest>,
    ) -> Result<Response<authz_pb::PolicyApprovalResponse>, Status> {
        self.reject_policy_draft_impl(request).await
    }

    async fn activate_policy_version(
        &self,
        request: Request<authz_pb::ActivatePolicyVersionRequest>,
    ) -> Result<Response<authz_pb::ActivationResponse>, Status> {
        self.activate_policy_version_impl(request).await
    }

    async fn rollback_policy_version(
        &self,
        request: Request<authz_pb::RollbackPolicyVersionRequest>,
    ) -> Result<Response<authz_pb::ActivationResponse>, Status> {
        self.rollback_policy_version_impl(request).await
    }

    async fn activate_canary(
        &self,
        request: Request<authz_pb::ActivateCanaryRequest>,
    ) -> Result<Response<authz_pb::CanaryResponse>, Status> {
        self.activate_canary_impl(request).await
    }

    async fn promote_canary(
        &self,
        request: Request<authz_pb::PromoteCanaryRequest>,
    ) -> Result<Response<authz_pb::CanaryResponse>, Status> {
        self.promote_canary_impl(request).await
    }

    async fn get_canary_status(
        &self,
        request: Request<authz_pb::GetCanaryStatusRequest>,
    ) -> Result<Response<authz_pb::GetCanaryStatusResponse>, Status> {
        self.get_canary_status_impl(request).await
    }

    async fn list_policy_versions(
        &self,
        request: Request<authz_pb::ListPolicyVersionsRequest>,
    ) -> Result<Response<authz_pb::ListPolicyVersionsResponse>, Status> {
        self.list_policy_versions_impl(request).await
    }

    async fn simulate_policy(
        &self,
        request: Request<authz_pb::SimulatePolicyRequest>,
    ) -> Result<Response<authz_pb::SimulatePolicyResponse>, Status> {
        self.simulate_policy_impl(request).await
    }

    async fn explain_policy(
        &self,
        request: Request<authz_pb::ExplainPolicyRequest>,
    ) -> Result<Response<authz_pb::ExplainPolicyResponse>, Status> {
        self.explain_policy_impl(request).await
    }

    async fn get_authz_revision(
        &self,
        request: Request<authz_pb::GetAuthzRevisionRequest>,
    ) -> Result<Response<authz_pb::GetAuthzRevisionResponse>, Status> {
        self.get_authz_revision_impl(request).await
    }

    async fn invalidate_policy_bundles(
        &self,
        request: Request<authz_pb::InvalidatePolicyBundlesRequest>,
    ) -> Result<Response<authz_pb::InvalidatePolicyBundlesResponse>, Status> {
        self.invalidate_policy_bundles_impl(request).await
    }

    async fn seed_builtin_roles(
        &self,
        request: Request<authz_pb::SeedBuiltinRolesRequest>,
    ) -> Result<Response<authz_pb::SeedBuiltinRolesResponse>, Status> {
        self.seed_builtin_roles_impl(request).await
    }

    async fn migrate_legacy_policies(
        &self,
        request: Request<authz_pb::MigrateLegacyPoliciesRequest>,
    ) -> Result<Response<authz_pb::MigrateLegacyPoliciesResponse>, Status> {
        self.migrate_legacy_policies_impl(request).await
    }
}

/// Derive a content-addressed snapshot version for the policy set. Unlike a
/// count-only `pg-{len}` version, this changes whenever any policy's *content*
/// changes (effect flip, condition edit, scope change) even if the row count is
/// unchanged — which is exactly the case a count-only version missed, letting
/// SDK-cached bundles and cross-node snapshot caches serve stale policy. The
/// hash is computed over a sorted canonical form, so DB row order never affects
/// it; the `pg-{len}-…` shape keeps the version human-readable. `DefaultHasher`
/// is seeded with fixed keys, so it is deterministic across nodes running the
/// same binary (which is all snapshot-cache invalidation requires).
fn policy_content_version(policies: &[AuthzPolicy]) -> String {
    use std::hash::{Hash, Hasher};
    let mut entries: Vec<String> = policies
        .iter()
        .map(|p| {
            let mut scopes = p.required_scopes.clone();
            scopes.sort();
            format!(
                "{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{:?}\u{1f}{}\u{1f}{:?}",
                p.id, p.priority, p.enabled, p.effect.as_str(), p.tenant, p.project, p.subject,
                p.role, p.action, p.resource, p.purpose, p.conditions, p.relationship, scopes,
            )
        })
        .collect();
    entries.sort();
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    entries.len().hash(&mut hasher);
    for entry in &entries {
        entry.hash(&mut hasher);
    }
    format!("pg-{}-{:016x}", policies.len(), hasher.finish())
}

/// Content-addressed version for the relationship-tuple set (see
/// [`policy_content_version`] for the rationale and determinism guarantees).
fn tuple_content_version(tuples: &[RelationshipTuple]) -> String {
    use std::hash::{Hash, Hasher};
    let mut entries: Vec<String> = tuples
        .iter()
        .map(|t| {
            format!(
                "{}\u{1f}{}\u{1f}{}\u{1f}{}\u{1f}{}",
                t.subject, t.relation, t.object, t.tenant, t.project,
            )
        })
        .collect();
    entries.sort();
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    entries.len().hash(&mut hasher);
    for entry in &entries {
        entry.hash(&mut hasher);
    }
    format!("pg-{}-{:016x}", tuples.len(), hasher.finish())
}

#[cfg(test)]
mod version_tests {
    use super::*;

    fn policy(id: &str, effect: Effect) -> AuthzPolicy {
        AuthzPolicy {
            id: id.to_string(),
            priority: 0,
            enabled: true,
            effect,
            tenant: "acme".to_string(),
            project: String::new(),
            subject: "u1".to_string(),
            role: String::new(),
            action: "read".to_string(),
            resource: "doc".to_string(),
            purpose: String::new(),
            relationship: String::new(),
            conditions: Default::default(),
            required_scopes: Vec::new(),
        }
    }

    #[test]
    fn version_changes_on_in_place_edit_same_count() {
        let before = vec![policy("p1", Effect::Allow)];
        // Same row count, but the effect flipped — a count-only version would NOT
        // change; the content version MUST.
        let after = vec![policy("p1", Effect::Deny)];
        assert_ne!(
            policy_content_version(&before),
            policy_content_version(&after),
            "an in-place effect change must bump the version"
        );
    }

    #[test]
    fn version_is_order_independent_and_stable() {
        let a = vec![policy("p1", Effect::Allow), policy("p2", Effect::Deny)];
        let b = vec![policy("p2", Effect::Deny), policy("p1", Effect::Allow)];
        // DB row order must not change the version.
        assert_eq!(policy_content_version(&a), policy_content_version(&b));
        // And it is stable across calls.
        assert_eq!(policy_content_version(&a), policy_content_version(&a));
    }
}

#[cfg(test)]
mod validation_tests {
    use super::*;
    use crate::proto::udb::core::authz::services::v1::authz_service_server::AuthzService;
    use crate::proto::{ErrorDetail, ErrorKind};
    use crate::runtime::authz::AuthzSnapshot;
    use crate::runtime::executor_utils::ERROR_DETAIL_METADATA_KEY;
    use tonic::{Code, Request, Status};

    fn svc() -> AuthzServiceImpl {
        AuthzServiceImpl::new(AuthzSnapshot::default())
    }

    fn decode_detail(status: &Status) -> ErrorDetail {
        let raw = status
            .metadata()
            .get_bin(ERROR_DETAIL_METADATA_KEY)
            .expect("typed detail trailer is present");
        crate::runtime::executor_utils::decode_error_detail_from_raw(&raw)
    }

    fn assert_validation_fields(status: &Status, expected: &[(&str, &str)]) {
        assert_eq!(status.code(), Code::InvalidArgument);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Validation as i32);
        assert_eq!(detail.field_violations.len(), expected.len());
        for (actual, (field, description)) in detail.field_violations.iter().zip(expected) {
            assert_eq!(actual.field, *field);
            assert_eq!(actual.description, *description);
        }
    }

    fn assert_capability_detail(
        status: &Status,
        operation: &str,
        capability_required: &str,
        message: &str,
    ) {
        assert_eq!(status.code(), Code::FailedPrecondition);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Capability as i32);
        assert_eq!(detail.backend, "authz");
        assert_eq!(detail.operation, operation);
        assert_eq!(detail.capability_required, capability_required);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
    }

    fn assert_schema_detail(status: &Status, operation: &str, schema_code: &str, message: &str) {
        assert_eq!(status.code(), Code::NotFound);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Schema as i32);
        assert_eq!(detail.backend, "authz");
        assert_eq!(detail.operation, operation);
        assert_eq!(detail.capability_required, schema_code);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
    }

    fn assert_policy_detail(
        status: &Status,
        operation: &str,
        policy_decision_id: &str,
        message: &str,
    ) {
        assert_eq!(status.code(), Code::FailedPrecondition);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Policy as i32);
        assert_eq!(detail.operation, operation);
        assert_eq!(detail.policy_decision_id, policy_decision_id);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
    }

    fn assert_permission_policy_detail(
        status: &Status,
        operation: &str,
        policy_decision_id: &str,
        message: &str,
    ) {
        assert_eq!(status.code(), Code::PermissionDenied);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Policy as i32);
        assert_eq!(detail.operation, operation);
        assert_eq!(detail.policy_decision_id, policy_decision_id);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
    }

    fn assert_internal_detail(status: &Status, operation: &str, message: &str) {
        assert_eq!(status.code(), Code::Internal);
        assert_eq!(status.message(), message);
        let detail = decode_detail(status);
        assert_eq!(detail.kind, ErrorKind::Internal as i32);
        assert_eq!(detail.backend, "authz");
        assert_eq!(detail.operation, operation);
        assert!(!detail.retryable);
        assert_eq!(detail.retry_after_ms, 0);
        assert!(detail.field_violations.is_empty());
    }

    #[test]
    fn authz_internal_status_carries_typed_detail() {
        let status = authz_internal_status("load_authz_policies", "load authz policies failed");

        assert_internal_detail(&status, "load_authz_policies", "load authz policies failed");
    }

    #[test]
    fn authz_missing_store_capabilities_carry_typed_detail() {
        let svc = svc();

        let pool_err = match svc.require_pool() {
            Err(status) => status,
            Ok(_) => panic!("pool-less authz service must fail closed"),
        };
        assert_capability_detail(
            &pool_err,
            "postgres_auth_store",
            "postgres_auth_store",
            "this operation requires a Postgres-backed auth store (no PG pool configured)",
        );

        let fallback_err = match svc.require_snapshot_fallback() {
            Err(status) => status,
            Ok(_) => panic!("snapshot fallback without Postgres must fail closed"),
        };
        assert_capability_detail(
            &fallback_err,
            "snapshot_fallback",
            "postgres_auth_store",
            "native authz requires a Postgres-backed auth store",
        );
    }

    #[test]
    fn authz_missing_runtime_capabilities_carry_typed_detail() {
        for (operation, message) in [
            (
                "policy_persistence",
                "native authz requires runtime-backed policy persistence",
            ),
            (
                "role_persistence",
                "native authz requires runtime-backed role persistence",
            ),
            (
                "tuple_persistence",
                "native authz requires runtime-backed tuple persistence",
            ),
            (
                "user_role_persistence",
                "native authz requires runtime-backed user-role persistence",
            ),
            (
                "draft_persistence",
                "native authz requires runtime-backed draft persistence",
            ),
            (
                "policy_set_persistence",
                "native authz requires runtime-backed policy-set persistence",
            ),
            (
                "revision_persistence",
                "native authz requires runtime-backed revision persistence",
            ),
            (
                "canary_persistence",
                "native authz requires runtime-backed canary persistence",
            ),
        ] {
            let status =
                authz_capability_status(operation, "runtime_native_entity_dispatch", message);
            assert_capability_detail(
                &status,
                operation,
                "runtime_native_entity_dispatch",
                message,
            );
        }
    }

    #[test]
    fn policy_bundle_signing_missing_secret_carries_capability_detail() {
        let status = policy_bundle_signing_not_configured_status();

        assert_capability_detail(
            &status,
            "policy_bundle_signing",
            "policy_bundle_signing_secret",
            "policy bundle signing is not configured; set UDB_POLICY_BUNDLE_SECRET (or UDB_SESSION_HASH_SECRET)",
        );
    }

    #[test]
    fn authz_not_found_denials_carry_schema_detail() {
        for (status, operation, schema_code, message) in [
            (
                authz_not_found_status("get_role", "role_not_found", "role not found"),
                "get_role",
                "role_not_found",
                "role not found",
            ),
            (
                authz_not_found_status("update_role", "role_not_found", "role not found"),
                "update_role",
                "role_not_found",
                "role not found",
            ),
            (
                authz_not_found_status(
                    "get_policy_rule",
                    "policy_rule_not_found",
                    "policy rule not found",
                ),
                "get_policy_rule",
                "policy_rule_not_found",
                "policy rule not found",
            ),
            (
                authz_not_found_status(
                    "load_policy_draft",
                    "policy_draft_not_found",
                    "policy draft not found",
                ),
                "load_policy_draft",
                "policy_draft_not_found",
                "policy draft not found",
            ),
            (
                authz_not_found_status(
                    "load_policy_version",
                    "policy_version_not_found",
                    "policy version not found",
                ),
                "load_policy_version",
                "policy_version_not_found",
                "policy version not found",
            ),
            (
                authz_not_found_status(
                    "load_policy_set",
                    "policy_set_not_found",
                    "policy set not found",
                ),
                "load_policy_set",
                "policy_set_not_found",
                "policy set not found",
            ),
            (
                authz_not_found_status(
                    "load_canary",
                    "policy_canary_not_found",
                    "canary not found",
                ),
                "load_canary",
                "policy_canary_not_found",
                "canary not found",
            ),
        ] {
            assert_schema_detail(&status, operation, schema_code, message);
        }
    }

    #[test]
    fn governed_direct_mutation_denials_carry_policy_detail() {
        for (rpc, decision_id) in [
            ("PutAuthzPolicy", "put_authz_policy_disabled"),
            ("CreatePolicyRule", "create_policy_rule_disabled"),
            ("PutRoleBinding", "put_role_binding_disabled"),
            ("PutRelationship", "put_relationship_disabled"),
        ] {
            assert_policy_detail(
                &governed_direct_mutation_status(rpc, decision_id),
                "authz_governed_direct_mutation",
                decision_id,
                &format!(
                    "governed mode: direct {rpc} is disabled; create a policy draft and activate it (or use break-glass governance)"
                ),
            );
        }
    }

    #[tokio::test]
    async fn put_authz_policy_missing_policy_carries_field_violation() {
        let err = svc()
            .put_authz_policy(Request::new(authz_pb::PutAuthzPolicyRequest::default()))
            .await
            .expect_err("missing policy must fail before persistence");

        assert_eq!(err.message(), "policy is required");
        assert_validation_fields(&err, &[("policy", "must include an authz policy")]);
    }

    #[tokio::test]
    async fn put_authz_policy_missing_policy_id_carries_field_violation() {
        let err = svc()
            .put_authz_policy(Request::new(authz_pb::PutAuthzPolicyRequest {
                policy: Some(authz_pb::AuthzPolicyRecord {
                    enabled: true,
                    effect: "allow".to_string(),
                    ..Default::default()
                }),
            }))
            .await
            .expect_err("missing policy id must fail before persistence");

        assert_eq!(err.message(), "policy id is required");
        assert_validation_fields(&err, &[("policy.id", "must be a non-empty policy id")]);
    }

    #[tokio::test]
    async fn put_authz_policy_invalid_effect_carries_field_violation() {
        let err = svc()
            .put_authz_policy(Request::new(authz_pb::PutAuthzPolicyRequest {
                policy: Some(authz_pb::AuthzPolicyRecord {
                    id: "policy-1".to_string(),
                    enabled: true,
                    effect: "maybe".to_string(),
                    ..Default::default()
                }),
            }))
            .await
            .expect_err("invalid policy effect must fail before persistence");

        assert_eq!(
            err.message(),
            "policy effect must be 'allow' or 'deny', got 'maybe'"
        );
        assert_validation_fields(
            &err,
            &[("policy.effect", "must be either 'allow' or 'deny'")],
        );
    }

    #[tokio::test]
    async fn check_access_missing_user_id_carries_field_violation() {
        let err = svc()
            .check_access(Request::new(authz_pb::CheckAccessRequest {
                object: "invoice".to_string(),
                action: "read".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing user_id must fail before policy evaluation");

        assert_eq!(err.message(), "user_id is required");
        assert_validation_fields(&err, &[("user_id", "must be a non-empty user id")]);
    }

    #[tokio::test]
    async fn check_access_missing_object_carries_field_violation() {
        let err = svc()
            .check_access(Request::new(authz_pb::CheckAccessRequest {
                user_id: "user-1".to_string(),
                action: "read".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing object must fail before policy evaluation");

        assert_eq!(err.message(), "object is required");
        assert_validation_fields(&err, &[("object", "must be a non-empty object")]);
    }

    #[tokio::test]
    async fn check_access_missing_action_carries_field_violation() {
        let err = svc()
            .check_access(Request::new(authz_pb::CheckAccessRequest {
                user_id: "user-1".to_string(),
                object: "invoice".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing action must fail before policy evaluation");

        assert_eq!(err.message(), "action is required");
        assert_validation_fields(&err, &[("action", "must be a non-empty action")]);
    }

    #[tokio::test]
    async fn create_role_missing_name_carries_field_violation() {
        let err = svc()
            .create_role(Request::new(authz_pb::CreateRoleRequest {
                tenant_id: "tenant-a".to_string(),
                created_by: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing role name must fail before runtime access");

        assert_eq!(err.message(), "name is required");
        assert_validation_fields(&err, &[("name", "must be a non-empty role name")]);
    }

    #[tokio::test]
    async fn create_role_missing_scope_carries_field_violations() {
        let err = svc()
            .create_role(Request::new(authz_pb::CreateRoleRequest {
                name: "Reader".to_string(),
                created_by: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing tenant scope must fail before runtime access");

        assert_eq!(err.message(), "tenant_id or domain is required");
        assert_validation_fields(
            &err,
            &[
                (
                    "tenant_id",
                    "must include tenant_id or a tenant/project/resource domain",
                ),
                (
                    "domain",
                    "must include tenant_id or a tenant/project/resource domain",
                ),
            ],
        );
    }

    #[tokio::test]
    async fn create_role_missing_created_by_carries_field_violation() {
        let err = svc()
            .create_role(Request::new(authz_pb::CreateRoleRequest {
                name: "Reader".to_string(),
                tenant_id: "tenant-a".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing creator must fail before runtime access");

        assert_eq!(err.message(), "created_by is required");
        assert_validation_fields(&err, &[("created_by", "must be a non-empty creator id")]);
    }

    #[tokio::test]
    async fn create_role_invalid_created_by_carries_field_violation() {
        let err = svc()
            .create_role(Request::new(authz_pb::CreateRoleRequest {
                name: "Reader".to_string(),
                tenant_id: "tenant-a".to_string(),
                created_by: "not-a-uuid".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("invalid creator UUID must fail before runtime access");

        assert_eq!(err.message(), "created_by must be a UUID");
        assert_validation_fields(&err, &[("created_by", "must be a UUID")]);
    }

    #[tokio::test]
    async fn create_role_created_by_mismatch_carries_policy_detail() {
        let ctx = crate::runtime::service::method_security::test_claim_context(
            "role-admin",
            "tenant-a",
            "",
            &["udb:authz:admin"],
            &[],
        );
        let req = Request::new(authz_pb::CreateRoleRequest {
            name: "Reader".to_string(),
            tenant_id: "tenant-a".to_string(),
            created_by: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
            ..Default::default()
        });
        let err = crate::runtime::service::method_security::scope_claim_context_for_test(
            ctx,
            svc().create_role(req),
        )
        .await
        .expect_err("created_by mismatch must fail before runtime access");

        assert_permission_policy_detail(
            &err,
            "create_role",
            "created_by_caller_mismatch",
            "created_by must match the authenticated caller",
        );
    }

    #[tokio::test]
    async fn assign_role_missing_identity_carries_field_violations() {
        let err = svc()
            .assign_role(Request::new(authz_pb::AssignRoleRequest::default()))
            .await
            .expect_err("missing assignment identity must fail before runtime access");

        assert_eq!(
            err.message(),
            "user_id (or principal_id) and role_id are required"
        );
        assert_validation_fields(
            &err,
            &[
                (
                    "user_id",
                    "must include user_id or principal_id for the role binding",
                ),
                (
                    "principal_id",
                    "must include user_id or principal_id for the role binding",
                ),
                ("role_id", "must be a non-empty role id"),
            ],
        );
    }

    #[tokio::test]
    async fn assign_role_group_missing_principal_id_carries_field_violation() {
        let err = svc()
            .assign_role(Request::new(authz_pb::AssignRoleRequest {
                user_id: "external-group".to_string(),
                role_id: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                principal_kind: authz_entity_pb::PrincipalKind::Group as i32,
                ..Default::default()
            }))
            .await
            .expect_err("group binding without principal_id must fail before runtime access");

        assert_eq!(
            err.message(),
            "group role bindings require an explicit principal_id (IdP/SCIM group mapping)"
        );
        assert_validation_fields(
            &err,
            &[("principal_id", "must be explicit for group role bindings")],
        );
    }

    #[tokio::test]
    async fn assign_role_missing_assigned_by_carries_field_violation() {
        let err = svc()
            .assign_role(Request::new(authz_pb::AssignRoleRequest {
                user_id: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                role_id: "3d89cab2-1b72-46c8-9577-4a09d3a08848".to_string(),
                tenant_id: "tenant-a".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing assigner must fail before runtime access");

        assert_eq!(err.message(), "assigned_by is required");
        assert_validation_fields(&err, &[("assigned_by", "must be a non-empty assigner id")]);
    }

    #[tokio::test]
    async fn assign_role_assigned_by_mismatch_carries_policy_detail() {
        let ctx = crate::runtime::service::method_security::test_claim_context(
            "role-admin",
            "tenant-a",
            "",
            &["udb:authz:admin"],
            &[],
        );
        let req = Request::new(authz_pb::AssignRoleRequest {
            user_id: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
            role_id: "3d89cab2-1b72-46c8-9577-4a09d3a08848".to_string(),
            tenant_id: "tenant-a".to_string(),
            assigned_by: "4b0d3c76-16d1-4c91-9831-d62a25d6e37b".to_string(),
            ..Default::default()
        });
        let err = crate::runtime::service::method_security::scope_claim_context_for_test(
            ctx,
            svc().assign_role(req),
        )
        .await
        .expect_err("assigned_by mismatch must fail before runtime access");

        assert_permission_policy_detail(
            &err,
            "assign_role",
            "assigned_by_caller_mismatch",
            "assigned_by must match the authenticated caller",
        );
    }

    #[tokio::test]
    async fn assign_role_missing_scope_carries_field_violations() {
        let err = svc()
            .assign_role(Request::new(authz_pb::AssignRoleRequest {
                user_id: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                role_id: "3d89cab2-1b72-46c8-9577-4a09d3a08848".to_string(),
                assigned_by: "4b0d3c76-16d1-4c91-9831-d62a25d6e37b".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing assignment scope must fail before runtime access");

        assert_eq!(err.message(), "tenant_id or domain is required");
        assert_validation_fields(
            &err,
            &[
                (
                    "tenant_id",
                    "must include tenant_id or a tenant/project/resource domain",
                ),
                (
                    "domain",
                    "must include tenant_id or a tenant/project/resource domain",
                ),
            ],
        );
    }

    #[tokio::test]
    async fn create_policy_rule_missing_subject_carries_field_violation() {
        let err = svc()
            .create_policy_rule(Request::new(authz_pb::CreatePolicyRuleRequest {
                domain: "tenant:tenant-a".to_string(),
                object: "invoice".to_string(),
                action: "read".to_string(),
                created_by: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing policy subject must fail before runtime access");

        assert_eq!(err.message(), "subject is required");
        assert_validation_fields(&err, &[("subject", "must be a non-empty policy subject")]);
    }

    #[tokio::test]
    async fn create_policy_rule_missing_effect_carries_field_violation() {
        let err = svc()
            .create_policy_rule(Request::new(authz_pb::CreatePolicyRuleRequest {
                subject: "user:reader".to_string(),
                domain: "tenant:tenant-a".to_string(),
                object: "invoice".to_string(),
                action: "read".to_string(),
                created_by: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing policy effect must fail before runtime access");

        assert_eq!(err.message(), "policy effect is required");
        assert_validation_fields(&err, &[("effect", "must be either ALLOW or DENY")]);
    }

    #[tokio::test]
    async fn create_policy_rule_created_by_mismatch_carries_policy_detail() {
        let ctx = crate::runtime::service::method_security::test_claim_context(
            "policy-admin",
            "tenant-a",
            "",
            &["udb:authz:admin"],
            &[],
        );
        let req = Request::new(authz_pb::CreatePolicyRuleRequest {
            subject: "user:reader".to_string(),
            domain: "tenant:tenant-a".to_string(),
            object: "invoice".to_string(),
            action: "read".to_string(),
            effect: authz_entity_pb::PolicyEffect::Allow as i32,
            created_by: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
            ..Default::default()
        });
        let err = crate::runtime::service::method_security::scope_claim_context_for_test(
            ctx,
            svc().create_policy_rule(req),
        )
        .await
        .expect_err("created_by mismatch must fail before runtime access");

        assert_permission_policy_detail(
            &err,
            "create_policy_rule",
            "created_by_caller_mismatch",
            "created_by must match the authenticated caller",
        );
    }

    #[tokio::test]
    async fn list_user_permissions_missing_user_id_carries_field_violation() {
        let err = svc()
            .list_user_permissions(Request::new(authz_pb::ListUserPermissionsRequest::default()))
            .await
            .expect_err("missing user_id must fail before snapshot access");

        assert_eq!(err.message(), "user_id is required");
        assert_validation_fields(&err, &[("user_id", "must be a non-empty user id")]);
    }

    #[tokio::test]
    async fn get_role_missing_lookup_carries_field_violations() {
        let err = svc()
            .get_role(Request::new(authz_pb::GetRoleRequest::default()))
            .await
            .expect_err("missing role lookup must fail before Postgres access");

        assert_eq!(err.message(), "role_id or role_code is required");
        assert_validation_fields(
            &err,
            &[
                ("role_id", "must include role_id or role_code"),
                ("role_code", "must include role_id or role_code"),
            ],
        );
    }

    #[tokio::test]
    async fn update_role_missing_updated_by_carries_field_violation() {
        let err = svc()
            .update_role(Request::new(authz_pb::UpdateRoleRequest {
                role_id: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing updater must fail before Postgres access");

        assert_eq!(err.message(), "updated_by is required");
        assert_validation_fields(&err, &[("updated_by", "must be a non-empty updater id")]);
    }

    #[tokio::test]
    async fn delete_role_missing_deleted_by_carries_field_violation() {
        let err = svc()
            .delete_role(Request::new(authz_pb::DeleteRoleRequest {
                role_id: "2a75f9e0-11b2-4625-80a3-1f47e4b45151".to_string(),
                ..Default::default()
            }))
            .await
            .expect_err("missing deleter must fail before Postgres access");

        assert_eq!(err.message(), "deleted_by is required");
        assert_validation_fields(&err, &[("deleted_by", "must be a non-empty deleter id")]);
    }

    #[tokio::test]
    async fn revoke_role_missing_user_role_id_carries_field_violation() {
        let err = svc()
            .revoke_role(Request::new(authz_pb::RevokeRoleRequest::default()))
            .await
            .expect_err("missing user_role_id must fail before runtime access");

        assert_eq!(err.message(), "user_role_id is required");
        assert_validation_fields(
            &err,
            &[(
                "user_role_id",
                "must be a non-empty user-role assignment id",
            )],
        );
    }

    #[tokio::test]
    async fn get_policy_rule_missing_policy_id_carries_field_violation() {
        let err = svc()
            .get_policy_rule(Request::new(authz_pb::GetPolicyRuleRequest::default()))
            .await
            .expect_err("missing policy id must fail before lookup");

        assert_eq!(err.message(), "policy_id is required");
        assert_validation_fields(&err, &[("policy_id", "must be a non-empty policy id")]);
    }

    #[tokio::test]
    async fn delete_policy_rule_missing_policy_id_carries_field_violation() {
        let err = svc()
            .delete_policy_rule(Request::new(authz_pb::DeletePolicyRuleRequest::default()))
            .await
            .expect_err("missing policy id must fail before delete");

        assert_eq!(err.message(), "policy_id is required");
        assert_validation_fields(&err, &[("policy_id", "must be a non-empty policy id")]);
    }

    #[tokio::test]
    async fn get_native_access_missing_tenant_id_carries_field_violation() {
        let err = svc()
            .get_native_access(Request::new(authz_pb::NativeAccessRequest {
                principal: Some(authz_pb::Principal {
                    subject: "user-1".to_string(),
                    ..Default::default()
                }),
                ..Default::default()
            }))
            .await
            .expect_err("missing native-access tenant must fail before decision evaluation");

        assert_eq!(err.message(), "tenant_id is required");
        assert_validation_fields(&err, &[("tenant_id", "must be a non-empty tenant id")]);
    }

    #[tokio::test]
    async fn get_policy_bundle_missing_tenant_id_carries_field_violation() {
        let err = svc()
            .get_policy_bundle(Request::new(authz_pb::PolicyBundleRequest::default()))
            .await
            .expect_err("missing bundle tenant must fail before signing config access");

        assert_eq!(err.message(), "tenant_id is required for a policy bundle");
        assert_validation_fields(
            &err,
            &[(
                "tenant_id",
                "must be a non-empty tenant id for a policy bundle",
            )],
        );
    }
}

#[cfg(test)]
mod fair_admission_tests {
    use super::*;

    /// Tier-0 #1: with a wired `ChannelManager`, the hot authz decision path
    /// acquires a per-tenant `Admin` fair-admission permit (held across the
    /// decision). Without channels (bare/test construction) it degrades to a
    /// no-op permit so callers are admitted unchanged.
    #[tokio::test]
    async fn admit_acquires_permit_when_channels_wired() {
        // Bare construction: no channels → admit without a permit (no-op).
        let bare = AuthzServiceImpl::new(AuthzSnapshot::default());
        let none = bare
            .admit("tenant-a")
            .await
            .expect("bare admit must never reject");
        assert!(
            none.is_none(),
            "no channels wired ⇒ admit must return None (no-op, callers still admitted)"
        );

        // Wired construction: a real ChannelManager → admit acquires a permit.
        let svc = AuthzServiceImpl::new(AuthzSnapshot::default())
            .with_channels(Some(ChannelManager::from_env()));
        let permit = svc
            .admit("tenant-a")
            .await
            .expect("Admin channel has capacity ⇒ permit must be granted");
        assert!(
            permit.is_some(),
            "channels wired + capacity available ⇒ admit must hold a ChannelPermit"
        );
    }
}