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
//! The dashboard maintained projection (#1584 — split from #1577, part of
//! the read-path-convergence epic #1574).
//!
//! `GET /api/dashboard` (`crates/control-plane/src/forensics.rs::api_dashboard`)
//! today replays every conversation partition on every poll and folds it
//! through `compute_stats` — a full-fleet replay every two seconds, per open
//! tab. This module builds the write side of the replacement: a query-owned
//! row per conversation, kept current from the durable commit feed rather
//! than a poll-time replay. **Query exposure (the `/api/dashboard`
//! endpoint swap) is #1585 (C2) — this module is deliberately unreachable
//! from any read path yet.**
//!
//! # Ownership (the R1 fix)
//!
//! [`DashboardProjection`] is a `polyc-query`-owned type, not a
//! control-plane one exposed through `ReferenceData`. The cell is
//! query-owned (or shared-component) and the control plane *mutates* it,
//! mirroring [`crate::authority::PersonaCell`]. The
//! control plane holds a [`DashboardCell`] handle (an `Arc`, cloned freely)
//! and calls [`DashboardProjection::rebuild_from_full_fleet`] and
//! [`DashboardProjection::apply_commits`]; it never constructs or reads a
//! row directly. C2 registers this same cell as a Fleet-only reference table
//! the query engine serves.
//!
//! Unlike [`crate::authority::PersonaCell`] (a single `ArcSwapOption` swapped
//! wholesale on every persona-host handoff), this projection needs granular,
//! per-conversation, per-event mutation — a `RwLock`-guarded map is the more
//! apt shape for that access pattern, but the *role* is the same: one shared
//! handle, owned by this crate, mutated by the control plane through a
//! narrow API, never reached around.
//!
//! # Feed: the durable commit feed, not N hand-placed hooks
//!
//! The design record's own count: at least ten non-`persist_turn` paths
//! touch a conversation partition (settlement receipts, approve/deny, taint
//! excision, grant suspend/repair, `append_turn_dispatch`, attribution
//! self-healing, handoff appends, wallet/credential/enrollment flows, and the
//! `summary` append that runs *before* `persist_turn`). [`DashboardProjection::apply_commits`]
//! folds every one of them uniformly, because every one of them commits and
//! every commit drives the feed (INV-11) — never a second hook per call site.
//!
//! This projection's input is the durable commit feed, not an in-process
//! observer on an event-log host (#1565, chunk B6): delivery is at-least-once
//! over a network, not exactly-once in-process, so a chunk may arrive
//! twice and a subscription may stop without saying so. The position
//! high-water mark below already made a redelivery a no-op, and
//! [`DashboardProjection::rebuild_from_full_fleet`] is what makes a subscription that never
//! resumes a latency problem instead of a permanently wrong row — it runs on an
//! hourly schedule (`crates/control-plane/src/lib.rs`) as well as at boot and on
//! the admin route, so every row converges on the journal with no notification
//! of any kind.
//!
//! # Idempotency: journal position, not turn id
//!
//! The design record calls for "the event POSITIONS as the idempotency
//! key... stronger than turn-id high-water, since positions are monotonic and
//! never renumbered." Each `TrackedRow` keeps `applied_position`, the highest
//! journal position already folded in; a feed chunk whose positions are all
//! `<=` that mark is a redelivery and contributes nothing (see
//! `TrackedRow::apply`). This is what makes the feed's at-least-once delivery
//! safe: applying the same chunk twice leaves the row byte-for-byte identical.
//!
//! # Per-field merge rules
//!
//! - `total_events`: incremented once per NEW event (position-gated),
//!   regardless of kind or commit status — mirrors `compute_stats`'
//!   `events.len()`. The feed and a replay agree exactly on what that counts
//!   (#1565, chunk B6): a commit brackets the caller's own submitted records,
//!   and the journal keeps its per-commit tamper-evidence marker out of every
//!   read rather than numbering it into the partition, so an incrementally-fed
//!   row and a rebuilt one reach the same figure. Before the cutover a replay
//!   read the marker off disk while the feed never carried it, and a row fed
//!   purely incrementally undercounted by up to one per commit until its next
//!   rebuild. No other field was affected: the marker's kind matches none of
//!   `usage`/`summary`/`model_call`/`user_msg`/`turn_start`/`turn_complete`/
//!   `caller`/`participant`/either receipt kind this fold reads.
//! - `input_tokens`/`output_tokens`: additive, applied only above the
//!   high-water mark, and — matching `compute_stats` exactly — summed over
//!   *every* `usage` event, committed or not.
//! - `summary_text`: last-wins over every `summary` event's non-empty text,
//!   also uncommitted-inclusive (matches `compute_stats`; a `summary` append
//!   runs before its `persist_turn`, so gating this on commit would make the
//!   projection lag the existing endpoint, not just this one).
//! - `edges`/`settlements`: unconditional, uncommitted-inclusive accumulation
//!   (matches the pre-#1585 `conversation_edges`/`conversation_spend` exactly
//!   — neither gated on commit). `settlements` keeps the two directions in
//!   SEPARATE totals per `subject` ([`DashboardSettlement`]) rather than
//!   summing them: an outbound receipt is money leaving a caller's own
//!   delegated wallet (their cost), an inbound one is money arriving in this
//!   deployment's recipient account (its revenue), and they are not even
//!   denominated in the same asset label. The two kinds also store DIFFERENT
//!   units in the same `amount` string, so each is read through its own
//!   [`polyc_payments::amount`] reader before it reaches its own base-unit
//!   total, and a receipt whose amount cannot be read is counted and logged
//!   rather than skipped in silence (#1739). This is deliberately a different
//!   failure policy from the `usage` fold above, which counts an undecodable
//!   payload as zero: a zero token count is a net-zero contribution, a
//!   dropped settlement is missing money.
//! - `committed_turns`/`last_turn_id`/`created_at_ms`/`last_activity_ms`/
//!   `persona_id`/`first_message_preview`: resolved once per turn, at the
//!   instant that turn's `turn_start` AND `turn_complete` are BOTH observed
//!   (see `TrackedRow::commit_turn`). `persona_id`/`created_at_ms`/
//!   `first_message_preview` each keep the FIRST committed turn that
//!   actually carries a value, not literally the conversation's first
//!   committed turn — a turn without its own `caller` event (#1512), nonzero
//!   dispatch clock, or user message must not permanently blank the field
//!   when a later committed turn actually has one. `last_activity_ms` uses **max**
//!   across every committed turn's own dispatch clock — the design record's
//!   specified rule — which is a deliberate, documented divergence from
//!   `compute_stats`' literal "last committed turn's own clock, `None` if
//!   that one is zero/absent" behavior: under the real invariant that a
//!   conversation runs one turn at a time and dispatch clocks are
//!   non-decreasing, the two agree on every partition except the vanishingly
//!   rare one where the LAST committed turn's own clock is absent while an
//!   earlier one had a valid clock (`compute_stats` would regress to `None`
//!   there; this projection keeps the earlier, valid value — never regressing
//!   on redelivery is the more useful behavior for a live-maintained row).
//!
//! # Documented staleness: post-commit corrections
//!
//! `persona_id`/`created_at_ms` are resolved from whatever caller/clock state
//! a turn has accumulated AT THE MOMENT it commits, then frozen — an
//! attribution self-healing append that later corrects a turn's caller
//! (`grpc/attribution.rs`) after that turn already committed does not
//! retroactively patch an already-resolved `persona_id` here, unlike
//! `compute_stats`, which recomputes from a fresh full replay every poll and
//! so always reflects the latest correction. This is the one accepted
//! staleness this design takes on in exchange for never re-replaying a
//! partition on every append: [`DashboardProjection::rebuild_from_full_fleet`]
//! (boot, then hourly) and the admin rebuild path
//! (`crates/control-plane/src/forensics.rs`'s `admin_rebuild_dashboard`) both
//! resolve it, since both replay from scratch.
//!
//! # Mutations
//!
//! A destroy, an excision, a repair, or a migration changes a partition's
//! durable content without producing a commit, so none of them reaches this
//! projection through the feed. They arrive instead from whoever issued the
//! command, after that command returned its receipt —
//! [`DashboardProjection::note_partition_change`], taking a [`PartitionChange`].
//!
//! [`PartitionChange::Destroyed`]/[`PartitionChange::MigratedAway`] remove the
//! row (cheap, no I/O). [`PartitionChange::Rewritten`] rebuilds that ONE
//! partition's row from a fresh replay: a rewrite hands this projection no new
//! content the way a commit does, so reconstructing it needs a replay.
//! `repair_partition`'s quarantine (`#799`) shrinks a partition's durable
//! content exactly like an excision's drop does — same treatment, same
//! reason: the quarantined events' contribution (to usage/messages/
//! attribution/whatever they carried) must come back out of the row, and
//! only a fresh replay recomputes that.
//!
//! An invalidation that never arrives is not a correctness gap either. A
//! destroyed partition leaves the fleet listing, and
//! [`DashboardProjection::rebuild_from_full_fleet`] prunes the rows of conversations the
//! fleet no longer holds; a rewritten one is replayed from scratch by that
//! same pass. The command-result path is what makes the correction prompt,
//! not what makes it happen.
//!
//! # Readiness contract (boot rebuild)
//!
//! Startup does not block process readiness on the full-fleet replay
//! completing — [`DashboardProjection::rebuild_status`] exposes an explicit
//! [`RebuildStatus`] so a consumer (C2's endpoint) can render "still
//! populating" truthfully instead of silently serving an incomplete or empty
//! row set as if it were exhaustive.
//!
//! **`RebuildStatus::Complete` is scoped to the full-fleet replay ONLY** —
//! it says nothing about an in-flight ONE-partition rebuild (the
//! `rewrite`/`migrate`-destination/`repair` mutation path, "Mutations"
//! above). A consumer can legitimately observe `Complete` while a specific
//! row is mid-repair and therefore still reflects pre-mutation content for a
//! few more milliseconds — the SAME bounded, self-healing staleness window
//! the "Mutations" section already names, restated here because
//! `RebuildStatus` is the one signal a caller might otherwise mistake for
//! "every row is exhaustively current right now," which it was never meant
//! to promise.

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};
use std::time::Instant;

use crate::journal::{JournalError, PartitionJournal};
use polyc_eventlog::Event;
use polyc_payments::amount::SettlementDirection;
use polyc_proto::events_decode::{decode_event_payload, try_decode_event_payload};
use polyc_proto::kinds;
use polyc_proto::proto::polychrome::agent::v1::Message;
use polyc_proto::proto::polychrome::events::v1::SummaryEvent;
use polyc_state::feed::FeedRecord;
use uuid::Uuid;

use crate::feed::{PartitionChange, commit_events};

/// Partition-name prefix identifying a conversation partition — matches
/// `crate::grpc::CONVERSATION_PARTITION_PREFIX`/`partition_for` in the
/// control plane (duplicated here rather than depended on: a Component
/// cannot depend on the Container that composes it).
const CONVERSATION_PARTITION_PREFIX: &str = "conv-";

/// Cap on [`DashboardRow::first_message_preview`], matching
/// `forensics::CONVERSATION_PREVIEW_BYTES` byte-for-byte so the projected
/// row renders identically to today's endpoint once C2 swaps it in.
const PREVIEW_BYTES: usize = 120;

/// One `subject`'s settled amounts within one conversation, kept apart by
/// settlement direction.
///
/// The projection's mirror of `crate::dashboard::PersonaSettlement` in the
/// control plane, kept as an independent type here per the layer rule: a
/// Component cannot name a Container's private type.
///
/// # Why two totals and not one
///
/// The two receipt kinds answer different questions, so they are never added
/// together here:
///
/// - an `outbound_payment_receipt` settles OUT of that caller's own delegated
///   wallet (`harness_dialer`'s payment path) — the caller's **cost**, and
///   what "spend" means;
/// - a `payment_receipt` settles INTO this deployment's own configured
///   recipient (`polyc_payments_server`'s inbound metering) — the
///   deployment's **revenue**, which no caller's spend column may absorb.
///
/// They are not even denominated in the same asset label (an inbound receipt's
/// `currency` is the settlement symbol, an outbound one's is the token
/// contract address), and their `subject` attribution differs too: an inbound
/// receipt's `subject` is empty for every receipt this control plane writes,
/// so inbound totals land under `"(unattributed)"`. An outbound receipt
/// written before persona attribution lands there as well — which is exactly
/// why the bucket needs two fields rather than one sum.
///
/// The two kinds also store different UNITS in the same `amount` string (see
/// [`polyc_payments::amount`]), so each is read with its own reader before it
/// reaches its own total below.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DashboardSettlement {
    /// The `subject` a receipt names, or `"(unattributed)"` when it names
    /// none — every inbound receipt, plus any outbound receipt written before
    /// persona attribution.
    pub persona: String,
    /// What settled OUT of this subject's delegated wallet (outbound
    /// receipts): their cost. In the settlement token's base units, the unit
    /// an outbound receipt already stores.
    pub spend_base_units: u128,
    /// What this subject was CHARGED by the deployment, and so what the
    /// deployment took in (inbound receipts). In the settlement token's base
    /// units, normalized from the receipt's stored decimal figure at the
    /// deployment's configured settlement scale
    /// ([`DashboardProjection::new`]'s `settlement_decimals`).
    pub charged_base_units: u128,
}

/// One conversation's maintained dashboard row.
///
/// The projection's mirror of `forensics::compute_stats`'s `Stats` type plus
/// the per-conversation edge and settlement rollups the pre-#1585
/// `api_dashboard` replay computed inline (`conversation_edges` /
/// `conversation_spend`, both deleted by that swap), enumerated
/// field-for-field against what `api_dashboard` emits today. Does NOT carry a resolved
/// persona display name: that resolution needs an async `PersonaHost::profile`
/// call per distinct initiator, batched across the whole fleet scan — exactly
/// as `api_dashboard` does it today — so it stays a read-time enrichment for
/// whichever endpoint (C2) ultimately serves this row, not a field this
/// write-side projection carries.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DashboardRow {
    /// The conversation id (the partition name with the `conv-` prefix
    /// stripped).
    pub conversation_id: String,
    /// Total events folded in so far, committed and dropped alike.
    pub total_events: usize,
    /// Fully-committed turns (`turn_start`/`turn_complete` pairs).
    pub committed_turns: usize,
    /// Running prompt-side token total, summed over every `usage` event
    /// (committed or not — see the module doc's merge rules).
    pub input_tokens: u64,
    /// Running completion-side token total, same scope as `input_tokens`.
    pub output_tokens: u64,
    /// The active anchored-iterative summary text, if any (last-wins over
    /// every non-empty `summary` event observed).
    pub summary_text: Option<String>,
    /// The most recently committed turn id, `as_simple` hex form.
    pub last_turn_id: Option<String>,
    /// Distinct edge providers observed as caller or participant, in
    /// first-seen order.
    pub edges: Vec<String>,
    /// This conversation's signature-verified, trusted-signer allow-listed
    /// settlements, summed by `subject` and kept apart by direction — see
    /// [`DashboardSettlement`] for why the two are never one number.
    pub settlements: Vec<DashboardSettlement>,
    /// Unix ms of the first committed turn with a nonzero captured dispatch
    /// clock. `None` when no committed turn has resolved one yet.
    pub created_at_ms: Option<u64>,
    /// The MAX captured dispatch clock across every committed turn (see the
    /// module doc's merge-rule note on why this is `max`, not "last").
    pub last_activity_ms: Option<u64>,
    /// The FIRST committed turn's initiator, unresolved (raw `caller`
    /// attribution id) — frozen at that turn's commit (see the module doc's
    /// "Documented staleness" section).
    pub persona_id: Option<String>,
    /// The first committed turn's first non-`internal_only` user message,
    /// truncated to `PREVIEW_BYTES`.
    pub first_message_preview: Option<String>,
}

impl DashboardRow {
    /// Whether an anchored-iterative summary is currently active — derived,
    /// never stored twice, from [`Self::summary_text`].
    #[must_use]
    pub const fn summary_active(&self) -> bool {
        self.summary_text.is_some()
    }
}

/// Per-turn accumulator, buffered until that turn's `turn_start` AND
/// `turn_complete` are both observed — see `TrackedRow::commit_turn`.
/// Removed from [`TrackedRow::turns`] once the turn commits (a turn that
/// never completes stays buffered indefinitely; see the module doc for why
/// that bounded, documented cost is accepted rather than solved here).
#[derive(Debug, Clone, Default)]
struct TurnAccum {
    /// `turn_start` observed for this turn id.
    started: bool,
    /// `turn_complete` observed for this turn id.
    completed: bool,
    /// Last-wins captured dispatch clock from this turn's own `model_call`
    /// event(s) — `Some(0)` is a real "no clock captured" value, filtered at
    /// the point of use, not here (matches `compute_stats`' own
    /// `clock_by_turn`).
    clock_ms: Option<u64>,
    /// Last-wins raw caller persona id, from this turn's own `caller`
    /// attribution event(s).
    caller_id: Option<String>,
    /// First non-`internal_only`, successfully-decoded `user_msg` text seen
    /// for this turn, already truncated to `PREVIEW_BYTES`.
    first_user_msg_preview: Option<String>,
}

/// One conversation's row plus the private bookkeeping
/// `TrackedRow::apply` needs to fold future deltas in correctly.
#[derive(Debug, Clone, Default)]
struct TrackedRow {
    /// The public, cloneable snapshot.
    row: DashboardRow,
    /// Highest journal position already folded into `row` — the idempotency
    /// high-water mark (see the module doc). `None` means nothing has been
    /// applied yet.
    applied_position: Option<u64>,
    /// Turns not yet committed (or committed-but-still-buffered this same
    /// call) — see [`TurnAccum`].
    turns: HashMap<Uuid, TurnAccum>,
}

impl TrackedRow {
    fn new(conversation_id: String) -> Self {
        Self {
            row: DashboardRow {
                conversation_id,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Fold `events` (each paired with its durable journal position) into
    /// this row, skipping any whose position is already covered by
    /// [`Self::applied_position`] — the idempotent-redelivery guard. A no-op
    /// if every position in `events` is already covered.
    fn apply<'a>(
        &mut self,
        events: impl IntoIterator<Item = (u64, &'a Event)>,
        trusted_signers: &[Vec<u8>],
        settlement_decimals: u32,
    ) {
        let new_events: Vec<(u64, &Event)> = events
            .into_iter()
            .filter(|(position, _)| self.applied_position.is_none_or(|hw| *position > hw))
            .collect();
        if new_events.is_empty() {
            return;
        }

        // The `polyc-facts` folds, batched over just the new slice —
        // unconditional on commit status, exactly matching `compute_stats`' own
        // `caller_by_turn` construction (see the module doc's merge rules).
        // Cloned once into an owned `Vec<Event>` since these folds want
        // `&[Event]`.
        let batch: Vec<Event> = new_events.iter().map(|(_, e)| (*e).clone()).collect();

        for fact in polyc_facts::attribution_events(&batch, polyc_facts::AttributionScope::Both) {
            let provider = fact.identity.map(|i| i.provider).unwrap_or_default();
            if !provider.is_empty() && !self.row.edges.contains(&provider) {
                self.row.edges.push(provider);
            }
        }
        for (turn, persona_id) in polyc_facts::caller_by_turn_last_wins(
            polyc_facts::attribution_events(&batch, polyc_facts::AttributionScope::CallerOnly),
        ) {
            self.turns.entry(turn).or_default().caller_id = Some(persona_id);
        }
        // BOTH directions, each read in ITS OWN unit AND kept in its own total
        // (#1739). The direction rides alongside each receipt rather than being
        // lost by chaining them into one anonymous stream, because it decides
        // two things: which `polyc_payments::amount` reader can read the stored
        // string (outbound stores base units, inbound a decimal figure), and
        // which of `DashboardSettlement`'s two totals the result belongs in
        // (outbound is the subject's cost, inbound is this deployment's
        // revenue — see that type's doc).
        let receipts = polyc_facts::verified_receipts(
            &batch,
            kinds::OUTBOUND_PAYMENT_RECEIPT,
            trusted_signers,
        )
        .map(|r| (SettlementDirection::Outbound, r))
        .chain(
            polyc_facts::verified_receipts(&batch, kinds::PAYMENT_RECEIPT, trusted_signers)
                .map(|r| (SettlementDirection::Inbound, r)),
        );
        for (direction, receipt) in receipts {
            let read = match direction {
                SettlementDirection::Outbound => {
                    polyc_payments::amount::read_base_unit_amount(&receipt.amount)
                }
                // The DEPLOYMENT's configured settlement scale, never a
                // hardcoded 6: `TEMPO_CURRENCY_DECIMALS` is real config
                // (`polyc_payments::config::PaymentsConfig::currency_decimals`)
                // that every other consumer of a stored dollar string already
                // threads, and reading against the wrong scale here would
                // produce a rollup wrong by a power of ten that PARSES — so
                // `polychrome_settlement_amount_unreadable_total` would never
                // see it.
                SettlementDirection::Inbound => {
                    polyc_payments::amount::read_dollar_amount(&receipt.amount, settlement_decimals)
                }
            };
            let amount = match read {
                Ok(amount) => amount,
                Err(error) => {
                    // Loud, never silent: this row is money that really
                    // settled but will not reach the totals a reader sees.
                    // One shared trailer (counter + `warn!`) across all three
                    // readers of a stored amount.
                    polyc_payments::amount::record_unreadable_amount(
                        &polyc_payments::amount::UnreadableAmount {
                            site: polyc_payments::amount::AmountReadSite::DashboardRollup,
                            direction,
                            error,
                            scope: &self.row.conversation_id,
                            reference: &receipt.reference,
                            tool_call_id: &receipt.tool_call_id,
                            approval_pos: &receipt.approval_pos,
                            subject: &receipt.subject,
                            timestamp: &receipt.timestamp,
                        },
                    );
                    continue;
                }
            };
            // An empty `subject` names no payer. Both directions can land
            // here — every inbound receipt this control plane writes carries
            // an empty subject, and so does an outbound receipt written
            // before persona attribution — which is why this bucket holds
            // two totals rather than one sum.
            let persona = if receipt.subject.is_empty() {
                "(unattributed)".to_owned()
            } else {
                receipt.subject
            };
            let entry = if let Some(existing) = self
                .row
                .settlements
                .iter_mut()
                .find(|s| s.persona == persona)
            {
                existing
            } else {
                self.row.settlements.push(DashboardSettlement {
                    persona,
                    spend_base_units: 0,
                    charged_base_units: 0,
                });
                self.row
                    .settlements
                    .last_mut()
                    .expect("just-pushed settlement row")
            };
            match direction {
                SettlementDirection::Outbound => {
                    entry.spend_base_units = entry.spend_base_units.saturating_add(amount);
                }
                SettlementDirection::Inbound => {
                    entry.charged_base_units = entry.charged_base_units.saturating_add(amount);
                }
            }
        }

        // Position-ordered single pass: total_events, usage/summary/
        // model_call accumulation, first-user-message buffering, and the
        // turn-commit fold.
        for (position, event) in &new_events {
            self.apply_one(*position, event);
            self.applied_position = Some(
                self.applied_position
                    .map_or(*position, |hw| hw.max(*position)),
            );
        }
    }

    /// Fold one already-new (position-checked by the caller) event in.
    fn apply_one(&mut self, position: u64, event: &Event) {
        let _ = position; // carried only for symmetry with the caller's loop.
        self.row.total_events += 1;
        let (base, turn_id) = kinds::parse(&event.kind);

        if base == kinds::USAGE {
            // Routed through the shared `polyc_facts::fold_usage_event` fold
            // (#1579) rather than a hand-rolled `try_decode_event_payload`
            // call — the same primitive `crate::decode::usage`'s typed table
            // and control-plane's own `decode_usage_payload` both decode
            // through. What a decode `Err` MEANS stays this row's own
            // policy, though, not the fold's (`fold_usage_event`'s own doc):
            // lenient, matching `forensics::decode_usage_payload` — a
            // non-empty payload that fails to decode counts as zero rather
            // than being skipped (net-zero contribution either way).
            let usage = polyc_facts::fold_usage_event(&event.payload).unwrap_or_default();
            // `saturating_add`, matching the settlement accumulation just
            // above: a plain `+=` panics on overflow in a debug build, and
            // since every row shares ONE lock, that panic (inside a write
            // guard) poisons every other conversation's row too — a single
            // bogus `usage` payload must never be able to do that.
            self.row.input_tokens = self.row.input_tokens.saturating_add(usage.input_tokens);
            self.row.output_tokens = self.row.output_tokens.saturating_add(usage.output_tokens);
        }

        if base == kinds::SUMMARY
            && let Ok(summary) = try_decode_event_payload::<SummaryEvent>(&event.payload)
            && !summary.text.is_empty()
        {
            self.row.summary_text = Some(summary.text);
        }

        if base == kinds::MODEL_CALL
            && let Some(id) = turn_id
            // Routed through the shared `polyc_facts::fold_model_call_event`
            // fold (#1579) — the same primitive `crate::decode::model_call`'s
            // typed table and control-plane's `decode_model_call_payload`
            // both decode through — rather than a hand-rolled
            // `try_decode_event_payload` call. A decode `Err` is skipped
            // here, same as before this change: this row only ever wanted
            // `captured_clock_unix_ms`, so there is no lenient/strict policy
            // choice to preserve the way `usage` has one.
            && let Ok(model_call) = polyc_facts::fold_model_call_event(&event.payload)
        {
            self.turns.entry(id).or_default().clock_ms = Some(model_call.captured_clock_unix_ms);
        }

        if base == kinds::USER_MSG
            && let Some(id) = turn_id
        {
            let accum = self.turns.entry(id).or_default();
            if accum.first_user_msg_preview.is_none()
                && let Some(msg) = decode_event_payload::<Message>(&event.payload)
                && !msg.internal_only
            {
                accum.first_user_msg_preview = Some(truncate_preview(&message_preview_text(&msg)));
            }
        }

        if base == kinds::TURN_START
            && let Some(id) = turn_id
        {
            let now_complete = {
                let accum = self.turns.entry(id).or_default();
                accum.started = true;
                accum.completed
            };
            if now_complete {
                self.commit_turn(id);
            }
        }

        if base == kinds::TURN_COMPLETE
            && let Some(id) = turn_id
        {
            let now_ready = {
                let accum = self.turns.entry(id).or_default();
                accum.completed = true;
                accum.started
            };
            if now_ready {
                self.commit_turn(id);
            }
        }
    }

    /// Fold a just-completed turn's buffered [`TurnAccum`] into the row and
    /// drop the buffer — see the module doc's merge rules and "Documented
    /// staleness" section for exactly what freezes here.
    fn commit_turn(&mut self, id: Uuid) {
        let Some(accum) = self.turns.remove(&id) else {
            return;
        };
        self.row.committed_turns += 1;
        self.row.last_turn_id = Some(id.as_simple().to_string());

        // `find_map`-shaped fallback, not "only the first committed turn
        // ever": a turn without its own `caller` event (the orphaned-dispatch
        // recovery path, #1511, is one real cause) must not permanently
        // blank `persona_id` when a LATER committed turn actually attributes
        // it (#1512) — mirrors `created_at_ms`'s own "if none, set" gate
        // immediately below.
        if self.row.persona_id.is_none()
            && let Some(caller_id) = &accum.caller_id
        {
            self.row.persona_id = Some(caller_id.clone());
        }
        if self.row.created_at_ms.is_none()
            && let Some(clock) = accum.clock_ms
            && clock != 0
        {
            self.row.created_at_ms = Some(clock);
        }
        if let Some(clock) = accum.clock_ms.filter(|&c| c != 0) {
            self.row.last_activity_ms = Some(
                self.row
                    .last_activity_ms
                    .map_or(clock, |prev| prev.max(clock)),
            );
        }
        if self.row.first_message_preview.is_none()
            && let Some(preview) = accum.first_user_msg_preview
        {
            self.row.first_message_preview = Some(preview);
        }
    }
}

/// Best-effort textual rendering of a decoded `user_msg`'s content block, for
/// [`DashboardRow::first_message_preview`] — a narrower mirror of
/// `forensics::wire_text`/`format_tool_call`/`format_tool_result`: a plain
/// text block renders verbatim; a tool-call/tool-result block (unusual for a
/// `user_msg` in practice — human turns are almost always plain text) renders
/// a short headline plus pretty-printed JSON, WITHOUT `forensics::wire_text`'s
/// `tool_result_lead` annotations or its 8 KiB intermediate cap — both are
/// moot here since [`truncate_preview`] already caps the final string to
/// `PREVIEW_BYTES`, two orders of magnitude smaller.
fn message_preview_text(msg: &Message) -> String {
    match polyc_facts::fold_message_content(msg, 0, None, "").content {
        polyc_facts::MessageContent::Text(t) => t.text,
        polyc_facts::MessageContent::ToolCall(c) => {
            let headline = if c.name.is_empty() {
                format!("tool · {}", c.tool_call_id)
            } else {
                format!("tool · {} · {}", c.name, c.tool_call_id)
            };
            format_tool_block(&headline, &c.arguments)
        }
        polyc_facts::MessageContent::ToolResult(r) => {
            let headline = if r.name.is_empty() {
                format!("result · {}", r.tool_call_id)
            } else {
                format!("result · {} · {}", r.name, r.tool_call_id)
            };
            format_tool_block(&headline, &r.result)
        }
        polyc_facts::MessageContent::None => String::new(),
    }
}

/// Append `value`'s pretty-printed JSON to `headline`, unless `value` is
/// null/an empty object/an empty array — mirrors
/// `forensics::format_tool_block`'s emptiness gate.
fn format_tool_block(headline: &str, value: &serde_json::Value) -> String {
    if value.is_null()
        || value.as_object().is_some_and(serde_json::Map::is_empty)
        || value.as_array().is_some_and(Vec::is_empty)
    {
        return headline.to_owned();
    }
    let pretty = serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string());
    format!("{headline}\n{pretty}")
}

/// Trim and cap `text` to `PREVIEW_BYTES`, appending an ellipsis when the
/// cap actually cut something — byte-for-byte the same policy as
/// `forensics::truncate_preview`.
fn truncate_preview(text: &str) -> String {
    let trimmed = text.trim();
    if trimmed.len() <= PREVIEW_BYTES {
        return trimmed.to_owned();
    }
    let mut end = PREVIEW_BYTES;
    while !trimmed.is_char_boundary(end) && end > 0 {
        end -= 1;
    }
    format!("{}", &trimmed[..end])
}

/// Conversation id named by `partition`, or `None` when `partition` is not a
/// conversation partition (a memory/audit/enrollment/etc. partition, which
/// this projection ignores entirely per the design record's scope).
fn conversation_id_from_partition(partition: &str) -> Option<String> {
    partition
        .strip_prefix(CONVERSATION_PARTITION_PREFIX)
        .filter(|id| !id.is_empty())
        .map(str::to_owned)
}

/// Merge one freshly-replayed `incoming` row for `id` into the live `rows`
/// map — the fix for #1632's severe review finding: a rebuild (full-fleet or
/// one-partition) races the SAME commit feed that keeps `rows`
/// current, so a blind replace/insert can silently regress a delta the
/// feed already applied during the rebuild's own replay window (a
/// permanent undercount, since nothing re-applies it later) or — for a
/// conversation whose partition didn't exist yet when
/// [`DashboardProjection::rebuild_from_full_fleet`] snapshotted the
/// partition list — delete a row outright with no path back.
///
/// This reuses the module's own idempotency principle
/// (`TrackedRow::applied_position` is the position high-water mark) rather
/// than inventing a second one: whichever of `incoming`/the current live row
/// has the HIGHER `applied_position` is further along and wins; a live row
/// for an id `incoming` doesn't name at all is left completely untouched —
/// there is nothing to compare it against, so it is never a candidate for
/// deletion here. Callers hold `rows`'s write lock for exactly this one
/// merge (see the call sites) so no third writer can interleave between the
/// comparison and the insert.
fn merge_row(rows: &mut HashMap<String, TrackedRow>, id: String, incoming: TrackedRow) {
    match rows.get(&id) {
        Some(live) if live.applied_position >= incoming.applied_position => {
            // The live row already reflects this position (or a later one a
            // concurrent append advanced it to) — keep it. Overwriting here
            // is exactly the regression #1632 found: `incoming` was replayed
            // from an older snapshot of the log.
        }
        _ => {
            rows.insert(id, incoming);
        }
    }
}

/// Whether [`DashboardProjection::rebuild_from_full_fleet`] has completed at
/// least once.
///
/// The readiness contract the module doc's "Readiness contract" section
/// describes: startup never blocks process readiness on this, so a consumer
/// needs an explicit signal rather than assuming an empty or partial row set
/// is exhaustive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RebuildStatus {
    /// No full-fleet rebuild has completed yet (one may be in flight).
    Pending,
    /// The most recent full-fleet rebuild's outcome.
    Complete {
        /// How many conversation partitions were folded in.
        conversation_count: usize,
        /// Wall-clock duration the replay + fold took, in milliseconds.
        duration_ms: u64,
    },
}

/// Outcome of one [`DashboardProjection::rebuild_from_full_fleet`] pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RebuildSummary {
    /// How many conversation partitions were folded in.
    pub conversation_count: usize,
    /// Wall-clock duration the replay + fold took, in milliseconds.
    pub duration_ms: u64,
}

/// The dashboard maintained projection — one [`DashboardRow`] per
/// conversation.
///
/// Kept current by [`DashboardProjection::apply_commits`] over the durable commit feed and
/// rebuildable wholesale via [`DashboardProjection::rebuild_from_full_fleet`] (boot, and the
/// periodic reconcile that makes a lost subscription a latency problem) or
/// `Self::rebuild_one_partition` (a rewrite this projection was told of). See the
/// module doc for the full ownership/feed/merge-rule contract.
///
/// No `Debug` derive: a [`PartitionJournal`] is not required to implement it.
pub struct DashboardProjection {
    /// Trusted-signer allow-list the settlement fold verifies receipts
    /// against — the same list the control plane holds for its own receipt
    /// reads (`ForensicsState::trusted_signers`).
    trusted_signers: Vec<Vec<u8>>,
    /// The settlement token's configured decimal scale, which an INBOUND
    /// receipt's stored dollar figure is read against (see the settlement
    /// fold in `TrackedRow::apply`). Held rather than resolved per read: it is
    /// deployment config the constructing Container already owns, and one
    /// value per process is exactly what keeps this rollup agreeing with
    /// every other consumer of a stored amount.
    settlement_decimals: u32,
    /// The partition journal this projection replays from on a rebuild. Held
    /// so [`DashboardProjection::note_partition_change`]'s rebuild (never
    /// awaited inline — see the module doc) has a handle without the caller
    /// re-supplying one per call.
    journal: Arc<dyn PartitionJournal>,
    /// One row per known conversation, keyed by conversation id.
    rows: RwLock<HashMap<String, TrackedRow>>,
    /// The most recent full-fleet rebuild's outcome.
    rebuild_status: RwLock<RebuildStatus>,
    /// Test-only deterministic race-injection point — see [`RaceHook`].
    /// Disarmed (a no-op) unless a test explicitly arms it; compiled out
    /// entirely in a non-test build.
    #[cfg(test)]
    race_hook: RaceHook,
}

/// Test-only deterministic rendezvous, used by
/// `tests::rebuild_never_loses_a_concurrent_delta_or_a_partition_created_after_the_snapshot`
/// to force #1632's exact race instead of relying on incidental scheduling:
/// [`DashboardProjection::rebuild_from_full_fleet`] pauses right after
/// snapshotting `fresh` and right before merging it into `self.rows` (see
/// that method's body) whenever a test has [`Self::arm`]ed the hook — a
/// no-op, disarmed by default, so this never blocks a real caller.
///
/// Two [`tokio::sync::Notify`]s, not one: `reached` lets the paused rebuild
/// tell the test it has arrived at the injection point (so
/// [`Self::wait_for_pause`] never races ahead of it), and `resume` lets the
/// test tell the paused rebuild to proceed once its own interleaved work is
/// durably applied. `Notify` buffers exactly one permit when `notify_one` is
/// called before the matching `notified().await` starts, so neither
/// direction depends on which side reaches its call first.
#[cfg(test)]
#[derive(Default)]
struct RaceHook {
    /// Whether the next `rebuild_from_full_fleet` call should pause at all.
    armed: std::sync::atomic::AtomicBool,
    /// Signalled by the rebuild once it reaches the injection point.
    reached: tokio::sync::Notify,
    /// Signalled by the test once its interleaved work is applied.
    resume: tokio::sync::Notify,
}

#[cfg(test)]
impl RaceHook {
    /// Arm the hook so the NEXT `rebuild_from_full_fleet` call pauses.
    fn arm(&self) {
        self.armed.store(true, std::sync::atomic::Ordering::SeqCst);
    }

    /// Block until a paused `rebuild_from_full_fleet` reaches the injection
    /// point. Only returns once it is safe to interleave work and know it
    /// lands strictly between that rebuild's snapshot and its merge.
    async fn wait_for_pause(&self) {
        self.reached.notified().await;
    }

    /// Let a paused `rebuild_from_full_fleet` proceed to the merge.
    fn resume(&self) {
        self.resume.notify_one();
    }

    /// Called from inside `rebuild_from_full_fleet`: a no-op unless
    /// [`Self::arm`] was called first, in which case this blocks until
    /// [`Self::resume`] is called.
    async fn pause_if_armed(&self) {
        if self.armed.load(std::sync::atomic::Ordering::SeqCst) {
            self.reached.notify_one();
            self.resume.notified().await;
        }
    }
}

/// Shared handle to a [`DashboardProjection`].
///
/// The query-owned cell the control plane mutates (constructs once, drives
/// from the commit feed, and calls the rebuild paths on), mirroring
/// [`crate::authority::PersonaCell`]'s role. See the module doc's
/// "Ownership" section for why the concrete wrapper type differs from
/// `PersonaCell`'s `ArcSwapOption`.
pub type DashboardCell = Arc<DashboardProjection>;

impl DashboardProjection {
    /// Construct an empty projection with no rows yet — a caller must run
    /// [`DashboardProjection::rebuild_from_full_fleet`] (and drive [`DashboardProjection::apply_commits`]
    /// from the same journal's commit feed) to populate it. `trusted_signers`
    /// and `journal` are the same values the control plane's own
    /// dashboard/spend code already holds (`ForensicsState::trusted_signers`,
    /// and the ONE partition journal this process reads).
    ///
    /// `settlement_decimals` is the deployment's configured settlement scale
    /// (`polyc_payments::config::PaymentsConfig::currency_decimals`, from
    /// `TEMPO_CURRENCY_DECIMALS`), passed in rather than read here because
    /// this Component never touches the process environment. It is required,
    /// not defaulted: an inbound receipt's stored dollar figure read against
    /// the wrong scale still parses, so a wrong scale would show a charged
    /// total off by a power of ten that no counter can catch.
    #[must_use]
    pub fn new(
        trusted_signers: Vec<Vec<u8>>,
        journal: Arc<dyn PartitionJournal>,
        settlement_decimals: u32,
    ) -> DashboardCell {
        Arc::new(Self {
            trusted_signers,
            settlement_decimals,
            journal,
            rows: RwLock::new(HashMap::new()),
            rebuild_status: RwLock::new(RebuildStatus::Pending),
            #[cfg(test)]
            race_hook: RaceHook::default(),
        })
    }

    /// This projection's most recent full-fleet rebuild outcome — the
    /// readiness signal described in the module doc.
    ///
    /// # Panics
    ///
    /// Panics if the internal rebuild-status lock is poisoned (a prior panic
    /// while it was held) — this cannot happen through this module's own
    /// code, since nothing here panics while holding it.
    #[must_use]
    pub fn rebuild_status(&self) -> RebuildStatus {
        *self.rebuild_status.read().expect("poison")
    }

    /// A snapshot of one conversation's row, or `None` if this projection has
    /// never observed that conversation.
    ///
    /// # Panics
    ///
    /// Panics if the internal row-map lock is poisoned (a prior panic while
    /// it was held) — this cannot happen through this module's own code,
    /// since nothing here panics while holding it.
    #[must_use]
    pub fn row(&self, conversation_id: &str) -> Option<DashboardRow> {
        self.rows
            .read()
            .expect("poison")
            .get(conversation_id)
            .map(|tracked| tracked.row.clone())
    }

    /// A snapshot of every row this projection currently holds, ordered by
    /// conversation id for a deterministic read.
    ///
    /// # Panics
    ///
    /// Panics if the internal row-map lock is poisoned (a prior panic while
    /// it was held) — this cannot happen through this module's own code,
    /// since nothing here panics while holding it.
    #[must_use]
    pub fn rows(&self) -> Vec<DashboardRow> {
        let mut rows: Vec<DashboardRow> = self
            .rows
            .read()
            .expect("poison")
            .values()
            .map(|tracked| tracked.row.clone())
            .collect();
        rows.sort_by(|a, b| a.conversation_id.cmp(&b.conversation_id));
        rows
    }

    /// Reports whether this projection has already folded `partition` through
    /// `position`.
    ///
    /// The question a follower asks before replaying a partition it has just
    /// started following: a boot rebuild may already have covered it, and
    /// replaying the fleet twice at every boot is the one way a per-partition
    /// bootstrap could cost more than the gap it closes.
    ///
    /// `position` is a PORT position, the same coordinate the rows are folded
    /// in under — not a State journal position, which counts from one. A
    /// caller holding one of those converts with
    /// [`crate::journal::port_position`] first; comparing the two directly is
    /// off by one, silently, in the direction that just replays more.
    ///
    /// False when no row exists, which is the case the bootstrap is for.
    ///
    /// # Panics
    ///
    /// Panics if the internal row-map lock is poisoned (a prior panic while
    /// it was held) — this cannot happen through this module's own code,
    /// since nothing here panics while holding it.
    #[must_use]
    pub fn covers(&self, partition: &str, position: u64) -> bool {
        let Some(id) = conversation_id_from_partition(partition) else {
            return false;
        };
        self.rows
            .read()
            .expect("poison")
            .get(&id)
            .and_then(|tracked| tracked.applied_position)
            .is_some_and(|applied| applied >= position)
    }

    /// Replay `partition` from the origin and fold it into this projection.
    ///
    /// Public for the one caller that cannot get the same result from the
    /// feed: a follower registering against a partition for the first time
    /// starts from a snapshot taken at the current head, so every commit that
    /// predates the registration is never delivered. Replaying here is what
    /// gives that partition a row at all.
    ///
    /// Merges rather than replaces, so a commit that lands mid-replay is not
    /// lost, on the same terms as every other replay this projection runs.
    ///
    /// # Errors
    ///
    /// Returns whatever the journal replay refused with. Unlike the background
    /// rebuilds, this one reports rather than logs: its caller is about to
    /// subscribe and acknowledge from a cursor that assumes the prefix landed,
    /// and doing that after a failed replay skips those commits for good.
    pub async fn bootstrap_partition(&self, partition: &str) -> Result<(), JournalError> {
        self.replay_one_partition(partition).await
    }

    /// Replay every conversation partition in the fleet and rebuild every row
    /// from scratch, MERGING the result into the current row set (see
    /// `merge_row`) rather than replacing it wholesale.
    ///
    /// The boot-time call (`polyc-control-plane`'s own startup) and the
    /// admin rebuild path (`forensics::admin_rebuild_dashboard`) both call
    /// this — see the module doc's "Documented staleness" section for why a
    /// wholesale re-derive is also the answer to any drift the incremental
    /// fold accumulates.
    ///
    /// Fails OPEN per partition (an unreadable partition contributes no row,
    /// exactly like `forensics::api_dashboard`'s own per-conversation replay
    /// failure handling) — the only propagated error is enumerating the
    /// partition list itself failing outright. Failing open covers the prune
    /// too: a partition this pass could not read leaves whatever row it
    /// already had exactly as it was, since a failed replay says nothing about
    /// whether the conversation still exists.
    ///
    /// This replay pass takes real time, during which the commit feed keeps
    /// applying live commits (and can even create rows for brand-new
    /// conversations this pass's own partition list never saw) — see
    /// `merge_row`'s doc for why the merge, not a
    /// blind swap, is what keeps that live activity from being silently
    /// undone (#1632).
    ///
    /// # Errors
    ///
    /// Returns the [`JournalError`] class listing partitions failed with.
    ///
    /// # Panics
    ///
    /// Panics if the internal row-map or rebuild-status lock is poisoned (a
    /// prior panic while it was held) — this cannot happen through this
    /// module's own code, since nothing here panics while holding either.
    pub async fn rebuild_from_full_fleet(&self) -> Result<RebuildSummary, JournalError> {
        let start = Instant::now();
        let partitions = self.journal.list_partitions().await?;
        // What every row had applied at the moment the listing was taken. A
        // row absent from the listing is a candidate for pruning, but only if
        // nothing advanced it meanwhile — see the prune below.
        let applied_at_listing: HashMap<String, Option<u64>> = self
            .rows
            .read()
            .expect("poison")
            .iter()
            .map(|(id, tracked)| (id.clone(), tracked.applied_position))
            .collect();
        let mut fresh: HashMap<String, TrackedRow> = HashMap::new();
        // Conversations the listing named but this pass could not read. Failing
        // open means this pass learned NOTHING about them, which is not the
        // same thing as learning they are gone — see the prune below.
        let mut unread: HashSet<String> = HashSet::new();
        let mut conversation_count = 0usize;
        for partition in partitions {
            let Some(id) = conversation_id_from_partition(&partition) else {
                continue;
            };
            let Ok(events) = self.journal.replay_with_positions(partition).await else {
                // Fail open per partition — matches every other replay-derived
                // fold in this codebase (usage_rollup, attribution, forensics).
                unread.insert(id);
                continue;
            };
            let mut tracked = TrackedRow::new(id.clone());
            tracked.apply(
                events.iter().map(|(position, event)| (*position, event)),
                &self.trusted_signers,
                self.settlement_decimals,
            );
            fresh.insert(id, tracked);
            conversation_count += 1;
        }

        // Test-only: deterministically pause here, between snapshotting
        // `fresh` and merging it in, so a test can interleave a live
        // `append_batch` — including one creating a brand-new conversation
        // the partition-list snapshot above never saw — exactly inside the
        // race #1632's review flagged. A no-op unless a test has armed it;
        // see `tests::RaceHook`.
        #[cfg(test)]
        self.race_hook.pause_if_armed().await;

        // Merge, never replace (#1632): `fresh` is a snapshot as of the
        // `list_partitions`/`replay_with_positions` calls above, and the
        // SAME commit feed that keeps `rows` live can advance a
        // row — or create a brand-new one this snapshot never saw — at any
        // point during this whole replay pass. `merge_row` keeps whichever
        // side is further along per conversation and never touches a live
        // row `fresh` has nothing to say about, so neither a concurrent
        // delta nor a just-created conversation can be lost to this rebuild.
        let pruned = {
            let mut rows = self.rows.write().expect("poison");
            for (id, tracked) in &fresh {
                merge_row(&mut rows, id.clone(), tracked.clone());
            }
            // Prune, which the merge above deliberately cannot do: a row for a
            // conversation the fleet no longer holds was destroyed or migrated
            // away, and this pass is what notices when no command result told
            // this projection so.
            //
            // A prune only ever deletes a row this pass POSITIVELY knows is
            // gone, which is the same fail-open contract the replay loop above
            // keeps: a partition whose replay failed is unread, not absent, so
            // it survives (a State restart fails many replays at once, and
            // pruning on that would empty the fleet's idle rows in one pass).
            // A row whose `applied_position` moved since the listing was taken
            // survives too, so a conversation created — or a partition
            // re-created — DURING this replay, which the listing could not have
            // named, is never pruned on the strength of a snapshot that
            // predates it.
            //
            // Deleting a live row here is not self-healing: the next commit
            // re-creates it at that commit's own position, and `merge_row`'s
            // position comparison then keeps that zeroed row over every later
            // rebuild's correct one until the process restarts.
            let before = rows.len();
            rows.retain(|id, tracked| {
                fresh.contains_key(id)
                    || unread.contains(id)
                    || applied_at_listing.get(id) != Some(&tracked.applied_position)
            });
            before - rows.len()
        };
        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
        *self.rebuild_status.write().expect("poison") = RebuildStatus::Complete {
            conversation_count,
            duration_ms,
        };
        tracing::info!(
            conversation_count,
            pruned,
            duration_ms,
            "dashboard projection rebuilt from a full-fleet replay"
        );
        Ok(RebuildSummary {
            conversation_count,
            duration_ms,
        })
    }

    /// Rebuild ONE partition's row from a fresh replay, MERGING it into
    /// whatever row (if any) currently exists for it — see `merge_row`'s
    /// doc. The `rewrite`/`migrate`-destination/`repair` mutation path (see
    /// [`DashboardProjection::note_partition_change`]) — a replay failure
    /// here is logged and leaves the existing row untouched (stale, not
    /// erased) rather than erroring, matching this codebase's
    /// fail-open-per-partition convention.
    ///
    /// One nested-race caveat `merge_row`'s position comparison does not
    /// resolve: `rewrite`/`repair` renumber a partition's surviving events
    /// from scratch (destroy + re-append), so if a SECOND such mutation
    /// raced this replay (mutation → spawn → ANOTHER mutation on the same
    /// partition completes → this replay finally runs), the position this
    /// task captured could be numerically LOWER than a stale pre-mutation
    /// live row's, and `merge_row` would wrongly keep the stale one. This is
    /// a narrower version of the same bounded, self-healing staleness the
    /// module doc's "Mutations" section already accepts for the ordinary
    /// (non-raced) case — the next full-fleet or admin rebuild corrects it —
    /// not a new correctness class.
    async fn rebuild_one_partition(&self, partition: &str) {
        if let Err(error) = self.replay_one_partition(partition).await {
            tracing::warn!(
                %error,
                partition,
                "dashboard projection: one-partition rebuild replay failed; the row stays stale \
                 until the next full-fleet rebuild"
            );
        }
    }

    /// Replays `partition` from the origin and folds it into this projection,
    /// reporting what the journal refused.
    ///
    /// The one implementation both replay paths share. Whether a failure is
    /// survivable is the CALLER's question, not this function's: a background
    /// rebuild logs and leaves the row stale, while a follower bootstrapping a
    /// prefix the feed will never deliver has to know, because subscribing
    /// after a failed replay would acknowledge past commits nothing applied.
    ///
    /// # Errors
    ///
    /// Returns whatever the journal replay refused with.
    async fn replay_one_partition(&self, partition: &str) -> Result<(), JournalError> {
        let Some(id) = conversation_id_from_partition(partition) else {
            return Ok(());
        };
        let events = self
            .journal
            .replay_with_positions(partition.to_owned())
            .await?;
        let mut tracked = TrackedRow::new(id.clone());
        tracked.apply(
            events.iter().map(|(position, event)| (*position, event)),
            &self.trusted_signers,
            self.settlement_decimals,
        );
        // Merge, not a blind insert (#1632) — same reasoning as
        // `rebuild_from_full_fleet`'s own fix: this replay takes real time,
        // and a live commit can land (and be applied via `apply_commits`)
        // before this task's own result is ready to merge in.
        merge_row(&mut self.rows.write().expect("poison"), id, tracked);
        Ok(())
    }

    /// Remove `partition`'s row entirely — the `destroy`/`migrate`-source
    /// mutation path, cheap and synchronous (no I/O).
    fn remove_row(&self, partition: &str) {
        if let Some(id) = conversation_id_from_partition(partition) {
            self.rows.write().expect("poison").remove(&id);
        }
    }

    /// Delta-apply one chunk of `partition`'s commit feed — the steady-state
    /// path, cheap, synchronous, in-memory only. The chunk already carries the
    /// durably-committed records and the positions they landed at, so no
    /// replay is needed.
    ///
    /// Safe to call with a chunk this projection already applied. Delivery is
    /// at-least-once, so a redelivery is expected rather than exceptional: the
    /// position high-water mark on each row drops every record at or below
    /// what it already folded in, leaving the row unchanged. A commit on a
    /// partition that is not a conversation is ignored.
    ///
    /// # Panics
    ///
    /// Panics if the internal row-map lock is poisoned (a prior panic while it
    /// was held) — this cannot happen through this module's own code, since
    /// nothing here panics while holding it.
    pub fn apply_commits(&self, partition: &str, commits: &[FeedRecord]) {
        let Some(id) = conversation_id_from_partition(partition) else {
            return;
        };
        let events = commit_events(commits);
        if events.is_empty() {
            return;
        }
        self.rows
            .write()
            .expect("poison")
            .entry(id.clone())
            .or_insert_with(|| TrackedRow::new(id))
            .apply(
                events.iter().map(|(position, event)| (*position, event)),
                &self.trusted_signers,
                self.settlement_decimals,
            );
    }

    /// Fold in a change the commit feed cannot report — see the module doc's
    /// "Mutations" section.
    ///
    /// The caller is whoever issued the mutating command, and it calls this
    /// only once that command returned its receipt: a request that has not
    /// earned one may never commit, and rebuilding against it would replace a
    /// correct row with a replay of a partition nothing changed.
    ///
    /// Idempotent for the same reason a redelivered chunk is harmless: a
    /// removal of a row that is already gone does nothing, and a rebuild
    /// re-derives the same row from the same journal.
    ///
    /// # Panics
    ///
    /// Panics if the internal row-map lock is poisoned (a prior panic while it
    /// was held) — this cannot happen through this module's own code, since
    /// nothing here panics while holding it.
    pub async fn note_partition_change(&self, partition: &str, change: PartitionChange) {
        match change {
            PartitionChange::Destroyed | PartitionChange::MigratedAway => {
                self.remove_row(partition);
            }
            PartitionChange::Rewritten => self.rebuild_one_partition(partition).await,
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use std::path::PathBuf;
    use std::sync::Arc;

    use buffa::Message as _;
    use polyc_crypto::approval::{ApprovalSigner, ReceiptPayload, receipt_payload};
    use polyc_eventlog::Event;
    use polyc_eventlog_host::EventLogHost;
    use polyc_proto::kinds;
    use polyc_proto::proto::polychrome::agent::v1::{
        Content, Message as WireMessage, TextContent, content,
    };
    use polyc_proto::proto::polychrome::events::v1::{
        AttributionEvent, ModelCallEvent, SummaryEvent, UsageEvent,
    };
    use polyc_proto::proto::polychrome::persona::v1::ExternalIdentity;
    use tokio_util::sync::CancellationToken;
    use uuid::Uuid;

    use super::*;

    /// Test-only `EventLogHost` fixture, mirroring `authority::tests::Fixture`'s
    /// own spawn/cleanup shape.
    struct Fixture {
        eventlog: Arc<EventLogHost>,
        shutdown: CancellationToken,
        dir: PathBuf,
        signer: ApprovalSigner,
    }

    impl Fixture {
        async fn build(test_name: &str) -> Self {
            let signer = ApprovalSigner::from_seed(7);
            let dir = std::env::temp_dir().join(format!(
                "polyc-query-dashboard-{test_name}-{}",
                std::process::id()
            ));
            let _ = std::fs::remove_dir_all(&dir);
            let shutdown = CancellationToken::new();
            let eventlog = Arc::new(
                EventLogHost::spawn(dir.clone(), shutdown.clone(), signer.relabel_for_test())
                    .expect("spawn eventlog host"),
            );
            Self {
                eventlog,
                shutdown,
                dir,
                signer,
            }
        }

        /// A fresh, unregistered `DashboardCell` sharing this fixture's own
        /// `eventlog` and trusted-signer allow-list, at the default
        /// settlement scale.
        fn dashboard(&self) -> DashboardCell {
            self.dashboard_at(polyc_payments::amount::DEFAULT_DECIMALS)
        }

        /// The same cell at an explicitly chosen settlement scale — what a
        /// deployment configuring `TEMPO_CURRENCY_DECIMALS` to anything but
        /// the default gets.
        fn dashboard_at(&self, settlement_decimals: u32) -> DashboardCell {
            DashboardProjection::new(
                vec![self.signer.public_key_bytes()],
                self.eventlog.clone(),
                settlement_decimals,
            )
        }

        /// Commit `events` to `partition` and hand `dashboard` the feed chunk
        /// a subscription would have carried for that commit — the test
        /// stand-in for a live `FeedSubscription`, so a test drives exactly
        /// what production drives.
        async fn commit_to(
            &self,
            dashboard: &DashboardCell,
            partition: &str,
            events: Vec<Event>,
        ) -> Vec<FeedRecord> {
            let positions = self
                .eventlog
                .append_batch(partition.to_owned(), events.clone())
                .await
                .expect("append");
            let chunk = vec![crate::feed::test_commit(partition, &events, &positions)];
            dashboard.apply_commits(partition, &chunk);
            chunk
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            self.shutdown.cancel();
            let _ = std::fs::remove_dir_all(&self.dir);
        }
    }

    fn text_message(role: &str, text: &str, internal_only: bool) -> Vec<u8> {
        WireMessage {
            role: role.to_owned(),
            content: buffa::MessageField::some(Content {
                r#type: Some(content::Type::Text(Box::new(TextContent {
                    text: text.to_owned(),
                    ..Default::default()
                }))),
                ..Default::default()
            }),
            internal_only,
            ..Default::default()
        }
        .encode_to_vec()
    }

    fn caller_payload(persona_id: &str, provider: &str) -> Vec<u8> {
        AttributionEvent {
            persona_id: persona_id.to_owned(),
            role: "initiator".to_owned(),
            identity: buffa::MessageField::some(ExternalIdentity {
                provider: provider.to_owned(),
                scope: "s".to_owned(),
                external_id: "u1".to_owned(),
                display_name: "A".to_owned(),
                ..Default::default()
            }),
            ..Default::default()
        }
        .encode_to_vec()
    }

    fn usage_payload(input_tokens: u64, output_tokens: u64) -> Vec<u8> {
        UsageEvent {
            input_tokens,
            output_tokens,
            ..Default::default()
        }
        .encode_to_vec()
    }

    fn model_call_payload(captured_clock_unix_ms: u64) -> Vec<u8> {
        ModelCallEvent {
            captured_clock_unix_ms,
            ..Default::default()
        }
        .encode_to_vec()
    }

    fn summary_payload(text: &str) -> Vec<u8> {
        SummaryEvent {
            text: text.to_owned(),
            covers_through_position: 0,
            ..Default::default()
        }
        .encode_to_vec()
    }

    /// A signed receipt of `kind`. The fold cross-checks the signed `kind`
    /// against the physical event kind, so a fixture must sign the same kind
    /// it is filed under.
    fn receipt_bytes_of_kind(
        signer: &ApprovalSigner,
        kind: &str,
        subject: &str,
        amount: &str,
    ) -> Vec<u8> {
        let (payload, _sig, _pk) = receipt_payload(
            &ReceiptPayload {
                kind,
                reference: "tx-1",
                amount,
                currency: "USDC",
                recipient: "0xrecipient",
                method: "tempo",
                timestamp: "2026-07-20T00:00:00Z",
                tool_call_id: "call-1",
                approval_pos: "1",
                approved_args_hash: "hash",
                subject,
                payer_kind: "linked_wallet",
                paying_account: "0xpayer",
            },
            signer,
        );
        payload
    }

    /// An OUTBOUND receipt: `amount` is in the token's base units (an integer
    /// string, or empty when the proxy could not capture the charge).
    fn receipt_bytes(signer: &ApprovalSigner, subject: &str, amount: &str) -> Vec<u8> {
        receipt_bytes_of_kind(signer, kinds::OUTBOUND_PAYMENT_RECEIPT, subject, amount)
    }

    /// An INBOUND receipt: `amount` is the per-call price as a decimal figure
    /// (`"0.01"`), and `subject` is empty in production — the public listener
    /// charges a caller by API key, not persona.
    fn inbound_receipt_bytes(signer: &ApprovalSigner, subject: &str, amount: &str) -> Vec<u8> {
        receipt_bytes_of_kind(signer, kinds::PAYMENT_RECEIPT, subject, amount)
    }

    /// The parity pin (task requirement #7): a projection folded from a
    /// seeded partition's events must equal what `forensics::compute_stats`
    /// plus the pre-#1585 inline edge/settlement rollups computed for the SAME
    /// events — pinning C2's future endpoint swap as behavior-preserving.
    /// Expected values below are hand-derived against that logic (this crate
    /// cannot depend on `polyc-control-plane` to call it directly — see the
    /// layer rule).
    #[tokio::test]
    async fn parity_row_matches_compute_stats_semantics_for_a_seeded_partition() {
        let fx = Fixture::build("parity").await;
        let dashboard = fx.dashboard();
        let partition = "conv-parity-1".to_owned();
        let turn = Uuid::now_v7();

        // Path 1: attribution self-healing-shaped append — a bare `caller`
        // event, its own batch, BEFORE the turn it attributes even starts.
        fx.eventlog
            .append_batch(
                partition.clone(),
                vec![Event::new(
                    kinds::tagged(kinds::CALLER, &turn),
                    caller_payload("persona-a", "web"),
                )],
            )
            .await
            .expect("append caller");

        // Path 2: a bare `summary` append — runs before `persist_turn`,
        // exactly as `grpc/summary.rs` does today.
        fx.eventlog
            .append_batch(
                partition.clone(),
                vec![Event::new(
                    kinds::SUMMARY,
                    summary_payload("condensed so far"),
                )],
            )
            .await
            .expect("append summary");

        // Path 3: the persist_turn-shaped atomic batch.
        fx.eventlog
            .append_batch(
                partition.clone(),
                vec![
                    Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                    Event::new(
                        kinds::tagged(kinds::USER_MSG, &turn),
                        text_message("user", "hello there", false),
                    ),
                    Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(10, 5)),
                    Event::new(
                        kinds::tagged(kinds::MODEL_CALL, &turn),
                        model_call_payload(1_700_000_000_000),
                    ),
                    Event::new(
                        kinds::tagged(kinds::OUTPUT_MSG, &turn),
                        text_message("model", "hi", false),
                    ),
                    Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
                ],
            )
            .await
            .expect("append persist_turn batch");

        // Path 4: settlement receipts, in the three shapes production
        // actually writes (#1739) — a captured outbound charge in base
        // units, an UNCAPTURED outbound charge with an empty amount, and an
        // inbound charge whose amount is the per-call price as a decimal
        // figure with no persona attribution.
        fx.eventlog
            .append_batch(
                partition.clone(),
                vec![
                    Event::new(
                        kinds::OUTBOUND_PAYMENT_RECEIPT,
                        receipt_bytes(&fx.signer, "persona-a", "1500"),
                    ),
                    Event::new(
                        kinds::OUTBOUND_PAYMENT_RECEIPT,
                        receipt_bytes(&fx.signer, "persona-a", ""),
                    ),
                    Event::new(
                        kinds::PAYMENT_RECEIPT,
                        inbound_receipt_bytes(&fx.signer, "", "0.01"),
                    ),
                ],
            )
            .await
            .expect("append receipts");

        dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");
        let row = dashboard.row("parity-1").expect("row exists");

        assert_eq!(
            row.total_events,
            // 11 real events (1 + 1 + 6 + 3) PLUS one `__mmr_signed_root__`
            // tamper-evidence marker per non-empty `append_batch` call (4
            // calls here) — `EventLogHost::append_batch` appends it after
            // the caller's own events on every commit
            // (`extend_mmr_and_append_signed_root`), and a REPLAY (what
            // `rebuild_from_full_fleet` uses) sees it, exactly like
            // `compute_stats`' own `events.len()` does (no kind-based
            // filtering exists for it there either) — so true parity means
            // counting it too, not filtering it out.
            11 + 4,
            "every appended event counts, including the host's own per-commit MMR marker \
             (matches compute_stats' unfiltered events.len())"
        );
        assert_eq!(row.committed_turns, 1);
        assert_eq!(row.input_tokens, 10);
        assert_eq!(row.output_tokens, 5);
        assert_eq!(row.summary_text.as_deref(), Some("condensed so far"));
        assert!(row.summary_active());
        assert_eq!(
            row.last_turn_id.as_deref(),
            Some(turn.as_simple().to_string().as_str())
        );
        assert_eq!(row.edges, vec!["web".to_owned()]);
        assert_eq!(
            row.settlements,
            vec![
                DashboardSettlement {
                    persona: "persona-a".to_owned(),
                    // The uncaptured (empty-amount) outbound receipt adds
                    // nothing — step 1 never invents an amount for it.
                    spend_base_units: 1500,
                    // This caller was never charged: the deployment's inbound
                    // revenue must not appear in their spend row.
                    charged_base_units: 0,
                },
                DashboardSettlement {
                    // The inbound charge: `"0.01"` at six decimals. It rolls
                    // up under the unattributed bucket because a production
                    // inbound receipt carries no `subject` — and it lands in
                    // `charged_base_units`, never in anyone's spend.
                    persona: "(unattributed)".to_owned(),
                    spend_base_units: 0,
                    charged_base_units: 10_000,
                },
            ]
        );
        assert_eq!(row.created_at_ms, Some(1_700_000_000_000));
        assert_eq!(row.last_activity_ms, Some(1_700_000_000_000));
        assert_eq!(row.persona_id.as_deref(), Some("persona-a"));
        assert_eq!(row.first_message_preview.as_deref(), Some("hello there"));
    }

    /// #1512: a conversation whose FIRST committed turn has no `caller`
    /// event (the orphaned-dispatch recovery case #1511 root-causes) must
    /// not freeze `persona_id` at `None` forever — a LATER committed turn's
    /// own attribution is the conversation's real initiator and must win.
    #[tokio::test]
    async fn persona_id_falls_back_to_a_later_committed_turns_caller() {
        let fx = Fixture::build("persona-fallback").await;
        let dashboard = fx.dashboard();
        let partition = "conv-persona-fallback".to_owned();
        let turn1 = Uuid::now_v7();
        let turn2 = Uuid::now_v7();

        // First committed turn: no `caller` event at all.
        fx.commit_to(
            &dashboard,
            &partition,
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn1), Vec::new()),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn1), Vec::new()),
            ],
        )
        .await;

        // Second committed turn: carries its own `caller` attribution.
        fx.commit_to(
            &dashboard,
            &partition,
            vec![
                Event::new(
                    kinds::tagged(kinds::CALLER, &turn2),
                    caller_payload("persona-a", "web"),
                ),
                Event::new(kinds::tagged(kinds::TURN_START, &turn2), Vec::new()),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn2), Vec::new()),
            ],
        )
        .await;

        let row = dashboard
            .row("persona-fallback")
            .expect("row exists after two committed turns");
        assert_eq!(row.committed_turns, 2);
        assert_eq!(
            row.persona_id.as_deref(),
            Some("persona-a"),
            "the first committed turn had no caller event; persona_id must fall back \
             to the second committed turn's own attribution instead of freezing at None"
        );

        // A conversation with NO caller anywhere in its committed turns
        // still reports `None` — never a fabricated id.
        let turn3 = Uuid::now_v7();
        let bare_partition = "conv-persona-fallback-bare".to_owned();
        fx.commit_to(
            &dashboard,
            &bare_partition,
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn3), Vec::new()),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn3), Vec::new()),
            ],
        )
        .await;
        let bare_row = dashboard
            .row("persona-fallback-bare")
            .expect("row exists after one committed turn");
        assert!(bare_row.persona_id.is_none());
    }

    /// #1739 bug 1: the settlement rollup reads each direction in ITS OWN
    /// unit, so a real inbound charge reaches a rendered total instead of
    /// being dropped by an integer parse it was never going to satisfy — and
    /// lands in the CHARGED total, not in any caller's spend.
    ///
    /// Inbound `payment_receipt` amounts are decimal price figures (`"0.01"`);
    /// outbound `outbound_payment_receipt` amounts are already base units.
    /// Reading both with one integer parse silently discarded every inbound
    /// receipt — all of the deployment's charged revenue — with no error and
    /// no counter, and every existing fixture used whole numbers, so the
    /// suite never saw it.
    #[tokio::test]
    async fn settlement_rollup_reads_each_direction_in_its_own_unit() {
        let fx = Fixture::build("units").await;
        let dashboard = fx.dashboard();
        let partition = "conv-units-1".to_owned();

        fx.eventlog
            .append_batch(
                partition.clone(),
                vec![
                    // Outbound: base units, captured.
                    Event::new(
                        kinds::OUTBOUND_PAYMENT_RECEIPT,
                        receipt_bytes(&fx.signer, "persona-a", "10000"),
                    ),
                    // Inbound: the per-call price, twice. Production shape:
                    // a decimal figure and an empty `subject`.
                    Event::new(
                        kinds::PAYMENT_RECEIPT,
                        inbound_receipt_bytes(&fx.signer, "", "0.01"),
                    ),
                    Event::new(
                        kinds::PAYMENT_RECEIPT,
                        inbound_receipt_bytes(&fx.signer, "", "0.25"),
                    ),
                ],
            )
            .await
            .expect("append receipts");

        dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");
        let row = dashboard.row("units-1").expect("row exists");

        assert_eq!(
            row.settlements,
            vec![
                DashboardSettlement {
                    persona: "persona-a".to_owned(),
                    spend_base_units: 10_000,
                    charged_base_units: 0,
                },
                DashboardSettlement {
                    persona: "(unattributed)".to_owned(),
                    spend_base_units: 0,
                    // 0.01 + 0.25 at six decimals = 10_000 + 250_000.
                    charged_base_units: 260_000,
                },
            ],
            "inbound decimal charges reach the rollup, normalized to base units, in the charged \
             total rather than added to the outbound caller's spend"
        );
    }

    /// The review finding this split exists for: the deployment's own inbound
    /// revenue must never be summed into a caller's spend, not even when both
    /// directions attribute to the SAME bucket.
    ///
    /// Every inbound receipt this control plane writes carries an empty
    /// `subject` (`grpc::mod`'s inbound receipt payload hardcodes it), and an
    /// outbound receipt written before persona attribution carries one too
    /// (`wallet_nav`'s own note), so `"(unattributed)"` genuinely holds both
    /// directions. One number for that bucket would report this deployment's
    /// takings as somebody's outlay.
    #[tokio::test]
    async fn one_bucket_holding_both_directions_keeps_them_apart() {
        let fx = Fixture::build("mixed").await;
        let dashboard = fx.dashboard();
        let partition = "conv-mixed-1".to_owned();

        fx.eventlog
            .append_batch(
                partition,
                vec![
                    // Outbound with no `subject` — the pre-attribution shape.
                    Event::new(
                        kinds::OUTBOUND_PAYMENT_RECEIPT,
                        receipt_bytes(&fx.signer, "", "10000"),
                    ),
                    // Inbound, which never carries a `subject`.
                    Event::new(
                        kinds::PAYMENT_RECEIPT,
                        inbound_receipt_bytes(&fx.signer, "", "0.5"),
                    ),
                ],
            )
            .await
            .expect("append receipts");

        dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");

        assert_eq!(
            dashboard.row("mixed-1").expect("row exists").settlements,
            vec![DashboardSettlement {
                persona: "(unattributed)".to_owned(),
                spend_base_units: 10_000,
                charged_base_units: 500_000,
            }],
            "one bucket, two totals: 510_000 would be a number describing nothing"
        );
    }

    /// The inbound read uses the DEPLOYMENT's configured settlement scale,
    /// not a hardcoded six.
    ///
    /// `TEMPO_CURRENCY_DECIMALS` is real, honored config
    /// (`polyc_payments::config::PaymentsConfig::currency_decimals`, bounded
    /// at 38) that every other consumer of a stored dollar string threads. A
    /// scale mismatch here is invisible to
    /// `polychrome_settlement_amount_unreadable_total`: `"0.01"` parses
    /// perfectly against either scale and simply lands a hundredfold off, so
    /// only comparing the two totals catches it.
    #[tokio::test]
    async fn the_inbound_rollup_scales_at_the_configured_settlement_decimals() {
        let fx = Fixture::build("decimals").await;
        let partition = "conv-decimals-1".to_owned();

        // ONE stored receipt, read twice: the journal is identical, so any
        // difference below is the configured scale and nothing else.
        fx.eventlog
            .append_batch(
                partition,
                vec![Event::new(
                    kinds::PAYMENT_RECEIPT,
                    inbound_receipt_bytes(&fx.signer, "", "0.01"),
                )],
            )
            .await
            .expect("append the inbound receipt");

        let at_default = fx.dashboard_at(polyc_payments::amount::DEFAULT_DECIMALS);
        at_default
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild at the default scale");
        assert_eq!(
            at_default
                .row("decimals-1")
                .expect("row exists")
                .settlements,
            vec![DashboardSettlement {
                persona: "(unattributed)".to_owned(),
                spend_base_units: 0,
                // 0.01 at six decimals.
                charged_base_units: 10_000,
            }],
            "the default scale reads 0.01 as 10_000 base units"
        );

        let at_eight = fx.dashboard_at(8);
        at_eight
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild at eight decimals");
        assert_eq!(
            at_eight.row("decimals-1").expect("row exists").settlements,
            vec![DashboardSettlement {
                persona: "(unattributed)".to_owned(),
                spend_base_units: 0,
                // 0.01 at eight decimals — a hundredfold apart from the same
                // stored string above.
                charged_base_units: 1_000_000,
            }],
            "a deployment configured at eight decimals scales the SAME stored amount at eight, \
             not at the default"
        );
    }

    /// #1739 bug 1, the loud half: a receipt whose recorded amount cannot be
    /// read is counted and logged, never skipped in silence.
    ///
    /// An uncaptured outbound charge (empty `amount`) and an inbound amount
    /// that is not a figure at all each land on their own labeled child of
    /// `polychrome_settlement_amount_unreadable_total`, so an operator can
    /// see money going unread without grepping logs.
    ///
    /// `#[traced_test]` pins that this call site passes its OWN
    /// `AmountReadSite`. The counter carries only `direction` and `reason`
    /// labels, so a copy-pasted variant leaves every count correct while the
    /// log line tells a reader the wrong thing was lost.
    #[tokio::test]
    #[tracing_test::traced_test]
    async fn an_unreadable_receipt_amount_is_counted_not_silently_skipped() {
        let fx = Fixture::build("unreadable").await;
        let dashboard = fx.dashboard();
        let partition = "conv-unreadable-1".to_owned();

        let absent_before = polyc_payments::amount::unreadable_amount_count(
            SettlementDirection::Outbound,
            polyc_payments::amount::AmountReadError::Absent,
        );
        let malformed_before = polyc_payments::amount::unreadable_amount_count(
            SettlementDirection::Inbound,
            polyc_payments::amount::AmountReadError::MalformedDollars,
        );

        fx.eventlog
            .append_batch(
                partition.clone(),
                vec![
                    // The uncaptured outbound charge: settled, no amount.
                    Event::new(
                        kinds::OUTBOUND_PAYMENT_RECEIPT,
                        receipt_bytes(&fx.signer, "persona-a", ""),
                    ),
                    // An inbound amount that is not a figure at all.
                    Event::new(
                        kinds::PAYMENT_RECEIPT,
                        inbound_receipt_bytes(&fx.signer, "", "not-a-number"),
                    ),
                ],
            )
            .await
            .expect("append receipts");

        dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");
        let row = dashboard.row("unreadable-1").expect("row exists");

        assert!(
            row.settlements.is_empty(),
            "no amount is invented for a receipt that recorded none"
        );
        assert_eq!(
            polyc_payments::amount::unreadable_amount_count(
                SettlementDirection::Outbound,
                polyc_payments::amount::AmountReadError::Absent,
            ) - absent_before,
            1,
            "the uncaptured outbound charge is counted"
        );
        assert_eq!(
            polyc_payments::amount::unreadable_amount_count(
                SettlementDirection::Inbound,
                polyc_payments::amount::AmountReadError::MalformedDollars,
            ) - malformed_before,
            1,
            "the unreadable inbound charge is counted"
        );
        assert!(
            logs_contain("below what really settled"),
            "this call site words the dashboard-rollup consequence"
        );
        assert!(
            !logs_contain("the reseeded budget is below actual spend"),
            "the committed-spend-floor consequence belongs to another call site"
        );
        assert!(
            !logs_contain("does not appear in their own history at all"),
            "the wallet-history consequence belongs to another call site"
        );
    }

    /// Task requirement: delta-apply from the commit feed across at least
    /// three DIFFERENT commit paths lands in the SAME cumulative row — a
    /// persist_turn-shaped batch, a bare summary append, and an
    /// approval-response append, each its own commit, none of them
    /// `persist_turn` itself.
    #[tokio::test]
    async fn feed_delta_applies_across_three_different_commit_paths() {
        let fx = Fixture::build("three-paths").await;
        let dashboard = fx.dashboard();
        let partition = "conv-three-paths".to_owned();
        let turn = Uuid::now_v7();

        // Path A: persist_turn-shaped batch.
        fx.commit_to(
            &dashboard,
            &partition,
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                Event::new(
                    kinds::tagged(kinds::USER_MSG, &turn),
                    text_message("user", "hi there", false),
                ),
                Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(3, 4)),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
            ],
        )
        .await;

        let after_a = dashboard
            .row("three-paths")
            .expect("row exists after path A");
        assert_eq!(after_a.committed_turns, 1);
        assert_eq!(after_a.input_tokens, 3);
        assert_eq!(after_a.total_events, 4);

        // Path B: a bare summary append — not `persist_turn`.
        fx.commit_to(
            &dashboard,
            &partition,
            vec![Event::new(kinds::SUMMARY, summary_payload("first summary"))],
        )
        .await;

        let after_b = dashboard
            .row("three-paths")
            .expect("row exists after path B");
        assert_eq!(after_b.summary_text.as_deref(), Some("first summary"));
        assert_eq!(after_b.total_events, 5, "the summary event also counts");
        assert_eq!(
            after_b.committed_turns, 1,
            "unaffected by the summary append"
        );

        // Path C: an approval-response append — not `persist_turn`, and not
        // a kind this projection derives any field FROM, but it must still
        // land as an event.
        let approval_chunk = fx
            .commit_to(
                &dashboard,
                &partition,
                vec![Event::new(
                    kinds::tagged(kinds::APPROVAL_RESPONSE, &turn),
                    Vec::new(),
                )],
            )
            .await;

        let after_c = dashboard
            .row("three-paths")
            .expect("row exists after path C");
        assert_eq!(after_c.total_events, 6, "the approval response also counts");
        assert_eq!(
            after_c.committed_turns, 1,
            "unaffected by the approval response"
        );
        assert_eq!(
            after_c.input_tokens, 3,
            "unaffected by the approval response"
        );

        // At-least-once delivery in practice: re-deliver the last chunk and
        // the row must not move at all.
        dashboard.apply_commits(&partition, &approval_chunk);
        assert_eq!(
            dashboard.row("three-paths").expect("row still exists"),
            after_c,
            "a redelivered chunk contributes nothing"
        );
    }

    /// Idempotent re-delivery: re-applying the SAME (position, event) pairs
    /// must not double-count anything — the position high-water mark is the
    /// idempotency key, not turn id.
    #[test]
    fn reapplying_the_same_positions_does_not_double_count() {
        let turn = Uuid::now_v7();
        let events = [
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
            Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(7, 2)),
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ];
        let positioned: Vec<(u64, &Event)> = events
            .iter()
            .enumerate()
            .map(|(i, e)| (i as u64, e))
            .collect();

        let mut tracked = TrackedRow::new("redelivery".to_owned());
        tracked.apply(
            positioned.iter().copied(),
            &[],
            polyc_payments::amount::DEFAULT_DECIMALS,
        );
        assert_eq!(tracked.row.total_events, 3);
        assert_eq!(tracked.row.input_tokens, 7);
        assert_eq!(tracked.row.committed_turns, 1);

        // Redeliver the exact same batch.
        tracked.apply(
            positioned.iter().copied(),
            &[],
            polyc_payments::amount::DEFAULT_DECIMALS,
        );
        assert_eq!(
            tracked.row.total_events, 3,
            "redelivery must not double-count events"
        );
        assert_eq!(
            tracked.row.input_tokens, 7,
            "redelivery must not double-count usage"
        );
        assert_eq!(
            tracked.row.committed_turns, 1,
            "redelivery must not double-count turns"
        );
    }

    /// Pins `apply_one`'s lenient corrupt-`usage`-payload policy across the
    /// #1579 refactor that routed it through the shared
    /// `polyc_facts::fold_usage_event` fold: a non-empty payload that fails
    /// to decode counts as zero tokens rather than being skipped outright
    /// (matches `forensics::decode_usage_payload` — see `apply_one`'s own
    /// doc comment on the `USAGE` branch).
    #[test]
    fn corrupt_usage_payload_counts_as_zero_tokens() {
        let turn = Uuid::now_v7();
        let events = [
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
            // Structurally invalid, non-empty payload — `fold_usage_event`
            // returns `Err` for this exact byte sequence (see
            // `polyc_facts::usage`'s own `garbage_bytes_return_an_error`
            // test).
            Event::new(kinds::tagged(kinds::USAGE, &turn), vec![0xFF, 0xFE, 0xFD]),
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ];
        let positioned: Vec<(u64, &Event)> = events
            .iter()
            .enumerate()
            .map(|(i, e)| (i as u64, e))
            .collect();

        let mut tracked = TrackedRow::new("corrupt-usage".to_owned());
        tracked.apply(
            positioned.iter().copied(),
            &[],
            polyc_payments::amount::DEFAULT_DECIMALS,
        );

        assert_eq!(
            tracked.row.total_events, 3,
            "a corrupt usage event still counts toward total_events"
        );
        assert_eq!(
            tracked.row.input_tokens, 0,
            "a corrupt usage payload contributes zero input tokens, not a skipped row"
        );
        assert_eq!(
            tracked.row.output_tokens, 0,
            "a corrupt usage payload contributes zero output tokens, not a skipped row"
        );
    }

    /// Pins the `saturating_add` accumulation `apply_one` uses for
    /// `input_tokens`/`output_tokens`: a token total already at `u64::MAX`
    /// must clamp rather than wrap or panic. A plain `+=` would panic on
    /// overflow in a debug build, and since every conversation's row shares
    /// ONE `RwLock`, that panic (inside a write guard) would poison every
    /// other row too — see `apply_one`'s own doc comment on the `USAGE`
    /// branch for why this property is load-bearing.
    #[test]
    fn usage_accumulation_saturates_at_the_boundary_instead_of_panicking() {
        let turn = Uuid::now_v7();
        let events = [
            Event::new(
                kinds::tagged(kinds::USAGE, &turn),
                usage_payload(u64::MAX, u64::MAX),
            ),
            Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(5, 5)),
        ];
        let positioned: Vec<(u64, &Event)> = events
            .iter()
            .enumerate()
            .map(|(i, e)| (i as u64, e))
            .collect();

        let mut tracked = TrackedRow::new("saturating".to_owned());
        // Must not panic even in a debug build.
        tracked.apply(
            positioned.iter().copied(),
            &[],
            polyc_payments::amount::DEFAULT_DECIMALS,
        );

        assert_eq!(tracked.row.input_tokens, u64::MAX);
        assert_eq!(tracked.row.output_tokens, u64::MAX);
    }

    /// Pins that `apply_one`'s `MODEL_CALL` branch, now routed through the
    /// shared `polyc_facts::fold_model_call_event` fold (#1579), keeps the
    /// same skip-on-decode-error behavior the raw `try_decode_event_payload`
    /// call had: a corrupt payload leaves `clock_ms` unset rather than
    /// panicking or substituting a default clock.
    #[test]
    fn corrupt_model_call_payload_is_skipped() {
        let turn = Uuid::now_v7();
        let events = [
            Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
            Event::new(
                kinds::tagged(kinds::MODEL_CALL, &turn),
                vec![0xFF, 0xFE, 0xFD],
            ),
            Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
        ];
        let positioned: Vec<(u64, &Event)> = events
            .iter()
            .enumerate()
            .map(|(i, e)| (i as u64, e))
            .collect();

        let mut tracked = TrackedRow::new("corrupt-model-call".to_owned());
        tracked.apply(
            positioned.iter().copied(),
            &[],
            polyc_payments::amount::DEFAULT_DECIMALS,
        );

        assert_eq!(tracked.row.committed_turns, 1);
        assert_eq!(
            tracked.row.last_activity_ms, None,
            "a corrupt model_call payload never resolves a dispatch clock for this turn"
        );
    }

    /// An excision must be reflected in the row: the dropped event's
    /// contribution is gone once the caller reports the change its command
    /// receipt confirmed.
    #[tokio::test]
    async fn a_reported_rewrite_rebuilds_the_row_with_erased_content_gone() {
        let fx = Fixture::build("rewrite").await;
        let dashboard = fx.dashboard();
        let partition = "conv-rewrite".to_owned();
        let turn = Uuid::now_v7();

        fx.commit_to(
            &dashboard,
            &partition,
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                Event::new(
                    kinds::tagged(kinds::USER_MSG, &turn),
                    text_message("user", "secret to erase", false),
                ),
                Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(9, 1)),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
            ],
        )
        .await;

        let before = dashboard.row("rewrite").expect("row exists before rewrite");
        assert_eq!(before.total_events, 4);
        assert_eq!(before.input_tokens, 9);
        assert_eq!(
            before.first_message_preview.as_deref(),
            Some("secret to erase")
        );

        // Erase the `usage` event's payload in place (#216/#860) — the
        // rewritten partition now has zero usage for this turn.
        fx.eventlog
            .rewrite_partition(
                partition,
                "test-dashboard-erase-usage".to_owned(),
                Box::new(|event: &Event| {
                    let (base, _) = kinds::parse(&event.kind);
                    if base == kinds::USAGE {
                        polyc_eventlog_host::RewriteDecision::Replace(usage_payload(0, 0))
                    } else {
                        polyc_eventlog_host::RewriteDecision::Keep
                    }
                }),
            )
            .await
            .expect("rewrite");

        // The caller reports the change its receipt confirmed — the one
        // notification the commit feed structurally cannot carry.
        dashboard
            .note_partition_change("conv-rewrite", PartitionChange::Rewritten)
            .await;

        {
            let row = dashboard.row("rewrite").expect("row still exists");
            assert_eq!(row.input_tokens, 0);
            assert_eq!(
                row.total_events,
                // 4 real events, plus ONE `__mmr_signed_root__` marker.
                // The host drops the marker `append_batch` wrote — it was
                // signed over the payload this rewrite replaces — and
                // signs one fresh root over the survivors, so a
                // post-rewrite REPLAY sees the 4 real events and one
                // marker, exactly as many records as before.
                5,
                "rewrite drops nothing here, only replaces — the partition is re-rooted rather \
                     than lengthened"
            );
        }
    }

    /// A `repair_partition` quarantine (`#799`) must trigger the SAME
    /// one-partition rebuild a rewrite does — the module doc's
    /// "Mutations" section commits to this. Mirrors
    /// `observer::tests::repair_bumps_the_epoch_and_notifies_when_it_quarantines_something`'s
    /// own corrupt-a-byte-on-disk setup (`crates/eventlog-host/src/observer.rs`):
    /// `repair_partition` detects and drops corrupted items itself — there is
    /// no caller-supplied decision closure like `rewrite_partition`'s — so a
    /// real quarantine needs genuine on-disk content corruption, not a
    /// `RewriteDecision`.
    #[tokio::test]
    async fn repair_partition_rebuilds_the_row_with_quarantined_content_gone() {
        let dir = std::env::temp_dir().join(format!(
            "polyc-query-dashboard-repair-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let signer = ApprovalSigner::from_seed(7);
        let partition = "conv-repair".to_owned();
        let marker = b"UNIQUE_QUARANTINE_MARKER".to_vec();

        // Write the corruptible content, then close the host — repair only
        // ever runs against a freshly (re)opened partition.
        {
            let shutdown = CancellationToken::new();
            let host = EventLogHost::spawn(dir.clone(), shutdown, signer.relabel_for_test())
                .expect("spawn");
            host.append_batch(
                partition.clone(),
                vec![
                    Event::new(kinds::TURN_START, Vec::new()),
                    // A deliberately non-buffa raw payload — repair's
                    // integrity check operates at the journal/section level,
                    // not the proto schema, exactly like the eventlog-host
                    // fixture this mirrors; our own decode of this event
                    // simply fails (and is skipped) either way.
                    Event::new(kinds::USER_MSG, marker.clone()),
                    Event::new(kinds::TURN_COMPLETE, Vec::new()),
                ],
            )
            .await
            .expect("append");
            drop(host);
        }

        // Flip a byte inside the marker payload on disk — a content tamper
        // `repair_partition` must detect and quarantine.
        let data_file = dir
            .join(format!("{partition}_data"))
            .join("0000000000000000");
        let mut bytes = std::fs::read(&data_file).expect("read section 0");
        let payload_at = bytes
            .windows(marker.len())
            .position(|w| w == marker.as_slice())
            .expect("the marker payload bytes are present on disk");
        bytes[payload_at] ^= 0xFF;
        std::fs::write(&data_file, &bytes).expect("write corrupted section 0");

        let shutdown2 = CancellationToken::new();
        let eventlog = Arc::new(
            EventLogHost::spawn(dir.clone(), shutdown2.clone(), signer.relabel_for_test())
                .expect("reopen"),
        );
        let dashboard = DashboardProjection::new(
            vec![signer.public_key_bytes()],
            eventlog.clone(),
            polyc_payments::amount::DEFAULT_DECIMALS,
        );
        // No seed rebuild: this fresh host has appended nothing yet through
        // this process, so the row does not exist — whatever populates it
        // below must be the reported repair's own rebuild, not a manual call
        // this test made.
        assert!(
            dashboard.row("repair").is_none(),
            "no row should exist before this projection has been told anything"
        );

        let quarantined = eventlog
            .repair_partition(partition.clone())
            .await
            .expect("repair completes");
        assert!(
            !quarantined.is_empty(),
            "the corrupted event must quarantine for this test to be meaningful"
        );

        // Ground truth: a direct replay AFTER repair, independent of the
        // dashboard entirely — the row this test polls for below must
        // eventually match it exactly. Not asserted against a hand-derived
        // count: a content tamper can invalidate more of the active section
        // than just the touched event (the eventlog-host fixture this
        // mirrors notes the same — "the WHOLE active section is invalidated,
        // not just the touched event"), so the precise surviving count isn't
        // this test's contract; that the dashboard eventually agrees with
        // reality is.
        // Not asserted `> 0`: this fixture's whole journal is one active
        // section, and a section-level integrity check can invalidate every
        // record in it once ANY one is tampered — including the untouched
        // `turn_start` that precedes the corrupted event — so `0` survivors
        // is a legitimate outcome here, not a test bug. What this test pins
        // is that the dashboard converges on whatever that ground truth
        // turns out to be, not a specific count.
        let ground_truth = eventlog
            .replay_with_positions(partition.clone())
            .await
            .expect("replay after repair");
        let expected_total_events = ground_truth.len();

        // A repair changes durable content in place, exactly like an
        // excision, so the caller reports it the same way once the command
        // returned.
        dashboard
            .note_partition_change(&partition, PartitionChange::Rewritten)
            .await;
        assert_eq!(
            dashboard
                .row("repair")
                .expect("the reported repair built the row")
                .total_events,
            expected_total_events,
            "the row agrees with a fresh replay of the repaired partition"
        );

        shutdown2.cancel();
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A reported destroy removes the row entirely (there is nothing left to
    /// replay), and reporting it twice is harmless.
    #[tokio::test]
    async fn a_reported_destroy_removes_the_row() {
        let fx = Fixture::build("destroy").await;
        let dashboard = fx.dashboard();
        let partition = "conv-destroy".to_owned();
        let turn = Uuid::now_v7();

        fx.commit_to(
            &dashboard,
            &partition,
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
            ],
        )
        .await;
        assert!(dashboard.row("destroy").is_some());

        fx.eventlog
            .destroy_partition(partition.clone())
            .await
            .expect("destroy");
        dashboard
            .note_partition_change(&partition, PartitionChange::Destroyed)
            .await;
        assert!(
            dashboard.row("destroy").is_none(),
            "a reported destroy removes the row"
        );

        dashboard
            .note_partition_change(&partition, PartitionChange::Destroyed)
            .await;
        assert!(
            dashboard.row("destroy").is_none(),
            "reporting the same destroy again is a no-op"
        );
    }

    /// The correctness fallback the reported-change path is only a latency
    /// improvement on: a partition is destroyed and NOTHING tells this
    /// projection, and the next full-fleet rebuild still prunes the row.
    #[tokio::test]
    async fn a_full_fleet_rebuild_prunes_a_row_no_notification_ever_reported() {
        let fx = Fixture::build("prune").await;
        let dashboard = fx.dashboard();
        let turn = Uuid::now_v7();

        for partition in ["conv-prune-gone", "conv-prune-kept"] {
            fx.commit_to(
                &dashboard,
                partition,
                vec![
                    Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                    Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
                ],
            )
            .await;
        }
        assert!(dashboard.row("prune-gone").is_some());

        fx.eventlog
            .destroy_partition("conv-prune-gone".to_owned())
            .await
            .expect("destroy");
        // Deliberately no `note_partition_change`: this is the case where the
        // invalidation was lost, the subscription died, or nobody was there
        // to hear the receipt.

        dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");

        assert!(
            dashboard.row("prune-gone").is_none(),
            "the reconcile prunes a conversation the fleet no longer holds"
        );
        assert!(
            dashboard.row("prune-kept").is_some(),
            "a conversation the fleet still holds is never pruned"
        );
    }

    /// A journal that answers exactly like the host behind it, except that
    /// every replay of a partition named in `unreadable` fails — the shape a
    /// State restart gives a rebuild that is already past its partition
    /// listing. The partition is still listed, and the conversation is still
    /// very much alive; only this pass's read of it did not land.
    struct FailingReplays {
        inner: Arc<EventLogHost>,
        unreadable: Vec<String>,
    }

    impl FailingReplays {
        fn refuses(&self, partition: &str) -> Option<JournalError> {
            self.unreadable
                .iter()
                .any(|p| p == partition)
                .then(|| JournalError::Unreachable("the state plane restarted mid-pass".to_owned()))
        }
    }

    #[async_trait::async_trait]
    impl PartitionJournal for FailingReplays {
        async fn partition_incarnation(
            &self,
            partition: String,
        ) -> Result<Option<polyc_state::revision::PartitionIncarnation>, JournalError> {
            if let Some(error) = self.refuses(&partition) {
                return Err(error);
            }
            PartitionJournal::partition_incarnation(self.inner.as_ref(), partition).await
        }

        async fn list_partitions(&self) -> Result<Vec<String>, JournalError> {
            PartitionJournal::list_partitions(self.inner.as_ref()).await
        }

        async fn partition_event_count(&self, partition: String) -> Result<u64, JournalError> {
            if let Some(error) = self.refuses(&partition) {
                return Err(error);
            }
            PartitionJournal::partition_event_count(self.inner.as_ref(), partition).await
        }

        async fn replay_with_positions(
            &self,
            partition: String,
        ) -> Result<Vec<(u64, Event)>, JournalError> {
            if let Some(error) = self.refuses(&partition) {
                return Err(error);
            }
            PartitionJournal::replay_with_positions(self.inner.as_ref(), partition).await
        }

        async fn replay_with_positions_bounded(
            &self,
            partition: String,
            max_bytes: u64,
        ) -> Result<polyc_eventlog::BoundedReplay, JournalError> {
            if let Some(error) = self.refuses(&partition) {
                return Err(error);
            }
            PartitionJournal::replay_with_positions_bounded(
                self.inner.as_ref(),
                partition,
                max_bytes,
            )
            .await
        }

        async fn replay_from_with_positions_bounded(
            &self,
            partition: String,
            start: u64,
            max_bytes: u64,
        ) -> Result<polyc_eventlog::BoundedReplay, JournalError> {
            if let Some(error) = self.refuses(&partition) {
                return Err(error);
            }
            PartitionJournal::replay_from_with_positions_bounded(
                self.inner.as_ref(),
                partition,
                start,
                max_bytes,
            )
            .await
        }

        async fn replay_range_with_positions_bounded(
            &self,
            partition: String,
            start: u64,
            end: u64,
            max_bytes: u64,
        ) -> Result<polyc_eventlog::BoundedReplay, JournalError> {
            if let Some(error) = self.refuses(&partition) {
                return Err(error);
            }
            PartitionJournal::replay_range_with_positions_bounded(
                self.inner.as_ref(),
                partition,
                start,
                end,
                max_bytes,
            )
            .await
        }

        async fn append_batch(
            &self,
            partition: String,
            events: Vec<Event>,
        ) -> Result<(), JournalError> {
            PartitionJournal::append_batch(self.inner.as_ref(), partition, events).await
        }

        fn is_stopping(&self) -> bool {
            PartitionJournal::is_stopping(self.inner.as_ref())
        }
    }

    /// The other half of the prune contract: a partition the listing NAMED but
    /// whose replay failed this pass keeps its row, counters and all.
    ///
    /// The prune's two conditions both read false for it — a failed
    /// replay contributes nothing to `fresh`, and an idle conversation's
    /// `applied_position` does not move during the pass — so without this
    /// handling it would be deleted for being unreadable rather than for
    /// being gone. In production
    /// the journal is one RPC client to the State plane, so a restart fails
    /// every in-flight replay at once and one hourly reconcile could empty the
    /// fleet's idle rows. Nor does it heal: the next commit re-creates a zeroed
    /// row at that commit's own position, and `merge_row` then keeps that row
    /// over every later rebuild's correct one until the process restarts.
    #[tokio::test]
    async fn a_full_fleet_rebuild_keeps_a_row_whose_replay_failed_this_pass() {
        let fx = Fixture::build("unread").await;
        let dashboard = DashboardProjection::new(
            vec![fx.signer.public_key_bytes()],
            Arc::new(FailingReplays {
                inner: fx.eventlog.clone(),
                // Alive, listed, idle — and unreadable for the length of this
                // pass.
                unreadable: vec!["conv-unread-quiet".to_owned()],
            }),
            polyc_payments::amount::DEFAULT_DECIMALS,
        );

        for (partition, tokens) in [("conv-unread-quiet", 13u64), ("conv-unread-readable", 4u64)] {
            let turn = Uuid::now_v7();
            fx.commit_to(
                &dashboard,
                partition,
                vec![
                    Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                    Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(tokens, 0)),
                    Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
                ],
            )
            .await;
        }
        let before = dashboard.row("unread-quiet").expect("row exists");
        assert_eq!(before.committed_turns, 1);
        assert_eq!(before.input_tokens, 13);

        // No commit lands on either conversation during this pass, so the
        // "its position moved" escape hatch cannot be what saves the row.
        let summary = dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");
        assert_eq!(
            summary.conversation_count, 1,
            "only the readable conversation was folded this pass"
        );

        assert_eq!(
            dashboard.row("unread-quiet").as_ref(),
            Some(&before),
            "a conversation this pass could not read keeps its row, counters intact — an \
             unreadable partition is not an absent one"
        );
        assert_eq!(
            dashboard
                .row("unread-readable")
                .expect("the readable row survives")
                .input_tokens,
            4
        );
    }

    /// Boot rebuild populates every conversation partition's row from one
    /// full-fleet replay, WITHOUT any observer ever having run — the boot
    /// path this projection uses when the control plane starts up against an
    /// already-populated event log.
    #[tokio::test]
    async fn boot_rebuild_populates_rows_for_every_partition() {
        let fx = Fixture::build("boot").await;
        let dashboard = fx.dashboard();
        // Deliberately NOT registering the observer: this exercises the
        // full-fleet replay path in isolation.

        for (id, tokens) in [("conv-boot-a", 5u64), ("conv-boot-b", 11u64)] {
            let turn = Uuid::now_v7();
            fx.eventlog
                .append_batch(
                    id.to_owned(),
                    vec![
                        Event::new(kinds::tagged(kinds::TURN_START, &turn), Vec::new()),
                        Event::new(kinds::tagged(kinds::USAGE, &turn), usage_payload(tokens, 0)),
                        Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn), Vec::new()),
                    ],
                )
                .await
                .expect("append");
        }
        // A non-conversation partition must be ignored entirely.
        fx.eventlog
            .append_batch(
                "audit-log".to_owned(),
                vec![Event::new("marker", Vec::new())],
            )
            .await
            .expect("append audit event");

        assert_eq!(dashboard.rebuild_status(), RebuildStatus::Pending);

        let summary = dashboard
            .rebuild_from_full_fleet()
            .await
            .expect("full-fleet rebuild");
        println!(
            "boot rebuild: {} conversation(s) in {} ms",
            summary.conversation_count, summary.duration_ms
        );
        assert_eq!(summary.conversation_count, 2);

        let a = dashboard.row("boot-a").expect("row a");
        assert_eq!(a.input_tokens, 5);
        assert_eq!(a.committed_turns, 1);
        let b = dashboard.row("boot-b").expect("row b");
        assert_eq!(b.input_tokens, 11);
        assert_eq!(b.committed_turns, 1);
        assert!(
            dashboard.row("audit-log").is_none() && dashboard.rows().len() == 2,
            "the non-conversation partition must never surface as a row"
        );

        assert_eq!(
            dashboard.rebuild_status(),
            RebuildStatus::Complete {
                conversation_count: 2,
                duration_ms: summary.duration_ms,
            }
        );
    }

    /// `rebuild_from_full_fleet` must never build `fresh` from a snapshot and
    /// then blindly `*self.rows.write() = fresh`: doing so would silently
    /// lose ANY delta the live commit feed applies during the replay window —
    /// both a NEW append on a conversation the snapshot already replayed
    /// (permanently undercounted, since nothing re-applies it) and an
    /// entirely NEW conversation created after the partition-list snapshot
    /// (deleted outright by the swap, no re-creation path). `merge_row`
    /// fixes this by keeping whichever side is further along per id and
    /// never touching a live-only row.
    ///
    /// Forced deterministically via [`RaceHook`] rather than left to
    /// incidental scheduling: the test spawns the rebuild, blocks on
    /// [`RaceHook::wait_for_pause`] until that rebuild has ALREADY
    /// snapshotted the partition list and replayed everything it saw (so
    /// `fresh` is fixed), interleaves two `append_batch` calls exactly in
    /// that window, then calls [`RaceHook::resume`] to let the merge run —
    /// so both assertions below exercise the exact race, every run, not
    /// "usually."
    #[tokio::test]
    async fn rebuild_never_loses_a_concurrent_delta_or_a_partition_created_after_the_snapshot() {
        let fx = Fixture::build("race").await;
        let dashboard = fx.dashboard();

        // One EXISTING conversation the partition-list snapshot will see
        // and this rebuild's own replay will capture.
        let turn1 = Uuid::now_v7();
        fx.commit_to(
            &dashboard,
            "conv-race-existing",
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn1), Vec::new()),
                Event::new(kinds::tagged(kinds::USAGE, &turn1), usage_payload(1, 1)),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn1), Vec::new()),
            ],
        )
        .await;

        dashboard.race_hook.arm();
        let rebuild_task = tokio::spawn({
            let dashboard = dashboard.clone();
            async move { dashboard.rebuild_from_full_fleet().await }
        });

        // Blocks until the spawned rebuild has snapshotted the partition
        // list and finished replaying every partition in it — i.e., it is
        // now paused immediately before merging `fresh` into `self.rows`.
        dashboard.race_hook.wait_for_pause().await;

        // Interleave #1: a NEW append on the conversation the rebuild's own
        // replay already captured — a delta the merge must not lose.
        let turn2 = Uuid::now_v7();
        fx.commit_to(
            &dashboard,
            "conv-race-existing",
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn2), Vec::new()),
                Event::new(kinds::tagged(kinds::USAGE, &turn2), usage_payload(9, 9)),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn2), Vec::new()),
            ],
        )
        .await;

        // Interleave #2: a BRAND-NEW conversation, created strictly after
        // the partition-list snapshot the paused rebuild took — a row the
        // merge must not delete.
        let turn3 = Uuid::now_v7();
        fx.commit_to(
            &dashboard,
            "conv-race-new",
            vec![
                Event::new(kinds::tagged(kinds::TURN_START, &turn3), Vec::new()),
                Event::new(kinds::tagged(kinds::USAGE, &turn3), usage_payload(5, 5)),
                Event::new(kinds::tagged(kinds::TURN_COMPLETE, &turn3), Vec::new()),
            ],
        )
        .await;

        dashboard.race_hook.resume();
        rebuild_task
            .await
            .expect("rebuild task did not panic")
            .expect("rebuild_from_full_fleet succeeds");

        let existing = dashboard
            .row("race-existing")
            .expect("the pre-existing row must survive the merge");
        assert_eq!(
            existing.committed_turns, 2,
            "the interleaved second turn on an already-replayed conversation must not be lost"
        );
        assert_eq!(existing.input_tokens, 1 + 9);

        let new_row = dashboard.row("race-new").expect(
            "a conversation created after the partition-list snapshot must survive the merge, \
             not be deleted by it",
        );
        assert_eq!(new_row.committed_turns, 1);
        assert_eq!(new_row.input_tokens, 5);
    }
}