udb 0.3.7

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
//! `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 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 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)
}

pub(super) fn parse_uuid_field(field_name: &str, value: &str) -> Result<Uuid, Status> {
    Uuid::parse_str(value)
        .map_err(|_| Status::invalid_argument(format!("{field_name} 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(Status::invalid_argument(format!(
            "{field_name} 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| Status::internal(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| Status::internal(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| Status::internal(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| Status::internal(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(|| {
            Status::failed_precondition(
                "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(Status::failed_precondition(
            "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| Status::internal(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| Status::internal(format!("decode authz fence failed: {err}")))?;
            let project_id: String = row
                .try_get("project_id")
                .map_err(|err| Status::internal(format!("decode authz fence failed: {err}")))?;
            let policy_revision: i64 = row
                .try_get("policy_revision")
                .map_err(|err| Status::internal(format!("decode authz fence failed: {err}")))?;
            let relationship_revision: i64 = row
                .try_get("relationship_revision")
                .map_err(|err| Status::internal(format!("decode authz fence failed: {err}")))?;
            let content_hash: String = row
                .try_get("content_hash")
                .map_err(|err| Status::internal(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| Status::internal(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| {
                    Status::internal(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| Status::internal(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| {
                    Status::internal(format!("decode role binding failed: {err}"))
                })?,
                role: row.try_get("role").map_err(|err| {
                    Status::internal(format!("decode role binding failed: {err}"))
                })?,
                tenant: row.try_get("tenant").map_err(|err| {
                    Status::internal(format!("decode role binding failed: {err}"))
                })?,
                project: row.try_get("project").map_err(|err| {
                    Status::internal(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| Status::internal(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| Status::internal(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| {
                    Status::internal(format!("decode grouping tuple failed: {err}"))
                })?,
                role: row.try_get("role").map_err(|err| {
                    Status::internal(format!("decode grouping tuple failed: {err}"))
                })?,
                tenant: row.try_get("tenant").map_err(|err| {
                    Status::internal(format!("decode grouping tuple failed: {err}"))
                })?,
                project: row.try_get("project").map_err(|err| {
                    Status::internal(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| Status::internal(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| {
                Status::internal(format!("decode relationship tuple failed: {err}"))
            })?;
            if tuple_condition_expired(&condition, now) {
                continue;
            }
            tuples.push(RelationshipTuple {
                subject: row.try_get("subject").map_err(|err| {
                    Status::internal(format!("decode relationship tuple failed: {err}"))
                })?,
                relation: row.try_get("relation").map_err(|err| {
                    Status::internal(format!("decode relationship tuple failed: {err}"))
                })?,
                object: row.try_get("object").map_err(|err| {
                    Status::internal(format!("decode relationship tuple failed: {err}"))
                })?,
                tenant: row.try_get("tenant").map_err(|err| {
                    Status::internal(format!("decode relationship tuple failed: {err}"))
                })?,
                project: row.try_get("project").map_err(|err| {
                    Status::internal(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,
            default_allow: false,
        }))
    }

    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(Status::aborted(
                "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(Status::failed_precondition(
                "governed mode: direct PutAuthzPolicy is disabled; create a policy draft and activate it (or use break-glass governance)",
            ));
        }
        let p = request
            .into_inner()
            .policy
            .ok_or_else(|| Status::invalid_argument("policy is required"))?;
        if p.id.trim().is_empty() {
            return Err(Status::invalid_argument("policy id is required"));
        }
        // 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(Status::invalid_argument(format!(
                "policy effect must be 'allow' or 'deny', got '{}'",
                p.effect
            )));
        };
        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(|| {
                Status::failed_precondition(
                    "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| Status::internal(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(Status::invalid_argument("user_id is required"));
        }
        if req.object.trim().is_empty() {
            return Err(Status::invalid_argument("object is required"));
        }
        if req.action.trim().is_empty() {
            return Err(Status::invalid_argument("action is required"));
        }

        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(Status::invalid_argument("name is required"));
        }
        // 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(Status::permission_denied(
                        "created_by must match the authenticated caller",
                    ));
                }
                supplied
            }
        } else {
            if req.created_by.trim().is_empty() {
                return Err(Status::invalid_argument("created_by is required"));
            }
            parse_uuid_field("created_by", &req.created_by)?
        };
        let runtime = self.runtime.as_ref().ok_or_else(|| {
            Status::failed_precondition("native authz requires runtime-backed role persistence")
        })?;
        let role_id = Uuid::new_v4().to_string();
        let tenant_id = tenant_from_domain(&req.tenant_id, &req.domain);
        if tenant_id.trim().is_empty() {
            return Err(Status::invalid_argument("tenant_id or domain is required"));
        }
        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(Status::invalid_argument(
                "user_id (or principal_id) and role_id are required",
            ));
        }
        if matches!(principal_kind, PrincipalKind::Group) && req.principal_id.trim().is_empty() {
            return Err(Status::invalid_argument(
                "group role bindings require an explicit principal_id (IdP/SCIM group mapping)",
            ));
        }
        // 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(Status::permission_denied(
                        "assigned_by must match the authenticated caller",
                    ));
                }
                supplied
            }
        } else {
            if req.assigned_by.trim().is_empty() {
                return Err(Status::invalid_argument("assigned_by is required"));
            }
            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(Status::invalid_argument("tenant_id or domain is required"));
        }

        // 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(|| {
                Status::failed_precondition(
                    "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| {
                    Status::internal(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(|| {
            Status::failed_precondition(
                "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| Status::internal(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(Status::failed_precondition(
                "governed mode: direct CreatePolicyRule is disabled; create a policy draft and activate it (or use break-glass governance)",
            ));
        }
        let req = request.into_inner();
        if req.subject.trim().is_empty() {
            return Err(Status::invalid_argument("subject is required"));
        }
        if req.domain.trim().is_empty() {
            return Err(Status::invalid_argument("domain is required"));
        }
        if req.object.trim().is_empty() {
            return Err(Status::invalid_argument("object is required"));
        }
        if req.action.trim().is_empty() {
            return Err(Status::invalid_argument("action is required"));
        }
        // 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(Status::permission_denied(
                        "created_by must match the authenticated caller",
                    ));
                }
                supplied
            }
        } else {
            if req.created_by.trim().is_empty() {
                return Err(Status::invalid_argument("created_by is required"));
            }
            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(|| {
                Status::failed_precondition(
                    "native authz requires runtime-backed policy persistence",
                )
            })?;
            let attributes = serde_json::to_value(&policy.conditions).map_err(|err| {
                Status::internal(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| Status::internal(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(|| {
                    Status::internal("create policy rule returned no persisted id".to_string())
                })?
                .to_string();
            if created_policy_id != policy.id {
                return Err(Status::internal(
                    "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(Status::invalid_argument("user_id is required"));
        }
        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()
                    },
                });
            }
        }
        Ok(Response::new(authz_pb::ListUserPermissionsResponse {
            permissions,
        }))
    }
    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(Status::invalid_argument("user_role_id is required"));
        }
        let user_role_id = parse_uuid_field("user_role_id", &req.user_role_id)?;
        let runtime = self.runtime.as_ref().ok_or_else(|| {
            Status::failed_precondition(
                "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| Status::internal(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(Status::invalid_argument("user_id is required"));
        }
        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| Status::internal(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)?);
        }
        Ok(Response::new(authz_pb::ListUserRolesResponse {
            user_roles,
        }))
    }
    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(Status::invalid_argument("role_id or role_code is required"));
        }
        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| Status::internal(format!("get role failed: {err}")))?;
        match row {
            Some(row) => Ok(Response::new(authz_pb::GetRoleResponse {
                role: Some(role_from_row(&row)?),
            })),
            None => Err(Status::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| Status::internal(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(Status::invalid_argument("user_id is required"));
        }
        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(Status::invalid_argument("role_id is required"));
        }
        let role_id = parse_uuid_field("role_id", &req.role_id)?;
        if req.updated_by.trim().is_empty() {
            return Err(Status::invalid_argument("updated_by is required"));
        }
        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} = COALESCE(NULLIF($2, ''), {name}), \
               {description} = COALESCE(NULLIF($3, ''), {description}), \
               {is_active} = COALESCE($4, {is_active}) \
             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(&req.name)
        .bind(&req.description)
        .bind(req.is_active)
        .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(Status::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(Status::invalid_argument("role_id is required"));
        }
        if req.deleted_by.trim().is_empty() {
            return Err(Status::invalid_argument("deleted_by is required"));
        }
        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| Status::internal(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(|| {
            Status::failed_precondition("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| Status::internal(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| {
                    Status::internal(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(Status::invalid_argument("policy_id is required"));
        }
        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| Status::internal(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(Status::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| Status::internal(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(Status::invalid_argument("policy_id is required"));
        }
        let mut deleted = false;
        if self.pg_pool.is_some() {
            let runtime = self.runtime.as_ref().ok_or_else(|| {
                Status::failed_precondition(
                    "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| Status::internal(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(Status::invalid_argument("tenant_id is required"));
        }

        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(Status::invalid_argument(
                "tenant_id is required for a policy bundle",
            ));
        }
        let cfg = PolicyBundleConfig::from_env();
        if !cfg.enabled() {
            return Err(Status::failed_precondition(
                "policy bundle signing is not configured; set UDB_POLICY_BUNDLE_SECRET \
                 (or UDB_SESSION_HASH_SECRET)",
            ));
        }
        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(|| Status::internal("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 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"
        );
    }
}