polyc-query 2026.9.0

Read layer over the event log: a DataFusion engine for SQL over replayed partitions, and a per-conversation Parquet projection for participation-scoped search.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
use arrow::array::{Array as _, Int32Array};
use arrow::datatypes::{DataType, Field, Schema};
use buffa::Message as _;
use commonware_runtime::{Runner, deterministic};
use datafusion::execution::memory_pool::FairSpillPool;
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
use polyc_crypto::approval::{
    ApprovalSigner, ReceiptPayload, RefusalPayload, WalletLinkLifecyclePayload, receipt_payload,
    refusal_payload, routine_created_payload, routine_deleted_payload, routine_paused_payload,
    routine_resumed_payload, routine_scope_changed_payload, wallet_link_lifecycle_payload,
};
use polyc_eventlog::{EventLog, EventLogConfig};
use polyc_proto::kinds;
use polyc_proto::proto::polychrome::agent::v1::{
    Content, FunctionCallContent, FunctionResultContent, Message as WireMessage, TextContent,
    ToolCallContent, ToolResultContent, content, function_result_content, tool_call_content,
    tool_result_content,
};
use polyc_proto::proto::polychrome::events::v1::{
    AttributionEvent, ModelCallEvent, RoutineFireOutcome, RoutineFireOutcomeEvent,
    RoutineFiredEvent, SummaryEvent, TurnDispatchedEvent, TurnFailedEvent, UsageEvent,
};
use polyc_proto::proto::polychrome::harness::v1::TurnFailureKind;
use polyc_proto::proto::polychrome::persona::v1::{
    ExternalIdentity, PersonaCredential, SpendPolicy, UsageRollup, WalletLink,
};
use uuid::Uuid;

use super::*;

/// Test-only convenience over [`QueryEngine::execute_with_params`].
///
/// The tests below never bind a parameter — they are about scope, redaction,
/// and the statement gate — so they would otherwise carry an empty slice at
/// every one of their call sites. Production code has exactly one entry
/// point, `execute_with_params`; an inherent impl compiles anywhere in the
/// module tree, so this one lives inside the test module it exists for, where
/// nothing has to say that it is test-only.
impl QueryEngine {
    /// Run `sql` with nothing bound. See
    /// [`QueryEngine::execute_with_params`] for everything this does.
    ///
    /// # Errors
    ///
    /// Same as [`QueryEngine::execute_with_params`].
    pub(crate) async fn execute(
        &self,
        sql: &str,
        allow_explain: bool,
    ) -> Result<QueryOutput, QueryEngineError> {
        self.execute_with_params(sql, &[], allow_explain).await
    }
}

/// A fresh base `SessionState` for one test's `QueryEngine::build` call —
/// mirrors `crate::authority`'s own `build_base_session_state`, at a small
/// fixed pool size (these fixtures are tiny, in-memory `MemTable`s; no test
/// here approaches the default 192 MiB production ceiling).
fn test_base_state() -> SessionState {
    let runtime = RuntimeEnvBuilder::new()
        .with_memory_pool(Arc::new(FairSpillPool::new(64 * 1024 * 1024)))
        .build_arc()
        .expect("build test runtime");
    SessionStateBuilder::new()
        .with_runtime_env(runtime)
        .with_default_features()
        .build()
}

/// A committed turn (`turn_start` + `user_msg` + `usage` +
/// `turn_complete`) plus one deliberately orphaned turn (`turn_start` +
/// `user_msg` + `output_msg`, no `turn_complete`) — the spike's own
/// fixture shape: 3 raw rows for the orphaned `turn_id`, 0 through the
/// committed view. Events are constructed directly (not through a
/// journal) for every test except
/// [`real_journal_round_trip_reproduces_the_spikes_3_vs_0`], which is
/// the one seam test that must go through a real `polyc-eventlog`
/// journal write+replay round trip end to end.
fn fixture_events(committed_turn: Uuid, orphaned_turn: Uuid) -> Vec<(u64, Event)> {
    let usage = UsageEvent {
        input_tokens: 11,
        output_tokens: 22,
        ..Default::default()
    };
    vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::trusted(
                kinds::tagged(kinds::USER_MSG, &committed_turn),
                b"hello".to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::USAGE, &committed_turn),
                usage.encode_to_vec(),
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            4,
            Event::new(kinds::tagged(kinds::TURN_START, &orphaned_turn), Vec::new()),
        ),
        (
            5,
            Event::trusted(
                kinds::tagged(kinds::USER_MSG, &orphaned_turn),
                b"orphaned".to_vec(),
            ),
        ),
        (
            6,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &orphaned_turn),
                b"partial reply".to_vec(),
            ),
        ),
    ]
}

fn one_partition(name: &str, committed_turn: Uuid, orphaned_turn: Uuid) -> Vec<PartitionEvents> {
    vec![PartitionEvents {
        partition: name.to_string(),
        events: fixture_events(committed_turn, orphaned_turn),
    }]
}

/// Collect one column of a single-row, single-batch `COUNT(*)`-shaped
/// result as `i64`.
fn single_count(output: &QueryOutput) -> i64 {
    assert_eq!(output.batches.len(), 1, "expected exactly one batch");
    let batch = &output.batches[0];
    assert_eq!(batch.num_rows(), 1, "expected exactly one row");
    batch
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::Int64Array>()
        .expect("COUNT(*) is Int64")
        .value(0)
}

/// The one seam test mandated by #1179 that must go through a real
/// `polyc-eventlog` journal write, commit, and replay — not
/// directly-constructed `Event`s. Mirrors the deterministic-runtime
/// pattern `polyc-eventlog`'s own tests use
/// (`doc_example_open_append_replay`,
/// `crates/eventlog/src/lib.rs`): the journal round trip runs to
/// completion inside `deterministic::Runner::start` (which cannot nest
/// inside a live tokio runtime — see `polyc-eventlog`'s crate docs), and
/// its owned `Vec<(u64, Event)>` output feeds a separate tokio runtime
/// that drives the engine, since `QueryEngine::build`/`execute` are
/// async.
///
/// Reproduces the spike's own verification pair byte-for-byte: a raw
/// count of 3 rows for the orphaned `turn_id`, 0 through the committed
/// `events` view.
#[test]
fn real_journal_round_trip_reproduces_the_spikes_3_vs_0() {
    let committed_turn = Uuid::from_u128(0x0195_abcd_ef01_2345_6789_abcd_ef01_2345);
    let orphaned_turn = Uuid::from_u128(0x0195_abcd_ef01_2345_6789_abcd_ef01_9999);

    let executor = deterministic::Runner::default();
    let replayed: Vec<(u64, Event)> = executor.start(|context| async move {
        let log = EventLog::open(context, EventLogConfig::for_partition("conv-p3-real"))
            .await
            .expect("open log");

        for (_position, event) in fixture_events(committed_turn, orphaned_turn) {
            log.append(&event).await.expect("append");
        }
        log.commit().await.expect("commit");

        log.replay_with_positions().await.expect("replay")
    });
    assert_eq!(replayed.len(), 7, "the fixture's own seven events");

    let tokio_rt = tokio::runtime::Runtime::new().expect("build a tokio runtime");
    tokio_rt.block_on(async move {
        let partitions = vec![PartitionEvents {
            partition: "conv-p3-real".to_string(),
            events: replayed,
        }];
        let engine = QueryEngine::build(
            &test_base_state(),
            &QueryScope::Fleet,
            partitions,
            ReferenceData::empty(),
            &[],
            QueryLimits::default(),
        )
        .await
        .expect("build");

        let raw = engine
            .execute(
                &format!("SELECT COUNT(*) AS c FROM events_raw WHERE turn_id = '{orphaned_turn}'"),
                false,
            )
            .await
            .expect("raw count query");
        assert_eq!(
            single_count(&raw),
            3,
            "raw replay includes the orphaned turn's rows"
        );

        let committed = engine
            .execute(
                &format!("SELECT COUNT(*) AS c FROM events WHERE turn_id = '{orphaned_turn}'"),
                false,
            )
            .await
            .expect("committed count query");
        assert_eq!(
            single_count(&committed),
            0,
            "the committed-turns view excludes the orphaned turn entirely"
        );
    });
}

#[tokio::test]
async fn fleet_scope_events_view_excludes_orphaned_turn_raw_includes_it() {
    let committed_turn = Uuid::from_u128(1);
    let orphaned_turn = Uuid::from_u128(2);
    let partitions = one_partition("conv-a", committed_turn, orphaned_turn);
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let raw = engine
        .execute(
            &format!("SELECT COUNT(*) AS c FROM events_raw WHERE turn_id = '{orphaned_turn}'"),
            false,
        )
        .await
        .expect("raw query");
    assert_eq!(single_count(&raw), 3);

    let committed = engine
        .execute(
            &format!("SELECT COUNT(*) AS c FROM events WHERE turn_id = '{orphaned_turn}'"),
            false,
        )
        .await
        .expect("committed query");
    assert_eq!(single_count(&committed), 0);
}

#[tokio::test]
async fn conversations_scope_hides_raw_table_by_every_name() {
    let committed_turn = Uuid::from_u128(3);
    let orphaned_turn = Uuid::from_u128(4);
    let partitions = one_partition("conv-b", committed_turn, orphaned_turn);
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-b".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let unqualified = engine.execute("SELECT * FROM events_raw", false).await;
    assert!(
        matches!(unqualified, Err(QueryEngineError::DataFusion(_))),
        "events_raw must not resolve for a non-Fleet scope: {unqualified:?}"
    );

    let qualified = engine
        .execute("SELECT * FROM datafusion.public.events_raw", false)
        .await;
    assert!(
        matches!(qualified, Err(QueryEngineError::DataFusion(_))),
        "a fully-qualified name must not reach the raw rows either: {qualified:?}"
    );

    // `attribution_raw` gets the identical fail-closed treatment — see the
    // engine module docs' "Identity redaction invariant" section.
    let attribution_raw_unqualified = engine.execute("SELECT * FROM attribution_raw", false).await;
    assert!(
        matches!(
            attribution_raw_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "attribution_raw must not resolve for a non-Fleet scope: {attribution_raw_unqualified:?}"
    );

    // `payments_raw` is deregistered by the same helper and must be equally
    // unreachable, so a persona can never read the Fleet-only
    // `signer_public_key` through the raw base table.
    let payments_raw_unqualified = engine.execute("SELECT * FROM payments_raw", false).await;
    assert!(
        matches!(
            payments_raw_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "payments_raw must not resolve for a non-Fleet scope: {payments_raw_unqualified:?}"
    );
}

/// A known [`PersonaProfile`]/[`Participation`] pair, supplied through
/// [`ReferenceData`], surfaces as exactly one row in each of `personas`/
/// `participations` for a [`QueryScope::Fleet`] session — and the
/// participation joins back to the conversation partition it names (see
/// `crate::decode::persona`'s "`conversation_id` vs. `partition`" doc
/// for why the join needs the `'conv-' ||` prefix).
#[tokio::test]
async fn fleet_scope_reference_tables_return_rows_and_participation_joins_to_its_conversation() {
    let committed_turn = Uuid::from_u128(20);
    let orphaned_turn = Uuid::from_u128(21);
    let partitions = one_partition("conv-ref", committed_turn, orphaned_turn);

    let profile = PersonaProfile {
        persona_id: "persona-ref-1".to_string(),
        display_name: "Ada".to_string(),
        created_at_ms: 5_000,
        status: "linked".to_string(),
        ..Default::default()
    };
    let participation = Participation {
        conversation_id: "ref".to_string(),
        role: "initiator".to_string(),
        first_at_ms: 6_000,
        ..Default::default()
    };
    let reference = ReferenceData {
        personas: vec![profile],
        participations: vec![("persona-ref-1".to_string(), participation)],
        ..ReferenceData::empty()
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let personas = engine
        .execute("SELECT COUNT(*) AS c FROM personas", false)
        .await
        .expect("personas query");
    assert_eq!(single_count(&personas), 1);

    let participations = engine
        .execute("SELECT COUNT(*) AS c FROM participations", false)
        .await
        .expect("participations query");
    assert_eq!(single_count(&participations), 1);

    let joined = engine
        .execute(
            "SELECT DISTINCT e.partition FROM participations p \
             JOIN events_raw e ON e.partition = 'conv-' || p.conversation_id \
             WHERE p.persona_id = 'persona-ref-1'",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches exactly one distinct conversation partition"
    );
    let partition_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("partition is Utf8");
    assert_eq!(partition_col.value(0), "conv-ref");
}

/// QRY-8's own bulk-export invariant proof ([`crate::decode::persona`]'s
/// module docs' "Bulk-export invariant (QRY-8)" section): a Fleet-scope SQL
/// query joining
/// `personas`/`persona_wallets`/`persona_spend_policies`/
/// `persona_credentials`/`persona_usage` returns EXACTLY the
/// `forensics::api_persona` parity columns (`wallet_address`, `"limit"`,
/// `allowed_hosts`, `rp_id`, `origin`, `revoked`, `committed_turns`) in one
/// query — proving the redaction bar is "unredacted, like forensics" not
/// "silently narrower" — while every key-material column
/// (`key_ref`/`credential_id`/`p256_public_key_sec1`/`signing_public_key`)
/// stays unreachable under any name, proven three ways: a direct `SELECT`
/// of each fails to plan, and a schema-level `information_schema.columns`
/// scan (itself Fleet-only) finds none of the four names among the four new
/// tables' columns at all — not merely that today's query happens not to
/// select them.
#[tokio::test]
#[allow(clippy::too_many_lines)] // one assertion per parity column plus the three-way key-material proof; no shared shape to extract
async fn qry8_bulk_export_query_returns_parity_columns_and_hides_key_material() {
    let committed_turn = Uuid::from_u128(28);
    let orphaned_turn = Uuid::from_u128(29);
    let partitions = one_partition("conv-parity", committed_turn, orphaned_turn);

    let profile = PersonaProfile {
        persona_id: "persona-parity-1".to_string(),
        display_name: "Ada".to_string(),
        created_at_ms: 1_000,
        status: "linked".to_string(),
        ..Default::default()
    };
    let wallet = WalletLink {
        persona_id: "persona-parity-1".to_string(),
        wallet_address: "0xParity".to_string(),
        currency: "0xUSDC".to_string(),
        expiry_unix: 123,
        key_ref: "keychain://persona-parity-1-secret".to_string(),
        created_at_ms: 1_000,
        revoked: false,
        revoked_at_ms: 0,
        ..Default::default()
    };
    let spend_policy = SpendPolicy {
        persona_id: "persona-parity-1".to_string(),
        limit: "5".to_string(),
        period_secs: 86_400,
        max_lifetime_secs: 604_800,
        allowed_hosts: vec!["api.example.com".to_string(), "pay.example.com".to_string()],
        updated_at_ms: 2_000,
        set_by: "admin-1".to_string(),
        ..Default::default()
    };
    let credential = PersonaCredential {
        persona_id: "persona-parity-1".to_string(),
        credential_id: vec![9, 9, 9],
        p256_public_key_sec1: vec![8, 8, 8],
        signing_public_key: vec![7, 7, 7],
        rp_id: "polychrome.example".to_string(),
        origin: "https://polychrome.example".to_string(),
        created_at_ms: 3_000,
        revoked: true,
        revoked_at_ms: 3_500,
        ..Default::default()
    };
    let usage_rollup = UsageRollup {
        persona_id: "persona-parity-1".to_string(),
        committed_turns: 5,
        input_tokens: 10,
        output_tokens: 20,
        last_active_ms: 4_000,
        conversation_ids: vec!["conv-parity".to_string()],
        updated_at_ms: 4_500,
        ..Default::default()
    };
    let reference = ReferenceData {
        personas: vec![profile],
        participations: Vec::new(),
        wallets: vec![("persona-parity-1".to_string(), wallet)],
        spend_policies: vec![("persona-parity-1".to_string(), spend_policy)],
        credentials: vec![("persona-parity-1".to_string(), credential)],
        usage_rollups: vec![("persona-parity-1".to_string(), usage_rollup)],
        routines: Vec::new(),
        dashboard: Vec::new(),
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    // The bulk-export query itself: one join across every new table,
    // selecting exactly the forensics-parity columns.
    let joined = engine
        .execute(
            "SELECT w.wallet_address, sp.\"limit\", sp.allowed_hosts, c.rp_id, c.origin, \
             c.revoked, u.committed_turns \
             FROM personas p \
             JOIN persona_wallets w ON w.persona_id = p.persona_id \
             JOIN persona_spend_policies sp ON sp.persona_id = p.persona_id \
             JOIN persona_credentials c ON c.persona_id = p.persona_id \
             JOIN persona_usage u ON u.persona_id = p.persona_id \
             WHERE p.persona_id = 'persona-parity-1'",
            false,
        )
        .await
        .expect("bulk-export join query");
    assert_eq!(joined.batches[0].num_rows(), 1);

    let wallet_address = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("wallet_address is Utf8")
        .value(0);
    assert_eq!(wallet_address, "0xParity", "wallet_address is unredacted");

    let limit = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("limit is Utf8")
        .value(0);
    assert_eq!(limit, "5", "spend limit is unredacted");

    let allowed_hosts = joined.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("allowed_hosts is Utf8")
        .value(0);
    assert_eq!(
        allowed_hosts, r#"["api.example.com","pay.example.com"]"#,
        "the full allowed_hosts list is unredacted"
    );

    let rp_id = joined.batches[0]
        .column(3)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("rp_id is Utf8")
        .value(0);
    assert_eq!(rp_id, "polychrome.example");

    let origin = joined.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("origin is Utf8")
        .value(0);
    assert_eq!(origin, "https://polychrome.example");

    let revoked = joined.batches[0]
        .column(5)
        .as_any()
        .downcast_ref::<arrow::array::BooleanArray>()
        .expect("revoked is Boolean")
        .value(0);
    assert!(revoked, "credential revocation state is unredacted");

    let committed_turns = joined.batches[0]
        .column(6)
        .as_any()
        .downcast_ref::<arrow::array::UInt64Array>()
        .expect("committed_turns is UInt64")
        .value(0);
    assert_eq!(committed_turns, 5);

    // Direct SELECTs of each key-material column fail to plan — the column
    // simply does not exist under any name.
    for (table, column) in [
        ("persona_wallets", "key_ref"),
        ("persona_credentials", "credential_id"),
        ("persona_credentials", "p256_public_key_sec1"),
        ("persona_credentials", "signing_public_key"),
    ] {
        let result = engine
            .execute(&format!("SELECT {column} FROM {table}"), false)
            .await;
        assert!(
            matches!(result, Err(QueryEngineError::DataFusion(_))),
            "{table}.{column} must not resolve: {result:?}"
        );
    }

    // Schema-level assertion: scan every column DataFusion's own catalog
    // knows about for the four new tables, and confirm none of the
    // key-material names appear — not merely that today's SQL doesn't
    // select them.
    let columns = engine
        .execute(
            "SELECT column_name FROM information_schema.columns WHERE table_name IN \
             ('persona_wallets', 'persona_spend_policies', 'persona_credentials', \
             'persona_usage')",
            false,
        )
        .await
        .expect("information_schema.columns query");
    let banned = [
        "key_ref",
        "credential_id",
        "p256_public_key_sec1",
        "signing_public_key",
    ];
    for batch in &columns.batches {
        let column_names = batch
            .column(0)
            .as_any()
            .downcast_ref::<arrow::array::StringArray>()
            .expect("column_name is Utf8");
        for i in 0..column_names.len() {
            let name = column_names.value(i);
            assert!(
                !banned.contains(&name),
                "key-material column {name} must not appear in any new reference table's schema"
            );
        }
    }
}

/// Fleet-only proof for the reference tables: for a
/// [`QueryScope::Conversations`] session, `personas`, `participations`,
/// `persona_identities`, and (#1578) `persona_wallets`/
/// `persona_spend_policies`/`persona_credentials`/`persona_usage` all fail
/// to resolve UNDER ANY NAME, even when [`ReferenceData`] carries real rows
/// — mirroring [`conversations_scope_hides_raw_table_by_every_name`]'s "the
/// name is gone from the catalog entirely" pattern for `events_raw`. Per the
/// module docs, this is not a filter that could be bypassed by a
/// mis-planned query — the tables are never registered at all for this
/// scope, so `information_schema` (itself off for non-Fleet, pinned
/// elsewhere) could not even reveal they exist.
///
/// This exercises [`QueryScope::Conversations`] directly rather than
/// threading a conversation-grant or persona [`crate::authority::Principal`]
/// through `scope_for` first: `crate::authority::QueryAuthority::scope_for`
/// maps BOTH principal kinds to this exact same `QueryScope::Conversations`
/// enum variant (never anything else), and every registration gate in this
/// module keys off the scope VALUE, not off which principal produced it —
/// so this one test already covers "both grant and persona principals" by
/// covering the only scope value either can ever produce.
#[tokio::test]
async fn conversations_scope_hides_reference_tables() {
    let committed_turn = Uuid::from_u128(22);
    let orphaned_turn = Uuid::from_u128(23);
    let partitions = one_partition("conv-ref-hidden", committed_turn, orphaned_turn);

    let profile = PersonaProfile {
        persona_id: "persona-hidden-1".to_string(),
        display_name: "Hidden".to_string(),
        created_at_ms: 1_000,
        status: "linked".to_string(),
        identities: vec![sample_identity("slack", "team-1", "U-HIDDEN", "Hidden")],
        ..Default::default()
    };
    let participation = Participation {
        conversation_id: "ref-hidden".to_string(),
        role: "initiator".to_string(),
        first_at_ms: 2_000,
        ..Default::default()
    };
    let wallet = WalletLink {
        persona_id: "persona-hidden-1".to_string(),
        wallet_address: "0xhidden".to_string(),
        currency: "0xusdc".to_string(),
        created_at_ms: 1_500,
        ..Default::default()
    };
    let spend_policy = SpendPolicy {
        persona_id: "persona-hidden-1".to_string(),
        limit: "5".to_string(),
        allowed_hosts: vec!["pay.example.com".to_string()],
        ..Default::default()
    };
    let credential = PersonaCredential {
        persona_id: "persona-hidden-1".to_string(),
        rp_id: "polychrome.example".to_string(),
        origin: "https://polychrome.example".to_string(),
        created_at_ms: 1_600,
        ..Default::default()
    };
    let usage_rollup = UsageRollup {
        persona_id: "persona-hidden-1".to_string(),
        committed_turns: 3,
        ..Default::default()
    };
    let reference = ReferenceData {
        personas: vec![profile],
        participations: vec![("persona-hidden-1".to_string(), participation)],
        wallets: vec![("persona-hidden-1".to_string(), wallet)],
        spend_policies: vec![("persona-hidden-1".to_string(), spend_policy)],
        credentials: vec![("persona-hidden-1".to_string(), credential)],
        usage_rollups: vec![("persona-hidden-1".to_string(), usage_rollup)],
        routines: Vec::new(),
        dashboard: Vec::new(),
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-ref-hidden".to_string()]),
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    for table in [
        "personas",
        "participations",
        "persona_identities",
        "persona_wallets",
        "persona_spend_policies",
        "persona_credentials",
        "persona_usage",
    ] {
        let bare = engine
            .execute(&format!("SELECT * FROM {table}"), false)
            .await;
        assert!(
            matches!(bare, Err(QueryEngineError::DataFusion(_))),
            "{table} must not resolve for a non-Fleet scope: {bare:?}"
        );

        let qualified = engine
            .execute(&format!("SELECT * FROM datafusion.public.{table}"), false)
            .await;
        assert!(
            matches!(qualified, Err(QueryEngineError::DataFusion(_))),
            "a fully-qualified name must not reach {table} either: {qualified:?}"
        );
    }
}

/// The `dashboard` reference table (#1584/#1585): a [`crate::dashboard::DashboardRow`]
/// supplied through [`ReferenceData::dashboard`] surfaces as exactly one row
/// for a [`QueryScope::Fleet`] session, with `summary_text` (the QRY-2-D
/// Fleet-only/admin-redacted field the `summary` table also carries) visible,
/// and `edges_json`/`settlements_json` navigable via `json_get_str` (this crate's
/// registered JSON functions, see `crate::decode` module docs' "The
/// schema-less residual" section) rather than a normalized child table.
#[tokio::test]
async fn fleet_scope_dashboard_table_returns_rows_with_summary_text_and_json_columns() {
    let committed_turn = Uuid::from_u128(30);
    let orphaned_turn = Uuid::from_u128(31);
    let partitions = one_partition("conv-dash-ref", committed_turn, orphaned_turn);

    let row = crate::dashboard::DashboardRow {
        conversation_id: "dash-ref".to_string(),
        total_events: 9,
        committed_turns: 1,
        input_tokens: 10,
        output_tokens: 5,
        summary_text: Some("condensed so far".to_string()),
        last_turn_id: Some(committed_turn.as_simple().to_string()),
        edges: vec!["web".to_string()],
        settlements: vec![crate::dashboard::DashboardSettlement {
            persona: "persona-a".to_string(),
            spend_base_units: 1_500,
            charged_base_units: 250,
        }],
        created_at_ms: Some(1_700_000_000_000),
        last_activity_ms: Some(1_700_000_000_000),
        persona_id: Some("persona-a".to_string()),
        first_message_preview: Some("hello there".to_string()),
    };
    let reference = ReferenceData {
        dashboard: vec![row],
        ..ReferenceData::empty()
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT conversation_id, summary_active, summary_text, edges_json, settlements_json \
             FROM dashboard",
            false,
        )
        .await
        .expect("dashboard query");
    assert_eq!(output.batches[0].num_rows(), 1);

    let conversation_id = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("conversation_id is Utf8");
    assert_eq!(conversation_id.value(0), "dash-ref");

    let summary_active = output.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::BooleanArray>()
        .expect("summary_active is Boolean");
    assert!(summary_active.value(0));

    let summary_text = output.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("summary_text is Utf8");
    assert_eq!(
        summary_text.value(0),
        "condensed so far",
        "a Fleet session sees summary_text — the same posture the `summary` table's own \
         QRY-2-D Fleet-only gate applies"
    );

    let edges_json = output.batches[0]
        .column(3)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("edges_json is Utf8");
    assert_eq!(edges_json.value(0), r#"["web"]"#);

    let settlements_json = output.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("settlements_json is Utf8");
    let decoded: serde_json::Value = serde_json::from_str(settlements_json.value(0)).unwrap();
    assert_eq!(decoded[0]["persona"], "persona-a");
    assert_eq!(decoded[0]["spend_base_units"], "1500");
    assert_eq!(decoded[0]["charged_base_units"], "250");
}

/// Fleet-only proof for `dashboard` (QRY-2-D, #1537): for a
/// [`QueryScope::Conversations`] session, `dashboard` fails to resolve UNDER
/// ANY NAME, even when [`ReferenceData::dashboard`] carries a row whose
/// `summary_text`/`first_message_preview` would otherwise leak — the same
/// "never even registered" posture [`conversations_scope_hides_reference_tables`]
/// pins for `personas`/`participations`, applied here to the table that
/// carries the summary redaction bar.
#[tokio::test]
async fn conversations_scope_hides_dashboard_table_and_its_summary_text() {
    let committed_turn = Uuid::from_u128(32);
    let orphaned_turn = Uuid::from_u128(33);
    let partitions = one_partition("conv-dash-hidden", committed_turn, orphaned_turn);

    let row = crate::dashboard::DashboardRow {
        conversation_id: "dash-hidden".to_string(),
        summary_text: Some("must never leak to a non-admin scope".to_string()),
        first_message_preview: Some("also must never leak".to_string()),
        ..Default::default()
    };
    let reference = ReferenceData {
        dashboard: vec![row],
        ..ReferenceData::empty()
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-dash-hidden".to_string()]),
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let dashboard = engine.execute("SELECT * FROM dashboard", false).await;
    assert!(
        matches!(dashboard, Err(QueryEngineError::DataFusion(_))),
        "dashboard must not resolve for a non-Fleet scope: {dashboard:?}"
    );

    let qualified = engine
        .execute("SELECT * FROM datafusion.public.dashboard", false)
        .await;
    assert!(
        matches!(qualified, Err(QueryEngineError::DataFusion(_))),
        "a fully-qualified name must not reach dashboard either: {qualified:?}"
    );
}

/// A merged persona's `merged_into` round-trips through SQL to the
/// surviving persona's id, and an unmerged persona's `merged_into` is the
/// empty string — the G1 gap that lets a Fleet consumer fold a merged
/// persona's data into its survivor without a second
/// `resolve_persona_id`-style lookup.
#[tokio::test]
async fn fleet_scope_personas_merged_into_column_resolves_the_survivor() {
    let committed_turn = Uuid::from_u128(24);
    let orphaned_turn = Uuid::from_u128(25);
    let partitions = one_partition("conv-merge", committed_turn, orphaned_turn);

    let survivor = PersonaProfile {
        persona_id: "persona-survivor".to_string(),
        display_name: "Ada".to_string(),
        created_at_ms: 1_000,
        status: "linked".to_string(),
        ..Default::default()
    };
    let absorbed = PersonaProfile {
        persona_id: "persona-absorbed".to_string(),
        display_name: "Ada (old)".to_string(),
        created_at_ms: 500,
        status: "merged".to_string(),
        merged_into: "persona-survivor".to_string(),
        ..Default::default()
    };
    let reference = ReferenceData {
        personas: vec![survivor, absorbed],
        participations: Vec::new(),
        ..ReferenceData::empty()
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let rows = engine
        .execute(
            "SELECT persona_id, merged_into FROM personas ORDER BY persona_id",
            false,
        )
        .await
        .expect("personas query");
    assert_eq!(rows.batches[0].num_rows(), 2);

    let persona_id_col = rows.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("persona_id is Utf8");
    let merged_into_col = rows.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("merged_into is Utf8");

    assert_eq!(persona_id_col.value(0), "persona-absorbed");
    assert_eq!(merged_into_col.value(0), "persona-survivor");
    assert_eq!(persona_id_col.value(1), "persona-survivor");
    assert_eq!(
        merged_into_col.value(1),
        "",
        "an unmerged survivor's merged_into is empty, not null"
    );
}

/// [`PersonaProfile::identities`] surfaces as one `persona_identities` row
/// per identity, joins back to `personas` on `persona_id`, and supports the
/// `/resolve` reverse lookup shape — `SELECT persona_id FROM
/// persona_identities WHERE provider = ? AND scope = ? AND external_id =
/// ?` — this table exists to back (#1312's G2 gap).
#[tokio::test]
async fn fleet_scope_persona_identities_are_queryable_and_resolve_by_identity() {
    let committed_turn = Uuid::from_u128(26);
    let orphaned_turn = Uuid::from_u128(27);
    let partitions = one_partition("conv-idents", committed_turn, orphaned_turn);

    let profile = PersonaProfile {
        persona_id: "persona-idents-1".to_string(),
        display_name: "Ada".to_string(),
        created_at_ms: 1_000,
        status: "linked".to_string(),
        identities: vec![
            sample_identity("slack", "team-1", "U-1", "Ada"),
            sample_identity("telegram", "", "T-1", "Ada"),
        ],
        ..Default::default()
    };
    let reference = ReferenceData {
        personas: vec![profile],
        participations: Vec::new(),
        ..ReferenceData::empty()
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM persona_identities", false)
        .await
        .expect("persona_identities query");
    assert_eq!(single_count(&count), 2);

    let joined = engine
        .execute(
            "SELECT DISTINCT p.display_name FROM persona_identities i \
             JOIN personas p ON p.persona_id = i.persona_id \
             WHERE i.persona_id = 'persona-idents-1'",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches the one persona exactly once"
    );
    let display_name_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("display_name is Utf8");
    assert_eq!(display_name_col.value(0), "Ada");

    let resolved = engine
        .execute(
            "SELECT persona_id FROM persona_identities \
             WHERE provider = 'slack' AND scope = 'team-1' AND external_id = 'U-1'",
            false,
        )
        .await
        .expect("resolve query");
    assert_eq!(
        resolved.batches[0].num_rows(),
        1,
        "the resolve-shape query matches exactly one identity"
    );
    let resolved_persona_id = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("persona_id is Utf8");
    assert_eq!(resolved_persona_id.value(0), "persona-idents-1");
}

/// Pins the module docs' "Payload redaction invariant" section: for a
/// [`QueryScope::Conversations`] session, `payload` and its
/// `payload_json` sibling (#1313) both fail to resolve from every
/// relation the catalog exposes, and neither exposed relation's own
/// schema names either field. Extends
/// [`conversations_scope_hides_raw_table_by_every_name`], which already
/// covers `events_raw`'s name being gone entirely; this test instead
/// proves the two relations that *do* stay resolvable (`events`,
/// `usage`) never carried either column to begin with.
/// [`conversations_scope_model_call_payload_column_is_unreachable`] pins
/// the same invariant for `model_call`, split into its own test rather
/// than grown onto this one (`clippy::too_many_lines`).
#[tokio::test]
async fn conversations_scope_payload_column_is_unreachable() {
    let committed_turn = Uuid::from_u128(17);
    let orphaned_turn = Uuid::from_u128(18);
    let partitions = one_partition("conv-redact", committed_turn, orphaned_turn);
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    // `payload`/`payload_json` are not columns of `events` or `usage`
    // for a non-Fleet scope, so selecting either fails to resolve — the
    // same fail-closed "unregistered/unresolvable" posture the module
    // docs commit to for out-of-scope tables, here applied to
    // out-of-scope columns.
    let events_payload = engine.execute("SELECT payload FROM events", false).await;
    assert!(
        matches!(events_payload, Err(QueryEngineError::DataFusion(_))),
        "`payload` must not resolve as a column of `events`: {events_payload:?}"
    );

    let usage_payload = engine.execute("SELECT payload FROM usage", false).await;
    assert!(
        matches!(usage_payload, Err(QueryEngineError::DataFusion(_))),
        "`payload` must not resolve as a column of `usage`: {usage_payload:?}"
    );

    let events_payload_json = engine
        .execute("SELECT payload_json FROM events", false)
        .await;
    assert!(
        matches!(events_payload_json, Err(QueryEngineError::DataFusion(_))),
        "`payload_json` must not resolve as a column of `events`: {events_payload_json:?}"
    );

    let usage_payload_json = engine
        .execute("SELECT payload_json FROM usage", false)
        .await;
    assert!(
        matches!(usage_payload_json, Err(QueryEngineError::DataFusion(_))),
        "`payload_json` must not resolve as a column of `usage`: {usage_payload_json:?}"
    );

    // Structural proof, not just a failed lookup: the schema of every
    // row this scope can actually read never names `payload` or
    // `payload_json` at all.
    let events_output = engine
        .execute("SELECT * FROM events", false)
        .await
        .expect("events view");
    let events_schema = events_output.batches[0].schema();
    let events_columns: Vec<&str> = events_schema
        .fields()
        .iter()
        .map(|f| f.name().as_str())
        .collect();
    assert_eq!(
        events_columns,
        vec!["partition", "position", "kind", "turn_id"],
        "events' schema for a non-Fleet scope must be exactly the committed-turns \
         projection, with no payload or payload_json column"
    );

    let usage_output = engine
        .execute("SELECT * FROM usage", false)
        .await
        .expect("usage table");
    let usage_schema = usage_output.batches[0].schema();
    let usage_columns: Vec<&str> = usage_schema
        .fields()
        .iter()
        .map(|f| f.name().as_str())
        .collect();
    assert_eq!(
        usage_columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "input_tokens",
            "output_tokens"
        ],
        "usage's schema for a non-Fleet scope carries its uniform keys but no \
         payload or payload_json column"
    );
}

/// [`conversations_scope_payload_column_is_unreachable`]'s same invariant,
/// pinned separately for `model_call` (kept as its own test rather than
/// grown onto that one, which already sits at `clippy::too_many_lines`'s
/// ceiling): `payload`/`payload_json` fail to resolve as columns of
/// `model_call` for a non-Fleet scope, and the table's own schema never
/// names either field.
#[tokio::test]
async fn conversations_scope_model_call_payload_column_is_unreachable() {
    let committed_turn = Uuid::from_u128(19);
    let orphaned_turn = Uuid::from_u128(20);
    let mut partitions = one_partition("conv-redact-mc", committed_turn, orphaned_turn);
    // A real, committed-turn-tagged row so `SELECT * FROM model_call` below
    // returns an actual `RecordBatch` to inspect — see
    // `conversations_scope_attribution_payload_column_is_unreachable`'s
    // identical comment for why a zero-row committed-turn-filtered view can
    // legitimately collect to zero batches.
    partitions[0].events.push((
        7,
        Event::new(
            kinds::tagged(kinds::MODEL_CALL, &committed_turn),
            ModelCallEvent {
                provider: "stub-provider".to_string(),
                model: "stub-model".to_string(),
                captured_clock_unix_ms: 1_700_000_000_000,
                ..Default::default()
            }
            .encode_to_vec(),
        ),
    ));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-redact-mc".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let payload = engine
        .execute("SELECT payload FROM model_call", false)
        .await;
    assert!(
        matches!(payload, Err(QueryEngineError::DataFusion(_))),
        "`payload` must not resolve as a column of `model_call`: {payload:?}"
    );

    let payload_json = engine
        .execute("SELECT payload_json FROM model_call", false)
        .await;
    assert!(
        matches!(payload_json, Err(QueryEngineError::DataFusion(_))),
        "`payload_json` must not resolve as a column of `model_call`: {payload_json:?}"
    );

    let output = engine
        .execute("SELECT * FROM model_call", false)
        .await
        .expect("model_call table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "provider",
            "model",
            "captured_clock_unix_ms",
        ],
        "model_call's schema for a non-Fleet scope carries its uniform keys but no \
         payload or payload_json column"
    );
}

/// [`conversations_scope_payload_column_is_unreachable`]'s same invariant,
/// pinned separately for `attribution` (kept as its own test rather than
/// grown onto that one, which already sits at `clippy::too_many_lines`'s
/// ceiling): `payload`/`payload_json` fail to resolve as columns of
/// `attribution` for a non-Fleet scope, and the table's own schema never
/// names either field.
#[tokio::test]
async fn conversations_scope_attribution_payload_column_is_unreachable() {
    let committed_turn = Uuid::from_u128(21);
    let orphaned_turn = Uuid::from_u128(22);
    let mut partitions = one_partition("conv-redact-attr", committed_turn, orphaned_turn);
    // A real, committed-turn-tagged row so `SELECT * FROM attribution` below
    // returns an actual `RecordBatch` to inspect — the committed-turn
    // semijoin `crate::views`'s module docs describe means a table with
    // zero committed rows can legitimately collect to zero batches, not one
    // empty batch, so this test's schema assertion needs real data behind
    // it (unlike before QRY-1's fix, when the redacted view had no such
    // filter and always returned exactly one batch).
    let caller = sample_attribution(
        "persona-payload-check",
        "initiator",
        sample_identity("slack", "team-payload", "U-PAYLOAD", "Payload Checker"),
    );
    partitions[0].events.push((
        7,
        Event::new(
            kinds::tagged(kinds::CALLER, &committed_turn),
            caller.encode_to_vec(),
        ),
    ));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-redact-attr".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let payload = engine
        .execute("SELECT payload FROM attribution", false)
        .await;
    assert!(
        matches!(payload, Err(QueryEngineError::DataFusion(_))),
        "`payload` must not resolve as a column of `attribution`: {payload:?}"
    );

    let payload_json = engine
        .execute("SELECT payload_json FROM attribution", false)
        .await;
    assert!(
        matches!(payload_json, Err(QueryEngineError::DataFusion(_))),
        "`payload_json` must not resolve as a column of `attribution`: {payload_json:?}"
    );

    let output = engine
        .execute("SELECT * FROM attribution", false)
        .await
        .expect("attribution table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec!["partition", "position", "turn_id", "persona_id", "role"],
        "attribution's schema for a non-Fleet scope carries its uniform keys and the \
         resolved persona_id/role, but no payload, payload_json, or identity_* column \
         (see conversations_scope_attribution_identity_columns_are_unreachable for the \
         identity_* redaction proof itself)"
    );
}

/// PR #1352's review finding, made airtight: a
/// [`QueryScope::Conversations`] session — the in-conversation agent's own
/// MCP tool — must never be able to read another participant's raw
/// external identity off `attribution`, even though it legitimately reads
/// that same row's RESOLVED `persona_id`/`role`.
///
/// Mirrors [`conversations_scope_payload_column_is_unreachable`]'s shape,
/// applied to `attribution`'s four flattened `identity_*` columns instead
/// of `payload`: each column individually fails to resolve (fail-closed,
/// same posture as an out-of-scope table failing to resolve — see the
/// engine module docs' "Identity redaction invariant" section), the
/// `SELECT *` schema for this scope names only the five redacted columns,
/// and — the part `payload`'s test doesn't need, since a `Conversations`
/// session has no legitimate `payload` fields at all — `persona_id`/`role`
/// still resolve and return the row's real values, proving the redaction
/// is scoped to the identity columns specifically, not the whole table.
#[tokio::test]
async fn conversations_scope_attribution_identity_columns_are_unreachable() {
    let turn = Uuid::from_u128(2_100);
    let identity = sample_identity("slack", "team-other", "U-OTHER", "Other Participant");
    let participant = sample_attribution("persona-other", "participant", identity);
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::PARTICIPANT, &turn),
                participant.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-identity-redact".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-identity-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    for column in [
        "identity_provider",
        "identity_scope",
        "identity_external_id",
        "identity_display_name",
    ] {
        let result = engine
            .execute(&format!("SELECT {column} FROM attribution"), false)
            .await;
        assert!(
            matches!(result, Err(QueryEngineError::DataFusion(_))),
            "`{column}` must not resolve as a column of `attribution` for a non-Fleet \
             scope — a conversation-scoped session must never read another \
             participant's raw external identity: {result:?}"
        );
    }

    let output = engine
        .execute("SELECT * FROM attribution", false)
        .await
        .expect("attribution table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec!["partition", "position", "turn_id", "persona_id", "role"],
        "a non-Fleet attribution schema must carry exactly the redacted column set, \
         never any identity_* column"
    );

    // The other half of the invariant: this scope keeps its legitimate,
    // already-resolved view of who attributed the turn — just not the raw
    // external identity behind it.
    let resolved = engine
        .execute("SELECT persona_id, role FROM attribution", false)
        .await
        .expect("persona_id/role must still resolve for a non-Fleet scope");
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let persona_id_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("persona_id is Utf8");
    let role_col = resolved.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("role is Utf8");
    assert_eq!(persona_id_col.value(0), "persona-other");
    assert_eq!(role_col.value(0), "participant");
}

#[tokio::test]
async fn conversations_scope_events_usage_model_call_attribution_and_turn_failed_still_work() {
    let committed_turn = Uuid::from_u128(5);
    let orphaned_turn = Uuid::from_u128(6);
    let failed_turn = Uuid::from_u128(7);
    let mut events = fixture_events(committed_turn, orphaned_turn);
    events.push((
        7,
        Event::new(kinds::tagged(kinds::TURN_START, &failed_turn), Vec::new()),
    ));
    events.push((
        8,
        Event::new(
            kinds::tagged(kinds::TURN_FAILED, &failed_turn),
            TurnFailedEvent {
                kind: TurnFailureKind::RateLimit.into(),
                message: "provider throttled the request".to_string(),
                __buffa_unknown_fields: buffa::UnknownFields::default(),
            }
            .encode_to_vec(),
        ),
    ));
    // Real emission always lands `turn_complete` unconditionally in the same
    // atomic batch as `turn_failed` (`crates/control-plane/src/grpc/mod.rs`)
    // — this fixture matches that so `failed_turn` is committed and its
    // `turn_failed` row is visible through the committed-turn filter, not
    // hidden as an orphaned/uncommitted row would be.
    events.push((
        9,
        Event::new(
            kinds::tagged(kinds::TURN_COMPLETE, &failed_turn),
            Vec::new(),
        ),
    ));
    let partitions = vec![PartitionEvents {
        partition: "conv-c".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-c".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let events = engine
        .execute("SELECT COUNT(*) AS c FROM events", false)
        .await
        .expect("events view");
    assert_eq!(
        single_count(&events),
        7,
        "the committed turn's four rows plus the now-committed failed turn's three \
         (turn_start, turn_failed, turn_complete)"
    );

    let usage = engine
        .execute("SELECT COUNT(*) AS c FROM usage", false)
        .await
        .expect("usage table");
    assert_eq!(single_count(&usage), 1);

    // `fixture_events` carries no `model_call`/attribution event, so these
    // only prove the tables resolve (and return zero rows) for a non-Fleet
    // scope — the same "registered for every scope" claim the module docs
    // make for `usage`, exercised here for `model_call`/`attribution` too.
    // Their rows actually being queryable/joinable is covered by
    // `model_call_rows_are_queryable_and_join_to_their_conversation` and
    // `attribution_rows_are_queryable_and_join_to_their_conversation`
    // below.
    let model_call = engine
        .execute("SELECT COUNT(*) AS c FROM model_call", false)
        .await
        .expect("model_call table");
    assert_eq!(
        single_count(&model_call),
        0,
        "the fixture carries no model_call events"
    );

    let attribution = engine
        .execute("SELECT COUNT(*) AS c FROM attribution", false)
        .await
        .expect("attribution table");
    assert_eq!(
        single_count(&attribution),
        0,
        "the fixture carries no caller/participant events"
    );

    // `turn_failed` must resolve (and return its seeded row) under
    // Conversations scope too — the fixture above adds a real failed turn
    // to the partition specifically to exercise this, unlike
    // usage/model_call/attribution which only prove the empty-table case
    // above. Guards against a future refactor accidentally scoping
    // `turn_failed` to Fleet-only (it's asserted end to end for Fleet by
    // `turn_failed_rows_are_queryable_and_join_to_their_conversation`).
    let turn_failed = engine
        .execute("SELECT failure_kind, message FROM turn_failed", false)
        .await
        .expect("turn_failed table");
    assert_eq!(turn_failed.batches[0].num_rows(), 1);
    let failure_kind_col = turn_failed.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("failure_kind is Utf8");
    let message_col = turn_failed.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("message is Utf8");
    assert_eq!(failure_kind_col.value(0), "rate_limit");
    assert_eq!(message_col.value(0), "provider throttled the request");
}

/// QRY-1's own regression proof: under [`QueryScope::Conversations`], an
/// UNCOMMITTED (orphaned — `turn_start` with no `turn_complete`) turn's
/// `usage`/`payments`/`tool_calls`/`approvals`/`turn_failed` rows are HIDDEN,
/// exactly like `events` already hides that turn's wide rows — the asymmetry
/// [`conversations_scope_events_usage_model_call_attribution_and_turn_failed_still_work`]
/// only proved existed for `events` before this fix. A SIBLING committed
/// turn's rows on the SAME typed tables stay visible (the fix is a filter,
/// not a blanket hide) — `turn_failed` included, since a normally-failed
/// turn carries `turn_complete` in the same atomic batch as `turn_failed`
/// (`crates/control-plane/src/grpc/mod.rs`) and so is committed exactly like
/// any other turn; a prior review pass wrongly carved `turn_failed` out as
/// permanently exempt from this filter, and this test's `committed_turn`/
/// `orphaned_turn` each now also carry a `turn_failed` event to pin the
/// corrected behavior: visible for the committed turn, hidden for the
/// orphaned one. Before QRY-1's fix, every uncommitted-turn assertion below
/// failed (the row was visible); this test pins the fixed behavior going
/// forward.
// Deliberately long: one cohesive fixture (committed + orphaned turn, five
// typed tables each) is what proves the filter together — splitting it
// would scatter one regression proof across several tests that all need the
// same fixture, mirroring `approvals`'/`handoffs`'/`grant_replays`' own
// precedent.
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn conversations_scope_hides_uncommitted_turn_usage_payments_tool_calls_approvals_and_turn_failed()
 {
    let committed_turn = Uuid::from_u128(9_001);
    let orphaned_turn = Uuid::from_u128(9_002);
    let signer = ApprovalSigner::from_seed(9_004);

    let committed_receipt =
        signed_payment_receipt(&signer, kinds::PAYMENT_RECEIPT, "call-committed");
    let orphaned_receipt = signed_payment_receipt(&signer, kinds::PAYMENT_RECEIPT, "call-orphaned");
    let committed_approval_request = polyc_crypto::approval::request_payload(
        "call-committed",
        "rm",
        r#"{"path":"/tmp/committed"}"#,
        "default",
        "",
        &[],
        "",
        "",
        "",
        &[],
        false,
    );
    let committed_approval_response = signed_approval_response(
        &signer,
        "call-committed",
        "rm",
        r#"{"path":"/tmp/committed"}"#,
        "caller-1",
        "ok",
        "conv-uncommitted-hidden",
        "nonce-committed",
    );
    let orphaned_approval_request = polyc_crypto::approval::request_payload(
        "call-orphaned",
        "rm",
        r#"{"path":"/tmp/orphaned"}"#,
        "default",
        "",
        &[],
        "",
        "",
        "",
        &[],
        false,
    );
    let orphaned_approval_response = signed_approval_response(
        &signer,
        "call-orphaned",
        "rm",
        r#"{"path":"/tmp/orphaned"}"#,
        "caller-1",
        "ok",
        "conv-uncommitted-hidden",
        "nonce-orphaned",
    );
    let committed_call = wire_tool_call_message("call-committed", "search", r#"{"q":"a"}"#);
    let orphaned_call = wire_tool_call_message("call-orphaned", "search", r#"{"q":"b"}"#);

    let events = vec![
        // Committed turn: usage, payment, approval request/response, tool
        // call, wrapped in turn_start/turn_complete.
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::USAGE, &committed_turn),
                UsageEvent {
                    input_tokens: 5,
                    output_tokens: 6,
                    ..Default::default()
                }
                .encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::PAYMENT_RECEIPT, &committed_turn),
                committed_receipt,
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::APPROVAL_REQUEST, &committed_turn),
                committed_approval_request,
            ),
        ),
        (
            4,
            Event::new(
                kinds::tagged(kinds::APPROVAL_RESPONSE, &committed_turn),
                committed_approval_response,
            ),
        ),
        (
            5,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &committed_turn),
                committed_call.encode_to_vec(),
            ),
        ),
        // A real emission always lands `turn_failed` immediately before
        // `turn_complete`, in the same atomic batch
        // (`crates/control-plane/src/grpc/mod.rs`) — so a normally-failed
        // turn is committed too, and its `turn_failed` row must stay
        // visible through the filter below.
        (
            6,
            Event::new(
                kinds::tagged(kinds::TURN_FAILED, &committed_turn),
                TurnFailedEvent {
                    kind: TurnFailureKind::RateLimit.into(),
                    message: "provider throttled the request".to_string(),
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
        (
            7,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
        // Orphaned turn: the identical shape, no turn_complete.
        (
            8,
            Event::new(kinds::tagged(kinds::TURN_START, &orphaned_turn), Vec::new()),
        ),
        (
            9,
            Event::new(
                kinds::tagged(kinds::USAGE, &orphaned_turn),
                UsageEvent {
                    input_tokens: 100,
                    output_tokens: 200,
                    ..Default::default()
                }
                .encode_to_vec(),
            ),
        ),
        (
            10,
            Event::new(
                kinds::tagged(kinds::PAYMENT_RECEIPT, &orphaned_turn),
                orphaned_receipt,
            ),
        ),
        (
            11,
            Event::new(
                kinds::tagged(kinds::APPROVAL_REQUEST, &orphaned_turn),
                orphaned_approval_request,
            ),
        ),
        (
            12,
            Event::new(
                kinds::tagged(kinds::APPROVAL_RESPONSE, &orphaned_turn),
                orphaned_approval_response,
            ),
        ),
        (
            13,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &orphaned_turn),
                orphaned_call.encode_to_vec(),
            ),
        ),
        // The orphaned turn also fails — no `turn_complete` follows (it
        // never lands, that's what "orphaned" means here), so this
        // `turn_failed` row must be hidden too, not just its
        // usage/payment/approval/tool_call siblings.
        (
            14,
            Event::new(
                kinds::tagged(kinds::TURN_FAILED, &orphaned_turn),
                TurnFailedEvent {
                    kind: TurnFailureKind::Timeout.into(),
                    message: "deadline exceeded before the turn could complete".to_string(),
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-uncommitted-hidden".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-uncommitted-hidden".to_string()]),
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    // The committed turn's rows are visible on every typed table.
    let usage = engine
        .execute(
            &format!("SELECT COUNT(*) AS c FROM usage WHERE turn_id = '{committed_turn}'"),
            false,
        )
        .await
        .expect("usage committed query");
    assert_eq!(
        single_count(&usage),
        1,
        "the committed turn's usage row is visible"
    );

    let payments = engine
        .execute(
            "SELECT COUNT(*) AS c FROM payments WHERE tool_call_id = 'call-committed'",
            false,
        )
        .await
        .expect("payments committed query");
    assert_eq!(
        single_count(&payments),
        1,
        "the committed turn's payment row is visible"
    );

    let approvals = engine
        .execute(
            "SELECT COUNT(*) AS c FROM approvals WHERE request_id = 'call-committed'",
            false,
        )
        .await
        .expect("approvals committed query");
    assert_eq!(
        single_count(&approvals),
        2,
        "the committed turn's request/response rows are both visible"
    );

    let tool_calls = engine
        .execute(
            "SELECT COUNT(*) AS c FROM tool_calls WHERE tool_call_id = 'call-committed'",
            false,
        )
        .await
        .expect("tool_calls committed query");
    assert_eq!(
        single_count(&tool_calls),
        1,
        "the committed turn's tool call row is visible"
    );

    let turn_failed_committed = engine
        .execute(
            &format!("SELECT COUNT(*) AS c FROM turn_failed WHERE turn_id = '{committed_turn}'"),
            false,
        )
        .await
        .expect("turn_failed committed query");
    assert_eq!(
        single_count(&turn_failed_committed),
        1,
        "the committed turn's turn_failed row is visible — turn_complete lands in the same \
         atomic batch as turn_failed, so this turn is committed like any other"
    );

    // The orphaned (uncommitted) turn's rows are hidden on every typed
    // table — the QRY-1 fix itself.
    let orphaned_usage = engine
        .execute(
            &format!("SELECT COUNT(*) AS c FROM usage WHERE turn_id = '{orphaned_turn}'"),
            false,
        )
        .await
        .expect("usage orphaned query");
    assert_eq!(
        single_count(&orphaned_usage),
        0,
        "the orphaned turn's usage row must be hidden"
    );

    let orphaned_payments = engine
        .execute(
            "SELECT COUNT(*) AS c FROM payments WHERE tool_call_id = 'call-orphaned'",
            false,
        )
        .await
        .expect("payments orphaned query");
    assert_eq!(
        single_count(&orphaned_payments),
        0,
        "the orphaned turn's payment row must be hidden"
    );

    let orphaned_approvals = engine
        .execute(
            "SELECT COUNT(*) AS c FROM approvals WHERE request_id = 'call-orphaned'",
            false,
        )
        .await
        .expect("approvals orphaned query");
    assert_eq!(
        single_count(&orphaned_approvals),
        0,
        "the orphaned turn's request/response rows must both be hidden"
    );

    let orphaned_tool_calls = engine
        .execute(
            "SELECT COUNT(*) AS c FROM tool_calls WHERE tool_call_id = 'call-orphaned'",
            false,
        )
        .await
        .expect("tool_calls orphaned query");
    assert_eq!(
        single_count(&orphaned_tool_calls),
        0,
        "the orphaned turn's tool call row must be hidden"
    );

    let orphaned_turn_failed = engine
        .execute(
            &format!("SELECT COUNT(*) AS c FROM turn_failed WHERE turn_id = '{orphaned_turn}'"),
            false,
        )
        .await
        .expect("turn_failed orphaned query");
    assert_eq!(
        single_count(&orphaned_turn_failed),
        0,
        "the orphaned turn's turn_failed row must be hidden too — no turn_complete ever \
         landed for it, so it is exactly as uncommitted as its usage/payment/approval/ \
         tool_call siblings"
    );
}

#[tokio::test]
async fn usage_sum_matches_encoded_usage_events() {
    let committed_turn = Uuid::from_u128(150);
    let partitions = vec![PartitionEvents {
        partition: "conv-usage".to_string(),
        events: vec![
            (
                0,
                Event::new(
                    kinds::tagged(kinds::TURN_START, &committed_turn),
                    Vec::new(),
                ),
            ),
            (
                1,
                Event::new(
                    kinds::tagged(kinds::USAGE, &committed_turn),
                    UsageEvent {
                        input_tokens: 10,
                        output_tokens: 3,
                        ..Default::default()
                    }
                    .encode_to_vec(),
                ),
            ),
            (
                2,
                Event::new(
                    kinds::tagged(kinds::USAGE, &committed_turn),
                    UsageEvent {
                        input_tokens: 40,
                        output_tokens: 7,
                        ..Default::default()
                    }
                    .encode_to_vec(),
                ),
            ),
            (
                3,
                Event::new(
                    kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                    Vec::new(),
                ),
            ),
        ],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT SUM(input_tokens) AS i, SUM(output_tokens) AS o FROM usage",
            false,
        )
        .await
        .expect("sum query");
    let batch = &output.batches[0];
    let input_sum = batch
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::UInt64Array>()
        .expect("UInt64 sum");
    let output_sum = batch
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::UInt64Array>()
        .expect("UInt64 sum");
    assert_eq!(input_sum.value(0), 50);
    assert_eq!(output_sum.value(0), 10);
}

/// #1311's second typed table end to end: a real buffa-encoded
/// `ModelCallEvent`, appended alongside a committed turn, surfaces as one
/// `model_call` row and joins back to the conversation it belongs to via
/// `model_call.partition = events.partition` — the same join shape
/// [`fleet_scope_reference_tables_return_rows_and_participation_joins_to_its_conversation`]
/// exercises for the reference tables. Asserts a typed field
/// (`provider`) survives the join, not just the row count.
#[tokio::test]
async fn model_call_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(200);
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::MODEL_CALL, &committed_turn),
                ModelCallEvent {
                    provider: "stub-provider".to_string(),
                    model: "stub-model".to_string(),
                    decode_params: buffa::MessageField::default(),
                    system_config_ref: String::new(),
                    captured_clock_unix_ms: 1_700_000_000_000,
                    clear_trigger_bytes: 0,
                    clear_keep_recent: 0,
                    clear_marker: String::new(),
                    persona_block_placement: 0,
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-model-call".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM model_call", false)
        .await
        .expect("model_call count query");
    assert_eq!(single_count(&count), 1);

    let joined = engine
        .execute(
            "SELECT DISTINCT mc.provider FROM model_call mc \
             JOIN events e ON e.partition = mc.partition \
             WHERE mc.partition = 'conv-model-call'",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches the one model_call row's provider exactly once"
    );
    let provider_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("provider is Utf8");
    assert_eq!(provider_col.value(0), "stub-provider");
}

/// #1311's fourth typed table end to end: a real buffa-encoded
/// `TurnFailedEvent`, appended alongside a COMMITTED turn (`turn_start` +
/// `turn_failed` + `turn_complete`, matching the control plane's real
/// emission order — `crates/control-plane/src/grpc/mod.rs` pushes
/// `turn_complete` unconditionally in the same atomic batch immediately
/// after `turn_failed`), surfaces as one `turn_failed` row and joins back to
/// the conversation it belongs to via `turn_failed.partition =
/// events_raw.partition` — the same join shape
/// [`model_call_rows_are_queryable_and_join_to_their_conversation`]
/// exercises for `model_call`. Asserts `failure_kind`/`message` survive the
/// join, not just the row count.
#[tokio::test]
async fn turn_failed_rows_are_queryable_and_join_to_their_conversation() {
    let failed_turn = Uuid::from_u128(300);
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &failed_turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::TURN_FAILED, &failed_turn),
                TurnFailedEvent {
                    kind: TurnFailureKind::RateLimit.into(),
                    message: "provider throttled the request".to_string(),
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &failed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-turn-failed".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM turn_failed", false)
        .await
        .expect("turn_failed count query");
    assert_eq!(single_count(&count), 1);

    let joined = engine
        .execute(
            "SELECT DISTINCT tf.failure_kind, tf.message FROM turn_failed tf \
             JOIN events_raw e ON e.partition = tf.partition \
             WHERE tf.partition = 'conv-turn-failed'",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches the one turn_failed row's failure_kind/message exactly once"
    );
    let failure_kind_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("failure_kind is Utf8");
    let message_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("message is Utf8");
    assert_eq!(failure_kind_col.value(0), "rate_limit");
    assert_eq!(message_col.value(0), "provider throttled the request");
}

/// The tenth typed table end to end: a real buffa-encoded `SummaryEvent`,
/// appended alongside a committed turn, surfaces as one `summary` row and
/// joins back to the conversation it belongs to via `summary.partition =
/// events_raw.partition` — the same join shape
/// [`turn_failed_rows_are_queryable_and_join_to_their_conversation`]
/// exercises for `turn_failed`. Asserts `text`/`covers_through_position`
/// survive the join, not just the row count, and that the summary's own
/// tagged `turn_id` is the synthetic uuid it was tagged with — never a real
/// turn's id (see `crate::decode::summary`'s module docs).
#[tokio::test]
async fn summary_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(400);
    let summary_id = Uuid::from_u128(401);
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::SUMMARY, &summary_id),
                SummaryEvent {
                    text: "the older prefix, condensed".to_string(),
                    covers_through_position: 2,
                    ..Default::default()
                }
                .encode_to_vec(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-summary".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM summary", false)
        .await
        .expect("summary count query");
    assert_eq!(single_count(&count), 1);

    let joined = engine
        .execute(
            "SELECT DISTINCT s.text, s.covers_through_position, s.turn_id \
             FROM summary s \
             JOIN events_raw e ON e.partition = s.partition \
             WHERE s.partition = 'conv-summary'",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches the one summary row's text/covers_through_position exactly once"
    );
    let text_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("text is Utf8");
    let covers_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::UInt64Array>()
        .expect("covers_through_position is UInt64");
    let turn_id_col = joined.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("turn_id is Utf8");
    assert_eq!(text_col.value(0), "the older prefix, condensed");
    assert_eq!(covers_col.value(0), 2);
    assert_eq!(
        turn_id_col.value(0),
        summary_id.to_string(),
        "summary.turn_id is the summary's OWN synthetic tag, not the committed turn's id"
    );
}

/// QRY-1's Fleet-only gate on `summary`, pinned end to end: a
/// [`QueryScope::Conversations`] session must never see summary content at
/// all — `summary` fails to resolve under any qualification, the same
/// "never even registered" posture
/// [`conversations_scope_hides_reference_tables`] pins for
/// `personas`/`participations`/`persona_identities`, not the
/// "resolvable but redacted" posture every other typed table uses. Mirrors
/// [`summary_rows_are_queryable_and_join_to_their_conversation`]'s Fleet-side
/// proof that the identical partition DOES resolve for
/// [`QueryScope::Fleet`].
#[tokio::test]
async fn conversations_scope_hides_summary_rows() {
    let summary_id = Uuid::from_u128(410);
    let events = vec![(
        0,
        Event::new(
            kinds::tagged(kinds::SUMMARY, &summary_id),
            SummaryEvent {
                text: "fleet-only content".to_string(),
                covers_through_position: 9,
                ..Default::default()
            }
            .encode_to_vec(),
        ),
    )];

    let conversations_engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-summary-hidden".to_string()]),
        vec![PartitionEvents {
            partition: "conv-summary-hidden".to_string(),
            events,
        }],
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build conversations engine");

    let unqualified = conversations_engine
        .execute("SELECT * FROM summary", false)
        .await;
    assert!(
        matches!(unqualified, Err(QueryEngineError::DataFusion(_))),
        "summary must not resolve for a non-Fleet scope: {unqualified:?}"
    );

    let qualified = conversations_engine
        .execute("SELECT * FROM datafusion.public.summary", false)
        .await;
    assert!(
        matches!(qualified, Err(QueryEngineError::DataFusion(_))),
        "a fully-qualified name must not reach summary either: {qualified:?}"
    );

    let raw_unqualified = conversations_engine
        .execute("SELECT * FROM summary_raw", false)
        .await;
    assert!(
        matches!(raw_unqualified, Err(QueryEngineError::DataFusion(_))),
        "summary_raw must not resolve for a non-Fleet scope either: {raw_unqualified:?}"
    );
}

/// "Which turns failed with kind X" — the forensics query `turn_failed`
/// exists for (see `crate::decode::turn_failed`'s module docs): filtering
/// `WHERE failure_kind = ...` returns exactly the rows of that kind, and no
/// others, across a partition carrying more than one failure kind. Every
/// turn here is wrapped `turn_start`/`turn_failed`/`turn_complete` — a
/// COMMITTED failed turn, matching real emission
/// (`crates/control-plane/src/grpc/mod.rs`) — so the committed-turn filter
/// `turn_failed`'s view now carries does not hide any of them.
// Deliberately long: wrapping each of the three turns in its own
// turn_start/turn_complete pair (needed since turn_failed is now
// committed-turn filtered) triples the fixture's line count without adding
// any real complexity.
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn turn_failed_filter_by_failure_kind() {
    let turn_a = Uuid::from_u128(301);
    let turn_b = Uuid::from_u128(302);
    let turn_c = Uuid::from_u128(303);
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn_a), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::TURN_FAILED, &turn_a),
                TurnFailedEvent {
                    kind: TurnFailureKind::Timeout.into(),
                    message: "deadline exceeded".to_string(),
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn_a), Vec::new()),
        ),
        (
            3,
            Event::new(kinds::tagged(kinds::TURN_START, &turn_b), Vec::new()),
        ),
        (
            4,
            Event::new(
                kinds::tagged(kinds::TURN_FAILED, &turn_b),
                TurnFailedEvent {
                    kind: TurnFailureKind::Timeout.into(),
                    message: "second deadline exceeded".to_string(),
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
        (
            5,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn_b), Vec::new()),
        ),
        (
            6,
            Event::new(kinds::tagged(kinds::TURN_START, &turn_c), Vec::new()),
        ),
        (
            7,
            Event::new(
                kinds::tagged(kinds::TURN_FAILED, &turn_c),
                TurnFailedEvent {
                    kind: TurnFailureKind::Auth.into(),
                    message: "credential rejected".to_string(),
                    __buffa_unknown_fields: buffa::UnknownFields::default(),
                }
                .encode_to_vec(),
            ),
        ),
        (
            8,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn_c), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-turn-failed-filter".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let timeouts = engine
        .execute(
            "SELECT turn_id, message FROM turn_failed \
             WHERE failure_kind = 'timeout' ORDER BY turn_id",
            false,
        )
        .await
        .expect("failure_kind filter query");
    assert_eq!(
        timeouts.batches[0].num_rows(),
        2,
        "exactly the two timeout rows, not the auth row"
    );
    let message_col = timeouts.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("message is Utf8");
    let messages: Vec<&str> = (0..2).map(|i| message_col.value(i)).collect();
    assert!(messages.contains(&"deadline exceeded"));
    assert!(messages.contains(&"second deadline exceeded"));

    let auths = engine
        .execute(
            "SELECT COUNT(*) AS c FROM turn_failed WHERE failure_kind = 'auth'",
            false,
        )
        .await
        .expect("auth filter query");
    assert_eq!(single_count(&auths), 1);
}

/// A flat, fully-named [`ExternalIdentity`] fixture — every field explicit
/// rather than a `..Default::default()` spread, shared by every attribution
/// test below rather than each one hand-building the struct.
fn sample_identity(
    provider: &str,
    scope: &str,
    external_id: &str,
    display_name: &str,
) -> ExternalIdentity {
    ExternalIdentity {
        provider: provider.to_string(),
        scope: scope.to_string(),
        external_id: external_id.to_string(),
        display_name: display_name.to_string(),
        time_zone: String::new(),
        __buffa_unknown_fields: buffa::UnknownFields::default(),
    }
}

/// A fully-named [`AttributionEvent`] fixture pairing `persona_id`/`role`
/// with a [`sample_identity`]-shaped `identity`.
fn sample_attribution(
    persona_id: &str,
    role: &str,
    identity: ExternalIdentity,
) -> AttributionEvent {
    AttributionEvent {
        persona_id: persona_id.to_string(),
        identity: buffa::MessageField::some(identity),
        role: role.to_string(),
        asserting_edge_id: String::new(),
        signer_pk_hex: String::new(),
        signature_hex: String::new(),
        __buffa_unknown_fields: buffa::UnknownFields::default(),
    }
}

/// #1311's third typed table end to end: real buffa-encoded
/// `AttributionEvent`s under both source kinds (`caller` and
/// `participant`), appended alongside a committed turn, surface as two
/// `attribution` rows and join back to the conversation they belong to via
/// `attribution.partition = events.partition` — the same join shape
/// [`model_call_rows_are_queryable_and_join_to_their_conversation`]
/// exercises for `model_call`. Asserts the flattened `identity_*` columns
/// and each row's own `role` survive the join, not just the row count.
#[tokio::test]
async fn attribution_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(210);
    let caller = sample_attribution(
        "persona-ada",
        "initiator",
        sample_identity("slack", "team-caller", "U-CALLER", "Ada"),
    );
    let participant = sample_attribution(
        "persona-bob",
        "participant",
        sample_identity("telegram", "", "T-PARTICIPANT", "Bob"),
    );
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::CALLER, &committed_turn),
                caller.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::PARTICIPANT, &committed_turn),
                participant.encode_to_vec(),
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-attribution".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM attribution", false)
        .await
        .expect("attribution count query");
    assert_eq!(single_count(&count), 2, "both caller and participant rows");

    let joined = engine
        .execute(
            "SELECT a.role, a.identity_provider, a.identity_external_id \
             FROM attribution a \
             JOIN events e ON e.partition = a.partition \
             WHERE a.partition = 'conv-attribution' \
             GROUP BY a.role, a.identity_provider, a.identity_external_id \
             ORDER BY a.role",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        2,
        "the join matches both attribution rows exactly once each"
    );
    let role_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("role is Utf8");
    let provider_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("identity_provider is Utf8");
    let external_id_col = joined.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("identity_external_id is Utf8");
    assert_eq!(role_col.value(0), "initiator");
    assert_eq!(provider_col.value(0), "slack");
    assert_eq!(external_id_col.value(0), "U-CALLER");
    assert_eq!(role_col.value(1), "participant");
    assert_eq!(provider_col.value(1), "telegram");
    assert_eq!(external_id_col.value(1), "T-PARTICIPANT");
}

/// The Fleet-side half of PR #1352's redaction fix, split into its own test
/// rather than grown onto
/// [`attribution_rows_are_queryable_and_join_to_their_conversation`] (which
/// already sits at `clippy::too_many_lines`'s ceiling): unlike a
/// `Conversations` session (see
/// [`conversations_scope_attribution_identity_columns_are_unreachable`]), a
/// [`QueryScope::Fleet`] session's `attribution` still carries every
/// `identity_*` column, full stop — the redaction is scope-dependent, not a
/// regression that also strips Fleet's own maintainer visibility.
#[tokio::test]
async fn fleet_scope_attribution_returns_full_identity_columns() {
    let committed_turn = Uuid::from_u128(212);
    let caller = sample_attribution(
        "persona-ada",
        "initiator",
        sample_identity("slack", "team-caller", "U-CALLER", "Ada"),
    );
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::CALLER, &committed_turn),
                caller.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-attribution-fleet".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let full = engine
        .execute(
            "SELECT identity_scope, identity_display_name FROM attribution \
             WHERE persona_id = 'persona-ada'",
            false,
        )
        .await
        .expect("identity_scope/identity_display_name must resolve for Fleet");
    assert_eq!(full.batches[0].num_rows(), 1);
    let scope_col = full.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("identity_scope is Utf8");
    let display_name_col = full.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("identity_display_name is Utf8");
    assert_eq!(scope_col.value(0), "team-caller");
    assert_eq!(display_name_col.value(0), "Ada");

    let star_output = engine
        .execute("SELECT * FROM attribution", false)
        .await
        .expect("attribution table");
    let star_schema = star_output.batches[0].schema();
    let star_columns: Vec<&str> = star_schema
        .fields()
        .iter()
        .map(|f| f.name().as_str())
        .collect();
    assert_eq!(
        star_columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "persona_id",
            "role",
            "identity_provider",
            "identity_scope",
            "identity_external_id",
            "identity_display_name",
        ],
        "a Fleet session's attribution schema must carry every identity_* column"
    );
}

/// `attribution.persona_id` joins to the `personas` reference table
/// (#1312, this crate's first non-journal data source) exactly the way
/// [`fleet_scope_reference_tables_return_rows_and_participation_joins_to_its_conversation`]
/// already proves `participations.persona_id` does — proving the fact
/// model's typed event tables and the persona directory's reference tables
/// share one join key, not two independently-spelled ids.
#[tokio::test]
async fn attribution_persona_id_joins_to_personas_reference_table() {
    let committed_turn = Uuid::from_u128(211);
    let caller = sample_attribution(
        "persona-join-1",
        "initiator",
        sample_identity("slack", "team-1", "U-JOIN", "Ada"),
    );
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::CALLER, &committed_turn),
                caller.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-attr-join".to_string(),
        events,
    }];

    let profile = PersonaProfile {
        persona_id: "persona-join-1".to_string(),
        display_name: "Ada".to_string(),
        created_at_ms: 3_000,
        status: "linked".to_string(),
        ..Default::default()
    };
    let reference = ReferenceData {
        personas: vec![profile],
        participations: Vec::new(),
        ..ReferenceData::empty()
    };

    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let joined = engine
        .execute(
            "SELECT p.display_name FROM attribution a \
             JOIN personas p ON p.persona_id = a.persona_id \
             WHERE a.partition = 'conv-attr-join'",
            false,
        )
        .await
        .expect("persona join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches the one attribution row's persona exactly once"
    );
    let display_name_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("display_name is Utf8");
    assert_eq!(display_name_col.value(0), "Ada");
}

/// A fully-named, real-signed v2 `payment_receipt`/`outbound_payment_receipt`
/// payload — mirrors `crate::decode::payments`'s own test fixture shape
/// (named fields, no `..Default::default()` spread, since `ReceiptPayload`
/// has no default).
fn signed_payment_receipt(
    signer: &ApprovalSigner,
    kind: &'static str,
    tool_call_id: &str,
) -> Vec<u8> {
    let (payload, sig, pk) = receipt_payload(
        &ReceiptPayload {
            kind,
            reference: "tx-engine-1",
            amount: "2.75",
            currency: "USDC",
            recipient: "0xengine-recipient",
            method: "tempo",
            timestamp: "2026-07-21T00:00:00Z",
            tool_call_id,
            approval_pos: "1",
            approved_args_hash: "hash-engine",
            subject: "persona-payer",
            payer_kind: "linked_wallet",
            paying_account: "0xengine-payer",
        },
        signer,
    );
    let _ = (sig, pk);
    payload
}

/// A fully-named, real-signed `payment_refusal` payload — the `refusals`
/// engine tests' sibling of [`signed_payment_receipt`].
fn signed_refusal(signer: &ApprovalSigner, tool_call_id: &str) -> Vec<u8> {
    let (payload, sig, pk) = refusal_payload(
        &RefusalPayload {
            kind: kinds::PAYMENT_REFUSAL,
            reason: "over_spend_cap",
            reason_detail: "payment of 500 base units exceeds the cap of 100",
            merchant_host: "merchant.example",
            requested_base_units: "500",
            permitted_base_units: "100",
            tool_call_id,
            subject: "persona-payer",
            timestamp: "1780000000",
        },
        signer,
    );
    let _ = (sig, pk);
    payload
}

/// The CRITICAL redaction-bypass regression this pins (`#2090` review): a
/// [`QueryScope::Conversations`] session — the in-conversation agent's own
/// MCP tool — must never be able to read the raw `signer_public_key` off
/// `refusals`, even reaching straight for `refusals_raw` (the bypass a
/// missing `ctx.deregister_table(REFUSALS_RAW_TABLE)` call left open).
/// Mirrors [`conversations_scope_payments_signer_public_key_is_unreachable`]'s
/// shape exactly.
#[tokio::test]
async fn conversations_scope_refusals_signer_public_key_is_unreachable() {
    let turn = Uuid::from_u128(602);
    let signer = ApprovalSigner::from_seed(204);
    let bytes = signed_refusal(&signer, "call-redact");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::PAYMENT_REFUSAL, &turn), bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-refusals-redact".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-refusals-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT signer_public_key FROM refusals", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "`signer_public_key` must not resolve as a column of `refusals` for a \
         non-Fleet scope: {result:?}"
    );

    // The bypass this test exists to close: reaching straight for the raw
    // table, around the view's redaction entirely.
    let raw_result = engine.execute("SELECT * FROM refusals_raw", false).await;
    assert!(
        matches!(raw_result, Err(QueryEngineError::DataFusion(_))),
        "`refusals_raw` must not resolve at all for a non-Fleet scope: {raw_result:?}"
    );

    let output = engine
        .execute("SELECT * FROM refusals", false)
        .await
        .expect("refusals table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "reason",
            "reason_detail",
            "merchant_host",
            "requested_base_units",
            "permitted_base_units",
            "tool_call_id",
            "subject",
            "timestamp",
        ],
        "a non-Fleet refusals schema must carry every column except signer_public_key"
    );

    let resolved = engine
        .execute(
            "SELECT reason, requested_base_units, subject FROM refusals WHERE tool_call_id = 'call-redact'",
            false,
        )
        .await
        .expect("reason/requested_base_units/subject must still resolve for a non-Fleet scope");
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let reason_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("reason is Utf8");
    let requested_col = resolved.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("requested_base_units is Utf8");
    let subject_col = resolved.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("subject is Utf8");
    assert_eq!(reason_col.value(0), "over_spend_cap");
    assert_eq!(requested_col.value(0), "500");
    assert_eq!(subject_col.value(0), "persona-payer");
}

/// The Fleet-side half of the refusals redaction rule: unlike a
/// `Conversations` session (see
/// [`conversations_scope_refusals_signer_public_key_is_unreachable`]), a
/// [`QueryScope::Fleet`] session's `refusals` still carries
/// `signer_public_key`, full stop.
#[tokio::test]
async fn fleet_scope_refusals_returns_signer_public_key() {
    let turn = Uuid::from_u128(603);
    let signer = ApprovalSigner::from_seed(205);
    let bytes = signed_refusal(&signer, "call-fleet");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::PAYMENT_REFUSAL, &turn), bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-refusals-fleet".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT signer_public_key FROM refusals WHERE tool_call_id = 'call-fleet'",
            false,
        )
        .await
        .expect("signer_public_key must resolve for Fleet");
    assert_eq!(output.batches[0].num_rows(), 1);
    let signer_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BinaryArray>()
        .expect("signer_public_key is Binary");
    assert_eq!(signer_col.value(0), signer.public_key_bytes());
}

/// A fully-named, real-signed `wallet_link_lifecycle` payload (`#2123`) —
/// the `wallet_link_lifecycle` engine tests' sibling of [`signed_refusal`].
fn signed_wallet_link_lifecycle_event(signer: &ApprovalSigner, conversation_id: &str) -> Vec<u8> {
    let (payload, sig, pk) = wallet_link_lifecycle_payload(
        &WalletLinkLifecyclePayload {
            kind: kinds::WALLET_LINK_LIFECYCLE,
            transition: "linked",
            subject: "persona-payer",
            wallet_address: "0x1111111111111111111111111111111111111111",
            currency: "0x2222222222222222222222222222222222222222",
            chain_id: "42431",
            limit_base_units: "5000000",
            limit_human: "5",
            period_secs: "86400",
            expiry_unix: "1780086400",
            recipients: "",
            conversation_id,
            timestamp: "1780000000",
        },
        signer,
    );
    let _ = (sig, pk);
    payload
}

/// The CRITICAL redaction-bypass regression this pins (`#2123`, mirroring
/// `#2090`'s own review finding on `refusals` — the single highest-risk
/// omission called out in this issue's own research map): a
/// [`QueryScope::Conversations`] session must never be able to read the raw
/// `signer_public_key` off `wallet_link_lifecycle`, even reaching straight
/// for `wallet_link_lifecycle_raw` (the bypass a missing
/// `ctx.deregister_table(WALLET_LINK_LIFECYCLE_RAW_TABLE)` call would leave
/// open). Mirrors
/// [`conversations_scope_refusals_signer_public_key_is_unreachable`]'s shape
/// exactly.
#[tokio::test]
async fn conversations_scope_wallet_link_lifecycle_signer_public_key_is_unreachable() {
    let signer = ApprovalSigner::from_seed(304);
    let bytes = signed_wallet_link_lifecycle_event(&signer, "conv-wll-redact");
    let events = vec![(0, Event::new(kinds::WALLET_LINK_LIFECYCLE, bytes))];
    let partitions = vec![PartitionEvents {
        partition: "conv-wll-redact".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-wll-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT signer_public_key FROM wallet_link_lifecycle", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "`signer_public_key` must not resolve as a column of `wallet_link_lifecycle` for a \
         non-Fleet scope: {result:?}"
    );

    // The bypass this test exists to close: reaching straight for the raw
    // table, around the view's redaction entirely.
    let raw_result = engine
        .execute("SELECT * FROM wallet_link_lifecycle_raw", false)
        .await;
    assert!(
        matches!(raw_result, Err(QueryEngineError::DataFusion(_))),
        "`wallet_link_lifecycle_raw` must not resolve at all for a non-Fleet scope: {raw_result:?}"
    );

    let output = engine
        .execute("SELECT * FROM wallet_link_lifecycle", false)
        .await
        .expect("wallet_link_lifecycle table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "transition",
            "subject",
            "wallet_address",
            "currency",
            "chain_id",
            "limit_base_units",
            "limit_human",
            "period_secs",
            "expiry_unix",
            "recipients",
            "conversation_id",
            "timestamp",
        ],
        "a non-Fleet wallet_link_lifecycle schema must carry every column except signer_public_key"
    );

    let resolved = engine
        .execute(
            "SELECT transition, subject, wallet_address FROM wallet_link_lifecycle WHERE conversation_id = 'conv-wll-redact'",
            false,
        )
        .await
        .expect("transition/subject/wallet_address must still resolve for a non-Fleet scope");
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let transition_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("transition is Utf8");
    assert_eq!(transition_col.value(0), "linked");
}

/// The Fleet-side half of the wallet-link-lifecycle redaction rule (`#2123`):
/// unlike a `Conversations` session (see
/// [`conversations_scope_wallet_link_lifecycle_signer_public_key_is_unreachable`]),
/// a [`QueryScope::Fleet`] session's `wallet_link_lifecycle` still carries
/// `signer_public_key`, full stop.
#[tokio::test]
async fn fleet_scope_wallet_link_lifecycle_returns_signer_public_key() {
    let signer = ApprovalSigner::from_seed(305);
    let bytes = signed_wallet_link_lifecycle_event(&signer, "conv-wll-fleet");
    let events = vec![(0, Event::new(kinds::WALLET_LINK_LIFECYCLE, bytes))];
    let partitions = vec![PartitionEvents {
        partition: "conv-wll-fleet".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT signer_public_key FROM wallet_link_lifecycle WHERE conversation_id = 'conv-wll-fleet'",
            false,
        )
        .await
        .expect("signer_public_key must resolve for Fleet");
    assert_eq!(output.batches[0].num_rows(), 1);
    let signer_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BinaryArray>()
        .expect("signer_public_key is Binary");
    assert_eq!(signer_col.value(0), signer.public_key_bytes());
}

/// The fold model's payments table end to end: real signed
/// `payment_receipt` (inbound) and `outbound_payment_receipt` (outbound)
/// events, appended alongside a committed turn, surface as two `payments`
/// rows — each with the right `direction` — and join back to the
/// conversation they belong to via `payments.partition = events.partition`,
/// the same join shape
/// [`model_call_rows_are_queryable_and_join_to_their_conversation`]
/// exercises for `model_call`.
#[tokio::test]
async fn payments_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(400);
    let signer = ApprovalSigner::from_seed(101);
    let inbound = signed_payment_receipt(&signer, kinds::PAYMENT_RECEIPT, "call-in");
    let outbound = signed_payment_receipt(&signer, kinds::OUTBOUND_PAYMENT_RECEIPT, "call-out");
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::PAYMENT_RECEIPT, &committed_turn),
                inbound,
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::OUTBOUND_PAYMENT_RECEIPT, &committed_turn),
                outbound,
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-payments".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM payments", false)
        .await
        .expect("payments count query");
    assert_eq!(single_count(&count), 2, "both inbound and outbound rows");

    let joined = engine
        .execute(
            "SELECT p.direction, p.tool_call_id FROM payments p \
             JOIN events e ON e.partition = p.partition \
             WHERE p.partition = 'conv-payments' \
             GROUP BY p.direction, p.tool_call_id \
             ORDER BY p.direction",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        2,
        "the join matches both payments rows exactly once each"
    );
    let direction_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("direction is Utf8");
    let tool_call_id_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("tool_call_id is Utf8");
    assert_eq!(direction_col.value(0), "inbound");
    assert_eq!(tool_call_id_col.value(0), "call-in");
    assert_eq!(direction_col.value(1), "outbound");
    assert_eq!(tool_call_id_col.value(1), "call-out");
}

/// The fold-coupling's own end-to-end proof, at the engine seam rather than
/// the decode-module seam `crate::decode::payments`'s own tests already
/// cover: a forged receipt — signed by a key OUTSIDE the engine's
/// `trusted_signers` — never surfaces as a `payments` row, alongside a
/// legitimately-signed sibling in the same partition that DOES. This proves
/// the typed table inherits `polyc_facts::verified_receipts`'s trust
/// boundary all the way through `QueryEngine::build`'s registration, not
/// just at the decode function in isolation.
#[tokio::test]
async fn payments_excludes_a_forged_or_untrusted_signer_receipt() {
    let turn = Uuid::from_u128(401);
    let trusted = ApprovalSigner::from_seed(102);
    let untrusted = ApprovalSigner::from_seed(103);
    let legit = signed_payment_receipt(&trusted, kinds::PAYMENT_RECEIPT, "call-legit");
    let forged = signed_payment_receipt(&untrusted, kinds::PAYMENT_RECEIPT, "call-forged");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::PAYMENT_RECEIPT, &turn), legit),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::PAYMENT_RECEIPT, &turn), forged),
        ),
        (
            3,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-payments-forged".to_string(),
        events,
    }];
    let trusted_signers = vec![trusted.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute("SELECT tool_call_id FROM payments", false)
        .await
        .expect("payments query");
    assert_eq!(
        output.batches[0].num_rows(),
        1,
        "only the legitimately-signed receipt appears — the forged one is dropped by \
         the shared fold, not by this table's own logic"
    );
    let tool_call_id = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("tool_call_id is Utf8");
    assert_eq!(tool_call_id.value(0), "call-legit");
}

/// PR-equivalent of PR #1352's attribution redaction fix, applied to
/// `payments`: a [`QueryScope::Conversations`] session — the in-conversation
/// agent's own MCP tool — must never be able to read the raw
/// `signer_public_key` off `payments`, even though it legitimately reads
/// every other payment fact for its own conversation (amount, recipient,
/// subject, direction, ...).
///
/// Mirrors
/// [`conversations_scope_attribution_identity_columns_are_unreachable`]'s
/// shape: the redacted column fails to resolve (fail-closed), the
/// `SELECT *` schema for this scope names every column except it, and every
/// other payment column still resolves with its real value — proving the
/// redaction is scoped to `signer_public_key` specifically, not the whole
/// table.
#[tokio::test]
#[allow(clippy::too_many_lines)] // the v3 payer-attribution assertions extend an already-thorough pin
async fn conversations_scope_payments_signer_public_key_is_unreachable() {
    let turn = Uuid::from_u128(402);
    let signer = ApprovalSigner::from_seed(104);
    let bytes = signed_payment_receipt(&signer, kinds::PAYMENT_RECEIPT, "call-redact");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::PAYMENT_RECEIPT, &turn), bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-payments-redact".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-payments-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT signer_public_key FROM payments", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "`signer_public_key` must not resolve as a column of `payments` for a \
         non-Fleet scope: {result:?}"
    );

    let output = engine
        .execute("SELECT * FROM payments", false)
        .await
        .expect("payments table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "direction",
            "reference",
            "amount",
            "currency",
            "recipient",
            "method",
            "timestamp",
            "version",
            "tool_call_id",
            "approval_pos",
            "approved_args_hash",
            "subject",
            "payer_kind",
            "paying_account",
        ],
        "a non-Fleet payments schema must carry every column except signer_public_key"
    );

    let resolved = engine
        .execute(
            "SELECT direction, amount, subject, payer_kind, paying_account FROM payments WHERE tool_call_id = 'call-redact'",
            false,
        )
        .await
        .expect("direction/amount/subject/payer_kind/paying_account must still resolve for a non-Fleet scope");
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let direction_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("direction is Utf8");
    let amount_col = resolved.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("amount is Utf8");
    let subject_col = resolved.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("subject is Utf8");
    let payer_kind_col = resolved.batches[0]
        .column(3)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("payer_kind is Utf8");
    let paying_account_col = resolved.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("paying_account is Utf8");
    assert_eq!(direction_col.value(0), "inbound");
    assert_eq!(amount_col.value(0), "2.75");
    assert_eq!(subject_col.value(0), "persona-payer");
    assert_eq!(
        payer_kind_col.value(0),
        "linked_wallet",
        "payer_kind must resolve with its real value at a non-Fleet scope — same non-redacted \
         class as subject/recipient, not the raw signer key"
    );
    assert_eq!(paying_account_col.value(0), "0xengine-payer");
}

/// The Fleet-side half of the payments redaction rule: unlike a
/// `Conversations` session (see
/// [`conversations_scope_payments_signer_public_key_is_unreachable`]), a
/// [`QueryScope::Fleet`] session's `payments` still carries
/// `signer_public_key`, full stop — the redaction is scope-dependent, not a
/// regression that also strips Fleet's own maintainer visibility.
#[tokio::test]
async fn fleet_scope_payments_returns_signer_public_key() {
    let turn = Uuid::from_u128(403);
    let signer = ApprovalSigner::from_seed(105);
    let bytes = signed_payment_receipt(&signer, kinds::PAYMENT_RECEIPT, "call-fleet");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::PAYMENT_RECEIPT, &turn), bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-payments-fleet".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT signer_public_key, payer_kind, paying_account FROM payments WHERE tool_call_id = 'call-fleet'",
            false,
        )
        .await
        .expect("signer_public_key/payer_kind/paying_account must resolve for Fleet");
    assert_eq!(output.batches[0].num_rows(), 1);
    let signer_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BinaryArray>()
        .expect("signer_public_key is Binary");
    assert_eq!(signer_col.value(0), signer.public_key_bytes());
    let payer_kind_col = output.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("payer_kind is Utf8");
    let paying_account_col = output.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("paying_account is Utf8");
    assert_eq!(payer_kind_col.value(0), "linked_wallet");
    assert_eq!(paying_account_col.value(0), "0xengine-payer");
}

/// A signed `approval_response` payload for the `approvals` engine tests —
/// mirrors `signed_payment_receipt`'s own role for `payments`' engine tests,
/// naming every field explicitly (no `..Default::default()` spread).
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field, matches `response_payload` itself
fn signed_approval_response(
    signer: &ApprovalSigner,
    request_id: &str,
    tool_name: &str,
    args_json: &str,
    caller: &str,
    reason: &str,
    conversation_id: &str,
    nonce: &str,
) -> Vec<u8> {
    polyc_crypto::approval::response_payload(
        request_id,
        tool_name,
        args_json,
        "",
        true,
        false,
        &[],
        caller,
        "",
        "default",
        reason,
        "",
        conversation_id,
        nonce,
        "",
        signer,
    )
    .0
}

/// A real signed `approval_request`+`approval_response` pair decodes to two
/// `approvals` rows — one per `phase` — and joins back to the conversation
/// it belongs to, the same join shape
/// [`payments_rows_are_queryable_and_join_to_their_conversation`] exercises
/// for `payments`.
#[tokio::test]
async fn approvals_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(500);
    let signer = ApprovalSigner::from_seed(106);
    let request_bytes = polyc_crypto::approval::request_payload(
        "call-approve",
        "rm",
        r#"{"path":"/tmp"}"#,
        "default",
        "",
        &[],
        "",
        "",
        "",
        &[],
        false,
    );
    let response_bytes = signed_approval_response(
        &signer,
        "call-approve",
        "rm",
        r#"{"path":"/tmp"}"#,
        "caller-1",
        "ok",
        "conv-approvals",
        "nonce-1",
    );
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::APPROVAL_REQUEST, &committed_turn),
                request_bytes,
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::APPROVAL_RESPONSE, &committed_turn),
                response_bytes,
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-approvals".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM approvals", false)
        .await
        .expect("approvals count query");
    assert_eq!(single_count(&count), 2, "both request and response rows");

    let joined = engine
        .execute(
            "SELECT a.phase, a.request_id FROM approvals a \
             JOIN events e ON e.partition = a.partition \
             WHERE a.partition = 'conv-approvals' \
             GROUP BY a.phase, a.request_id \
             ORDER BY a.phase",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        2,
        "the join matches both approvals rows exactly once each"
    );
    let phase_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("phase is Utf8");
    assert_eq!(phase_col.value(0), "request");
    assert_eq!(phase_col.value(1), "response");
}

/// PR-equivalent of [`conversations_scope_payments_signer_public_key_is_unreachable`],
/// applied to `approvals`: a [`QueryScope::Conversations`] session — the
/// in-conversation agent's own MCP tool — must never be able to read
/// `signer_public_key` (or any of the other eight Fleet-only columns) off
/// `approvals`, even though it legitimately reads every participant-visible
/// approval fact for its own conversation.
// Slightly over the line budget: one cohesive redaction proof (column
// unreachable, `approvals_raw` unreachable, `SELECT *` schema, remaining
// columns still resolve) — splitting it would scatter one invariant across
// several tests that all need the same fixture.
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn conversations_scope_approvals_signer_public_key_is_unreachable() {
    let turn = Uuid::from_u128(501);
    let signer = ApprovalSigner::from_seed(107);
    let response_bytes = signed_approval_response(
        &signer,
        "call-redact",
        "rm",
        "{}",
        "caller-redact",
        "ok",
        "conv-approvals-redact",
        "nonce-1",
    );
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::APPROVAL_RESPONSE, &turn),
                response_bytes,
            ),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-approvals-redact".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-approvals-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT signer_public_key FROM approvals", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "`signer_public_key` must not resolve as a column of `approvals` for a \
         non-Fleet scope: {result:?}"
    );

    // `approvals_raw` is deregistered by the same helper and must be equally
    // unreachable — mirrors `conversations_scope_hides_raw_table_by_every_name`'s
    // own assertion for `payments_raw`.
    let approvals_raw_unqualified = engine.execute("SELECT * FROM approvals_raw", false).await;
    assert!(
        matches!(
            approvals_raw_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "approvals_raw must not resolve for a non-Fleet scope: {approvals_raw_unqualified:?}"
    );

    let output = engine
        .execute("SELECT * FROM approvals", false)
        .await
        .expect("approvals table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "phase",
            "request_id",
            "tool_name",
            "args_json",
            "approved",
            "response_reason",
            "signature_status",
            "routine_grant",
            "tool_descriptor_hash",
            "grant_scope",
        ],
        "a non-Fleet approvals schema must carry exactly the participant-visible column set"
    );

    let resolved = engine
        .execute(
            "SELECT approved, response_reason, signature_status FROM approvals \
             WHERE request_id = 'call-redact'",
            false,
        )
        .await
        .expect(
            "approved/response_reason/signature_status must still resolve for a non-Fleet scope",
        );
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let approved_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BooleanArray>()
        .expect("approved is Boolean");
    let reason_col = resolved.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("response_reason is Utf8");
    let signature_col = resolved.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("signature_status is Utf8");
    assert!(approved_col.value(0));
    assert_eq!(reason_col.value(0), "ok");
    assert_eq!(signature_col.value(0), "verified");
}

/// The Fleet-side half of the approvals redaction rule: unlike a
/// `Conversations` session (see
/// [`conversations_scope_approvals_signer_public_key_is_unreachable`]), a
/// [`QueryScope::Fleet`] session's `approvals` still carries every
/// Fleet-only column, full stop.
#[tokio::test]
async fn fleet_scope_approvals_returns_signer_public_key() {
    let turn = Uuid::from_u128(502);
    let signer = ApprovalSigner::from_seed(108);
    let response_bytes = signed_approval_response(
        &signer,
        "call-fleet-approval",
        "rm",
        "{}",
        "caller-fleet",
        "ok",
        "conv-approvals-fleet",
        "nonce-1",
    );
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::APPROVAL_RESPONSE, &turn),
                response_bytes,
            ),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-approvals-fleet".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT signer_public_key FROM approvals WHERE request_id = 'call-fleet-approval'",
            false,
        )
        .await
        .expect("signer_public_key must resolve for Fleet");
    assert_eq!(output.batches[0].num_rows(), 1);
    let signer_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BinaryArray>()
        .expect("signer_public_key is Binary");
    assert_eq!(signer_col.value(0), signer.public_key_bytes());
}

/// A signed `Handoff` payload for the
/// `handoffs` engine tests — named fields, no `..Default::default()`
/// spread, mirroring `signed_payment_receipt`/`signed_approval_response`'s
/// own discipline for their tables.
fn signed_handoff_bytes(
    signer: &polyc_crypto::signing_role::HandoffSigner,
    child_conversation_id: &str,
    child_agent_id: &str,
    carried_count: u32,
    reason: &str,
) -> Vec<u8> {
    let mut h = polyc_proto::proto::polychrome::handoff::v1::Handoff {
        child_conversation_id: child_conversation_id.to_owned(),
        child_agent_id: child_agent_id.to_owned(),
        carried_count,
        reason: reason.to_owned(),
        ..Default::default()
    };
    polyc_crypto::handoff::sign_handoff_into(signer, &mut h);
    h.encode_to_vec()
}

/// A signed `HandoffDenied` payload.
#[allow(clippy::too_many_arguments)] // each arg is a distinct signed field, matches `response_payload` itself
fn signed_handoff_denied_bytes(
    signer: &polyc_crypto::signing_role::HandoffSigner,
    parent_conversation_id: &str,
    parent_agent_id: &str,
    child_agent_id: &str,
    reason: &str,
    denial_reason: &str,
    allowed: &[&str],
) -> Vec<u8> {
    let mut d = polyc_proto::proto::polychrome::handoff::v1::HandoffDenied {
        parent_conversation_id: parent_conversation_id.to_owned(),
        parent_agent_id: parent_agent_id.to_owned(),
        child_agent_id: child_agent_id.to_owned(),
        reason: reason.to_owned(),
        denial_reason: denial_reason.to_owned(),
        allowed: allowed.iter().map(|s| (*s).to_owned()).collect(),
        ..Default::default()
    };
    polyc_crypto::handoff::sign_handoff_denied_into(signer, &mut d);
    d.encode_to_vec()
}

/// A signed handoff and denial decode to two rows. Both join to their
/// conversation, like the payment and approval table tests.
#[tokio::test]
async fn handoffs_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(600);
    let signer = super::fixture_handoff_signer();
    let handoff_bytes = signed_handoff_bytes(&signer, "child-x", "researcher", 2, "delegate");
    let denied_bytes = signed_handoff_denied_bytes(
        &signer,
        "conv-handoffs",
        "assistant",
        "banned-agent",
        "delegate weird task",
        "this agent can't hand off to that agent",
        &["coding", "research"],
    );
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::HANDOFF, &committed_turn),
                handoff_bytes,
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::HANDOFF_DENIED, &committed_turn),
                denied_bytes,
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-handoffs".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM handoffs", false)
        .await
        .expect("handoffs count query");
    assert_eq!(single_count(&count), 2, "handoff and handoff_denied rows");

    let joined = engine
        .execute(
            "SELECT h.phase, h.child_conversation_id FROM handoffs h \
             JOIN events e ON e.partition = h.partition \
             WHERE h.partition = 'conv-handoffs' \
             GROUP BY h.phase, h.child_conversation_id \
             ORDER BY h.phase",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        2,
        "the join matches every handoffs row exactly once each"
    );
    let phase_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("phase is Utf8");
    assert_eq!(phase_col.value(0), "handoff");
    assert_eq!(phase_col.value(1), "handoff_denied");
}

/// Production writes handoff records under independent synthetic identifiers.
#[tokio::test]
async fn independently_committed_handoffs_are_queryable() {
    let handoff_id = Uuid::from_u128(603);
    let denied_id = Uuid::from_u128(604);
    let signer = super::fixture_handoff_signer();
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::HANDOFF, &handoff_id),
                signed_handoff_bytes(&signer, "child-live", "researcher", 1, "delegate"),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::HANDOFF_DENIED, &denied_id),
                signed_handoff_denied_bytes(
                    &signer,
                    "conv-handoffs-live",
                    "assistant",
                    "blocked",
                    "delegate",
                    "not allowed",
                    &["researcher"],
                ),
            ),
        ),
    ];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        vec![PartitionEvents {
            partition: "conv-handoffs-live".to_owned(),
            events,
        }],
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM handoffs", false)
        .await
        .expect("handoffs count query");
    assert_eq!(
        single_count(&count),
        2,
        "independently committed handoff records must remain visible"
    );
}

/// PR-equivalent of [`conversations_scope_payments_signer_public_key_is_unreachable`]/
/// [`conversations_scope_approvals_signer_public_key_is_unreachable`],
/// applied to `handoffs`: a [`QueryScope::Conversations`] session — the
/// in-conversation agent's own MCP tool — must never be able to read
/// `signed_by` off `handoffs`, even though it legitimately reads every
/// other handoff fact for its own conversation.
// Slightly over the line budget: one cohesive redaction proof (column
// unreachable, `handoffs_raw` unreachable, `SELECT *` schema, remaining
// columns still resolve) — splitting it would scatter one invariant across
// several tests that all need the same fixture, mirroring `approvals`' own
// precedent.
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn conversations_scope_handoffs_signed_by_is_unreachable() {
    let handoff_id = Uuid::from_u128(601);
    let denied_id = Uuid::from_u128(605);
    let signer = super::fixture_handoff_signer();
    let handoff_bytes =
        signed_handoff_bytes(&signer, "child-redact", "researcher", 1, "delegate-redact");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::HANDOFF, &handoff_id), handoff_bytes),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::HANDOFF_DENIED, &denied_id),
                signed_handoff_denied_bytes(
                    &signer,
                    "conv-handoffs-redact",
                    "assistant",
                    "blocked",
                    "delegate-redact",
                    "not allowed",
                    &["researcher"],
                ),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-handoffs-redact".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-handoffs-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT signed_by FROM handoffs", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "`signed_by` must not resolve as a column of `handoffs` for a non-Fleet scope: {result:?}"
    );

    // `handoffs_raw` is deregistered by the same helper and must be equally
    // unreachable — mirrors `conversations_scope_approvals_signer_public_key_is_unreachable`'s
    // own assertion for `approvals_raw`.
    let handoffs_raw_unqualified = engine.execute("SELECT * FROM handoffs_raw", false).await;
    assert!(
        matches!(
            handoffs_raw_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "handoffs_raw must not resolve for a non-Fleet scope: {handoffs_raw_unqualified:?}"
    );

    let output = engine
        .execute("SELECT * FROM handoffs", false)
        .await
        .expect("handoffs table");
    assert_eq!(
        output.batches[0].num_rows(),
        2,
        "the redacted view keeps independent handoff commands"
    );
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "phase",
            "child_conversation_id",
            "child_agent_id",
            "carried_count",
            "reason",
            "parent_agent_id",
            "denial_reason",
            "allowed",
            "signature_status",
        ],
        "a non-Fleet handoffs schema must carry every column except signed_by"
    );

    let resolved = engine
        .execute(
            "SELECT child_agent_id, carried_count, reason FROM handoffs \
             WHERE child_conversation_id = 'child-redact'",
            false,
        )
        .await
        .expect("child_agent_id/carried_count/reason must still resolve for a non-Fleet scope");
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let child_agent_id_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("child_agent_id is Utf8");
    let carried_count_col = resolved.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::UInt32Array>()
        .expect("carried_count is UInt32");
    let reason_col = resolved.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("reason is Utf8");
    assert_eq!(child_agent_id_col.value(0), "researcher");
    assert_eq!(carried_count_col.value(0), 1);
    assert_eq!(reason_col.value(0), "delegate-redact");
}

/// The Fleet-side half of the handoffs redaction rule: unlike a
/// `Conversations` session (see
/// [`conversations_scope_handoffs_signed_by_is_unreachable`]), a
/// [`QueryScope::Fleet`] session's `handoffs` still carries `signed_by`,
/// full stop.
#[tokio::test]
async fn fleet_scope_handoffs_returns_signed_by() {
    let turn = Uuid::from_u128(602);
    let signer = super::fixture_handoff_signer();
    let handoff_bytes =
        signed_handoff_bytes(&signer, "child-fleet", "researcher", 3, "delegate-fleet");
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::HANDOFF, &turn), handoff_bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-handoffs-fleet".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT signed_by FROM handoffs WHERE child_conversation_id = 'child-fleet'",
            false,
        )
        .await
        .expect("signed_by must resolve for Fleet");
    assert_eq!(output.batches[0].num_rows(), 1);
    let signed_by_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BinaryArray>()
        .expect("signed_by is Binary");
    assert_eq!(signed_by_col.value(0), signer.public_key_bytes());
}

/// A signed `grant_replay` payload for the `grant_replays` engine tests —
/// mirrors `signed_approval_response`'s own role for `approvals`' engine
/// tests, naming every field explicitly (no `..Default::default()` spread).
fn signed_grant_replay(
    signer: &ApprovalSigner,
    conversation_id: &str,
    turn_id: &str,
    tool: &str,
    grant_ref: &str,
    covered_capabilities: &[String],
    coverage_hash: &str,
) -> Vec<u8> {
    polyc_crypto::approval::test_util::grant_replay_payload(
        conversation_id,
        turn_id,
        tool,
        grant_ref,
        covered_capabilities,
        coverage_hash,
        signer,
    )
    .0
}

/// A real signed `grant_replay` decodes to one `grant_replays` row and joins
/// back to the conversation it belongs to, the same join shape
/// [`approvals_rows_are_queryable_and_join_to_their_conversation`] exercises
/// for `approvals`.
#[tokio::test]
async fn grant_replays_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(700);
    let signer = ApprovalSigner::from_seed(120);
    let payload_bytes = signed_grant_replay(
        &signer,
        "conv-grant-replays",
        &committed_turn.to_string(),
        "read_file",
        "grant-ref-engine",
        &["fs.read".to_owned()],
        "sha256:coverage-engine",
    );
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::GRANT_REPLAY, &committed_turn),
                payload_bytes,
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-grant-replays".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let count = engine
        .execute("SELECT COUNT(*) AS c FROM grant_replays", false)
        .await
        .expect("grant_replays count query");
    assert_eq!(single_count(&count), 1);

    let joined = engine
        .execute(
            "SELECT g.tool, g.grant_ref FROM grant_replays g \
             JOIN events e ON e.partition = g.partition \
             WHERE g.partition = 'conv-grant-replays' \
             GROUP BY g.tool, g.grant_ref",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "the join matches the grant_replays row exactly once"
    );
    let tool_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("tool is Utf8");
    assert_eq!(tool_col.value(0), "read_file");
}

/// PR-equivalent of [`conversations_scope_handoffs_signed_by_is_unreachable`],
/// applied to `grant_replays`: a [`QueryScope::Conversations`] session — the
/// in-conversation agent's own MCP tool — must never be able to read
/// `signer_public_key` off `grant_replays`, even though it legitimately reads
/// every participant-visible grant-replay fact for its own conversation.
// Slightly over the line budget: one cohesive redaction proof (column
// unreachable, `grant_replays_raw` unreachable, `SELECT *` schema, remaining
// columns still resolve) — splitting it would scatter one invariant across
// several tests that all need the same fixture, mirroring `approvals`'/
// `handoffs`' own equivalent tests.
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn conversations_scope_grant_replays_signer_public_key_is_unreachable() {
    let turn = Uuid::from_u128(701);
    let signer = ApprovalSigner::from_seed(121);
    let payload_bytes = signed_grant_replay(
        &signer,
        "conv-grant-replays-redact",
        &turn.to_string(),
        "read_file",
        "grant-ref-redact",
        &["fs.read".to_owned()],
        "sha256:coverage-redact",
    );
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::GRANT_REPLAY, &turn), payload_bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-grant-replays-redact".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-grant-replays-redact".to_string()]),
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT signer_public_key FROM grant_replays", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "`signer_public_key` must not resolve as a column of `grant_replays` for a \
         non-Fleet scope: {result:?}"
    );

    // `grant_replays_raw` is deregistered by the same helper and must be
    // equally unreachable — mirrors
    // `conversations_scope_handoffs_signed_by_is_unreachable`'s own assertion
    // for `handoffs_raw`.
    let grant_replays_raw_unqualified = engine
        .execute("SELECT * FROM grant_replays_raw", false)
        .await;
    assert!(
        matches!(
            grant_replays_raw_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "grant_replays_raw must not resolve for a non-Fleet scope: {grant_replays_raw_unqualified:?}"
    );

    let output = engine
        .execute("SELECT * FROM grant_replays", false)
        .await
        .expect("grant_replays table");
    let schema = output.batches[0].schema();
    let columns: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
    assert_eq!(
        columns,
        vec![
            "partition",
            "position",
            "turn_id",
            "tool",
            "grant_ref",
            "covered_capabilities",
            "coverage_hash",
            "signature_status",
        ],
        "a non-Fleet grant_replays schema must carry exactly the participant-visible column set"
    );

    let resolved = engine
        .execute(
            "SELECT tool, grant_ref, covered_capabilities, coverage_hash, signature_status \
             FROM grant_replays WHERE grant_ref = 'grant-ref-redact'",
            false,
        )
        .await
        .expect(
            "tool/grant_ref/covered_capabilities/coverage_hash/signature_status must still \
             resolve for a non-Fleet scope",
        );
    assert_eq!(resolved.batches[0].num_rows(), 1);
    let tool_col = resolved.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("tool is Utf8");
    let signature_col = resolved.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("signature_status is Utf8");
    assert_eq!(tool_col.value(0), "read_file");
    assert_eq!(signature_col.value(0), "verified");
}

/// The Fleet-side half of the `grant_replays` redaction rule: unlike a
/// `Conversations` session (see
/// [`conversations_scope_grant_replays_signer_public_key_is_unreachable`]), a
/// [`QueryScope::Fleet`] session's `grant_replays` still carries
/// `signer_public_key`, full stop.
#[tokio::test]
async fn fleet_scope_grant_replays_returns_signer_public_key() {
    let turn = Uuid::from_u128(702);
    let signer = ApprovalSigner::from_seed(122);
    let payload_bytes = signed_grant_replay(
        &signer,
        "conv-grant-replays-fleet",
        &turn.to_string(),
        "read_file",
        "grant-ref-fleet",
        &["fs.read".to_owned()],
        "sha256:coverage-fleet",
    );
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(kinds::tagged(kinds::GRANT_REPLAY, &turn), payload_bytes),
        ),
        (
            2,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-grant-replays-fleet".to_string(),
        events,
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT signer_public_key FROM grant_replays WHERE grant_ref = 'grant-ref-fleet'",
            false,
        )
        .await
        .expect("signer_public_key must resolve for Fleet");
    assert_eq!(output.batches[0].num_rows(), 1);
    let signer_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::BinaryArray>()
        .expect("signer_public_key is Binary");
    assert_eq!(signer_col.value(0), signer.public_key_bytes());
}

/// A wire [`WireMessage`] carrying a plain text block — `role`/
/// `internal_only` named explicitly (`polyc-query`'s own test convention:
/// no `..Default::default()` spread — see `crate::decode::attribution`'s
/// test fixtures for the same discipline).
fn wire_text_message(role: &str, text: &str, internal_only: bool) -> WireMessage {
    WireMessage {
        role: role.to_string(),
        content: buffa::MessageField::some(Content {
            r#type: Some(content::Type::Text(Box::new(TextContent {
                text: text.to_string(),
                ..Default::default()
            }))),
            ..Default::default()
        }),
        internal_only,
        __buffa_unknown_fields: buffa::UnknownFields::default(),
    }
}

/// A wire [`WireMessage`] carrying a tool-call content block.
fn wire_tool_call_message(id: &str, name: &str, args_json: &str) -> WireMessage {
    let arguments = serde_json::from_str::<buffa_types::google::protobuf::Struct>(args_json)
        .map(buffa::MessageField::some)
        .unwrap_or_default();
    WireMessage {
        role: "model".to_string(),
        content: buffa::MessageField::some(Content {
            r#type: Some(content::Type::ToolCall(Box::new(ToolCallContent {
                id: id.to_string(),
                r#type: Some(tool_call_content::Type::FunctionCall(Box::new(
                    FunctionCallContent {
                        name: name.to_string(),
                        arguments,
                        ..Default::default()
                    },
                ))),
                ..Default::default()
            }))),
            ..Default::default()
        }),
        internal_only: false,
        __buffa_unknown_fields: buffa::UnknownFields::default(),
    }
}

/// A wire [`WireMessage`] carrying a tool-result content block.
fn wire_tool_result_message(
    id: &str,
    name: &str,
    result_json: &str,
    first_party: bool,
) -> WireMessage {
    let response = serde_json::from_str::<buffa_types::google::protobuf::Struct>(result_json)
        .ok()
        .map(|s| function_result_content::Result::Response(Box::new(s)));
    WireMessage {
        role: "tool".to_string(),
        content: buffa::MessageField::some(Content {
            r#type: Some(content::Type::ToolResult(Box::new(ToolResultContent {
                call_id: id.to_string(),
                first_party,
                r#type: Some(tool_result_content::Type::FunctionResult(Box::new(
                    FunctionResultContent {
                        name: name.to_string(),
                        result: response,
                        ..Default::default()
                    },
                ))),
                ..Default::default()
            }))),
            ..Default::default()
        }),
        internal_only: false,
        __buffa_unknown_fields: buffa::UnknownFields::default(),
    }
}

/// The fact model's sixth typed table (message content) end to end: a
/// committed turn's `user_msg` (text), `output_msg` (tool call), and
/// `user_msg` (tool result) surface as one `messages` row and two
/// `tool_calls` rows (`block_type = 'call'`/`'result'`), both joining back
/// to the conversation via `partition` — the same join shape
/// [`attribution_rows_are_queryable_and_join_to_their_conversation`]
/// exercises. This is also the "content fold's behavior is inherited"
/// proof: a message with a tool call produces a `tool_calls` row, decoded
/// through the SAME `polyc_facts::fold_message_content` the trace projector
/// calls, not a second hand-rolled match.
#[tokio::test]
async fn message_content_rows_are_queryable_and_join_to_their_conversation() {
    let committed_turn = Uuid::from_u128(310);
    let text = wire_text_message("user", "please search", false);
    let call = wire_tool_call_message("call-1", "search", r#"{"q":"rust"}"#);
    let result = wire_tool_result_message("call-1", "search", r#"{"hits":3}"#, true);
    let events = vec![
        (
            0,
            Event::new(
                kinds::tagged(kinds::TURN_START, &committed_turn),
                Vec::new(),
            ),
        ),
        (
            1,
            Event::trusted(
                kinds::tagged(kinds::USER_MSG, &committed_turn),
                text.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &committed_turn),
                call.encode_to_vec(),
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::USER_MSG, &committed_turn),
                result.encode_to_vec(),
            ),
        ),
        (
            4,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &committed_turn),
                Vec::new(),
            ),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-message-content".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let messages_count = engine
        .execute("SELECT COUNT(*) AS c FROM messages", false)
        .await
        .expect("messages count query");
    assert_eq!(single_count(&messages_count), 1, "one text block");

    let tool_calls_count = engine
        .execute("SELECT COUNT(*) AS c FROM tool_calls", false)
        .await
        .expect("tool_calls count query");
    assert_eq!(
        single_count(&tool_calls_count),
        2,
        "one call row and one result row"
    );

    let joined = engine
        .execute(
            "SELECT m.role, m.text FROM messages m \
             JOIN events e ON e.partition = m.partition \
             WHERE m.partition = 'conv-message-content' \
             GROUP BY m.role, m.text",
            false,
        )
        .await
        .expect("messages join query");
    assert_eq!(joined.batches[0].num_rows(), 1);
    let role_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("role is Utf8");
    let text_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("text is Utf8");
    assert_eq!(role_col.value(0), "user");
    assert_eq!(text_col.value(0), "please search");
}

/// A tool call and its later result share the same `tool_call_id` — a
/// caller pairs them with an ordinary SQL self-join, never a merged row
/// (see `crate::decode::message_content`'s module docs for why the two
/// stay separate rows). Also proves `arguments`/`result`/`first_party` land
/// on the correct row (`NULL` where "not applicable to this block type",
/// never a wrong-shaped default).
#[tokio::test]
async fn tool_call_and_its_result_share_a_tool_call_id() {
    let turn = Uuid::from_u128(311);
    let call = wire_tool_call_message("call-1", "search", r#"{"q":"rust"}"#);
    let result = wire_tool_result_message("call-1", "search", r#"{"hits":3}"#, true);
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &turn),
                call.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::USER_MSG, &turn),
                result.encode_to_vec(),
            ),
        ),
        (
            3,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partitions = vec![PartitionEvents {
        partition: "conv-pairing".to_string(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let paired = engine
        .execute(
            "SELECT c.arguments, r.result, r.first_party \
             FROM tool_calls c \
             JOIN tool_calls r ON r.tool_call_id = c.tool_call_id AND r.block_type = 'result' \
             WHERE c.block_type = 'call' AND c.tool_call_id = 'call-1'",
            false,
        )
        .await
        .expect("call/result self-join");
    assert_eq!(paired.batches[0].num_rows(), 1);
    let arguments_col = paired.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("arguments is Utf8");
    let result_col = paired.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("result is Utf8");
    let first_party_col = paired.batches[0]
        .column(2)
        .as_any()
        .downcast_ref::<arrow::array::BooleanArray>()
        .expect("first_party is Boolean");
    assert_eq!(arguments_col.value(0), r#"{"q":"rust"}"#);
    assert_eq!(result_col.value(0), r#"{"hits":3.0}"#);
    assert!(first_party_col.value(0));

    // The `NULL`-not-a-default-value contract: the `call` row's own
    // `result`/`first_party` are absent, never a falsy stand-in.
    let call_row = engine
        .execute(
            "SELECT result, first_party FROM tool_calls \
             WHERE block_type = 'call' AND tool_call_id = 'call-1'",
            false,
        )
        .await
        .expect("call row query");
    assert!(
        call_row.batches[0].column(0).is_null(0),
        "call row has no result"
    );
    assert!(
        call_row.batches[0].column(1).is_null(0),
        "call row has no first_party, not false"
    );
}

/// A partition mixing one visible `user_msg` text block, one `internal_only`
/// `output_msg` text block, and one `internal_only` `output_msg` tool call —
/// shared by [`fleet_scope_message_content_includes_internal_only_rows`] and
/// [`conversations_scope_hides_internal_only_messages_and_tool_calls`], the
/// same "one fixture, two scope-side tests" split
/// [`attribution_rows_are_queryable_and_join_to_their_conversation`]/
/// [`fleet_scope_attribution_returns_full_identity_columns`] already use
/// once a single combined test would cross `clippy::too_many_lines`.
/// `#743` under D5: the redacted views honour the withholding marker.
///
/// The views filter `internal_only = false`, and D5 leaves a paused turn's
/// earlier narration durable and unmarked — the flag is applied on read from a
/// content-free marker the terminal batch wrote. `decode_partition_tables` is
/// where a partition becomes rows, so it is where the marker is applied; this
/// pins that a marked turn's narration never reaches a conversation-scoped
/// reader.
#[tokio::test]
async fn conversations_scope_hides_a_paused_turns_narration() {
    let turn = Uuid::from_u128(743);
    let narration = wire_text_message("model", "Removing it now (pending your approval).", false);
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::USER_MSG, &turn),
                wire_text_message("user", "remove the export", false).encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &turn),
                narration.encode_to_vec(),
            ),
        ),
        (
            3,
            Event::new(kinds::tagged(kinds::TURN_TEXT_WITHHELD, &turn), Vec::new()),
        ),
        (
            4,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    let partition_name = "conv-paused-withheld".to_owned();
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec![partition_name.clone()]),
        vec![PartitionEvents {
            partition: partition_name,
            events,
        }],
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("conversations build");

    let messages = engine
        .execute("SELECT text FROM messages", false)
        .await
        .expect("conversations messages query");
    let texts: Vec<String> = messages
        .batches
        .iter()
        .flat_map(|batch| {
            let col = batch
                .column(0)
                .as_any()
                .downcast_ref::<arrow::array::StringArray>()
                .expect("text is Utf8");
            (0..batch.num_rows())
                .map(|i| col.value(i).to_owned())
                .collect::<Vec<_>>()
        })
        .collect();
    assert!(
        texts.iter().any(|t| t == "remove the export"),
        "the person's own message stays visible: {texts:?}"
    );
    assert!(
        !texts
            .iter()
            .any(|t| t == "Removing it now (pending your approval)."),
        "a paused turn's narration must not reach a conversation-scoped \
         reader: {texts:?}"
    );
}

fn internal_only_redaction_fixture() -> (String, Vec<(u64, Event)>) {
    let turn = Uuid::from_u128(312);
    let visible = wire_text_message("user", "visible to the participant", false);
    let hidden = wire_text_message("model", "internal ground-truth note", true);
    let hidden_call = {
        let mut call = wire_tool_call_message("call-hidden", "search", r#"{"q":"x"}"#);
        call.internal_only = true;
        call
    };
    let events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::USER_MSG, &turn),
                visible.encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &turn),
                hidden.encode_to_vec(),
            ),
        ),
        (
            3,
            Event::new(
                kinds::tagged(kinds::OUTPUT_MSG, &turn),
                hidden_call.encode_to_vec(),
            ),
        ),
        (
            4,
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ),
    ];
    ("conv-internal-redact".to_string(), events)
}

/// The Fleet-side half: unlike a `Conversations` session (see
/// [`conversations_scope_hides_internal_only_messages_and_tool_calls`]), a
/// [`QueryScope::Fleet`] session's `messages`/`tool_calls` still carry every
/// `internal_only` row, full stop — the redaction is scope-dependent, not a
/// regression that also strips Fleet's own maintainer visibility (mirroring
/// [`fleet_scope_attribution_returns_full_identity_columns`]'s own point for
/// `attribution`).
#[tokio::test]
async fn fleet_scope_message_content_includes_internal_only_rows() {
    let (partition_name, events) = internal_only_redaction_fixture();
    let partitions = vec![PartitionEvents {
        partition: partition_name,
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("fleet build");

    let messages = engine
        .execute("SELECT COUNT(*) AS c FROM messages", false)
        .await
        .expect("fleet messages count");
    assert_eq!(
        single_count(&messages),
        2,
        "Fleet sees both the visible and the internal_only message"
    );
    let tool_calls = engine
        .execute("SELECT COUNT(*) AS c FROM tool_calls", false)
        .await
        .expect("fleet tool_calls count");
    assert_eq!(
        single_count(&tool_calls),
        1,
        "Fleet sees the internal_only tool call too"
    );
}

/// The redaction posture `crate::decode::message_content`'s module docs
/// state: an `internal_only` message (and any tool call/result folded from
/// one) is invisible to a non-Fleet scope, because it is by definition
/// never emitted to any client — the identical boundary condition
/// [`conversations_scope_attribution_identity_columns_are_unreachable`]
/// enforces for a different column shape. `messages_raw`/`tool_calls_raw`
/// fail to resolve entirely, the same fail-closed treatment
/// [`conversations_scope_hides_raw_table_by_every_name`] pins for
/// `events_raw`/`attribution_raw`.
#[tokio::test]
async fn conversations_scope_hides_internal_only_messages_and_tool_calls() {
    let (partition_name, events) = internal_only_redaction_fixture();
    let partitions = vec![PartitionEvents {
        partition: partition_name.clone(),
        events,
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec![partition_name]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("conversations build");

    let messages = engine
        .execute("SELECT text FROM messages", false)
        .await
        .expect("conversations messages query");
    assert_eq!(
        messages.batches[0].num_rows(),
        1,
        "the internal_only row must not reach a non-Fleet scope"
    );
    let text_col = messages.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("text is Utf8");
    assert_eq!(text_col.value(0), "visible to the participant");

    let tool_calls = engine
        .execute("SELECT COUNT(*) AS c FROM tool_calls", false)
        .await
        .expect("conversations tool_calls count");
    assert_eq!(
        single_count(&tool_calls),
        0,
        "the internal_only tool call must not reach a non-Fleet scope either"
    );

    for table in ["messages_raw", "tool_calls_raw"] {
        let result = engine
            .execute(&format!("SELECT * FROM {table}"), false)
            .await;
        assert!(
            matches!(result, Err(QueryEngineError::DataFusion(_))),
            "`{table}` must not resolve for a non-Fleet scope: {result:?}"
        );
    }
}

#[tokio::test]
async fn row_cap_truncates_to_exactly_the_cap() {
    let events: Vec<(u64, Event)> = (0..25)
        .map(|i| (i, Event::new(format!("k{i}"), Vec::new())))
        .collect();
    let partitions = vec![PartitionEvents {
        partition: "conv-cap".to_string(),
        events,
    }];
    let limits = QueryLimits {
        row_cap: 10,
        ..QueryLimits::default()
    };
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        limits,
    )
    .await
    .expect("build");

    let output = engine
        .execute("SELECT * FROM events_raw ORDER BY position", false)
        .await
        .expect("query");
    let total_rows: usize = output.batches.iter().map(RecordBatch::num_rows).sum();
    assert_eq!(total_rows, 10);
    assert!(output.truncated);
}

#[tokio::test]
async fn row_cap_not_truncated_when_rows_are_at_or_below_cap() {
    let events: Vec<(u64, Event)> = (0..5)
        .map(|i| (i, Event::new(format!("k{i}"), Vec::new())))
        .collect();
    let partitions = vec![PartitionEvents {
        partition: "conv-under-cap".to_string(),
        events,
    }];
    let limits = QueryLimits {
        row_cap: 5,
        ..QueryLimits::default()
    };
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        limits,
    )
    .await
    .expect("build");

    let output = engine
        .execute("SELECT * FROM events_raw", false)
        .await
        .expect("query");
    let total_rows: usize = output.batches.iter().map(RecordBatch::num_rows).sum();
    assert_eq!(total_rows, 5);
    assert!(!output.truncated);
}

/// `row_cap == usize::MAX` must not PANIC pushing `row_cap.saturating_add(1)`
/// into the plan. Before the `saturating_add` fix, a bare `row_cap + 1`
/// overflowed `usize::MAX` and panicked with "attempt to add with overflow"
/// in any overflow-checked build (the default for `cargo nextest`'s dev
/// profile) — before `DataFusion` itself was ever consulted. After the fix,
/// the addition no longer overflows; `DataFrame::limit`'s own internal
/// `usize -> i64` cast then fails gracefully instead (`usize::MAX` has no
/// `i64` representation) — a normal, typed `QueryEngineError`, never a
/// panic. This test proves the latter, not the former: it would abort the
/// whole test binary if the overflow panic still fired.
#[tokio::test]
async fn row_cap_usize_max_does_not_panic_building_the_limit() {
    let events: Vec<(u64, Event)> = (0..3)
        .map(|i| (i, Event::new(format!("k{i}"), Vec::new())))
        .collect();
    let partitions = vec![PartitionEvents {
        partition: "conv-max-cap".to_string(),
        events,
    }];
    let limits = QueryLimits {
        row_cap: usize::MAX,
        ..QueryLimits::default()
    };
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        limits,
    )
    .await
    .expect("build");

    let result = engine.execute("SELECT * FROM events_raw", false).await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "row_cap == usize::MAX must fail gracefully through DataFusion's own limit-conversion \
         error, never panic: {result:?}"
    );
}

/// Build a synthetic single-column `Int32` batch of `rows` sequential
/// values starting at `start`. `cap_rows` is schema-agnostic, so a
/// trivial one-column batch is enough to drive it directly without going
/// through `QueryEngine::execute`'s SQL/`MemTable` path (which — as the
/// two tests above show — doesn't reliably hand back more than one
/// physical `RecordBatch` from a single small `MemTable` partition).
fn int_batch(start: i32, rows: i32) -> RecordBatch {
    let schema = Arc::new(Schema::new(vec![Field::new("n", DataType::Int32, false)]));
    let values: Vec<i32> = (start..start + rows).collect();
    RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(values))]).expect("batch build")
}

/// Concatenate every batch's `n` column, in batch order, into one `Vec`
/// for a straightforward equality assertion against expected row values.
fn collect_n_column(batches: &[RecordBatch]) -> Vec<i32> {
    batches
        .iter()
        .flat_map(|batch| {
            batch
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .expect("Int32 column")
                .values()
                .iter()
                .copied()
        })
        .collect()
}

#[test]
fn cap_rows_truncates_mid_batch_across_multiple_physical_batches() {
    // Three physical batches (3, 4, 5 rows = 12 total), cap = 6, falling
    // mid the second batch: the first batch is kept whole, the second is
    // sliced from 4 rows down to 3, and the third is dropped entirely.
    let batches = vec![int_batch(0, 3), int_batch(3, 4), int_batch(7, 5)];

    let (kept, truncated) = cap_rows(batches, 6);

    assert!(truncated, "12 total rows exceeds the cap of 6");
    let total_rows: usize = kept.iter().map(RecordBatch::num_rows).sum();
    assert_eq!(total_rows, 6, "exactly cap rows are returned");
    assert_eq!(
        kept.len(),
        2,
        "the third batch is dropped once the cap is exhausted"
    );
    assert_eq!(kept[0].num_rows(), 3, "first batch kept whole");
    assert_eq!(kept[1].num_rows(), 3, "second batch sliced from 4 to 3");
    assert_eq!(
        collect_n_column(&kept),
        vec![0, 1, 2, 3, 4, 5],
        "returned rows are the first `cap` in original order"
    );
}

#[test]
fn cap_rows_exact_total_is_not_truncated() {
    // Two physical batches (3 + 3 = 6 total) exactly meeting the cap:
    // both batches pass through untouched and truncated is false.
    let batches = vec![int_batch(0, 3), int_batch(3, 3)];

    let (kept, truncated) = cap_rows(batches, 6);

    assert!(!truncated, "total rows exactly equals the cap");
    let total_rows: usize = kept.iter().map(RecordBatch::num_rows).sum();
    assert_eq!(total_rows, 6, "all rows are returned");
    assert_eq!(kept.len(), 2, "both batches pass through unmodified");
    assert_eq!(collect_n_column(&kept), vec![0, 1, 2, 3, 4, 5]);
}

#[tokio::test]
async fn information_schema_resolves_under_fleet() {
    let partitions = one_partition("conv-info-fleet", Uuid::from_u128(7), Uuid::from_u128(8));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT table_name FROM information_schema.tables WHERE table_name = 'usage'",
            false,
        )
        .await
        .expect("information_schema must resolve under Fleet");
    let total_rows: usize = output.batches.iter().map(RecordBatch::num_rows).sum();
    assert_eq!(total_rows, 1);
}

#[tokio::test]
async fn information_schema_fails_under_conversations() {
    let partitions = one_partition("conv-info-conv", Uuid::from_u128(9), Uuid::from_u128(10));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-info-conv".to_string()]),
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute("SELECT * FROM information_schema.tables", false)
        .await;
    assert!(
        matches!(result, Err(QueryEngineError::DataFusion(_))),
        "information_schema must not resolve outside Fleet: {result:?}"
    );
}

/// QRY-9: [`crate::decode::REGISTRY`] exists solely to drive
/// [`crate::decode`]'s own `registry_is_exhaustive_over_kinds_rs` structural
/// test (see that module's doc) — the RUNTIME table set
/// `engine::registration`'s helpers actually build is a SEPARATE,
/// independently hand-maintained list, so the two could silently diverge:
/// a kind could gain a `Decode::Typed("foo")` entry with no `"foo"` table
/// ever registered, or a table could be registered with no matching
/// `REGISTRY` entry naming it. This test closes that gap directly: build a
/// real Fleet [`QueryEngine`] (no partitions/reference rows needed — only
/// the catalog's own table SHAPE is under test) and diff
/// `information_schema.tables` against every [`crate::decode::Decode::Typed`]
/// label in [`crate::decode::REGISTRY`], expanded through the one documented
/// multi-table exception (`Decode::Typed("message_content")` fans out to
/// `messages` AND `tool_calls` — see that variant's own doc).
///
/// Deliberately reads the row set into a `BTreeSet` rather than relying on
/// SQL's own `ORDER BY` here: an unrelated `DataFusion` 54 planner quirk
/// this test's own development surfaced silently drops the
/// alphabetically-first row when `ORDER BY` is combined with
/// [`QueryEngine::execute`]'s automatic row-cap `LIMIT` push, specifically
/// over `information_schema.tables`' physical plan shape (reproduced
/// directly: `SELECT table_name FROM information_schema.tables ORDER BY
/// table_name` returns 33 rows and is missing `"approvals"`, the
/// alphabetically-first one, while the identical query with no `ORDER BY`
/// correctly returns all 34) — collecting the unordered result into a
/// `BTreeSet` in Rust sidesteps that entirely and is what this test's own
/// correctness actually depends on, not a workaround for THIS test's
/// assertions specifically. That quirk is orthogonal to QRY-9 and outside
/// this batch's scope; it is not exercised by any other existing test
/// because no other test combines `ORDER BY` with a query shaped like
/// `information_schema.tables`'s.
#[tokio::test]
async fn registry_typed_kinds_match_the_tables_query_engine_build_actually_registers() {
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        Vec::new(),
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute("SELECT table_name FROM information_schema.tables", false)
        .await
        .expect("information_schema query");
    let table_name_col = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("table_name is Utf8");
    let mut registered: std::collections::BTreeSet<String> = (0..output.batches[0].num_rows())
        .map(|i| table_name_col.value(i).to_string())
        .collect();

    // Exclude every relation outside this cross-check's scope: `events`/
    // `events_raw` (the wide table — not a per-kind REGISTRY decode), every
    // `*_raw` sibling (the raw/view split is an implementation detail of the
    // SAME typed table REGISTRY already names via its public view name),
    // the seven persona-store reference tables — `personas`/
    // `participations`/`persona_identities` (#1312) plus `persona_wallets`/
    // `persona_spend_policies`/`persona_credentials`/`persona_usage` (#1578)
    // — plus the `dashboard` maintained-projection reference table
    // (#1584/#1585), none of which is REGISTRY-driven (a non-journal source
    // — see the engine module docs' "Reference data" section), the
    // `crate::routine_catalog`-backed `routines` reference table (#1592,
    // also non-journal, and conveniently already excluded below since it
    // shares its name with `information_schema`'s own built-in `routines`
    // table), `information_schema`'s own remaining built-in tables, and
    // `routine_grants`/`routine_active_grants`/`routine_overview`/
    // `routine_refusals` — pure SQL compositions over
    // `approvals`/`fires`/`routine_setup` (themselves already
    // REGISTRY-driven), never a journal kind of their own.
    registered.retain(|name| {
        name != "events"
            && !name.ends_with("_raw")
            && name != "personas"
            && name != "participations"
            && name != "persona_identities"
            && name != "persona_wallets"
            && name != "persona_spend_policies"
            && name != "persona_credentials"
            && name != "persona_usage"
            && name != "dashboard"
            && name != "routine_grants"
            && name != "routine_active_grants"
            && name != "routine_overview"
            && name != "routine_refusals"
            && !matches!(
                name.as_str(),
                "tables"
                    | "views"
                    | "columns"
                    | "df_settings"
                    | "schemata"
                    | "routines"
                    | "parameters"
            )
    });

    let mut expected: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for (_kind_base, decision) in crate::decode::REGISTRY {
        if let crate::decode::Decode::Typed(label) = decision {
            if *label == "message_content" {
                expected.insert("messages".to_string());
                expected.insert("tool_calls".to_string());
            } else {
                expected.insert((*label).to_string());
            }
        }
    }

    assert_eq!(
        registered, expected,
        "REGISTRY's typed kinds and QueryEngine::build's actual table registrations have \
         diverged — every REGISTRY Typed kind must have a matching registered table, and \
         every registered typed table must have a matching REGISTRY entry"
    );
}

#[tokio::test]
async fn url_table_reference_fails_under_every_scope() {
    for scope in [
        QueryScope::Fleet,
        QueryScope::Conversations(vec!["conv-url".to_string()]),
    ] {
        let partitions = one_partition("conv-url", Uuid::from_u128(11), Uuid::from_u128(12));
        let engine = QueryEngine::build(
            &test_base_state(),
            &scope,
            partitions,
            ReferenceData::empty(),
            &[],
            QueryLimits::default(),
        )
        .await
        .expect("build");

        let result = engine.execute("SELECT * FROM 'x.csv'", false).await;
        assert!(
            matches!(result, Err(QueryEngineError::DataFusion(_))),
            "ad hoc external tables must never resolve ({scope:?}): {result:?}"
        );
    }
}

#[tokio::test]
async fn explain_honors_allow_explain_both_ways() {
    let partitions = one_partition("conv-explain", Uuid::from_u128(13), Uuid::from_u128(14));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let allowed = engine.execute("EXPLAIN SELECT * FROM events", true).await;
    assert!(
        allowed.is_ok(),
        "opted-in EXPLAIN must succeed: {allowed:?}"
    );
    assert!(!allowed.expect("checked above").batches.is_empty());

    let rejected = engine.execute("EXPLAIN SELECT * FROM events", false).await;
    assert!(
        matches!(rejected, Err(QueryEngineError::Rejected(_))),
        "EXPLAIN without opt-in must be rejected before planning: {rejected:?}"
    );
}

#[tokio::test]
async fn explain_analyze_is_always_rejected() {
    let partitions = one_partition("conv-analyze", Uuid::from_u128(15), Uuid::from_u128(16));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    for allow_explain in [true, false] {
        let result = engine
            .execute("EXPLAIN ANALYZE SELECT * FROM events", allow_explain)
            .await;
        assert!(
            matches!(result, Err(QueryEngineError::Rejected(_))),
            "EXPLAIN ANALYZE executes the query and stays banned everywhere \
             (allow_explain={allow_explain}): {result:?}"
        );
    }
}

#[tokio::test]
async fn multi_partition_tables_union_every_supplied_partition() {
    let partitions = vec![
        PartitionEvents {
            partition: "conv-x".to_string(),
            events: vec![(0, Event::new(kinds::TURN_START, Vec::new()))],
        },
        PartitionEvents {
            partition: "conv-y".to_string(),
            events: vec![
                (0, Event::new(kinds::TURN_START, Vec::new())),
                (1, Event::new(kinds::TURN_START, Vec::new())),
            ],
        },
    ];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT partition, COUNT(*) AS c FROM events_raw GROUP BY partition ORDER BY partition",
            false,
        )
        .await
        .expect("group-by query");
    let batch = &output.batches[0];
    assert_eq!(batch.num_rows(), 2, "one row per unioned partition");
    let partition_col = batch
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("partition is Utf8");
    assert_eq!(partition_col.value(0), "conv-x");
    assert_eq!(partition_col.value(1), "conv-y");
}

/// A `Binary` `payload` column (Fleet's `events_raw` includes it, see
/// `crate::provider`) must round-trip through
/// [`crate::output::output_to_json`], the shared wire-JSON conversion
/// every query surface uses. `arrow-json` 58.3's writer
/// (`arrow-json-58.3.0/src/writer/encoder.rs`'s `BinaryEncoder`) encodes
/// `Binary` as a lowercase hex string, one `{byte:02x}` per byte, no
/// `0x` prefix — confirmed by reading that source rather than assumed —
/// so this asserts the exact hex string a known byte sequence produces,
/// not just that the column survives as non-null.
#[tokio::test]
async fn output_to_json_round_trips_the_raw_payload_column() {
    let payload = vec![0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01];
    let partitions = vec![PartitionEvents {
        partition: "conv-payload".to_string(),
        events: vec![(0, Event::trusted(kinds::USER_MSG, payload.clone()))],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT position, payload FROM events_raw ORDER BY position",
            false,
        )
        .await
        .expect("payload query");
    let json = crate::output::output_to_json(&output, 0).expect("convert to wire JSON");

    assert_eq!(json.columns, vec!["position", "payload"]);
    assert_eq!(json.rows.len(), 1, "one event, one row");
    assert_eq!(
        json.rows[0][1],
        serde_json::json!("deadbeef0001"),
        "Binary encodes as lowercase hex with no 0x prefix"
    );
}

/// #1313's "opaque and JSON-queryable now" exposure end to end, for one
/// of the six kinds with no proto schema at all:
/// `payload_json` is both filterable through plain SQL string ops (no
/// dedicated `DataFusion` JSON scalar function ships in the pinned
/// `datafusion = "=54.0.0"` — see `crate::decode` module docs) and, once
/// returned, parses back as JSON so a caller can pull a specific field
/// out client-side.
#[tokio::test]
async fn events_raw_payload_json_is_queryable_for_a_schemaless_kind() {
    let partitions = vec![PartitionEvents {
        partition: "conv-json".to_string(),
        events: vec![(
            0,
            Event::new(
                kinds::APPROVAL_DEFERRED,
                br#"{"reason":"awaiting reviewer","attempt":2}"#.to_vec(),
            ),
        )],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT payload_json FROM events_raw \
             WHERE kind_base = 'approval_deferred' AND payload_json LIKE '%\"attempt\":2%'",
            false,
        )
        .await
        .expect("payload_json query");
    assert_eq!(
        output.batches[0].num_rows(),
        1,
        "the LIKE predicate matches the one row"
    );

    let payload_json = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("payload_json is Utf8")
        .value(0);
    let parsed: serde_json::Value =
        serde_json::from_str(payload_json).expect("payload_json is valid JSON text");
    assert_eq!(
        parsed["reason"], "awaiting reviewer",
        "a field is extractable from the returned JSON text"
    );
}

/// The other half of #1313's contract: a binary/non-JSON payload
/// decodes `payload_json` to `NULL`, not a query error — the column has
/// no failure mode (`crate::decode::events_batch`'s
/// `decode_payload_json` helper).
#[tokio::test]
async fn events_raw_payload_json_is_null_for_a_non_json_payload() {
    let partitions = vec![PartitionEvents {
        partition: "conv-nonjson".to_string(),
        events: vec![(
            0,
            Event::trusted(kinds::USER_MSG, vec![0xFF, 0xFE, 0x00, 0x01]),
        )],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute("SELECT payload_json FROM events_raw", false)
        .await
        .expect("payload_json query");
    let array = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("payload_json is Utf8");
    assert_eq!(array.len(), 1);
    assert!(
        array.is_null(0),
        "a non-JSON/binary payload must decode to NULL, not a query error"
    );
}

/// This item's own follow-up to #1313: `crate::engine::QueryEngine::build`
/// now registers `datafusion-functions-json`'s scalar UDFs (see
/// `crate::decode`'s module docs), so `payload_json` is extractable with
/// real JSON navigation — both the `->>` operator (rewritten to
/// `json_as_text`) and an explicit typed function call
/// (`json_get_int`) — not just `LIKE`-style string matching.
#[tokio::test]
async fn events_raw_payload_json_is_queryable_via_json_get_for_a_schemaless_kind() {
    let partitions = vec![PartitionEvents {
        partition: "conv-json-get".to_string(),
        events: vec![(
            0,
            Event::new(
                kinds::APPROVAL_DEFERRED,
                br#"{"reason":"awaiting reviewer","attempt":2}"#.to_vec(),
            ),
        )],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT payload_json ->> 'reason' AS reason, \
                    json_get_int(payload_json, 'attempt') AS attempt \
             FROM events_raw WHERE kind_base = 'approval_deferred'",
            false,
        )
        .await
        .expect("json_get query over payload_json");
    assert_eq!(output.batches[0].num_rows(), 1);

    let reason = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("reason (->>) is Utf8")
        .value(0);
    assert_eq!(reason, "awaiting reviewer");

    let attempt = output.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::Int64Array>()
        .expect("attempt (json_get_int) is Int64")
        .value(0);
    assert_eq!(attempt, 2);
}

/// The JSON functions apply the same way to any other JSON-string column
/// this crate exposes, not just `events_raw.payload_json` — here,
/// `tool_calls.arguments` (a `google.protobuf.Struct`-derived JSON string,
/// [`crate::decode::message_content::tool_calls_schema`]).
#[tokio::test]
async fn tool_calls_arguments_is_queryable_via_json_get() {
    let turn = Uuid::from_u128(320);
    let call = wire_tool_call_message("call-1", "search", r#"{"q":"rust"}"#);
    let partitions = vec![PartitionEvents {
        partition: "conv-json-tool-call".to_string(),
        events: vec![
            (
                0,
                Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
            ),
            (
                1,
                Event::new(
                    kinds::tagged(kinds::OUTPUT_MSG, &turn),
                    call.encode_to_vec(),
                ),
            ),
            (
                2,
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
            ),
        ],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT arguments ->> 'q' AS q FROM tool_calls WHERE block_type = 'call'",
            false,
        )
        .await
        .expect("json_get query over tool_calls.arguments");
    assert_eq!(output.batches[0].num_rows(), 1);
    let q = output.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("q (->>) is Utf8")
        .value(0);
    assert_eq!(q, "rust");
}

/// The other half of this item's contract: a `Typed` kind's `payload_json`
/// is `NULL` (see `crate::decode`'s module docs), and every JSON function
/// this crate registers returns `NULL` for a `NULL` input rather than
/// panicking or erroring — the same "no failure mode" guarantee
/// [`events_raw_payload_json_is_null_for_a_non_json_payload`] pins for
/// plain string ops, now exercised through the JSON functions themselves.
///
/// `json_get_str` (not the untyped `json_get`) is the one asserted here:
/// `json_get`'s return type is a `DataFusion`/Arrow `Union` array, and a
/// `UnionArray` carries no top-level validity bitmap at all (Arrow unions
/// encode nullability, if any, inside the active child array instead) —
/// `RecordBatch::column(..).is_null(0)` is therefore not a meaningful
/// check for `json_get`'s own column, only for a concretely-typed sibling
/// like `json_get_str`/`json_as_text` (`->>`, checked here too).
#[tokio::test]
async fn events_raw_payload_json_extraction_is_null_for_a_typed_payload() {
    let usage = UsageEvent {
        input_tokens: 1,
        output_tokens: 2,
        ..Default::default()
    };
    let partitions = vec![PartitionEvents {
        partition: "conv-json-null".to_string(),
        events: vec![(0, Event::new(kinds::USAGE, usage.encode_to_vec()))],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT payload_json ->> 'anything' AS extracted, \
                    json_get_str(payload_json, 'anything') AS typed_get \
             FROM events_raw",
            false,
        )
        .await
        .expect("json functions over a NULL payload_json must not error");
    assert_eq!(output.batches[0].num_rows(), 1);
    assert!(
        output.batches[0].column(0).is_null(0),
        "->> over NULL payload_json is NULL, not an error"
    );
    assert!(
        output.batches[0].column(1).is_null(0),
        "json_get_str over NULL payload_json is NULL, not an error"
    );
}

/// The committed `events` view (unlike `events_raw`, already covered by
/// [`multi_partition_tables_union_every_supplied_partition`]) must also
/// union correctly across multiple partitions: each partition's own
/// committed turn should surface, and neither partition's orphaned turn
/// should leak through, whether from its own partition or the other
/// one's.
#[tokio::test]
#[allow(clippy::similar_names)] // `orphaned_x`/`orphaned_y` name the two partitions' fixtures.
async fn multi_partition_committed_view_includes_each_partitions_committed_rows_only() {
    let committed_x = Uuid::from_u128(101);
    let orphaned_x = Uuid::from_u128(102);
    let committed_y = Uuid::from_u128(103);
    let orphaned_y = Uuid::from_u128(104);

    let partitions = vec![
        PartitionEvents {
            partition: "conv-mp-x".to_string(),
            events: fixture_events(committed_x, orphaned_x),
        },
        PartitionEvents {
            partition: "conv-mp-y".to_string(),
            events: fixture_events(committed_y, orphaned_y),
        },
    ];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let output = engine
        .execute(
            "SELECT partition, turn_id FROM events ORDER BY partition, position",
            false,
        )
        .await
        .expect("committed view query");
    let batch = &output.batches[0];
    assert_eq!(
        batch.num_rows(),
        8,
        "each partition's four committed rows (turn_start, user_msg, usage, \
         turn_complete), no orphaned rows from either partition"
    );

    let partition_col = batch
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("partition is Utf8");
    let turn_id_col = batch
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("turn_id is Utf8");

    let orphaned_x_str = orphaned_x.to_string();
    let orphaned_y_str = orphaned_y.to_string();
    let mut x_rows = 0;
    let mut y_rows = 0;
    for i in 0..batch.num_rows() {
        let turn_id = turn_id_col.value(i);
        assert_ne!(
            turn_id, orphaned_x_str,
            "conv-mp-x's orphaned turn must not appear"
        );
        assert_ne!(
            turn_id, orphaned_y_str,
            "conv-mp-y's orphaned turn must not appear"
        );
        match partition_col.value(i) {
            "conv-mp-x" => x_rows += 1,
            "conv-mp-y" => y_rows += 1,
            other => panic!("unexpected partition {other}"),
        }
    }
    assert_eq!(x_rows, 4, "conv-mp-x's committed turn's four rows");
    assert_eq!(y_rows, 4, "conv-mp-y's committed turn's four rows");
}

/// QRY-5's own regression proof: two DIFFERENT conversations (`partition`s)
/// sharing the IDENTICAL `turn_id` — a client-minted UUID the journal itself
/// never enforces as globally unique — must not cross-contaminate each
/// other's commit status. `conv-qry5-committed` completes its turn normally;
/// `conv-qry5-orphaned` carries the SAME `turn_id` but never lands
/// `turn_complete`. Before QRY-5 (a plain `WHERE turn_id IN (SELECT turn_id
/// FROM events)` semijoin, correlated on `turn_id` ALONE), the committed
/// partition's `turn_complete` marker would satisfy the orphaned partition's
/// filter too, since both share the same `turn_id` — this test proves that
/// no longer happens, for both [`COMMITTED_TURNS_VIEW_SQL`] itself and a
/// downstream typed table (`usage`).
// Deliberately long: one cohesive fixture (two conversations sharing a
// turn_id, one committed one not) plus proofs on both `events` and `usage`
// is what makes this one regression test, mirroring the file's other
// `#[allow(clippy::too_many_lines)]` fixtures (e.g.
// `conversations_scope_hides_uncommitted_turn_usage_payments_tool_calls_approvals_and_turn_failed`).
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn qry5_shared_turn_id_across_partitions_does_not_cross_contaminate_commit_status() {
    let shared_turn = Uuid::from_u128(0x0195_abcd_ef01_2345_6789_abcd_ef01_5005);

    let committed_events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &shared_turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::USAGE, &shared_turn),
                UsageEvent {
                    input_tokens: 7,
                    output_tokens: 8,
                    ..Default::default()
                }
                .encode_to_vec(),
            ),
        ),
        (
            2,
            Event::new(
                kinds::tagged(kinds::TURN_COMPLETE, &shared_turn),
                Vec::new(),
            ),
        ),
    ];
    // The SAME `turn_id`, in a DIFFERENT conversation, that never commits —
    // no `turn_complete` marker anywhere in this partition.
    let orphaned_events = vec![
        (
            0,
            Event::new(kinds::tagged(kinds::TURN_START, &shared_turn), Vec::new()),
        ),
        (
            1,
            Event::new(
                kinds::tagged(kinds::USAGE, &shared_turn),
                UsageEvent {
                    input_tokens: 999,
                    output_tokens: 999,
                    ..Default::default()
                }
                .encode_to_vec(),
            ),
        ),
    ];

    let partitions = vec![
        PartitionEvents {
            partition: "conv-qry5-committed".to_string(),
            events: committed_events,
        },
        PartitionEvents {
            partition: "conv-qry5-orphaned".to_string(),
            events: orphaned_events,
        },
    ];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    // `events`: the committed partition's rows under the shared `turn_id`
    // are visible; the orphaned partition's rows under the IDENTICAL
    // `turn_id` are hidden.
    let committed_count = engine
        .execute(
            &format!(
                "SELECT COUNT(*) AS c FROM events \
                 WHERE partition = 'conv-qry5-committed' AND turn_id = '{shared_turn}'"
            ),
            false,
        )
        .await
        .expect("committed partition events query");
    assert_eq!(
        single_count(&committed_count),
        3,
        "the committed partition's own three rows under the shared turn_id are visible"
    );

    let orphaned_count = engine
        .execute(
            &format!(
                "SELECT COUNT(*) AS c FROM events \
                 WHERE partition = 'conv-qry5-orphaned' AND turn_id = '{shared_turn}'"
            ),
            false,
        )
        .await
        .expect("orphaned partition events query");
    assert_eq!(
        orphaned_count.batches[0].num_rows(),
        1,
        "COUNT(*) still returns exactly one row"
    );
    assert_eq!(
        single_count(&orphaned_count),
        0,
        "the orphaned partition's rows under the SAME turn_id must stay hidden — the \
         committed partition's turn_complete marker must never vouch for a different \
         conversation's uncommitted turn under the identical turn_id"
    );

    // The identical proof one level up, on a downstream typed table: the
    // committed partition's usage row is visible, the orphaned partition's
    // usage row under the shared turn_id is hidden.
    let usage_committed = engine
        .execute(
            &format!(
                "SELECT COUNT(*) AS c FROM usage \
                 WHERE partition = 'conv-qry5-committed' AND turn_id = '{shared_turn}'"
            ),
            false,
        )
        .await
        .expect("committed partition usage query");
    assert_eq!(single_count(&usage_committed), 1);

    let usage_orphaned = engine
        .execute(
            &format!(
                "SELECT COUNT(*) AS c FROM usage \
                 WHERE partition = 'conv-qry5-orphaned' AND turn_id = '{shared_turn}'"
            ),
            false,
        )
        .await
        .expect("orphaned partition usage query");
    assert_eq!(
        single_count(&usage_orphaned),
        0,
        "the orphaned partition's usage row must stay hidden even though another \
         conversation committed the identical turn_id"
    );
}

/// Pins `crate::views`'s "NULL `turn_id` rows are dropped, intentionally"
/// doc section: a typed-table row whose `turn_id` is `NULL` (a bare,
/// un-tagged event — no production emitter writes one for a typed kind
/// today, but nothing stops a corrupt/synthetic fixture from carrying one)
/// is visible through the Fleet-only raw table and HIDDEN through the
/// committed-turn-filtered public view, exactly like an orphaned/uncommitted
/// turn's row is — `NULL = NULL` is `UNKNOWN`, never `TRUE`, so the `EXISTS`
/// correlation this crate's committed-turn filter uses can never match a
/// `NULL` `turn_id` against anything, the identical three-valued-logic
/// reason `NULL IN (...)` was never `TRUE` under the pre-QRY-5 semijoin
/// either.
#[tokio::test]
async fn null_turn_id_typed_row_is_dropped_by_the_committed_turn_filter() {
    let bare_usage = UsageEvent {
        input_tokens: 3,
        output_tokens: 4,
        ..Default::default()
    };
    let partitions = vec![PartitionEvents {
        partition: "conv-null-turn-id".to_string(),
        // A bare, un-tagged `usage` kind — `kinds::parse` yields `turn_id =
        // None` for this row, the same shape `bare_kind_has_no_turn_id`
        // (`crate::decode::handoffs`'s own tests) exercises for `handoffs`.
        events: vec![(
            0,
            Event::new(kinds::USAGE.to_owned(), bare_usage.encode_to_vec()),
        )],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let raw = engine
        .execute("SELECT COUNT(*) AS c FROM usage_raw", false)
        .await
        .expect("usage_raw query");
    assert_eq!(
        single_count(&raw),
        1,
        "the bare-kind row is visible through the Fleet-only raw table, turn_id NULL and all"
    );

    let raw_turn_id = engine
        .execute("SELECT turn_id FROM usage_raw", false)
        .await
        .expect("usage_raw turn_id query");
    assert!(
        raw_turn_id.batches[0].column(0).is_null(0),
        "the row's own turn_id is genuinely NULL, not an empty string"
    );

    let filtered = engine
        .execute("SELECT COUNT(*) AS c FROM usage", false)
        .await
        .expect("usage query");
    assert_eq!(
        single_count(&filtered),
        0,
        "a NULL turn_id row must be dropped by the committed-turn filter, exactly like an \
         orphaned/uncommitted turn's row"
    );
}

/// Fix A: a `CREATE TABLE` submitted through the full
/// [`QueryEngine::execute`] pipeline is rejected — caught by
/// [`statement_gate::check_statement_allowed`] before it ever reaches
/// `sql_with_options`.
#[tokio::test]
async fn ddl_is_rejected_through_the_engine() {
    let partitions = one_partition("conv-ddl", Uuid::from_u128(17), Uuid::from_u128(18));
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine.execute("CREATE TABLE t (a INT)", false).await;
    assert!(
        matches!(result, Err(QueryEngineError::Rejected(_))),
        "DDL must be rejected before it ever reaches planning: {result:?}"
    );
}

/// Fix A's belt-and-suspenders layer, exercised directly against a bare
/// `SessionContext` — not through [`QueryEngine::execute`] — so this
/// proves `DataFusion`'s own `SQLOptions` guard rejects DDL on its own.
/// Even if the hand-written statement gate above it were ever removed or
/// grew a bug, this second, independent layer would still reject a
/// `CREATE TABLE` before `sql_with_options` would ever plan and execute
/// it.
#[tokio::test]
async fn sql_options_reject_ddl_independent_of_the_statement_gate() {
    let ctx = SessionContext::new();
    let sql_options = SQLOptions::new()
        .with_allow_ddl(false)
        .with_allow_dml(false)
        .with_allow_statements(false);

    let result = ctx
        .sql_with_options("CREATE TABLE t (a INT)", sql_options)
        .await;
    assert!(
        result.is_err(),
        "DataFusion's own SQLOptions guard must reject DDL even without the statement \
         gate's involvement: {result:?}"
    );
}

// A deterministic timeout test is deliberately not included:
// `tokio::time::timeout` polls the wrapped future before checking
// whether the deadline has elapsed, so a query cheap enough to resolve
// on its very first poll — which every fixture in this file is, being
// an in-memory `MemTable` scan with no real I/O wait point — never
// observes even a `Duration::from_nanos(1)` timeout; it races the timer
// and always wins. Making the race land the other way needs either a
// genuinely slow/paused clock harness or a query shaped to force
// multiple poll cycles before completing, and either one risks
// reintroducing exactly the flakiness this test is trying to avoid.
// `QueryLimits::timeout`'s wiring is exercised structurally instead:
// `execute` always routes the collect step through
// `tokio::time::timeout(self.limits.timeout, ...)`, visible in this
// file's source, and every other test above runs under that same path
// with the default 30 s ceiling without ever hitting it.

/// The eleventh typed table end to end: a real buffa-encoded
/// `RoutineFiredEvent`, appended to the scheduler's own dedicated
/// `"routine-scheduler"` partition (never a conversation partition — see
/// `crate::authority`'s "Admitting the scheduler partition" section),
/// surfaces as one `fires` row with every field intact, and the caller-
/// supplied `routines` reference row for the same routine name is
/// queryable and joins to it.
#[tokio::test]
async fn fires_and_routines_rows_are_queryable_and_join_by_routine_name() {
    let fired = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-28461600".to_string(),
        scheduled_at_ms: 1_753_300_800_000,
        fired_at_ms: 1_753_300_805_000,
        ..Default::default()
    };
    let partitions = vec![PartitionEvents {
        partition: "routine-scheduler".to_string(),
        events: vec![(
            0,
            Event::trusted(kinds::ROUTINE_FIRED, fired.encode_to_vec()),
        )],
    }];
    let reference = ReferenceData {
        routines: vec![crate::routine_catalog::RoutineStatusRecord {
            name: "daily-standup".to_string(),
            uid: "uid-daily-standup".to_string(),
            fire_conversation_id: "fire-conv-fixture".to_string(),
            ready: true,
            phase: Some("Ready".to_string()),
            message: None,
            last_fire_time_ms: Some(1_784_797_200_000),
            next_fire_time_ms: Some(1_784_883_600_000),
            conditions_json: "[]".to_string(),
            creator_persona: "persona-1".to_string(),
            provenance_conversation_id: "conv-1".to_string(),
            schedule_json: r#"{"kind":"cron","expression":"0 9 * * *","timezone":null}"#
                .to_string(),
            next_fires_json: r"[1784883600000]".to_string(),
            suspended: false,
            paused_by: None,
            paused_at_ms: None,
            pause_reason: None,
            prompt: "post the morning standup".to_string(),
            scope: "private".to_string(),
            orphaned: false,
            display_name: String::new(),
            description: String::new(),
            schedule_timezone: "UTC".to_owned(),
        }],
        ..ReferenceData::empty()
    };
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let fires_count = engine
        .execute("SELECT COUNT(*) AS c FROM fires", false)
        .await
        .expect("fires count query");
    assert_eq!(single_count(&fires_count), 1);

    let joined = engine
        .execute(
            "SELECT f.occurrence, f.scheduled_at_ms, f.fired_at_ms, r.ready, r.next_fire_time_ms \
             FROM fires f JOIN routines r ON r.name = f.routine \
             WHERE f.routine = 'daily-standup'",
            false,
        )
        .await
        .expect("join query");
    assert_eq!(joined.batches[0].num_rows(), 1);

    let occurrence_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("occurrence is Utf8");
    assert_eq!(occurrence_col.value(0), "daily-standup-28461600");

    let scheduled_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::UInt64Array>()
        .expect("scheduled_at_ms is UInt64");
    assert_eq!(scheduled_col.value(0), 1_753_300_800_000);

    let ready_col = joined.batches[0]
        .column(3)
        .as_any()
        .downcast_ref::<arrow::array::BooleanArray>()
        .expect("ready is Boolean");
    assert!(ready_col.value(0));

    let next_fire_col = joined.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::Int64Array>()
        .expect("next_fire_time_ms is Int64");
    assert_eq!(next_fire_col.value(0), 1_784_883_600_000);
}

/// #1656 end to end through the SQL engine: a `routine_fire_outcome` event
/// appended alongside a `routine_fired` marker (same partition, same
/// `(routine, occurrence)` key) surfaces as the `fires` view's `outcome`
/// column — proving the view itself (`FIRES_VIEW_SQL`) selects the column,
/// not just `fires_raw`/`decode_fires_events`.
#[tokio::test]
async fn fires_outcome_column_is_selectable_through_the_view() {
    let fired = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-28461600".to_string(),
        scheduled_at_ms: 1_753_300_800_000,
        fired_at_ms: 1_753_300_805_000,
        ..Default::default()
    };
    let outcome = RoutineFireOutcomeEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-28461600".to_string(),
        outcome: RoutineFireOutcome::Ok.into(),
        fired_at_ms: 1_753_300_805_000,
        ..Default::default()
    };
    let partitions = vec![PartitionEvents {
        partition: "routine-scheduler".to_string(),
        events: vec![
            (
                0,
                Event::trusted(kinds::ROUTINE_FIRED, fired.encode_to_vec()),
            ),
            (
                1,
                Event::trusted(kinds::ROUTINE_FIRE_OUTCOME, outcome.encode_to_vec()),
            ),
        ],
    }];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute(
            "SELECT outcome FROM fires WHERE routine = 'daily-standup'",
            false,
        )
        .await
        .expect("outcome query");
    assert_eq!(result.batches[0].num_rows(), 1);
    let outcome_col = result.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("outcome is Utf8");
    assert_eq!(outcome_col.value(0), "ok");
}

/// Issue #1593 acceptance criterion: `fires` joins turns by `occurrence`
/// where a fired turn exists — a routine's fire and the turn its schedule
/// opened (`turn_dispatch`) share the identical occurrence identity, so an
/// `INNER JOIN` on it surfaces exactly the fires a turn actually opened for,
/// silently dropping any fire with no matching dispatched turn (a tick fired
/// before the control plane's in-process turn-dispatch handle existed, or
/// whose dispatch handle/routine `uid` were unset at fire time — see
/// `crate::decode::turn_dispatch`'s own module docs).
#[tokio::test]
async fn fires_joins_turn_dispatch_by_occurrence_where_a_fired_turn_exists() {
    let turn = Uuid::from_u128(0x0195_abcd_ef01_2345_6789_abcd_ef01_7777);
    let fired = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-28461600".to_string(),
        scheduled_at_ms: 1_753_300_800_000,
        fired_at_ms: 1_753_300_805_000,
        ..Default::default()
    };
    let dispatched = TurnDispatchedEvent {
        occurrence: "daily-standup-28461600".to_string(),
        ..Default::default()
    };
    // A second fire with NO matching dispatched turn — the join must drop
    // it, not spuriously match it against the other fire's turn.
    let orphan_fired = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-28465200".to_string(),
        scheduled_at_ms: 1_753_300_800_000 + 3_600_000,
        fired_at_ms: 1_753_300_800_000 + 3_600_005,
        ..Default::default()
    };

    let partitions = vec![
        PartitionEvents {
            partition: "routine-scheduler".to_string(),
            events: vec![
                (
                    0,
                    Event::trusted(kinds::ROUTINE_FIRED, fired.encode_to_vec()),
                ),
                (
                    1,
                    Event::trusted(kinds::ROUTINE_FIRED, orphan_fired.encode_to_vec()),
                ),
            ],
        },
        PartitionEvents {
            partition: "conv-standup-1".to_string(),
            events: vec![
                (
                    0,
                    Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                ),
                (
                    1,
                    Event::new(
                        kinds::tagged(kinds::TURN_DISPATCHED, &turn),
                        dispatched.encode_to_vec(),
                    ),
                ),
                (
                    2,
                    Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
                ),
            ],
        },
    ];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let joined = engine
        .execute(
            "SELECT f.occurrence, t.partition, t.turn_id \
             FROM fires f JOIN turn_dispatch t ON t.occurrence = f.occurrence",
            false,
        )
        .await
        .expect("fires-joins-turn_dispatch query");
    assert_eq!(
        joined.batches[0].num_rows(),
        1,
        "only the fire with a matching dispatched turn must survive the join"
    );

    let occurrence_col = joined.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("occurrence is Utf8");
    assert_eq!(occurrence_col.value(0), "daily-standup-28461600");

    let partition_col = joined.batches[0]
        .column(1)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("partition is Utf8");
    assert_eq!(partition_col.value(0), "conv-standup-1");
}

/// Issue #1593 acceptance criterion: the lifecycle timeline decodes the
/// signed event kinds — a real signed `routine_created`/`routine_paused`/
/// `routine_resumed`/`routine_deleted`/`routine_scope_changed` (`#1806`)
/// event, appended to the scheduler partition exactly the way `routine_nav`
/// appends them, is queryable through the `routine_lifecycle` table end to
/// end (through `QueryEngine::build`, not just the decode module's own unit
/// tests).
#[tokio::test]
#[allow(clippy::too_many_lines)] // one payload builder call per phase, now each multi-line for tool_call_id (#1638)
async fn routine_lifecycle_decodes_the_five_signed_kinds_end_to_end() {
    let signer = ApprovalSigner::from_seed(42);
    let (created, _, _) = routine_created_payload(
        "daily-standup",
        "persona-1",
        "conv-1",
        "call-1",
        "hash-1",
        1_000,
        &signer,
    );
    let (paused, _, _) = routine_paused_payload(
        "daily-standup",
        "persona-1",
        "conv-2",
        "call-2",
        "hash-2",
        "chat",
        2_000,
        Some("rotating out old announcements"),
        &signer,
    );
    let (resumed, _, _) = routine_resumed_payload(
        "daily-standup",
        "persona-1",
        "conv-3",
        "call-3",
        "hash-3",
        "chat",
        3_000,
        &signer,
    );
    let (deleted, _, _) = routine_deleted_payload(
        "daily-standup",
        "persona-1",
        "conv-4",
        "call-4",
        "hash-4",
        "chat",
        4_000,
        &signer,
    );
    let (scope_changed, _, _) = routine_scope_changed_payload(
        "daily-standup",
        "persona-1",
        "conv-5",
        "call-5",
        "hash-5",
        "public",
        5_000,
        &signer,
    );

    let partitions = vec![PartitionEvents {
        partition: "routine-scheduler".to_string(),
        events: vec![
            (0, Event::new(kinds::ROUTINE_CREATED, created)),
            (1, Event::new(kinds::ROUTINE_PAUSED, paused)),
            (2, Event::new(kinds::ROUTINE_RESUMED, resumed)),
            (3, Event::new(kinds::ROUTINE_DELETED, deleted)),
            (4, Event::new(kinds::ROUTINE_SCOPE_CHANGED, scope_changed)),
        ],
    }];
    let trusted_signers = vec![signer.public_key_bytes()];
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &trusted_signers,
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute(
            "SELECT phase, routine, actor_persona, at_ms, reason, scope FROM routine_lifecycle \
             ORDER BY at_ms",
            false,
        )
        .await
        .expect("routine_lifecycle query");
    assert_eq!(result.batches[0].num_rows(), 5);

    let phase = result.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("phase is Utf8");
    assert_eq!(phase.value(0), "routine_created");
    assert_eq!(phase.value(1), "routine_paused");
    assert_eq!(phase.value(2), "routine_resumed");
    assert_eq!(phase.value(3), "routine_deleted");
    assert_eq!(phase.value(4), "routine_scope_changed");

    let reason = result.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("reason is Utf8");
    assert!(reason.is_null(0), "routine_created carries no reason");
    assert_eq!(reason.value(1), "rotating out old announcements");
    assert!(reason.is_null(2), "routine_resumed carries no reason");
    assert!(reason.is_null(3), "routine_deleted carries no reason");
    assert!(reason.is_null(4), "routine_scope_changed carries no reason");

    let scope = result.batches[0]
        .column(5)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("scope is Utf8");
    assert!(scope.is_null(0), "routine_created carries no scope");
    assert!(scope.is_null(1), "routine_paused carries no scope");
    assert!(scope.is_null(2), "routine_resumed carries no scope");
    assert!(scope.is_null(3), "routine_deleted carries no scope");
    assert_eq!(scope.value(4), "public");
}

/// Issue #1592's own fleet-scope test, mirroring
/// [`conversations_scope_hides_summary_rows`]'s "never even registered
/// outside Fleet" proof and the payments-table precedent this issue's own
/// acceptance criteria names (`conversations_scope_payments_signer_public_key_is_unreachable`'s
/// sibling for a whole table rather than one column): a
/// [`QueryScope::Conversations`] session must never see `fires`/`fires_raw`/
/// `routines` at all, under any qualification — table not found, not a
/// redacted/empty result. Also covers `routines.prompt`, the routines
/// explorer table's row-hierarchy fix — a SPEC field, so it rides this
/// exact same Fleet-only gate.
// One cohesive fixture proving every one of `fires`/`fires_raw`/`routines`/
// `routine_lifecycle`/`routine_lifecycle_raw` (plus `routines.prompt`
// specifically) is unreachable together — splitting it would scatter one
// whole-table-unreachable proof across several tests that all need the same
// fixture, the same reasoning the module's other `clippy::too_many_lines`
// exemptions already give.
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn conversations_scope_hides_fires_and_routines_tables() {
    let fired = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-1".to_string(),
        scheduled_at_ms: 1,
        fired_at_ms: 2,
        ..Default::default()
    };
    // A conversation-scoped replay never even lists the scheduler partition
    // (see `crate::authority`'s "Admitting the scheduler partition"
    // section) — this fixture hands the engine the fire event directly
    // under a `conv-` partition name purely to prove the TABLE itself is
    // unreachable even when rows exist for the query to (wrongly) return;
    // in production this partition is never reached at all for this scope.
    let conversations_engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Conversations(vec!["fires-hidden".to_string()]),
        vec![PartitionEvents {
            partition: "conv-fires-hidden".to_string(),
            events: vec![(
                0,
                Event::trusted(kinds::ROUTINE_FIRED, fired.encode_to_vec()),
            )],
        }],
        ReferenceData {
            routines: vec![crate::routine_catalog::RoutineStatusRecord {
                name: "daily-standup".to_string(),
                uid: "uid-daily-standup".to_string(),
                fire_conversation_id: "fire-conv-fixture".to_string(),
                ready: true,
                phase: None,
                message: None,
                last_fire_time_ms: None,
                next_fire_time_ms: None,
                conditions_json: "[]".to_string(),
                creator_persona: "persona-1".to_string(),
                provenance_conversation_id: "conv-1".to_string(),
                schedule_json: r#"{"kind":"cron","expression":"0 9 * * *","timezone":null}"#
                    .to_string(),
                next_fires_json: "[]".to_string(),
                suspended: false,
                paused_by: None,
                paused_at_ms: None,
                pause_reason: None,
                prompt: "post the morning standup".to_string(),
                scope: "private".to_string(),
                orphaned: false,
                display_name: String::new(),
                description: String::new(),
                schedule_timezone: "UTC".to_owned(),
            }],
            ..ReferenceData::empty()
        },
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build conversations engine");

    let fires_unqualified = conversations_engine
        .execute("SELECT * FROM fires", false)
        .await;
    assert!(
        matches!(fires_unqualified, Err(QueryEngineError::DataFusion(_))),
        "fires must not resolve for a non-Fleet scope: {fires_unqualified:?}"
    );

    let fires_raw_unqualified = conversations_engine
        .execute("SELECT * FROM fires_raw", false)
        .await;
    assert!(
        matches!(fires_raw_unqualified, Err(QueryEngineError::DataFusion(_))),
        "fires_raw must not resolve for a non-Fleet scope either: {fires_raw_unqualified:?}"
    );

    let routines_unqualified = conversations_engine
        .execute("SELECT * FROM routines", false)
        .await;
    assert!(
        matches!(routines_unqualified, Err(QueryEngineError::DataFusion(_))),
        "routines must not resolve for a non-Fleet scope: {routines_unqualified:?} — note \
         ReferenceData.routines is never even registered for this scope regardless of the \
         (non-empty) value this fixture supplied"
    );

    let qualified = conversations_engine
        .execute("SELECT * FROM datafusion.public.fires", false)
        .await;
    assert!(
        matches!(qualified, Err(QueryEngineError::DataFusion(_))),
        "a fully-qualified name must not reach fires either: {qualified:?}"
    );

    // `prompt` (the routines explorer table's row-hierarchy fix) is a SPEC
    // field, exactly like `schedule_json`/`suspended` above — it must be
    // just as unreachable, not merely absent from an otherwise-resolvable
    // projection. Naming the column explicitly (rather than relying only on
    // `SELECT * FROM routines` above) proves the whole TABLE is gone, not
    // that this one column alone got redacted out of an otherwise-resolvable
    // `routines`.
    let routines_prompt_unqualified = conversations_engine
        .execute("SELECT prompt FROM routines", false)
        .await;
    assert!(
        matches!(
            routines_prompt_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "routines.prompt must not resolve for a non-Fleet scope: {routines_prompt_unqualified:?}"
    );

    // Issue #1593: `routine_lifecycle` follows the exact same Fleet-only
    // posture `fires` does — its one source partition is admitted into
    // replay only for a Fleet scope, so neither the view nor its raw table
    // resolves for a non-Fleet scope.
    let routine_lifecycle_unqualified = conversations_engine
        .execute("SELECT * FROM routine_lifecycle", false)
        .await;
    assert!(
        matches!(
            routine_lifecycle_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "routine_lifecycle must not resolve for a non-Fleet scope: {routine_lifecycle_unqualified:?}"
    );
    let routine_lifecycle_raw_unqualified = conversations_engine
        .execute("SELECT * FROM routine_lifecycle_raw", false)
        .await;
    assert!(
        matches!(
            routine_lifecycle_raw_unqualified,
            Err(QueryEngineError::DataFusion(_))
        ),
        "routine_lifecycle_raw must not resolve for a non-Fleet scope either: \
         {routine_lifecycle_raw_unqualified:?}"
    );
}

/// INV-OAF18 (a review finding on issue #1882's rollout): a persona-scoped
/// session that OWNS a routine still must not resolve `fires_raw` directly —
/// only the owner-filtered `fires` view. Before this fix,
/// `QueryEngine::build_from_tables`'s non-Fleet deregister step skipped
/// `fires_raw` whenever `register_owner_scoped_routines` was set, on the
/// false theory that direct resolution was impossible; since a persona
/// session runs arbitrary SQL, `SELECT * FROM fires_raw` would have returned
/// every OTHER member's fires too, unfiltered — the exact leak the owner
/// join in `FIRES_OWNED_VIEW_SQL` exists to prevent. Built through the same
/// owner-scoped path `crate::authority::ScopedQuery::execute` drives in
/// production (`QueryEngine::build_scoped` with
/// `register_owner_scoped_routines: true`), mirroring
/// `conversations_scope_hides_fires_and_routines_tables`'s own
/// unreachable-under-any-qualification proof.
#[tokio::test]
async fn owner_scoped_session_cannot_resolve_fires_raw_directly() {
    let fired = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-1".to_string(),
        scheduled_at_ms: 1,
        fired_at_ms: 2,
        routine_uid: "uid-daily-standup".to_string(),
        ..Default::default()
    };
    let reference = ReferenceData {
        routines: vec![crate::routine_catalog::RoutineStatusRecord {
            name: "daily-standup".to_string(),
            uid: "uid-daily-standup".to_string(),
            fire_conversation_id: "fire-conv-fixture".to_string(),
            ready: true,
            phase: None,
            message: None,
            last_fire_time_ms: None,
            next_fire_time_ms: None,
            conditions_json: "[]".to_string(),
            creator_persona: "persona-owner".to_string(),
            provenance_conversation_id: "conv-1".to_string(),
            schedule_json: r#"{"kind":"cron","expression":"0 9 * * *","timezone":null}"#
                .to_string(),
            next_fires_json: "[]".to_string(),
            suspended: false,
            paused_by: None,
            paused_at_ms: None,
            pause_reason: None,
            prompt: "post the morning standup".to_string(),
            scope: "private".to_string(),
            orphaned: false,
            display_name: String::new(),
            description: String::new(),
            schedule_timezone: "UTC".to_owned(),
        }],
        ..ReferenceData::empty_except_routines(vec![])
    };
    let owner_engine = QueryEngine::build_scoped(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-1".to_string()]),
        vec![PartitionEvents {
            partition: "routine-scheduler".to_string(),
            events: vec![(
                0,
                Event::trusted(kinds::ROUTINE_FIRED, fired.encode_to_vec()),
            )],
        }],
        reference,
        &[],
        QueryLimits::default(),
        true,
    )
    .await
    .expect("build owner-scoped engine");

    // The owner-filtered view still resolves and returns the owner's own fire.
    let fires_owned = owner_engine
        .execute("SELECT * FROM fires", false)
        .await
        .expect("owned fires view resolves");
    assert_eq!(fires_owned.batches[0].num_rows(), 1);

    // The raw table must never resolve directly — that would bypass the
    // owner-filtering join entirely.
    let fires_raw_unqualified = owner_engine.execute("SELECT * FROM fires_raw", false).await;
    assert!(
        matches!(fires_raw_unqualified, Err(QueryEngineError::DataFusion(_))),
        "fires_raw must not resolve for an owner-scoped session either: \
         {fires_raw_unqualified:?}"
    );

    let qualified = owner_engine
        .execute("SELECT * FROM datafusion.public.fires_raw", false)
        .await;
    assert!(
        matches!(qualified, Err(QueryEngineError::DataFusion(_))),
        "a fully-qualified name must not reach fires_raw either: {qualified:?}"
    );
}

/// INV-OAF18's uid-churn fix (part of issue #1882's review): member A's
/// routine `"daily-standup"` is deleted and member B later creates a routine
/// under the SAME name. Before this fix, [`crate::views::FIRES_OWNED_VIEW_SQL`]
/// joined `fires_raw.routine = routines.name`, so B's owner-scoped session
/// would see A's OWN historical fires too — a cross-owner leak on name
/// reuse. Joining on `routine_uid = routines.uid` instead closes it: A's old
/// fire (`routine_uid = "uid-A"`) never matches B's currently-registered
/// `routines` row (`uid = "uid-B"`), even though both rows share the
/// `routine` NAME `"daily-standup"`.
#[tokio::test]
async fn recreated_routine_name_does_not_leak_the_previous_owners_fires() {
    let fire_from_a = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-1".to_string(),
        scheduled_at_ms: 1,
        fired_at_ms: 2,
        routine_uid: "uid-A".to_string(),
        ..Default::default()
    };
    let fire_from_b = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-2".to_string(),
        scheduled_at_ms: 3,
        fired_at_ms: 4,
        routine_uid: "uid-B".to_string(),
        ..Default::default()
    };
    // Only B's routine (uid-B) is currently registered — the caller
    // (`crate::authority::ScopedQuery::resolve_routines`) already filtered
    // `reference.routines` to B's own rows before this build; A's routine no
    // longer exists as a CR at all.
    let reference = ReferenceData {
        routines: vec![crate::routine_catalog::RoutineStatusRecord {
            name: "daily-standup".to_string(),
            uid: "uid-B".to_string(),
            fire_conversation_id: "fire-conv-fixture".to_string(),
            ready: true,
            phase: None,
            message: None,
            last_fire_time_ms: None,
            next_fire_time_ms: None,
            conditions_json: "[]".to_string(),
            creator_persona: "persona-b".to_string(),
            provenance_conversation_id: "conv-b".to_string(),
            schedule_json: r#"{"kind":"cron","expression":"0 9 * * *","timezone":null}"#
                .to_string(),
            next_fires_json: "[]".to_string(),
            suspended: false,
            paused_by: None,
            paused_at_ms: None,
            pause_reason: None,
            prompt: "post the morning standup".to_string(),
            scope: "private".to_string(),
            orphaned: false,
            display_name: String::new(),
            description: String::new(),
            schedule_timezone: "UTC".to_owned(),
        }],
        ..ReferenceData::empty_except_routines(vec![])
    };
    let owner_engine = QueryEngine::build_scoped(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-b".to_string()]),
        vec![PartitionEvents {
            partition: "routine-scheduler".to_string(),
            events: vec![
                (
                    0,
                    Event::trusted(kinds::ROUTINE_FIRED, fire_from_a.encode_to_vec()),
                ),
                (
                    1,
                    Event::trusted(kinds::ROUTINE_FIRED, fire_from_b.encode_to_vec()),
                ),
            ],
        }],
        reference,
        &[],
        QueryLimits::default(),
        true,
    )
    .await
    .expect("build owner-scoped engine");

    let fires_owned = owner_engine
        .execute("SELECT occurrence FROM fires", false)
        .await
        .expect("owned fires view resolves");
    assert_eq!(
        fires_owned.batches[0].num_rows(),
        1,
        "only B's own fire should be visible, never A's — same name, different uid"
    );
    let occurrence = fires_owned.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .unwrap();
    assert_eq!(
        occurrence.value(0),
        "daily-standup-2",
        "the visible fire must be B's, never A's stale-uid row"
    );
}

/// `FIRES_OWNED_VIEW_SQL`'s own fail-closed guard: pre-uid fires (empty
/// `routine_uid`, the shape a marker recorded before this field existed
/// decodes as — `crate::decode::fires`'s own doc) must stay invisible even
/// when the owner-scoped `routines` row ALSO carries an empty `uid` —
/// `crate::routine_catalog::to_status_record`'s `Routine::uid().unwrap_or_default()`
/// makes that combination representable (never observed against a real
/// cluster, kube always assigns a uid before this crate sees a CR, but not
/// something the type system rules out). Without the explicit
/// `fires_raw.routine_uid <> ''` predicate, plain SQL equality would let
/// `'' = ''` match the pre-uid fire straight through — this test pins that it
/// does not.
#[tokio::test]
async fn empty_uid_fires_and_empty_uid_routines_never_match_each_other() {
    let pre_uid_fire = RoutineFiredEvent {
        routine: "daily-standup".to_string(),
        occurrence: "daily-standup-1".to_string(),
        scheduled_at_ms: 1,
        fired_at_ms: 2,
        routine_uid: String::new(),
        ..Default::default()
    };
    let reference = ReferenceData {
        routines: vec![crate::routine_catalog::RoutineStatusRecord {
            name: "daily-standup".to_string(),
            uid: String::new(),
            fire_conversation_id: String::new(),
            ready: true,
            phase: None,
            message: None,
            last_fire_time_ms: None,
            next_fire_time_ms: None,
            conditions_json: "[]".to_string(),
            creator_persona: "persona-owner".to_string(),
            provenance_conversation_id: "conv-1".to_string(),
            schedule_json: r#"{"kind":"cron","expression":"0 9 * * *","timezone":null}"#
                .to_string(),
            next_fires_json: "[]".to_string(),
            suspended: false,
            paused_by: None,
            paused_at_ms: None,
            pause_reason: None,
            prompt: "post the morning standup".to_string(),
            scope: "private".to_string(),
            orphaned: false,
            display_name: String::new(),
            description: String::new(),
            schedule_timezone: "UTC".to_owned(),
        }],
        ..ReferenceData::empty_except_routines(vec![])
    };
    let owner_engine = QueryEngine::build_scoped(
        &test_base_state(),
        &QueryScope::Conversations(vec!["conv-1".to_string()]),
        vec![PartitionEvents {
            partition: "routine-scheduler".to_string(),
            events: vec![(
                0,
                Event::trusted(kinds::ROUTINE_FIRED, pre_uid_fire.encode_to_vec()),
            )],
        }],
        reference,
        &[],
        QueryLimits::default(),
        true,
    )
    .await
    .expect("build owner-scoped engine");

    let fires_owned = owner_engine
        .execute("SELECT * FROM fires", false)
        .await
        .expect("owned fires view resolves");
    let total_rows: usize = fires_owned.batches.iter().map(RecordBatch::num_rows).sum();
    assert_eq!(
        total_rows, 0,
        "an empty-uid fire must stay invisible even against an empty-uid routines row"
    );
}

/// Issue #1593: the `routines` table's spec-derived columns
/// (provenance/pause/schedule) ride the SAME Fleet-only `routines` table
/// #1592 already gated — there is no separate redaction to prove here beyond
/// `conversations_scope_hides_fires_and_routines_tables`'s own
/// whole-table-unreachable proof, but this test also confirms a Fleet
/// session actually SEES the new columns (not just that the old status ones
/// still work), so a future accidental narrowing of the `routines` view's
/// column list would fail loudly. Also covers `prompt` (the routines
/// explorer table's row-hierarchy fix), added the same way.
#[tokio::test]
async fn fleet_scope_sees_provenance_pause_and_schedule_columns_on_routines() {
    let reference = ReferenceData {
        routines: vec![crate::routine_catalog::RoutineStatusRecord {
            name: "daily-standup".to_string(),
            uid: "uid-daily-standup".to_string(),
            fire_conversation_id: "fire-conv-fixture".to_string(),
            ready: true,
            phase: Some("Ready".to_string()),
            message: None,
            last_fire_time_ms: None,
            next_fire_time_ms: Some(1_784_883_600_000),
            conditions_json: "[]".to_string(),
            creator_persona: "persona-1".to_string(),
            provenance_conversation_id: "conv-1".to_string(),
            schedule_json:
                r#"{"kind":"cron","expression":"0 9 * * *","timezone":"America/New_York"}"#
                    .to_string(),
            next_fires_json: r"[1784883600000,1784970000000]".to_string(),
            suspended: true,
            paused_by: Some("persona-1".to_string()),
            paused_at_ms: Some(1_784_764_800_000),
            pause_reason: Some("rotating out old announcements".to_string()),
            prompt: "post the morning standup".to_string(),
            scope: "private".to_string(),
            orphaned: false,
            display_name: String::new(),
            description: String::new(),
            schedule_timezone: "UTC".to_owned(),
        }],
        ..ReferenceData::empty()
    };
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        vec![],
        reference,
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let result = engine
        .execute(
            "SELECT creator_persona, provenance_conversation_id, schedule_json, \
             next_fires_json, suspended, paused_by, paused_at_ms, pause_reason, prompt \
             FROM routines WHERE name = 'daily-standup'",
            false,
        )
        .await
        .expect("routines query with spec columns");
    assert_eq!(result.batches[0].num_rows(), 1);

    let creator_persona = result.batches[0]
        .column(0)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("creator_persona is Utf8");
    assert_eq!(creator_persona.value(0), "persona-1");

    let suspended = result.batches[0]
        .column(4)
        .as_any()
        .downcast_ref::<arrow::array::BooleanArray>()
        .expect("suspended is Boolean");
    assert!(suspended.value(0));

    let paused_by = result.batches[0]
        .column(5)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("paused_by is Utf8");
    assert_eq!(paused_by.value(0), "persona-1");

    let prompt = result.batches[0]
        .column(8)
        .as_any()
        .downcast_ref::<arrow::array::StringArray>()
        .expect("prompt is Utf8");
    assert_eq!(prompt.value(0), "post the morning standup");
}

/// A bound parameter is a VALUE, never SQL. Pinned at the engine layer,
/// where the binding actually happens
/// (`DataFrame::with_param_values` on the already-planned query), because
/// this is the property every fixed-template caller depends on — a surface
/// that binds text a conversation participant can influence has nothing else
/// standing between that text and the parser.
///
/// The proof is two-sided. Crafted payloads — quotes, a comment marker, a
/// semicolon, a `UNION SELECT` — match nothing, and the control arm shows a
/// legitimate value through the SAME placeholder does match, so "matched
/// nothing" is the value being compared literally rather than being
/// discarded on the way in.
#[tokio::test]
async fn a_bound_parameter_is_a_value_and_never_sql() {
    const SQL: &str = "SELECT COUNT(*) AS c FROM events WHERE turn_id = CAST($1 AS VARCHAR)";

    let committed_turn = Uuid::from_u128(4242);
    let orphaned_turn = Uuid::from_u128(4243);
    let partitions = one_partition("conv-param", committed_turn, orphaned_turn);
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    // Control arm: a real turn id through the placeholder finds its rows.
    let matched = engine
        .execute_with_params(SQL, &[&committed_turn.to_string()], false)
        .await
        .expect("bound query");
    assert_eq!(single_count(&matched), 4);

    for payload in [
        "' OR '1'='1",
        "x'; DROP TABLE events; --",
        "' UNION SELECT payload FROM events_raw --",
        "'; SELECT 1; --",
    ] {
        let result = engine
            .execute_with_params(SQL, &[payload], false)
            .await
            .unwrap_or_else(|e| panic!("`{payload}` must run as a plain value comparison: {e}"));
        assert_eq!(
            single_count(&result),
            0,
            "`{payload}` must be compared as literal text"
        );
    }

    // Nothing above changed the table it aimed at.
    let after = engine
        .execute_with_params(SQL, &[&committed_turn.to_string()], false)
        .await
        .expect("bound query");
    assert_eq!(single_count(&after), 4);
}

/// Placeholder/parameter correspondence is checked in ONE direction, and it
/// is not the safe one.
///
/// A placeholder no value was supplied for is refused outright. A SURPLUS
/// value — one no placeholder claims — is silently ignored, and the query
/// runs as if it had never been passed. That asymmetry is what makes an
/// optional predicate dangerous to assemble from two independent decisions:
/// dropping the clause while keeping its value yields a statement with no
/// `WHERE` that succeeds and returns every row. Callers derive the pair from
/// one decision instead; this pins the engine behavior that rule exists for,
/// so a `DataFusion` upgrade that started rejecting the surplus would surface
/// here rather than as a silently changed error path.
#[tokio::test]
async fn a_surplus_parameter_is_ignored_while_a_missing_one_is_refused() {
    const UNFILTERED: &str = "SELECT COUNT(*) AS c FROM events";
    const FILTERED: &str = "SELECT COUNT(*) AS c FROM events WHERE turn_id = CAST($1 AS VARCHAR)";

    let committed_turn = Uuid::from_u128(4242);
    let orphaned_turn = Uuid::from_u128(4243);
    let partitions = one_partition("conv-surplus", committed_turn, orphaned_turn);
    let engine = QueryEngine::build(
        &test_base_state(),
        &QueryScope::Fleet,
        partitions,
        ReferenceData::empty(),
        &[],
        QueryLimits::default(),
    )
    .await
    .expect("build");

    let baseline = engine
        .execute_with_params(UNFILTERED, &[], false)
        .await
        .expect("the unfiltered statement runs");
    let all_rows = single_count(&baseline);
    assert!(all_rows > 0, "the fixture must have rows to be filtered");

    // A value with no placeholder to claim it: accepted, and the statement
    // runs UNFILTERED — the fail-open direction.
    let surplus = engine
        .execute_with_params(UNFILTERED, &["never-bound"], false)
        .await
        .expect("a surplus parameter is silently ignored, not refused");
    assert_eq!(
        single_count(&surplus),
        all_rows,
        "a surplus parameter changes nothing: the statement ran unfiltered"
    );

    // Control arm: the same value through a statement that DOES name `$1`
    // filters, so the equality above is a missing predicate rather than a
    // value that never reached the engine.
    let filtered = engine
        .execute_with_params(FILTERED, &["never-bound"], false)
        .await
        .expect("the filtered statement runs");
    assert_eq!(
        single_count(&filtered),
        0,
        "with a placeholder to bind, the same value really does filter"
    );

    // The other direction is refused outright.
    let missing = engine.execute_with_params(FILTERED, &[], false).await;
    assert!(
        matches!(missing, Err(QueryEngineError::DataFusion(_))),
        "a placeholder with no value must be refused, not defaulted: {missing:?}"
    );
}

/// One `SchemaError::FieldNotFound` shaped exactly the way the planner emits
/// it, for the wrapping tests below.
fn field_not_found() -> DataFusionError {
    DataFusionError::SchemaError(
        Box::new(SchemaError::FieldNotFound {
            field: Box::new(Column::new(Some("events"), "message")),
            valid_fields: vec![
                Column::new(Some("events"), "partition"),
                Column::new(Some("events"), "turn_id"),
            ],
        }),
        Box::new(None),
    )
}

/// Issue #2206: `unresolved_column` finds the structured field-not-found
/// through every wrapper the planner puts around it, and returns the
/// planner's own two facts rather than anything scraped from `Display`.
///
/// The wrapping is the part a naive predicate gets wrong, and it is not
/// hypothetical: the SQL planner wraps its own error in a `Diagnostic` (and,
/// deeper in, a `Context`) before it ever leaves the planner, and a `Shared`
/// or `Collection` arrives from the shared and multi-error paths. A check of
/// only the outermost value would report every one of these as a generic
/// internal fault — exactly the failure this change exists to end.
#[test]
fn unresolved_column_walks_every_wrapper_the_planner_adds() {
    let wrappings: Vec<(&str, DataFusionError)> = vec![
        ("bare", field_not_found()),
        (
            "context",
            DataFusionError::Context("while planning".to_owned(), Box::new(field_not_found())),
        ),
        (
            "diagnostic",
            DataFusionError::Diagnostic(
                Box::new(datafusion::common::Diagnostic::new_error(
                    "column not found",
                    None,
                )),
                Box::new(field_not_found()),
            ),
        ),
        (
            "context around diagnostic",
            DataFusionError::Context(
                "while planning".to_owned(),
                Box::new(DataFusionError::Diagnostic(
                    Box::new(datafusion::common::Diagnostic::new_error(
                        "column not found",
                        None,
                    )),
                    Box::new(field_not_found()),
                )),
            ),
        ),
        (
            "shared",
            DataFusionError::Shared(std::sync::Arc::new(field_not_found())),
        ),
        (
            "collection",
            DataFusionError::Collection(vec![field_not_found()]),
        ),
    ];

    for (label, error) in wrappings {
        let unresolved = unresolved_column(&QueryEngineError::DataFusion(error))
            .unwrap_or_else(|| panic!("`{label}` must still be recognized as a column failure"));
        assert_eq!(unresolved.name, "message", "{label}");
        assert_eq!(unresolved.qualifier.as_deref(), Some("events"), "{label}");
        assert_eq!(
            unresolved.valid_fields,
            vec![
                (Some("events".to_owned()), "partition".to_owned()),
                (Some("events".to_owned()), "turn_id".to_owned()),
            ],
            "{label}"
        );
    }
}

/// A miss in `GROUP BY`, `ORDER BY`, or `HAVING` resolves against the
/// projection schema FOLLOWED BY the input schema, so `DataFusion` offers
/// every projected column twice — this is the shape it hands us, reproduced
/// here from a real `SELECT turn_id FROM events ORDER BY nope`. Each column
/// survives once, in the order first seen, so the caller-facing message
/// neither repeats a name nor counts a duplicate against its column bound.
#[test]
fn unresolved_column_offers_each_column_once() {
    let duplicated = DataFusionError::SchemaError(
        Box::new(SchemaError::FieldNotFound {
            field: Box::new(Column::new(None::<&str>, "nope")),
            valid_fields: vec![
                Column::new(Some("events"), "turn_id"),
                Column::new(Some("events"), "partition"),
                Column::new(Some("events"), "position"),
                Column::new(Some("events"), "kind"),
                Column::new(Some("events"), "turn_id"),
            ],
        }),
        Box::new(None),
    );

    let unresolved = unresolved_column(&QueryEngineError::DataFusion(duplicated))
        .expect("a duplicated valid_fields is still a column failure");
    assert_eq!(
        unresolved.valid_fields,
        vec![
            (Some("events".to_owned()), "turn_id".to_owned()),
            (Some("events".to_owned()), "partition".to_owned()),
            (Some("events".to_owned()), "position".to_owned()),
            (Some("events".to_owned()), "kind".to_owned()),
        ],
        "first-seen order, each column once"
    );
}

/// The other direction: `unresolved_column` claims nothing that is not a
/// field-not-found, so a genuine engine fault keeps collapsing into the
/// internal failure it is. `is_unresolved_table_error` is checked on the same
/// values, because the two predicates guard adjacent arms of one match and a
/// change that made either over-match would report a deployment fault as the
/// caller's mistake.
#[test]
fn unresolved_column_ignores_every_other_failure() {
    let others = vec![
        DataFusionError::Execution("the plan failed at runtime".to_owned()),
        DataFusionError::Plan("Invalid function 'nope'".to_owned()),
        DataFusionError::SchemaError(
            Box::new(SchemaError::DuplicateUnqualifiedField {
                name: "turn_id".to_owned(),
            }),
            Box::new(None),
        ),
        DataFusionError::Context(
            "while planning".to_owned(),
            Box::new(DataFusionError::Execution("still not a column".to_owned())),
        ),
    ];
    for error in others {
        let rendered = error.to_string();
        let engine_error = QueryEngineError::DataFusion(error);
        assert!(
            unresolved_column(&engine_error).is_none(),
            "`{rendered}` is not an unresolvable column"
        );
        assert!(
            !is_unresolved_table_error(&engine_error),
            "`{rendered}` is not an unresolvable table either"
        );
    }

    // A non-DataFusion engine failure is not either of them either.
    let decode = QueryEngineError::Decode {
        table: "events_raw",
        source: arrow::error::ArrowError::SchemaError("not a DataFusion error".to_owned()),
    };
    assert!(unresolved_column(&decode).is_none());
    assert!(!is_unresolved_table_error(&decode));
}