armdb 0.14.1

sharded bitcask key-value storage optimized for NVMe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
use std::cell::Cell;
use std::collections::VecDeque;
use std::future::Future;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::ptr;
use std::sync::Arc;
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};

use seize::Guard;

use crate::sync::{Condvar, Mutex, cv_wait, cv_wait_timeout, lock};
use crate::tree_meta::CollectionMeta;
use crate::{DbResult, Key};

/// Marker traits used to prevent external collection implementations from
/// claiming watch support without forwarding the runtime channel.
pub(crate) mod sealed {
    pub trait Spec {}
    pub trait Enabled {}
}

/// Decode a raw watch payload on the receiving side.
pub trait WatchDecoder<T>: Send + Sync {
    /// Decode one stored value payload.
    fn decode(&self, bytes: &[u8]) -> DbResult<T>;
}

/// A watch decoder backed by the collection's [`crate::Codec`].
pub struct CodecWatchDecoder<C, T> {
    codec: C,
    _value: PhantomData<fn() -> T>,
}
impl<C: Clone, T> Clone for CodecWatchDecoder<C, T> {
    fn clone(&self) -> Self {
        Self {
            codec: self.codec.clone(),
            _value: PhantomData,
        }
    }
}
impl<C: crate::codec::Codec<T>, T> WatchDecoder<T> for CodecWatchDecoder<C, T> {
    fn decode(&self, bytes: &[u8]) -> DbResult<T> {
        self.codec.decode_from(bytes)
    }
}
impl<C, T> CodecWatchDecoder<C, T> {
    pub(crate) fn new(codec: C) -> Self {
        Self {
            codec,
            _value: PhantomData,
        }
    }
}

/// The collection identity and decoder used by a watch receiver.
pub trait WatchSpec: sealed::Spec {
    /// Collection key carried by each event.
    type Key: Key;
    /// Decoded collection value returned by [`WatchEvent`].
    type Value;
    /// Decoder bound to each receiver at subscription time.
    type Decoder: WatchDecoder<Self::Value> + Clone;
}

/// Runtime carrier that adds subscriptions around an existing collection hook.
pub struct WatchHook<T: CollectionMeta, H, const OLD: bool> {
    pub(crate) channel: Arc<WatchChannel<T::SelfId>>,
    pub inner: H,
}

impl<T: CollectionMeta, H> WatchHook<T, H, true> {
    /// Subscribe with both old and new values retained by future publishers.
    pub fn with_old(inner: H) -> Self {
        Self {
            channel: WatchChannel::new(),
            inner,
        }
    }
}

impl<T: CollectionMeta, H> WatchHook<T, H, false> {
    /// Subscribe with new values only; future updates are reported as upserts.
    pub fn new_only(inner: H) -> Self {
        Self {
            channel: WatchChannel::new(),
            inner,
        }
    }
}

impl<T: CollectionMeta, H, const OLD: bool> Drop for WatchHook<T, H, OLD> {
    fn drop(&mut self) {
        self.channel.close_terminal();
    }
}

impl<T, H, const OLD: bool> crate::hook::TypedWriteHook<T::SelfId, T> for WatchHook<T, H, OLD>
where
    T: CollectionMeta,
    H: crate::hook::TypedWriteHook<T::SelfId, T>,
{
    const WATCHES: bool = true;
    const NEEDS_OLD_VALUE: bool = OLD || H::NEEDS_OLD_VALUE;
    const NEEDS_INIT: bool = H::NEEDS_INIT;
    const NEEDS_WRITE: bool = H::NEEDS_WRITE;
    const EXPIRES: bool = H::EXPIRES;
    const TTL_REVISION: u32 = H::TTL_REVISION;
    const PROJECTS: bool = H::PROJECTS;
    const COUNTS: bool = H::COUNTS;
    const CLAIMS: bool = H::CLAIMS;
    #[cfg(feature = "armour")]
    const EMITS: bool = H::EMITS;

    fn watch_channel(&self) -> Option<&Arc<WatchChannel<T::SelfId>>> {
        Some(&self.channel)
    }
    fn watch_old(&self) -> bool {
        OLD
    }
    fn deadline(&self, key: &T::SelfId, value: &T) -> Option<u64> {
        self.inner.deadline(key, value)
    }
    fn on_write(&self, key: &T::SelfId, old: Option<&T>, new: Option<&T>) {
        self.inner.on_write(key, old, new)
    }
    fn on_init(&self, key: &T::SelfId, value: &T) {
        self.inner.on_init(key, value)
    }
    fn project(
        &self,
        key: &T::SelfId,
        value: &T,
        sink: &mut crate::projection::ProjectionSink<'_>,
    ) -> DbResult<()> {
        self.inner.project(key, value, sink)
    }
    fn projection_targets(&self) -> Option<&crate::projection::IndexTargets> {
        self.inner.projection_targets()
    }
    fn projection_limits(&self) -> (usize, usize) {
        self.inner.projection_limits()
    }
    fn counter_project(
        &self,
        key: &T::SelfId,
        value: &T,
        sink: &mut crate::counter::CounterSink<'_>,
    ) -> DbResult<()> {
        self.inner.counter_project(key, value, sink)
    }
    fn counter_targets(&self) -> Option<&crate::counter::CounterTargets> {
        self.inner.counter_targets()
    }
    fn claim_project(
        &self,
        key: &T::SelfId,
        value: &T,
        sink: &mut crate::unique::ClaimSink<'_>,
    ) -> DbResult<()> {
        self.inner.claim_project(key, value, sink)
    }
    fn claim_targets(&self) -> Option<&crate::unique::UniqueTargets> {
        self.inner.claim_targets()
    }
    #[cfg(feature = "armour")]
    fn stream_project(
        &self,
        key: &T::SelfId,
        old: Option<&T>,
        new: Option<&T>,
        sink: &mut crate::EmitSink<'_>,
    ) -> DbResult<()> {
        self.inner.stream_project(key, old, new, sink)
    }
    #[cfg(feature = "armour")]
    fn stream_targets(&self) -> Option<&crate::QueueTargets> {
        self.inner.stream_targets()
    }
}

impl<T, H, const OLD: bool> sealed::Enabled for WatchHook<T, H, OLD>
where
    T: CollectionMeta,
    H: crate::hook::TypedWriteHook<T::SelfId, T>,
{
}

impl<T, H> sealed::Enabled for crate::ttl::TtlHook<T, H>
where
    T: CollectionMeta,
    H: sealed::Enabled,
{
}

impl<K, T, H, E> sealed::Enabled for crate::projection::Projected<K, T, H, E> where
    H: sealed::Enabled
{
}

#[cfg(feature = "typed-tree")]
impl<K, T, H> sealed::Enabled for crate::hook::ZeroHookAdapter<K, T, H> where H: sealed::Enabled {}

#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
impl<K, T, C, H> sealed::Enabled for crate::hook::VarTypedHookAdapter<K, T, C, H> where
    H: sealed::Enabled
{
}

/// Decoder for fixed-size zero-copy collection values.
pub struct ZeroWatchDecoder<T>(PhantomData<fn() -> T>);

impl<T> Clone for ZeroWatchDecoder<T> {
    fn clone(&self) -> Self {
        Self(PhantomData)
    }
}
impl<T> ZeroWatchDecoder<T> {
    pub(crate) fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: Copy + zerocopy::FromBytes> WatchDecoder<T> for ZeroWatchDecoder<T> {
    fn decode(&self, bytes: &[u8]) -> DbResult<T> {
        zerocopy::FromBytes::read_from_bytes(bytes)
            .map_err(|_| crate::error::DbError::CorruptedEntry { offset: 0 })
    }
}

/// Delivery detail available from a raw mutation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WatchKind {
    /// The key was previously absent and now has a value with old-value mode.
    Insert,
    /// The key's old and new values are both retained.
    Update,
    /// A value is present but no old value was retained.
    Upsert,
    /// The key was removed.
    Delete,
}

/// Receiver outcomes that are not decoded-value errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WatchError {
    /// The receiver ring is currently empty.
    Empty,
    /// A timed receive reached its deadline without an event.
    Timeout,
    /// The receiver fell behind and lost this many events.
    Lagged(u64),
    /// The collection's terminal owner was dropped or shut down.
    Closed,
}

/// Per-subscription bounded-ring configuration.
#[derive(Clone, Copy, Debug)]
pub struct WatchOptions {
    /// Per-receiver ring capacity.  A full ring reports [`WatchError::Lagged`].
    pub capacity: NonZeroUsize,
}

impl Default for WatchOptions {
    fn default() -> Self {
        Self {
            capacity: NonZeroUsize::new(1024).expect("1024 is non-zero"),
        }
    }
}

/// A decoded view of one shared raw watch event.
pub struct WatchEvent<S: WatchSpec> {
    inner: Arc<WatchEventInner<S::Key>>,
    decoder: S::Decoder,
    _spec: PhantomData<fn() -> S>,
}

impl<S: WatchSpec> std::fmt::Debug for WatchEvent<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WatchEvent")
            .field("kind", &self.kind())
            .finish_non_exhaustive()
    }
}

impl<S: WatchSpec> PartialEq for WatchEvent<S> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl<S: WatchSpec> Eq for WatchEvent<S> {}

impl<S: WatchSpec> WatchEvent<S> {
    /// Event key.
    pub fn key(&self) -> &S::Key {
        &self.inner.key
    }

    /// Event kind derived from the retained old/new payloads.
    pub fn kind(&self) -> WatchKind {
        self.inner.kind
    }

    #[allow(clippy::new_ret_no_self, clippy::wrong_self_convention)]
    /// Decode the new value, when the mutation has one.
    pub fn new(&self) -> DbResult<Option<S::Value>> {
        self.inner
            .new
            .as_deref()
            .map(|bytes| self.decoder.decode(bytes))
            .transpose()
    }

    /// Decode the old value, when `with_old` retained one.
    pub fn old(&self) -> DbResult<Option<S::Value>> {
        self.inner
            .old
            .as_deref()
            .map(|bytes| self.decoder.decode(bytes))
            .transpose()
    }

    /// Borrow the stored bytes for the new value without decoding.
    pub fn new_bytes(&self) -> Option<&[u8]> {
        self.inner.new.as_deref()
    }

    /// Borrow the stored bytes for the old value without decoding.
    pub fn old_bytes(&self) -> Option<&[u8]> {
        self.inner.old.as_deref()
    }
}

pub(crate) struct WatchEventInner<K> {
    key: K,
    old: Option<Box<[u8]>>,
    new: Option<Box<[u8]>>,
    kind: WatchKind,
}

impl<K> WatchEventInner<K> {
    /// Only the test publish helper builds an event outside a mutation.
    #[cfg(test)]
    pub(crate) fn new(key: K, old: Option<Box<[u8]>>, new: Option<Box<[u8]>>) -> Self {
        let existed = old.is_some();
        Self::from_write(key, old, new, false, existed)
    }

    /// Build an event from a watched write.
    ///
    /// `retains_old` distinguishes an insertion observed in `with_old` mode
    /// from a new-only upsert. `old_existed` is a fact about the mutation, not
    /// about this event's payload: a row that was overwritten is an `Update`
    /// even when its previous bytes could not be materialized. Deriving the
    /// kind from `old.is_some()` instead would let a failed materialization
    /// silently report an `Insert` over a live row.
    pub(crate) fn from_write(
        key: K,
        old: Option<Box<[u8]>>,
        new: Option<Box<[u8]>>,
        retains_old: bool,
        old_existed: bool,
    ) -> Self {
        let kind = match (&new, retains_old, old_existed) {
            (Some(_), true, true) => WatchKind::Update,
            (Some(_), true, false) => WatchKind::Insert,
            (Some(_), false, _) => WatchKind::Upsert,
            (None, _, _) => WatchKind::Delete,
        };
        Self {
            key,
            old,
            new,
            kind,
        }
    }
}

/// Wakers taken under subscriber locks and invoked after the caller releases
/// every lock relevant to a mutation.
pub(crate) struct WatchWakeBatch {
    inline: [Option<Waker>; 4],
    used: usize,
    spill: Vec<Waker>,
}

impl Default for WatchWakeBatch {
    fn default() -> Self {
        Self {
            inline: std::array::from_fn(|_| None),
            used: 0,
            spill: Vec::new(),
        }
    }
}

impl WatchWakeBatch {
    pub(crate) fn extend(&mut self, other: Self) {
        for waker in other.inline.into_iter().take(other.used).flatten() {
            self.push(waker);
        }
        self.spill.extend(other.spill);
    }

    fn push(&mut self, waker: Waker) {
        if self.used < self.inline.len() {
            self.inline[self.used] = Some(waker);
            self.used += 1;
        } else {
            self.spill.push(waker);
        }
    }

    pub(crate) fn drain(mut self) {
        for waker in self.inline[..self.used].iter_mut().filter_map(Option::take) {
            waker.wake();
        }
        for waker in self.spill.drain(..) {
            waker.wake();
        }
    }
}

/// Shared bounded fan-out state owned by a [`WatchHook`].
pub struct WatchChannel<K: Key> {
    head: AtomicPtr<SubscriberNode<K>>,
    registry: Mutex<()>,
    collector: seize::Collector,
    subscribers: AtomicUsize,
    gate: ProducerPhases,
    #[cfg(test)]
    publish_pause: std::sync::Mutex<Option<test_support::ParkPause>>,
    #[cfg(test)]
    close_pause: std::sync::Mutex<Option<test_support::ParkPause>>,
    #[cfg(test)]
    traversal_pause: std::sync::Mutex<Option<test_support::ParkPause>>,
    #[cfg(test)]
    ctx_lock_pause: std::sync::Mutex<Option<test_support::ParkPause>>,
    #[cfg(test)]
    gate_pause: std::sync::Mutex<Option<test_support::ParkPause>>,
    #[cfg(test)]
    subscribe_pause: std::sync::Mutex<Option<test_support::ParkPause>>,
}

impl<K: Key> WatchChannel<K> {
    pub(crate) fn new() -> Arc<Self> {
        Arc::new(Self {
            head: AtomicPtr::new(ptr::null_mut()),
            registry: Mutex::new(()),
            collector: seize::Collector::new(),
            subscribers: AtomicUsize::new(0),
            gate: ProducerPhases::new(),
            #[cfg(test)]
            publish_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            close_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            traversal_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            ctx_lock_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            gate_pause: std::sync::Mutex::new(None),
            #[cfg(test)]
            subscribe_pause: std::sync::Mutex::new(None),
        })
    }

    /// Sample the subscriber gate. Callers must already hold a
    /// [`WatchProducer`]: the guard is what makes a `false` answer safe, by
    /// forcing a receiver that registers afterwards to wait for this producer
    /// to make its row visible (so the receiver's own scan covers it).
    pub(crate) fn has_subscribers(&self) -> bool {
        !self.gate.is_closed() && self.subscribers.load(Ordering::Acquire) != 0
    }

    /// Join the current producer phase. `None` once the channel is terminal.
    pub(crate) fn enter_producer(&self) -> Option<WatchProducer<'_>> {
        let phase = self.gate.enter()?;
        Some(WatchProducer {
            gate: Some((&self.gate, phase)),
            active: self.has_subscribers(),
        })
    }

    pub(crate) fn subscribe<S: WatchSpec<Key = K>>(
        self: &Arc<Self>,
        decoder: S::Decoder,
        options: WatchOptions,
    ) -> WatchReceiver<S> {
        let subscriber = Arc::new(Subscriber::new(options.capacity));
        if self.is_closed() {
            subscriber.close(&mut WatchWakeBatch::default());
            return WatchReceiver {
                subscriber,
                channel: Arc::clone(self),
                node: ptr::null_mut(),
                decoder,
                _spec: PhantomData,
            };
        }
        let node = Box::into_raw(Box::new(SubscriberNode {
            subscriber: Arc::clone(&subscriber),
            next: AtomicPtr::new(ptr::null_mut()),
        }));
        {
            let _registry = lock(&self.registry);
            if self.is_closed() {
                // SAFETY: the node was never published into the intrusive list.
                unsafe { drop(Box::from_raw(node)) };
                subscriber.close(&mut WatchWakeBatch::default());
                return WatchReceiver {
                    subscriber,
                    channel: Arc::clone(self),
                    node: ptr::null_mut(),
                    decoder,
                    _spec: PhantomData,
                };
            }
            // SAFETY: `node` is freshly allocated and not visible until the
            // following release store publishes it.
            unsafe {
                (*node)
                    .next
                    .store(self.head.load(Ordering::Relaxed), Ordering::Relaxed);
            }
            self.head.store(node, Ordering::Release);
            self.subscribers.fetch_add(1, Ordering::Release);
        }
        #[cfg(test)]
        test_support::wait_pause(&self.subscribe_pause);
        // Every producer that may still observe the pre-registration count has
        // to finish before `watch()` returns. Those producers publish nothing
        // to this receiver, so the caller's catch-up scan is what must cover
        // them — and a scan only covers a row that is already visible, which is
        // exactly what leaving the producer phase guarantees.
        self.gate.flip_and_drain();
        WatchReceiver {
            subscriber,
            channel: Arc::clone(self),
            node,
            decoder,
            _spec: PhantomData,
        }
    }

    /// Fan one event out to every linked subscriber.
    ///
    /// The caller must hold the [`WatchProducer`] it sampled the gate under —
    /// that guard, not a check here, is what orders publication against both a
    /// concurrent registration and a terminal close. An event built under the
    /// guard is still delivered while `close_terminal` waits, and the drain
    /// there is what gets it to the receiver before `Closed`.
    pub(crate) fn publish(&self, event: Arc<WatchEventInner<K>>, wakes: &mut WatchWakeBatch) {
        #[cfg(test)]
        test_support::wait_pause(&self.publish_pause);
        if self.subscribers.load(Ordering::Acquire) != 0 {
            let guard = self.collector.enter();
            let mut current = guard.protect(&self.head, Ordering::Acquire);
            while let Some(node) = unsafe { current.as_ref() } {
                #[cfg(test)]
                test_support::wait_pause(&self.traversal_pause);
                node.subscriber.push(Arc::clone(&event), wakes);
                current = guard.protect(&node.next, Ordering::Acquire);
            }
        }
    }

    /// Tell every subscriber that a mutation happened whose event could not be
    /// built. Delivery is at-most-once, but a loss is never silent: it is
    /// reported as the same `Lagged` gap a ring overflow produces, so the
    /// consumer's existing resync path covers it.
    pub(crate) fn publish_lost(&self, wakes: &mut WatchWakeBatch) {
        if self.subscribers.load(Ordering::Acquire) == 0 {
            return;
        }
        let guard = self.collector.enter();
        let mut current = guard.protect(&self.head, Ordering::Acquire);
        while let Some(node) = unsafe { current.as_ref() } {
            node.subscriber.record_gap(wakes);
            current = guard.protect(&node.next, Ordering::Acquire);
        }
    }

    pub(crate) fn close_terminal(&self) {
        if !self.gate.close() {
            return;
        }
        #[cfg(test)]
        test_support::wait_pause(&self.close_pause);
        self.gate.drain_all();
        let mut wakes = WatchWakeBatch::default();
        let _registry = lock(&self.registry);
        let guard = self.collector.enter();
        let mut current = guard.protect(&self.head, Ordering::Acquire);
        while let Some(node) = unsafe { current.as_ref() } {
            node.subscriber.close(&mut wakes);
            current = guard.protect(&node.next, Ordering::Acquire);
        }
        drop(guard);
        drop(_registry);
        wakes.drain();
    }

    fn is_closed(&self) -> bool {
        self.gate.is_closed()
    }

    fn unsubscribe(&self, node: *mut SubscriberNode<K>) {
        self.subscribers.fetch_sub(1, Ordering::Release);
        let _registry = lock(&self.registry);
        let mut link = &self.head;
        loop {
            let current = link.load(Ordering::Acquire);
            if current.is_null() {
                return;
            }
            if current == node {
                // SAFETY: registry mutations are serialized; `current` remains
                // linked until this release store makes it unreachable.
                let next = unsafe { (*current).next.load(Ordering::Acquire) };
                link.store(next, Ordering::Release);
                // SAFETY: the node is unlinked and producer traversals protect
                // every pointer load with this collector.
                unsafe {
                    self.collector
                        .retire(current, seize::reclaim::boxed::<SubscriberNode<K>>);
                }
                return;
            }
            // SAFETY: a linked node cannot be retired while registry lock is held.
            link = unsafe { &(*current).next };
        }
    }
}

const CLOSED: usize = 1usize << (usize::BITS - 1);
const PHASE: usize = 1;

/// Producer-participation gate.
///
/// A producer samples the subscriber count *before* it makes its row visible,
/// so a bare count cannot be trusted on its own: a receiver registering between
/// that sample and the mutation would find the row in neither the stream (the
/// producer decided not to publish) nor its own catch-up scan (the row was not
/// visible yet). The gate closes that window by making the receiver wait for
/// those producers to finish.
///
/// Waiting on a single in-flight counter would starve under continuous writes,
/// so participation is split across two phases. A registering receiver flips
/// the phase new producers join, then waits only for the phase it left behind —
/// a set that is fixed at the moment of the flip and therefore drains.
struct ProducerPhases {
    /// [`PHASE`] selects the phase new producers join; [`CLOSED`] is terminal.
    phase: AtomicUsize,
    counts: [AtomicUsize; 2],
}

impl ProducerPhases {
    fn new() -> Self {
        Self {
            phase: AtomicUsize::new(0),
            counts: [AtomicUsize::new(0), AtomicUsize::new(0)],
        }
    }

    fn is_closed(&self) -> bool {
        self.phase.load(Ordering::Acquire) & CLOSED != 0
    }

    /// Join the current phase, or fail once the channel is terminal.
    ///
    /// The re-check after the increment is what keeps "no push lands after
    /// close" true: `close` sets the flag and only then waits for the counts,
    /// so a producer that read the phase just before the flag must withdraw
    /// itself rather than rely on having been seen.
    fn enter(&self) -> Option<usize> {
        let observed = self.phase.load(Ordering::Acquire);
        if observed & CLOSED != 0 {
            return None;
        }
        let idx = observed & PHASE;
        self.counts[idx].fetch_add(1, Ordering::AcqRel);
        if self.is_closed() {
            self.counts[idx].fetch_sub(1, Ordering::Release);
            return None;
        }
        Some(idx)
    }

    fn leave(&self, idx: usize) {
        self.counts[idx].fetch_sub(1, Ordering::Release);
    }

    /// Send new producers to the other phase, then wait out this one.
    ///
    /// The flip is `AcqRel` and the caller published its registration with a
    /// `Release` store beforehand, so any producer that joins the new phase is
    /// guaranteed to observe that registration.
    fn flip_and_drain(&self) {
        let previous = self.phase.fetch_xor(PHASE, Ordering::AcqRel) & PHASE;
        while self.counts[previous].load(Ordering::Acquire) != 0 {
            std::thread::yield_now();
        }
    }

    /// Mark terminal. `false` when another caller already did.
    fn close(&self) -> bool {
        let mut observed = self.phase.load(Ordering::Acquire);
        loop {
            if observed & CLOSED != 0 {
                return false;
            }
            match self.phase.compare_exchange_weak(
                observed,
                observed | CLOSED,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return true,
                Err(seen) => observed = seen,
            }
        }
    }

    fn drain_all(&self) {
        while self.counts[0].load(Ordering::Acquire) != 0
            || self.counts[1].load(Ordering::Acquire) != 0
        {
            std::thread::yield_now();
        }
    }
}

/// Participation in a channel's current producer phase, held across a mutation.
///
/// Entered before the subscriber gate is sampled and dropped only after the
/// event has been published, so the interval covers the whole window in which a
/// stale `active == false` could otherwise lose a row. [`Self::inactive`] is the
/// branch-free form for a family that carries no watch.
pub(crate) struct WatchProducer<'a> {
    gate: Option<(&'a ProducerPhases, usize)>,
    active: bool,
}

impl WatchProducer<'_> {
    #[inline]
    pub(crate) fn inactive() -> Self {
        Self {
            gate: None,
            active: false,
        }
    }

    /// Whether a receiver was linked when this producer joined its phase.
    #[inline]
    pub(crate) fn active(&self) -> bool {
        self.active
    }
}

impl Drop for WatchProducer<'_> {
    #[inline]
    fn drop(&mut self) {
        if let Some((gate, idx)) = self.gate {
            gate.leave(idx);
        }
    }
}

thread_local! {
    static CONTEXT_ACTIVE: Cell<bool> = const { Cell::new(false) };
}

/// Whether the current context captured an active receiver at its producer
/// linearization point.  Collection internals use this only to avoid building
/// watch payloads; public callbacks must use their explicit wake path.
#[inline]
pub(crate) fn context_active() -> bool {
    CONTEXT_ACTIVE.with(Cell::get)
}

pub(crate) struct ContextActiveGuard(bool);

impl ContextActiveGuard {
    #[inline]
    pub(crate) fn set(active: bool) -> Self {
        Self(CONTEXT_ACTIVE.with(|state| state.replace(active)))
    }
}

impl Drop for ContextActiveGuard {
    fn drop(&mut self) {
        CONTEXT_ACTIVE.with(|state| state.set(self.0));
    }
}

struct SubscriberNode<K: Key> {
    subscriber: Arc<Subscriber<K>>,
    next: AtomicPtr<SubscriberNode<K>>,
}

struct Subscriber<K: Key> {
    state: Mutex<SubscriberState<K>>,
    changed: Condvar,
    capacity: usize,
}

struct SubscriberState<K: Key> {
    events: VecDeque<Arc<WatchEventInner<K>>>,
    lagged: u64,
    gap_at: Option<usize>,
    waker: Option<Waker>,
    terminal: bool,
}

impl<K: Key> Subscriber<K> {
    fn new(capacity: NonZeroUsize) -> Self {
        Self {
            state: Mutex::new(SubscriberState {
                events: VecDeque::with_capacity(capacity.get()),
                lagged: 0,
                gap_at: None,
                waker: None,
                terminal: false,
            }),
            changed: Condvar::new(),
            capacity: capacity.get(),
        }
    }

    fn push(&self, event: Arc<WatchEventInner<K>>, wakes: &mut WatchWakeBatch) {
        let mut state = lock(&self.state);
        if state.terminal {
            return;
        }
        if state.events.len() == self.capacity {
            let _ = state.events.pop_front();
            state.lagged = state.lagged.saturating_add(1);
            state.gap_at = Some(match state.gap_at {
                Some(gap_at) => gap_at.saturating_sub(1),
                None => 0,
            });
        }
        state.events.push_back(event);
        self.changed.notify_one();
        if let Some(waker) = state.waker.take() {
            wakes.push(waker);
        }
    }

    /// Record an event that was produced but could not be delivered.
    ///
    /// The gap belongs after everything already queued — that is where the loss
    /// happened — so the consumer drains what it has and only then sees
    /// `Lagged`. An earlier, still-unreported gap keeps its position.
    fn record_gap(&self, wakes: &mut WatchWakeBatch) {
        let mut state = lock(&self.state);
        if state.terminal {
            return;
        }
        state.lagged = state.lagged.saturating_add(1);
        let at = state.events.len();
        state.gap_at = Some(state.gap_at.map_or(at, |existing| existing.min(at)));
        self.changed.notify_one();
        if let Some(waker) = state.waker.take() {
            wakes.push(waker);
        }
    }

    fn close(&self, wakes: &mut WatchWakeBatch) {
        let mut state = lock(&self.state);
        state.terminal = true;
        self.changed.notify_all();
        if let Some(waker) = state.waker.take() {
            wakes.push(waker);
        }
    }
}

/// A single-consumer subscription receiver.
pub struct WatchReceiver<S: WatchSpec> {
    subscriber: Arc<Subscriber<S::Key>>,
    channel: Arc<WatchChannel<S::Key>>,
    node: *mut SubscriberNode<S::Key>,
    decoder: S::Decoder,
    _spec: PhantomData<fn() -> S>,
}

impl<S: WatchSpec> WatchReceiver<S> {
    pub(crate) fn subscribe(
        channel: &Arc<WatchChannel<S::Key>>,
        decoder: S::Decoder,
        options: WatchOptions,
    ) -> Self {
        channel.subscribe(decoder, options)
    }
}

impl<S: WatchSpec> WatchReceiver<S> {
    pub fn try_recv(&mut self) -> Result<WatchEvent<S>, WatchError> {
        let mut state = lock(&self.subscriber.state);
        Self::take_next(&mut state, &self.decoder).unwrap_or(Err(WatchError::Empty))
    }

    pub fn recv_blocking(&mut self) -> Result<WatchEvent<S>, WatchError> {
        loop {
            {
                let mut state = lock(&self.subscriber.state);
                if let Some(next) = Self::take_next(&mut state, &self.decoder) {
                    return next;
                }
            }
            before_condvar_park();
            let mut state = lock(&self.subscriber.state);
            if let Some(next) = Self::take_next(&mut state, &self.decoder) {
                return next;
            }
            drop(cv_wait(&self.subscriber.changed, state));
        }
    }

    pub fn recv_timeout(&mut self, timeout: Duration) -> Result<WatchEvent<S>, WatchError> {
        let deadline = Instant::now() + timeout;
        loop {
            {
                let mut state = lock(&self.subscriber.state);
                if let Some(next) = Self::take_next(&mut state, &self.decoder) {
                    return next;
                }
            }
            if Instant::now() >= deadline {
                return Err(WatchError::Timeout);
            }
            let mut state = lock(&self.subscriber.state);
            if let Some(next) = Self::take_next(&mut state, &self.decoder) {
                return next;
            }
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(WatchError::Timeout);
            }
            drop(cv_wait_timeout(
                &self.subscriber.changed,
                &self.subscriber.state,
                state,
                remaining,
            ));
        }
    }

    pub fn recv(&mut self) -> RecvFuture<'_, S> {
        RecvFuture {
            receiver: self,
            registered: None,
        }
    }

    pub fn recv_many(
        &mut self,
        out: &mut Vec<WatchEvent<S>>,
        max: usize,
    ) -> Result<usize, WatchError> {
        if max == 0 {
            return Ok(0);
        }
        let mut state = lock(&self.subscriber.state);
        let mut received = 0;
        while received < max {
            if state.gap_at == Some(0) {
                return if received == 0 {
                    let lagged = std::mem::take(&mut state.lagged);
                    state.gap_at = None;
                    Err(WatchError::Lagged(lagged))
                } else {
                    Ok(received)
                };
            }
            if let Some(inner) = state.events.pop_front() {
                if let Some(gap_at) = &mut state.gap_at {
                    *gap_at -= 1;
                }
                out.push(WatchEvent {
                    inner,
                    decoder: self.decoder.clone(),
                    _spec: PhantomData,
                });
                received += 1;
            } else {
                return if state.terminal && received == 0 {
                    Err(WatchError::Closed)
                } else {
                    Ok(received)
                };
            }
        }
        Ok(received)
    }

    fn take_next(
        state: &mut SubscriberState<S::Key>,
        decoder: &S::Decoder,
    ) -> Option<Result<WatchEvent<S>, WatchError>> {
        if state.gap_at == Some(0) {
            state.gap_at = None;
            let lagged = std::mem::take(&mut state.lagged);
            return Some(Err(WatchError::Lagged(lagged)));
        }
        if let Some(inner) = state.events.pop_front() {
            if let Some(gap_at) = &mut state.gap_at {
                *gap_at -= 1;
            }
            return Some(Ok(WatchEvent {
                inner,
                decoder: decoder.clone(),
                _spec: PhantomData,
            }));
        }
        if state.terminal {
            return Some(Err(WatchError::Closed));
        }
        None
    }
}

/// Future returned by [`WatchReceiver::recv`].
pub struct RecvFuture<'a, S: WatchSpec> {
    receiver: &'a mut WatchReceiver<S>,
    registered: Option<Waker>,
}

impl<S: WatchSpec> Future for RecvFuture<'_, S> {
    type Output = Result<WatchEvent<S>, WatchError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.as_mut().get_mut();
        let mut state = lock(&this.receiver.subscriber.state);
        if let Some(next) = WatchReceiver::<S>::take_next(&mut state, &this.receiver.decoder) {
            return Poll::Ready(next);
        }
        let replace = state
            .waker
            .as_ref()
            .is_none_or(|registered| !registered.will_wake(cx.waker()));
        if replace {
            state.waker = Some(cx.waker().clone());
        }
        this.registered = Some(cx.waker().clone());
        Poll::Pending
    }
}

impl<S: WatchSpec> Drop for RecvFuture<'_, S> {
    fn drop(&mut self) {
        let Some(registered) = self.registered.take() else {
            return;
        };
        let mut state = lock(&self.receiver.subscriber.state);
        if state
            .waker
            .as_ref()
            .is_some_and(|waker| waker.will_wake(&registered))
        {
            state.waker = None;
        }
    }
}

impl<S: WatchSpec> Drop for WatchReceiver<S> {
    fn drop(&mut self) {
        if !self.node.is_null() {
            self.channel.unsubscribe(self.node);
        }
    }
}

// The raw pointer is only an intrusive-list identity. All dereferences are
// guarded by the channel registry or its seize collector.
unsafe impl<S: WatchSpec> Send for WatchReceiver<S> {}

#[cfg(test)]
fn before_condvar_park() {
    test_support::wait_before_condvar_park();
}

#[cfg(not(test))]
fn before_condvar_park() {}

#[cfg(test)]
fn test_channel<K: Key, T>(_capacity: NonZeroUsize) -> (Arc<WatchChannel<K>>, WatchReceiver<T>)
where
    T: WatchSpec<Key = K>,
    T::Decoder: Default,
{
    let channel = WatchChannel::new();
    let receiver = channel.subscribe::<T>(
        T::Decoder::default(),
        WatchOptions {
            capacity: _capacity,
        },
    );
    (channel, receiver)
}

#[cfg(test)]
impl<K: Key> WatchChannel<K> {
    fn publish_for_test(&self, key: K, old: Option<Box<[u8]>>, new: Option<Box<[u8]>>) {
        let mut wakes = WatchWakeBatch::default();
        // Mirror the production seam: the participation guard is entered by the
        // mutation context, and publication happens under it.
        if let Some(_producer) = self.enter_producer() {
            self.publish(Arc::new(WatchEventInner::new(key, old, new)), &mut wakes);
        }
        wakes.drain();
    }

    fn debug_registered_wakers(&self) -> usize {
        let guard = self.collector.enter();
        let mut count = 0;
        let mut current = guard.protect(&self.head, Ordering::Acquire);
        while let Some(node) = unsafe { current.as_ref() } {
            count += usize::from(lock(&node.subscriber.state).waker.is_some());
            current = guard.protect(&node.next, Ordering::Acquire);
        }
        count
    }

    fn arm_before_publish(&self) -> test_support::ParkPause {
        test_support::arm_pause(&self.publish_pause)
    }

    fn arm_after_terminal_mark(&self) -> test_support::ParkPause {
        test_support::arm_pause(&self.close_pause)
    }

    fn arm_after_traversal_starts(&self) -> test_support::ParkPause {
        test_support::arm_pause(&self.traversal_pause)
    }

    fn arm_before_ctx_lock(&self) -> test_support::ParkPause {
        test_support::arm_pause(&self.ctx_lock_pause)
    }

    pub(crate) fn wait_before_ctx_lock(&self) {
        test_support::wait_pause(&self.ctx_lock_pause);
    }

    /// Park a producer between its gate sample and its mutation — the window
    /// the participation guard exists to cover.
    fn arm_after_watch_gate(&self) -> test_support::ParkPause {
        test_support::arm_pause(&self.gate_pause)
    }

    pub(crate) fn wait_after_watch_gate(&self) {
        test_support::wait_pause(&self.gate_pause);
    }

    /// Park a registering receiver after it is linked and counted, but before
    /// it waits out the producers that may have missed it.
    fn arm_after_subscribe_link(&self) -> test_support::ParkPause {
        test_support::arm_pause(&self.subscribe_pause)
    }

    fn debug_subscriber_count(&self) -> usize {
        self.subscribers.load(Ordering::Acquire)
    }
}

#[cfg(test)]
mod test_support {
    use std::sync::{Arc, Barrier, LazyLock, Mutex};

    pub(super) type ParkPause = (Arc<Barrier>, Arc<Barrier>);

    static PARK_PAUSE: LazyLock<Mutex<Option<ParkPause>>> = LazyLock::new(|| Mutex::new(None));
    pub(super) fn arm_before_condvar_park() -> ParkPause {
        let pause = (Arc::new(Barrier::new(2)), Arc::new(Barrier::new(2)));
        *PARK_PAUSE.lock().expect("watch park pause lock") = Some(pause.clone());
        pause
    }

    pub(super) fn wait_before_condvar_park() {
        let pause = PARK_PAUSE
            .lock()
            .expect("watch park pause lock")
            .as_ref()
            .cloned();
        if let Some((checked_empty, release)) = pause {
            checked_empty.wait();
            release.wait();
        }
    }

    pub(super) fn arm_pause(pause_slot: &Mutex<Option<ParkPause>>) -> ParkPause {
        let pause = (Arc::new(Barrier::new(2)), Arc::new(Barrier::new(2)));
        *pause_slot.lock().expect("watch pause lock") = Some(pause.clone());
        pause
    }

    pub(super) fn wait_pause(pause_slot: &Mutex<Option<ParkPause>>) {
        let pause = pause_slot.lock().expect("watch pause lock").take();
        if let Some((checked, release)) = pause {
            checked.wait();
            release.wait();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::future::Future;
    // Only the follower test needs a socket, and it is gated on `replication`;
    // an ungated import here is an `unused_imports` failure under the crate's
    // `-D warnings` feature-matrix builds.
    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "replication"
    ))]
    use std::net::TcpListener;
    use std::num::NonZeroUsize;
    use std::pin::Pin;
    use std::sync::Arc;
    use std::task::{Context, Poll, Waker};
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    use std::time::Duration;
    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "replication"
    ))]
    use std::time::Instant;

    use super::*;

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    use crate::{
        ByteView, CollectionMeta, Config, NoHook, RapiraCodec, TtlPolicy, TypedMap, TypedTree,
        Upsert, VarTypedMap, VarTypedTree, ZeroMap, ZeroTree,
    };
    #[cfg(feature = "rapira-codec")]
    use armour_core::GetType;
    #[cfg(feature = "rapira-codec")]
    use rapira::Rapira;
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    use tempfile::tempdir;
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    use zerocopy::{FromBytes, Immutable, IntoBytes};

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[derive(Clone, Debug, PartialEq, Rapira, GetType)]
    struct WatchRow(u64);

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    impl CollectionMeta for WatchRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_api_rows";
    }

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    #[derive(Clone, Debug, PartialEq, Rapira, GetType)]
    struct EncodeOnceRow(u64);

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    impl CollectionMeta for EncodeOnceRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_encode_once_rows";
    }

    // Test-only codec state deliberately allows the storage encode and rejects
    // an accidental second encode during watch publication.
    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    thread_local! {
        static ENCODE_ONCE_REMAINING: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
    }

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    #[derive(Clone, Copy)]
    struct EncodeOnceCodec;

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    impl crate::Codec<EncodeOnceRow> for EncodeOnceCodec {
        fn encode_to(&self, value: &EncodeOnceRow, buf: &mut Vec<u8>) -> crate::DbResult<()> {
            let allowed = ENCODE_ONCE_REMAINING.with(|remaining| match remaining.get() {
                Some(0) => false,
                Some(left) => {
                    remaining.set(Some(left - 1));
                    true
                }
                None => true,
            });
            if !allowed {
                return Err(crate::DbError::Internal("test: second codec encode"));
            }
            buf.clear();
            buf.extend_from_slice(&value.0.to_be_bytes());
            Ok(())
        }

        fn decode_from(&self, bytes: &[u8]) -> crate::DbResult<EncodeOnceRow> {
            Ok(EncodeOnceRow(u64::from_be_bytes(
                bytes
                    .try_into()
                    .map_err(|_| crate::DbError::CorruptedEntry { offset: 0 })?,
            )))
        }
    }

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    struct EncodeOnceScope(Option<usize>);

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    impl EncodeOnceScope {
        fn allow_one() -> Self {
            Self::allow(1)
        }

        fn allow(budget: usize) -> Self {
            let previous = ENCODE_ONCE_REMAINING.with(|remaining| {
                let previous = remaining.get();
                remaining.set(Some(budget));
                previous
            });
            Self(previous)
        }
    }

    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    impl Drop for EncodeOnceScope {
        fn drop(&mut self) {
            ENCODE_ONCE_REMAINING.with(|remaining| remaining.set(self.0));
        }
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[derive(Clone, Debug, PartialEq, Rapira, GetType)]
    struct WatchRightRow(u64);

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    impl CollectionMeta for WatchRightRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_tx_right_rows";
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[derive(Clone, Debug, PartialEq, Rapira, GetType)]
    struct TtlWatchRow(u64);

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    impl CollectionMeta for TtlWatchRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_ttl_rows";
        const TTL: Option<TtlPolicy<Self>> = Some(TtlPolicy {
            revision: 1,
            deadline: |row, _| (row.0 > 0).then_some(row.0),
        });
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[derive(Clone, Copy, Debug, PartialEq, FromBytes, IntoBytes, Immutable, GetType)]
    #[repr(transparent)]
    struct WatchZeroRow(u64);

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    impl CollectionMeta for WatchZeroRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_api_zero_rows";
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[derive(Clone, Copy, FromBytes, IntoBytes, Immutable, GetType)]
    #[repr(transparent)]
    struct WatchZeroMapRow(u64);

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    impl CollectionMeta for WatchZeroMapRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_api_zero_map_rows";
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[derive(Clone, Copy, Debug, PartialEq, FromBytes, IntoBytes, Immutable, GetType)]
    #[repr(transparent)]
    struct TtlWatchZeroRow(u64);

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    impl CollectionMeta for TtlWatchZeroRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_ttl_zero_tree_rows";
        const TTL: Option<TtlPolicy<Self>> = Some(TtlPolicy {
            revision: 1,
            deadline: |row, _| (row.0 > 0).then_some(row.0),
        });
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[derive(Clone, Copy, Debug, PartialEq, FromBytes, IntoBytes, Immutable, GetType)]
    #[repr(transparent)]
    struct TtlWatchZeroMapRow(u64);

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    impl CollectionMeta for TtlWatchZeroMapRow {
        type SelfId = [u8; 8];
        const NAME: &'static str = "watch_ttl_zero_map_rows";
        const TTL: Option<TtlPolicy<Self>> = Some(TtlPolicy {
            revision: 1,
            deadline: |row, _| (row.0 > 0).then_some(row.0),
        });
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn all_six_families_return_a_typed_receiver() {
        let dir = tempdir().expect("temporary directory");
        let tree = TypedTree::open_hooked(
            dir.path().join("tree"),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open typed tree");
        let mut rx: WatchReceiver<_> = tree.watch(Default::default());
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));

        let map = TypedMap::open_hooked(
            dir.path().join("map"),
            Config::balanced().iterable(true).build(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open typed map");
        let _: WatchReceiver<_> = map.watch(Default::default());

        let var_tree = VarTypedTree::open_hooked(
            dir.path().join("var-tree"),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open var typed tree");
        let _: WatchReceiver<_> = var_tree.watch(Default::default());

        let var_map = VarTypedMap::open_hooked(
            dir.path().join("var-map"),
            Config::balanced().iterable(true).build(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open var typed map");
        let _: WatchReceiver<_> = var_map.watch(Default::default());

        let zero_tree: ZeroTree<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        > = ZeroTree::open_hooked(
            dir.path().join("zero-tree"),
            Config::test(),
            WatchHook::<WatchZeroRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open zero tree");
        let _: WatchReceiver<_> = zero_tree.watch(Default::default());

        let zero_map: ZeroMap<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        > = ZeroMap::open_hooked(
            dir.path().join("zero-map"),
            Config::balanced().iterable(true).build(),
            WatchHook::<WatchZeroRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open zero map");
        let _: WatchReceiver<_> = zero_map.watch(Default::default());
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn watch_map_without_iterable_is_refused_at_open() {
        let dir = tempdir().expect("temporary directory");
        let direct = TypedMap::open_hooked(
            dir.path(),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        );
        assert!(
            matches!(direct, Err(crate::DbError::WatchRequiresIterable)),
            "watched maps need iterable indexes"
        );

        let managed_dir = tempdir().expect("temporary directory");
        let db = crate::armour::Db::open_test(managed_dir.path()).expect("open db");
        let managed = db.open_typed_map::<WatchRow, RapiraCodec, _>(
            Config::test(),
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
            &[],
        );
        assert!(matches!(
            managed,
            Err(crate::DbError::WatchRequiresIterable)
        ));
    }

    /// `Db::drop` routes through `shutdown`, so a database that is simply
    /// dropped must close its subscriptions too — otherwise a receiver held
    /// past the `Db` would block forever on a channel nothing can publish to.
    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn dropping_the_database_closes_its_subscriptions() {
        let dir = tempdir().expect("temporary directory");
        let db = crate::armour::Db::open_test(dir.path()).expect("open db");
        let tree = db
            .open_typed_tree::<WatchRow, RapiraCodec, _>(
                Config::test(),
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
                &[],
            )
            .expect("open watched tree");
        let mut receiver = tree.watch(WatchOptions::default());
        tree.put(&key(1), WatchRow(1)).expect("write");

        drop(tree);
        drop(db);

        // Drained first, then terminal.
        assert_eq!(
            receiver
                .try_recv()
                .expect("event queued before drop")
                .new()
                .expect("decode"),
            Some(WatchRow(1))
        );
        assert_eq!(receiver.try_recv(), Err(WatchError::Closed));
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn watch_close_keeps_receiver_live_but_shutdown_closes_it() {
        let dir = tempdir().expect("temporary directory");
        let mut db = crate::armour::Db::open_test(dir.path()).expect("open db");
        let tree = db
            .open_typed_tree::<WatchRow, RapiraCodec, _>(
                Config::test(),
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
                &[],
            )
            .expect("open watched tree");
        let mut receiver = tree.watch(WatchOptions::default());

        db.close().expect("non-terminal close");
        tree.put(&key(1), WatchRow(1)).expect("write after close");
        assert_eq!(
            receiver.recv_blocking().unwrap().new().unwrap(),
            Some(WatchRow(1))
        );

        db.shutdown().expect("shutdown");
        assert_eq!(receiver.try_recv(), Err(WatchError::Closed));
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn watch_shutdown_after_sweeper_drains_ttl_delete_before_closed() {
        struct ReleaseOnDrop(Option<Arc<std::sync::Barrier>>);
        impl Drop for ReleaseOnDrop {
            fn drop(&mut self) {
                if let Some(release) = self.0.take() {
                    release.wait();
                }
            }
        }
        struct JoinOnDrop<T>(Option<std::thread::JoinHandle<T>>);
        impl<T> Drop for JoinOnDrop<T> {
            fn drop(&mut self) {
                if let Some(join) = self.0.take() {
                    let _ = join.join();
                }
            }
        }

        let dir = tempdir().expect("temporary directory");
        let mut db = crate::armour::Db::open_test(dir.path()).expect("open db");
        let hook = WatchHook::<TtlWatchRow, NoHook, true>::with_old(NoHook);
        let channel = Arc::clone(&hook.channel);
        let tree = db
            .open_typed_tree::<TtlWatchRow, RapiraCodec, _>(Config::test(), hook, &[])
            .expect("open ttl tree");
        let mut receiver = tree.watch(WatchOptions::default());
        let ttl_key = key(13);
        tree.put(&ttl_key, TtlWatchRow(1))
            .expect("insert expiring row");
        let _ = receiver.try_recv().expect("insert watch event");

        let (published, release_publish) = channel.arm_before_publish();
        let mut sweep = JoinOnDrop(Some({
            let tree = Arc::clone(&tree);
            std::thread::spawn(move || tree.sweep_expired(u64::MAX, 1))
        }));
        published.wait();
        let (disable_waiting, release_disable_wait) = tree.arm_ttl_disable_wait();
        let mut shutdown = JoinOnDrop(Some(std::thread::spawn(move || db.shutdown())));
        disable_waiting.wait();
        let mut publish_release = ReleaseOnDrop(Some(release_publish));
        let mut disable_release = ReleaseOnDrop(Some(release_disable_wait));
        assert!(
            !shutdown.0.as_ref().expect("shutdown handle").is_finished(),
            "shutdown must still be blocked on the active TTL pass"
        );
        publish_release.0.take().expect("publish release").wait();
        disable_release.0.take().expect("disable release").wait();
        assert_eq!(
            sweep
                .0
                .take()
                .expect("sweeper handle")
                .join()
                .expect("sweeper thread")
                .unwrap()
                .deleted,
            1
        );
        shutdown
            .0
            .take()
            .expect("shutdown handle")
            .join()
            .expect("shutdown thread")
            .expect("shutdown");

        let deleted = receiver.try_recv().expect("ttl delete remains queued");
        assert_eq!(*deleted.key(), ttl_key);
        assert_eq!(deleted.kind(), WatchKind::Delete);
        assert_eq!(receiver.try_recv(), Err(WatchError::Closed));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn watched_typed_tree() -> (
        TypedTree<[u8; 8], WatchRow, RapiraCodec, WatchHook<WatchRow, NoHook, true>>,
        WatchReceiver<TypedTree<[u8; 8], WatchRow, RapiraCodec, WatchHook<WatchRow, NoHook, true>>>,
    ) {
        let dir = tempdir().expect("temporary directory");
        // Keep the directory alive through the collection's engine handle.
        let path = dir.keep();
        let mut config = Config::test();
        config.shard_count = 1;
        let tree = TypedTree::open_hooked(
            path,
            config,
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open watched typed tree");
        let rx = tree.watch(Default::default());
        (tree, rx)
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    type WatchedTypedTree =
        TypedTree<[u8; 8], WatchRow, RapiraCodec, WatchHook<WatchRow, NoHook, true>>;

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_seed(tree: &WatchedTypedTree, key: [u8; 8], value: u64) -> DbResult<()> {
        tree.put(&key, WatchRow(value))?;
        Ok(())
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_put(tree: &WatchedTypedTree) -> DbResult<()> {
        matrix_seed(tree, key(1), 1)
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_insert(tree: &WatchedTypedTree) -> DbResult<()> {
        tree.insert(&key(2), WatchRow(2))
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_delete(tree: &WatchedTypedTree) -> DbResult<()> {
        matrix_seed(tree, key(3), 3)?;
        tree.delete(&key(3))?;
        Ok(())
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_cas(tree: &WatchedTypedTree) -> DbResult<()> {
        matrix_seed(tree, key(4), 4)?;
        tree.cas(&key(4), &WatchRow(4), WatchRow(5))
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_compare_delete(tree: &WatchedTypedTree) -> DbResult<()> {
        matrix_seed(tree, key(5), 5)?;
        tree.compare_delete(&key(5), &WatchRow(5))
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_update(tree: &WatchedTypedTree) -> DbResult<()> {
        matrix_seed(tree, key(6), 6)?;
        tree.update(&key(6), |_| WatchRow(7))?;
        Ok(())
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_fetch_update(tree: &WatchedTypedTree) -> DbResult<()> {
        matrix_seed(tree, key(7), 7)?;
        tree.fetch_update(&key(7), |_| WatchRow(8))?;
        Ok(())
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_upsert_put_and_keep(tree: &WatchedTypedTree) -> DbResult<()> {
        tree.upsert(&key(8), |_| Upsert::Put(WatchRow(8)))?;
        tree.upsert(&key(8), |_| Upsert::Keep)?;
        Ok(())
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_atomic_shard_handle(tree: &WatchedTypedTree) -> DbResult<()> {
        tree.atomic(&key(9), |shard| {
            shard.put(&key(9), WatchRow(9))?;
            Ok(())
        })
    }
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn matrix_update_many(tree: &WatchedTypedTree) -> DbResult<()> {
        tree.update_many(vec![(key(10), 10), (key(11), 11)], |_, _, value| {
            if *value == 10 {
                Upsert::Put(WatchRow(*value))
            } else {
                Upsert::Keep
            }
        })?;
        Ok(())
    }

    /// Table-driven public mutation inventory. The production mutation that must
    /// make each row fail is its missing/incorrect `publish_watch` branch; a
    /// `Keep` is deliberately represented by the absence of a second event.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_mutation_matrix_reports_exact_with_old_kinds() {
        struct Case {
            name: &'static str,
            run: fn(&WatchedTypedTree) -> DbResult<()>,
            expected: &'static [WatchKind],
        }
        const INSERT: &[WatchKind] = &[WatchKind::Insert];
        const UPDATE: &[WatchKind] = &[WatchKind::Insert, WatchKind::Update];
        const DELETE: &[WatchKind] = &[WatchKind::Insert, WatchKind::Delete];
        const PUT_AND_KEEP: &[WatchKind] = &[WatchKind::Insert];
        const UPDATE_MANY: &[WatchKind] = &[WatchKind::Insert];
        let cases = [
            Case {
                name: "put",
                run: matrix_put,
                expected: INSERT,
            },
            Case {
                name: "insert",
                run: matrix_insert,
                expected: INSERT,
            },
            Case {
                name: "delete",
                run: matrix_delete,
                expected: DELETE,
            },
            Case {
                name: "cas",
                run: matrix_cas,
                expected: UPDATE,
            },
            Case {
                name: "compare_delete",
                run: matrix_compare_delete,
                expected: DELETE,
            },
            Case {
                name: "update",
                run: matrix_update,
                expected: UPDATE,
            },
            Case {
                name: "fetch_update",
                run: matrix_fetch_update,
                expected: UPDATE,
            },
            Case {
                name: "upsert put and Keep",
                run: matrix_upsert_put_and_keep,
                expected: PUT_AND_KEEP,
            },
            Case {
                name: "atomic shard handle",
                run: matrix_atomic_shard_handle,
                expected: INSERT,
            },
            Case {
                name: "update_many",
                run: matrix_update_many,
                expected: UPDATE_MANY,
            },
        ];

        for case in cases {
            let (tree, mut rx) = watched_typed_tree();
            (case.run)(&tree).expect(case.name);
            let mut kinds = Vec::new();
            while let Ok(event) = rx.try_recv() {
                kinds.push(event.kind());
            }
            assert_eq!(kinds, case.expected, "{}", case.name);
        }
    }

    /// Both delivery modes must agree on row visibility while differing only in
    /// retained old data: with-old distinguishes an overwrite as `Update`, and
    /// new-only deliberately collapses it to `Upsert`.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_all_six_family_modes_preserve_kind_contract() {
        macro_rules! assert_mode {
            ($receiver:expr, $expected:expr, $name:expr) => {{
                let event = $receiver.try_recv().expect($name);
                assert_eq!(event.kind(), $expected, $name);
                if $expected == WatchKind::Update {
                    assert!(event.old().expect("decode old").is_some(), $name);
                } else {
                    assert_eq!(event.old().expect("decode old"), None, $name);
                }
            }};
        }
        let dir = tempdir().unwrap();
        let old_typed = TypedTree::open_hooked(
            dir.path().join("old-typed"),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .unwrap();
        let new_typed = TypedTree::open_hooked(
            dir.path().join("new-typed"),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
        )
        .unwrap();
        let old_var = VarTypedTree::open_hooked(
            dir.path().join("old-var"),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .unwrap();
        let new_var = VarTypedTree::open_hooked(
            dir.path().join("new-var"),
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
        )
        .unwrap();
        let old_map = TypedMap::open_hooked(
            dir.path().join("old-map"),
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .unwrap();
        let new_map = TypedMap::open_hooked(
            dir.path().join("new-map"),
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
        )
        .unwrap();
        let old_var_map = VarTypedMap::open_hooked(
            dir.path().join("old-var-map"),
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .unwrap();
        let new_var_map = VarTypedMap::open_hooked(
            dir.path().join("new-var-map"),
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
        )
        .unwrap();
        type ZOld = WatchHook<WatchZeroRow, NoHook, true>;
        type ZNew = WatchHook<WatchZeroRow, NoHook, false>;
        let old_zero = ZeroTree::<[u8; 8], 8, WatchZeroRow, ZOld>::open_hooked(
            dir.path().join("old-zero"),
            Config::test(),
            WatchHook::with_old(NoHook),
        )
        .unwrap();
        let new_zero = ZeroTree::<[u8; 8], 8, WatchZeroRow, ZNew>::open_hooked(
            dir.path().join("new-zero"),
            Config::test(),
            WatchHook::new_only(NoHook),
        )
        .unwrap();
        let old_zero_map = ZeroMap::<[u8; 8], 8, WatchZeroRow, ZOld>::open_hooked(
            dir.path().join("old-zero-map"),
            watched_map_config(),
            WatchHook::with_old(NoHook),
        )
        .unwrap();
        let new_zero_map = ZeroMap::<[u8; 8], 8, WatchZeroRow, ZNew>::open_hooked(
            dir.path().join("new-zero-map"),
            watched_map_config(),
            WatchHook::new_only(NoHook),
        )
        .unwrap();
        let mut r1 = old_typed.watch(Default::default());
        let mut r2 = new_typed.watch(Default::default());
        let mut r3 = old_var.watch(Default::default());
        let mut r4 = new_var.watch(Default::default());
        let mut r5 = old_map.watch(Default::default());
        let mut r6 = new_map.watch(Default::default());
        let mut r7 = old_var_map.watch(Default::default());
        let mut r8 = new_var_map.watch(Default::default());
        let mut r9 = old_zero.watch(Default::default());
        let mut r10 = new_zero.watch(Default::default());
        let mut r11 = old_zero_map.watch(Default::default());
        let mut r12 = new_zero_map.watch(Default::default());
        let k = key(91);
        old_typed.put(&k, WatchRow(1)).unwrap();
        new_typed.put(&k, WatchRow(1)).unwrap();
        old_var.put(&k, &WatchRow(1)).unwrap();
        new_var.put(&k, &WatchRow(1)).unwrap();
        old_map.put(&k, WatchRow(1)).unwrap();
        new_map.put(&k, WatchRow(1)).unwrap();
        old_var_map.put(&k, &WatchRow(1)).unwrap();
        new_var_map.put(&k, &WatchRow(1)).unwrap();
        old_zero.put(&k, &WatchZeroRow(1)).unwrap();
        new_zero.put(&k, &WatchZeroRow(1)).unwrap();
        old_zero_map.put(&k, &WatchZeroRow(1)).unwrap();
        new_zero_map.put(&k, &WatchZeroRow(1)).unwrap();
        assert_mode!(r1, WatchKind::Insert, "initial put");
        assert_mode!(r2, WatchKind::Upsert, "initial put");
        assert_mode!(r3, WatchKind::Insert, "initial put");
        assert_mode!(r4, WatchKind::Upsert, "initial put");
        assert_mode!(r5, WatchKind::Insert, "initial put");
        assert_mode!(r6, WatchKind::Upsert, "initial put");
        assert_mode!(r7, WatchKind::Insert, "initial put");
        assert_mode!(r8, WatchKind::Upsert, "initial put");
        assert_mode!(r9, WatchKind::Insert, "initial put");
        assert_mode!(r10, WatchKind::Upsert, "initial put");
        assert_mode!(r11, WatchKind::Insert, "initial put");
        assert_mode!(r12, WatchKind::Upsert, "initial put");
        old_typed.put(&k, WatchRow(2)).unwrap();
        new_typed.put(&k, WatchRow(2)).unwrap();
        old_var.put(&k, &WatchRow(2)).unwrap();
        new_var.put(&k, &WatchRow(2)).unwrap();
        old_map.put(&k, WatchRow(2)).unwrap();
        new_map.put(&k, WatchRow(2)).unwrap();
        old_var_map.put(&k, &WatchRow(2)).unwrap();
        new_var_map.put(&k, &WatchRow(2)).unwrap();
        old_zero.put(&k, &WatchZeroRow(2)).unwrap();
        new_zero.put(&k, &WatchZeroRow(2)).unwrap();
        old_zero_map.put(&k, &WatchZeroRow(2)).unwrap();
        new_zero_map.put(&k, &WatchZeroRow(2)).unwrap();
        assert_mode!(r1, WatchKind::Update, "with-old overwrite");
        assert_mode!(r3, WatchKind::Update, "with-old overwrite");
        assert_mode!(r5, WatchKind::Update, "with-old overwrite");
        assert_mode!(r7, WatchKind::Update, "with-old overwrite");
        assert_mode!(r9, WatchKind::Update, "with-old overwrite");
        assert_mode!(r11, WatchKind::Update, "with-old overwrite");
        assert_mode!(r2, WatchKind::Upsert, "new-only overwrite");
        assert_mode!(r4, WatchKind::Upsert, "new-only overwrite");
        assert_mode!(r6, WatchKind::Upsert, "new-only overwrite");
        assert_mode!(r8, WatchKind::Upsert, "new-only overwrite");
        assert_mode!(r10, WatchKind::Upsert, "new-only overwrite");
        assert_mode!(r12, WatchKind::Upsert, "new-only overwrite");
        old_typed.delete(&k).unwrap();
        new_typed.delete(&k).unwrap();
        old_var.delete(&k).unwrap();
        new_var.delete(&k).unwrap();
        old_map.delete(&k).unwrap();
        new_map.delete(&k).unwrap();
        old_var_map.delete(&k).unwrap();
        new_var_map.delete(&k).unwrap();
        old_zero.delete(&k).unwrap();
        new_zero.delete(&k).unwrap();
        old_zero_map.delete(&k).unwrap();
        new_zero_map.delete(&k).unwrap();
        macro_rules! assert_delete {
            ($receiver:expr, $old:expr) => {{
                let event = $receiver.try_recv().expect("delete event");
                assert_eq!(event.kind(), WatchKind::Delete);
                assert_eq!(event.new().expect("decode new"), None);
                assert_eq!(event.old().expect("decode old").is_some(), $old);
            }};
        }
        assert_delete!(r1, true);
        assert_delete!(r2, false);
        assert_delete!(r3, true);
        assert_delete!(r4, false);
        assert_delete!(r5, true);
        assert_delete!(r6, false);
        assert_delete!(r7, true);
        assert_delete!(r8, false);
        assert_delete!(r9, true);
        assert_delete!(r10, false);
        assert_delete!(r11, true);
        assert_delete!(r12, false);
    }

    // The production mutations these rows protect are the public facade calls
    // below.  In particular, a missing `publish_watch` in any success branch,
    // or publishing before a `KeyExists`/`CasMismatch`, changes an exact
    // receiver outcome.  `update_many` is intentionally NotApplicable to Map:
    // TypedMap, VarTypedMap, and ZeroMap expose no public `update_many`; Map
    // instead exposes the public `retain` operation covered by matrix_map.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_all_family_public_mutation_matrix() {
        macro_rules! payload {
            ($event:expr, $field:ident, $style:ident, none) => {
                assert_eq!($event.$field().expect("decode event"), None)
            };
            ($event:expr, $field:ident, $style:ident, $value:expr) => {
                assert_eq!(
                    $event.$field().expect("decode event"),
                    Some(row!($style, $value))
                )
            };
        }
        macro_rules! assert_event {
            ($rx:expr, $style:ident, old, $kind:expr, $key:expr, $old:tt, $new:tt, $name:expr) => {{
                let event = $rx.try_recv().expect($name);
                assert_eq!(event.kind(), $kind, $name);
                assert_eq!(event.key(), &$key, $name);
                payload!(event, old, $style, $old);
                payload!(event, new, $style, $new);
            }};
            ($rx:expr, $style:ident, new, $kind:expr, $key:expr, $old:tt, $new:tt, $name:expr) => {{
                let event = $rx.try_recv().expect($name);
                assert_eq!(
                    event.kind(),
                    if $kind == WatchKind::Delete {
                        WatchKind::Delete
                    } else {
                        WatchKind::Upsert
                    },
                    $name
                );
                assert_eq!(event.key(), &$key, $name);
                payload!(event, old, $style, none);
                payload!(event, new, $style, $new);
            }};
        }
        macro_rules! assert_one {
            ($rx:expr, $style:ident, $mode:ident, $kind:expr, $key:expr, $old:tt, $new:tt, $name:expr) => {{
                assert_event!($rx, $style, $mode, $kind, $key, $old, $new, $name);
                assert_eq!($rx.try_recv(), Err(WatchError::Empty), $name);
            }};
        }
        macro_rules! initial_kind {
            (old) => {
                WatchKind::Insert
            };
            (new) => {
                WatchKind::Upsert
            };
        }
        macro_rules! write {
            (owned, $target:expr, $key:expr, $value:expr) => {
                $target.put(&$key, WatchRow($value))
            };
            (borrowed, $target:expr, $key:expr, $value:expr) => {
                $target.put(&$key, &WatchRow($value))
            };
            (zero, $target:expr, $key:expr, $value:expr) => {
                $target.put(&$key, &WatchZeroRow($value))
            };
        }
        macro_rules! cas {
            (owned, $target:expr, $key:expr, $expected:expr, $value:expr) => {
                $target.cas(&$key, &WatchRow($expected), WatchRow($value))
            };
            (borrowed, $target:expr, $key:expr, $expected:expr, $value:expr) => {
                $target.cas(&$key, &WatchRow($expected), &WatchRow($value))
            };
            (zero, $target:expr, $key:expr, $expected:expr, $value:expr) => {
                $target.cas(&$key, &WatchZeroRow($expected), &WatchZeroRow($value))
            };
        }
        macro_rules! compare_delete {
            (owned, $target:expr, $key:expr, $expected:expr) => {
                $target.compare_delete(&$key, &WatchRow($expected))
            };
            (borrowed, $target:expr, $key:expr, $expected:expr) => {
                $target.compare_delete(&$key, &WatchRow($expected))
            };
            (zero, $target:expr, $key:expr, $expected:expr) => {
                $target.compare_delete(&$key, &WatchZeroRow($expected))
            };
        }
        macro_rules! row {
            (zero, $value:expr) => {
                WatchZeroRow($value)
            };
            ($style:ident, $value:expr) => {
                WatchRow($value)
            };
        }
        macro_rules! insert {
            (owned, $target:expr, $key:expr, $value:expr) => {
                $target.insert(&$key, WatchRow($value))
            };
            (borrowed, $target:expr, $key:expr, $value:expr) => {
                $target.insert(&$key, &WatchRow($value))
            };
            (zero, $target:expr, $key:expr, $value:expr) => {
                $target.insert(&$key, &WatchZeroRow($value))
            };
        }
        macro_rules! seed {
            ($style:ident, $target:expr, $rx:expr, $mode:ident, $key:expr, $value:expr) => {{
                write!($style, $target, $key, $value).expect("seed");
                assert_one!(
                    $rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    $key,
                    none,
                    $value,
                    "seed"
                );
            }};
        }
        macro_rules! matrix_tree {
            ($name:expr, $style:ident, $mode:ident, $open:expr) => {{
                let dir = tempdir().expect("temporary directory");
                let tree = $open(dir.path());
                let mut rx = tree.watch(Default::default());
                let insert_key = key(1);
                insert!($style, tree, insert_key, 1).expect("insert");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    insert_key,
                    none,
                    1,
                    "insert"
                );
                let absent_upsert_key = key(101);
                tree.upsert(&absent_upsert_key, |_| Upsert::Put(row!($style, 101)))
                    .expect("absent upsert put");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    absent_upsert_key,
                    none,
                    101,
                    "absent upsert put"
                );
                let occupied = key(2);
                seed!($style, tree, rx, $mode, occupied, 2);
                assert!(matches!(
                    insert!($style, tree, occupied, 3),
                    Err(crate::DbError::KeyExists)
                ));
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                let cas_key = key(3);
                seed!($style, tree, rx, $mode, cas_key, 3);
                cas!($style, tree, cas_key, 3, 4).expect("cas");
                assert_one!(rx, $style, $mode, WatchKind::Update, cas_key, 3, 4, "cas");
                let cas_mismatch = key(4);
                seed!($style, tree, rx, $mode, cas_mismatch, 4);
                assert!(matches!(
                    cas!($style, tree, cas_mismatch, 99, 5),
                    Err(crate::DbError::CasMismatch)
                ));
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                let delete_key = key(5);
                seed!($style, tree, rx, $mode, delete_key, 5);
                compare_delete!($style, tree, delete_key, 5).expect("compare delete");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Delete,
                    delete_key,
                    5,
                    none,
                    "compare delete"
                );
                let direct_delete_key = key(51);
                seed!($style, tree, rx, $mode, direct_delete_key, 51);
                tree.delete(&direct_delete_key).expect("direct delete");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Delete,
                    direct_delete_key,
                    51,
                    none,
                    "direct delete"
                );
                let delete_mismatch = key(6);
                seed!($style, tree, rx, $mode, delete_mismatch, 6);
                assert!(matches!(
                    compare_delete!($style, tree, delete_mismatch, 99),
                    Err(crate::DbError::CasMismatch)
                ));
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                let update_key = key(7);
                seed!($style, tree, rx, $mode, update_key, 7);
                tree.update(&update_key, |_| row!($style, 8))
                    .expect("update");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Update,
                    update_key,
                    7,
                    8,
                    "update"
                );
                let fetch_key = key(8);
                seed!($style, tree, rx, $mode, fetch_key, 8);
                tree.fetch_update(&fetch_key, |_| row!($style, 9))
                    .expect("fetch update");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Update,
                    fetch_key,
                    8,
                    9,
                    "fetch update"
                );
                let upsert_key = key(9);
                seed!($style, tree, rx, $mode, upsert_key, 9);
                tree.upsert(&upsert_key, |_| Upsert::Put(row!($style, 10)))
                    .expect("upsert put");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Update,
                    upsert_key,
                    9,
                    10,
                    "upsert put"
                );
                tree.upsert(&upsert_key, |_| Upsert::<_>::Keep)
                    .expect("upsert keep");
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                tree.atomic(&key(52), |_| Ok(())).expect("atomic closure");
                assert_eq!(
                    rx.try_recv(),
                    Err(WatchError::Empty),
                    "empty atomic is silent"
                );
                let atomic_key = key(10);
                tree.atomic(&atomic_key, |shard| {
                    write!($style, shard, atomic_key, 10).map(|_| ())
                })
                .expect("atomic shard put");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    atomic_key,
                    none,
                    10,
                    "atomic shard put"
                );
                tree.update_many(vec![(key(11), 11u64), (key(12), 12u64)], |_, _, value| {
                    Upsert::Put(row!($style, *value))
                })
                .expect("update many");
                assert_event!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    key(11),
                    none,
                    11,
                    "update many first"
                );
                assert_event!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    key(12),
                    none,
                    12,
                    "update many second"
                );
                assert_eq!(
                    rx.try_recv(),
                    Err(WatchError::Empty),
                    "update many drains exactly"
                );
                let _ = $name;
            }};
        }
        macro_rules! matrix_map {
            ($name:expr, $style:ident, $mode:ident, $open:expr) => {{
                let dir = tempdir().expect("temporary directory");
                let map = $open(dir.path());
                let mut rx = map.watch(Default::default());
                let insert_key = key(21);
                insert!($style, map, insert_key, 1).expect("insert");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    insert_key,
                    none,
                    1,
                    "insert"
                );
                let absent_upsert_key = key(121);
                map.upsert(&absent_upsert_key, |_| Upsert::Put(row!($style, 121)))
                    .expect("absent upsert put");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    absent_upsert_key,
                    none,
                    121,
                    "absent upsert put"
                );
                let occupied = key(22);
                seed!($style, map, rx, $mode, occupied, 2);
                assert!(matches!(
                    insert!($style, map, occupied, 3),
                    Err(crate::DbError::KeyExists)
                ));
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                let cas_key = key(23);
                seed!($style, map, rx, $mode, cas_key, 3);
                cas!($style, map, cas_key, 3, 4).expect("cas");
                assert_one!(rx, $style, $mode, WatchKind::Update, cas_key, 3, 4, "cas");
                let cas_mismatch = key(24);
                seed!($style, map, rx, $mode, cas_mismatch, 4);
                assert!(matches!(
                    cas!($style, map, cas_mismatch, 99, 5),
                    Err(crate::DbError::CasMismatch)
                ));
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                let delete_key = key(25);
                seed!($style, map, rx, $mode, delete_key, 5);
                compare_delete!($style, map, delete_key, 5).expect("compare delete");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Delete,
                    delete_key,
                    5,
                    none,
                    "compare delete"
                );
                let direct_delete_key = key(61);
                seed!($style, map, rx, $mode, direct_delete_key, 61);
                map.delete(&direct_delete_key).expect("direct delete");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Delete,
                    direct_delete_key,
                    61,
                    none,
                    "direct delete"
                );
                let delete_mismatch = key(26);
                seed!($style, map, rx, $mode, delete_mismatch, 6);
                assert!(matches!(
                    compare_delete!($style, map, delete_mismatch, 99),
                    Err(crate::DbError::CasMismatch)
                ));
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                let update_key = key(27);
                seed!($style, map, rx, $mode, update_key, 7);
                map.update(&update_key, |_| row!($style, 8))
                    .expect("update");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Update,
                    update_key,
                    7,
                    8,
                    "update"
                );
                let fetch_key = key(28);
                seed!($style, map, rx, $mode, fetch_key, 8);
                map.fetch_update(&fetch_key, |_| row!($style, 9))
                    .expect("fetch update");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Update,
                    fetch_key,
                    8,
                    9,
                    "fetch update"
                );
                let upsert_key = key(29);
                seed!($style, map, rx, $mode, upsert_key, 9);
                map.upsert(&upsert_key, |_| Upsert::Put(row!($style, 10)))
                    .expect("upsert put");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Update,
                    upsert_key,
                    9,
                    10,
                    "upsert put"
                );
                map.upsert(&upsert_key, |_| Upsert::<_>::Keep)
                    .expect("upsert keep");
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
                map.atomic(&key(62), |_| Ok(())).expect("atomic closure");
                assert_eq!(
                    rx.try_recv(),
                    Err(WatchError::Empty),
                    "empty atomic is silent"
                );
                let atomic_key = key(30);
                map.atomic(&atomic_key, |shard| {
                    write!($style, shard, atomic_key, 10).map(|_| ())
                })
                .expect("atomic shard put");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    initial_kind!($mode),
                    atomic_key,
                    none,
                    10,
                    "atomic shard put"
                );
                let remove = key(31);
                let keep = key(32);
                seed!($style, map, rx, $mode, remove, 31);
                seed!($style, map, rx, $mode, keep, 32);
                map.iter_view()
                    .expect("watched map is iterable")
                    .retain(|key, _| *key != remove)
                    .expect("retain");
                assert_one!(
                    rx,
                    $style,
                    $mode,
                    WatchKind::Delete,
                    remove,
                    31,
                    none,
                    "retain remove"
                );
                assert_eq!(
                    rx.try_recv(),
                    Err(WatchError::Empty),
                    "retain keep is silent"
                );
                let _ = $name;
            }};
        }

        matrix_tree!("typed tree old", owned, old, |path| TypedTree::open_hooked(
            path,
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook)
        )
        .unwrap());
        matrix_tree!("typed tree new", owned, new, |path| TypedTree::open_hooked(
            path,
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook)
        )
        .unwrap());
        matrix_tree!("var typed tree old", borrowed, old, |path| {
            VarTypedTree::open_hooked(
                path,
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
            )
            .unwrap()
        });
        matrix_tree!("var typed tree new", borrowed, new, |path| {
            VarTypedTree::open_hooked(
                path,
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
            )
            .unwrap()
        });
        matrix_tree!("zero tree old", zero, old, |path| ZeroTree::<
            [u8; 8],
            8,
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        >::open_hooked(
            path,
            Config::test(),
            WatchHook::with_old(NoHook)
        )
        .unwrap());
        matrix_tree!("zero tree new", zero, new, |path| ZeroTree::<
            [u8; 8],
            8,
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, false>,
        >::open_hooked(
            path,
            Config::test(),
            WatchHook::new_only(NoHook)
        )
        .unwrap());
        matrix_map!("typed map old", owned, old, |path| TypedMap::open_hooked(
            path,
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook)
        )
        .unwrap());
        matrix_map!("typed map new", owned, new, |path| TypedMap::open_hooked(
            path,
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook)
        )
        .unwrap());
        matrix_map!("var typed map old", borrowed, old, |path| {
            VarTypedMap::open_hooked(
                path,
                watched_map_config(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
            )
            .unwrap()
        });
        matrix_map!("var typed map new", borrowed, new, |path| {
            VarTypedMap::open_hooked(
                path,
                watched_map_config(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
            )
            .unwrap()
        });
        matrix_map!("zero map old", zero, old, |path| ZeroMap::<
            [u8; 8],
            8,
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        >::open_hooked(
            path,
            watched_map_config(),
            WatchHook::with_old(NoHook)
        )
        .unwrap());
        matrix_map!("zero map new", zero, new, |path| ZeroMap::<
            [u8; 8],
            8,
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, false>,
        >::open_hooked(
            path,
            watched_map_config(),
            WatchHook::new_only(NoHook)
        )
        .unwrap());
    }

    /// Each public Tree facade must surface a real later `update_many` error
    /// after publishing exactly its applied prefix. The scoped fault guards live
    /// below the public facade and restore their thread-local state on drop.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_public_update_many_error_keeps_exact_applied_prefix() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct CountWake(Arc<AtomicUsize>);
        impl std::task::Wake for CountWake {
            fn wake(self: Arc<Self>) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }

        macro_rules! row {
            (zero, $value:expr) => {
                WatchZeroRow($value)
            };
            ($style:ident, $value:expr) => {
                WatchRow($value)
            };
        }
        macro_rules! assert_prefix {
            ($event:expr, $style:ident, old, $key:expr, $value:expr) => {{
                let event = $event;
                assert_eq!(event.key(), &$key);
                assert_eq!(event.kind(), WatchKind::Insert);
                assert_eq!(event.old().expect("decode old"), None);
                assert_eq!(event.new().expect("decode new"), Some(row!($style, $value)));
            }};
            ($event:expr, $style:ident, new, $key:expr, $value:expr) => {{
                let event = $event;
                assert_eq!(event.key(), &$key);
                assert_eq!(event.kind(), WatchKind::Upsert);
                assert_eq!(event.old().expect("decode old"), None);
                assert_eq!(event.new().expect("decode new"), Some(row!($style, $value)));
            }};
        }
        macro_rules! run {
            ($style:ident, $mode:ident, $open:expr, $fault:expr) => {{
                let dir = tempdir().expect("temporary directory");
                let tree = $open(dir.path());
                let mut rx = tree.watch(Default::default());
                let first = key(71);
                let second = key(72);
                let wakes = Arc::new(AtomicUsize::new(0));
                let waker = Waker::from(Arc::new(CountWake(Arc::clone(&wakes))));
                let mut pending = Box::pin(rx.recv());
                assert!(matches!(
                    pending.as_mut().poll(&mut Context::from_waker(&waker)),
                    Poll::Pending
                ));
                let _fault = $fault;
                let err = tree
                    .update_many(vec![(first, 1u64), (second, 2u64)], |_, _, value| {
                        Upsert::Put(row!($style, *value))
                    })
                    .expect_err("second public update_many mutation fails");
                assert!(matches!(
                    err,
                    crate::DbError::Internal("test: update_many injected failure")
                ));
                assert_eq!(
                    wakes.load(Ordering::SeqCst),
                    1,
                    "applied prefix wakes receiver exactly once"
                );
                let event = match pending.as_mut().poll(&mut Context::from_waker(&waker)) {
                    Poll::Ready(Ok(event)) => event,
                    other => panic!("woken receiver must yield applied prefix, got {other:?}"),
                };
                assert_prefix!(event, $style, $mode, first, 1);
                drop(pending);
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
            }};
        }
        run!(
            owned,
            old,
            |path| TypedTree::open_hooked(
                path,
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook)
            )
            .unwrap(),
            crate::typed_tree::UpdateManyFailAfter::after(1)
        );
        run!(
            owned,
            new,
            |path| TypedTree::open_hooked(
                path,
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, false>::new_only(NoHook)
            )
            .unwrap(),
            crate::typed_tree::UpdateManyFailAfter::after(1)
        );
        run!(
            borrowed,
            old,
            |path| VarTypedTree::open_hooked(
                path,
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook)
            )
            .unwrap(),
            crate::var_tree::UpdateManyFailAfter::after(1)
        );
        run!(
            borrowed,
            new,
            |path| VarTypedTree::open_hooked(
                path,
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, false>::new_only(NoHook)
            )
            .unwrap(),
            crate::var_tree::UpdateManyFailAfter::after(1)
        );
        run!(
            zero,
            old,
            |path| {
                ZeroTree::<[u8; 8], 8, WatchZeroRow, WatchHook<WatchZeroRow, NoHook, true>>::open_hooked(path, Config::test(), WatchHook::with_old(NoHook)).unwrap()
            },
            crate::const_tree::UpdateManyFailAfter::after(1)
        );
        run!(
            zero,
            new,
            |path| {
                ZeroTree::<[u8; 8], 8, WatchZeroRow, WatchHook<WatchZeroRow, NoHook, false>>::open_hooked(path, Config::test(), WatchHook::new_only(NoHook)).unwrap()
            },
            crate::const_tree::UpdateManyFailAfter::after(1)
        );
    }

    /// Recovery and migration rebuild internal state, not application writes.
    /// Enabling hook delivery in either path would make this test observe an
    /// event before a caller performs a post-open mutation.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_migration_and_recovery_emit_nothing() {
        let dir = tempdir().expect("temporary directory");
        let path = dir.path().join("recovered");
        let key = key(42);
        {
            let tree = TypedTree::<[u8; 8], WatchRow, RapiraCodec>::open(
                &path,
                Config::test(),
                RapiraCodec,
            )
            .expect("seed collection");
            tree.put(&key, WatchRow(1)).expect("seed row");
            tree.close().expect("close seeded collection");
        }

        let tree = TypedTree::open_hooked(
            &path,
            Config::test(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("recover watched collection");
        let mut rx = tree.watch(Default::default());
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));

        tree.migrate(|_, _| crate::MigrateAction::Update(WatchRow(2)))
            .expect("hook-free migration");
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
        assert_eq!(tree.get(&key).map(|row| row.0), Some(2));
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "replication"
    ))]
    #[test]
    fn watch_follower_apply_emits_nothing_but_facade_writes_do() {
        let leader_dir = tempdir().unwrap();
        let follower_dir = tempdir().unwrap();
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        drop(listener);
        let leader =
            Arc::new(VarTypedTree::open(leader_dir.path(), Config::test(), RapiraCodec).unwrap());
        let follower = Arc::new(
            VarTypedTree::open_hooked(
                follower_dir.path(),
                Config::test(),
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
            )
            .unwrap(),
        );
        let mut rx = follower.watch(Default::default());
        let local_key = key(70);
        follower.put(&local_key, &WatchRow(70)).unwrap();
        assert_eq!(
            rx.try_recv().unwrap().key(),
            &local_key,
            "watch hook is live"
        );
        follower.delete(&local_key).unwrap();
        let _ = rx.try_recv().unwrap();

        let leader_signal = crate::ShutdownSignal::new();
        let follower_signal = crate::ShutdownSignal::new();
        let _server = leader
            .test_inner_arc()
            .start_replication_server(addr, leader_signal.clone())
            .unwrap();
        let follower_raw = follower.test_inner_arc();
        let registry = Arc::new(crate::replication::ReplicationRegistry::new(
            follower_raw.as_replication_target(),
        ));
        let _client = follower_raw
            .start_replication_client(addr, registry, follower_signal.clone())
            .unwrap();
        let replicated_key = key(71);
        leader.put(&replicated_key, &WatchRow(71)).unwrap();
        let start = Instant::now();
        while follower.get(&replicated_key).is_none() && start.elapsed() < Duration::from_secs(10) {
            std::thread::sleep(Duration::from_millis(10));
        }
        assert_eq!(follower.get(&replicated_key).map(|row| row.0), Some(71));
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
        follower_signal.shutdown();
        leader_signal.shutdown();
    }

    /// The safe consumer recipe is subscribe, scan, then rescan on `Lagged`.
    /// `iter_view` is deliberately used here: watched Maps require it and its
    /// weak iterator is never treated as a snapshot.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_then_scan_and_post_lagged_rebuild_converge() {
        let dir = tempdir().expect("temporary directory");
        let map = TypedMap::open_hooked(
            dir.path(),
            watched_map_config(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open watched iterable map");
        let mut rx = map.watch(WatchOptions {
            capacity: NonZeroUsize::new(1).unwrap(),
        });
        let first = key(1);
        let second = key(2);
        map.put(&first, WatchRow(10)).unwrap();
        map.put(&second, WatchRow(20)).unwrap();

        let scan = || {
            map.iter_view()
                .expect("watched map is iterable")
                .iter()
                .map(|(key, row)| (key, row.0))
                .collect::<std::collections::BTreeMap<_, _>>()
        };
        let initial_mirror = scan();
        assert_eq!(
            initial_mirror.len(),
            2,
            "watch-first scan sees both seeded rows"
        );
        map.put(&first, WatchRow(11)).unwrap();
        map.delete(&second).unwrap();
        assert!(matches!(rx.try_recv(), Err(WatchError::Lagged(_))));

        // The operational rule: an event is a pointer, not a snapshot. Only its
        // key is used — the handler re-reads the row and applies what it finds.
        // Applying `event.new()` instead would converge here by accident (the
        // writes have stopped) while being wrong against a live writer.
        let mut mirror = scan();
        let mut applied = 0usize;
        while let Ok(event) = rx.try_recv() {
            match map.get(event.key()) {
                Some(row) => {
                    mirror.insert(*event.key(), row.0);
                }
                None => {
                    mirror.remove(event.key());
                }
            }
            applied += 1;
        }
        assert!(applied > 0, "the rebuild must consume the post-gap events");
        assert_eq!(mirror, scan());
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_then_scan_observes_a_writer_that_waited_for_the_shard_lock() {
        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.shard_count = 1;
        let hook = WatchHook::<WatchRow, NoHook, false>::new_only(NoHook);
        let (writer_at_gate, release_writer) = hook.channel.arm_before_ctx_lock();
        let tree = Arc::new(
            TypedTree::open_hooked(dir.path(), config, RapiraCodec, hook)
                .expect("open watched tree"),
        );
        let key = key(93);
        let (shard_locked, release_shard) = (
            Arc::new(std::sync::Barrier::new(2)),
            Arc::new(std::sync::Barrier::new(2)),
        );
        let blocker = {
            let tree = Arc::clone(&tree);
            let shard_locked = Arc::clone(&shard_locked);
            let release_shard = Arc::clone(&release_shard);
            std::thread::spawn(move || {
                tree.atomic(&key, |_| {
                    shard_locked.wait();
                    release_shard.wait();
                    Ok(())
                })
                .expect("release blocking atomic")
            })
        };
        shard_locked.wait();

        let writer = {
            let tree = Arc::clone(&tree);
            std::thread::spawn(move || tree.put(&key, WatchRow(1)).map(|_| ()))
        };
        writer_at_gate.wait();

        let mut receiver = tree.watch(Default::default());
        assert!(
            tree.get(&key).is_none(),
            "the watch-first scan runs before the waiting writer commits"
        );

        release_writer.wait();
        release_shard.wait();
        blocker.join().expect("blocking atomic thread");
        writer
            .join()
            .expect("writer thread")
            .expect("writer result");

        let event = receiver
            .try_recv()
            .expect("watch-first scan must not lose the waiting write");
        assert_eq!(event.kind(), WatchKind::Upsert);
        assert_eq!(event.key(), &key);
        assert_eq!(event.new().expect("decode new"), Some(WatchRow(1)));
    }

    /// The window the participation guard exists for: a producer samples the
    /// gate, finds no receiver, and only *then* makes its row visible. A
    /// receiver registering in between is in neither half of the recipe — the
    /// producer will publish nothing to it, and its catch-up scan runs before
    /// the row exists. `watch()` must therefore not return until that producer
    /// has finished.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_waits_out_a_producer_that_already_sampled_an_empty_gate() {
        use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};

        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.shard_count = 1;
        let hook = WatchHook::<WatchRow, NoHook, false>::new_only(NoHook);
        let (writer_past_gate, release_writer) = hook.channel.arm_after_watch_gate();
        let (receiver_linked, release_receiver) = hook.channel.arm_after_subscribe_link();
        let tree = Arc::new(
            TypedTree::open_hooked(dir.path(), config, RapiraCodec, hook)
                .expect("open watched tree"),
        );
        let key = key(94);

        let writer = {
            let tree = Arc::clone(&tree);
            std::thread::spawn(move || tree.put(&key, WatchRow(7)).map(|_| ()))
        };
        // Parked past its gate sample (no receiver linked), before its row exists.
        writer_past_gate.wait();

        let scanned = Arc::new(AtomicBool::new(false));
        let subscriber = {
            let tree = Arc::clone(&tree);
            let scanned = Arc::clone(&scanned);
            std::thread::spawn(move || {
                let receiver = tree.watch(Default::default());
                let seen = tree.get(&key).is_some();
                scanned.store(true, AtomicOrdering::Release);
                (receiver, seen)
            })
        };
        // Linked and counted, but not yet draining.
        receiver_linked.wait();
        release_receiver.wait();

        // Asserting a *non*-event: the only way to observe that `watch()` has
        // not returned is to give it time to. The wait is one-sided — a correct
        // build spends it, a regressed one fails immediately.
        std::thread::sleep(Duration::from_millis(200));
        assert!(
            !scanned.load(AtomicOrdering::Acquire),
            "watch() returned while a producer that sampled an empty gate was still in flight"
        );

        release_writer.wait();
        writer
            .join()
            .expect("writer thread")
            .expect("writer result");
        let (_receiver, seen) = subscriber.join().expect("subscriber thread");
        assert!(
            seen,
            "the catch-up scan must cover the write the producer decided not to publish"
        );
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn watched_map_config() -> Config {
        let mut config = Config::test();
        config.iterable = true;
        config
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    fn watched_typed_map() -> (
        TypedMap<[u8; 8], WatchRow, RapiraCodec, WatchHook<WatchRow, NoHook, true>>,
        WatchReceiver<TypedMap<[u8; 8], WatchRow, RapiraCodec, WatchHook<WatchRow, NoHook, true>>>,
    ) {
        let dir = tempdir().expect("temporary directory");
        let path = dir.keep();
        let map = TypedMap::open_hooked(
            path,
            Config::balanced().iterable(true).build(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open watched typed map");
        let rx = map.watch(Default::default());
        (map, rx)
    }

    /// Two halves of one contract.
    ///
    /// The **new** payload is the bytes the successful write stored, so
    /// publication never calls the codec for it again — a write gets exactly
    /// one encode, and the event still carries the right value.
    ///
    /// The **old** payload is encoded from the value the mutation swapped out,
    /// which is still a live `T` in RAM; reading it back from its `DiskLoc`
    /// would put a `pread` inside the shard lock. That encode can fail, and
    /// when it does the event degrades — it must keep reporting `Update`, since
    /// the kind is a fact about the mutation, not about what could be
    /// materialized. Reporting `Insert` over a live row is the failure this
    /// pins.
    #[cfg(all(feature = "rapira-codec", feature = "typed-tree"))]
    #[test]
    fn typed_watch_new_bytes_are_stored_bytes_and_a_failed_old_encode_degrades() {
        let dir = tempfile::tempdir().expect("temporary directory");
        let key = 7u64.to_be_bytes();

        let tree = crate::TypedTree::open_hooked(
            dir.path().join("tree"),
            crate::Config::test(),
            EncodeOnceCodec,
            WatchHook::<EncodeOnceRow, crate::NoHook, true>::with_old(crate::NoHook),
        )
        .expect("open typed tree");
        let mut tree_rx = tree.watch(Default::default());

        {
            let _encode = EncodeOnceScope::allow_one();
            tree.put(&key, EncodeOnceRow(1)).expect("tree insert");
        }
        let tree_insert = tree_rx.try_recv().expect("tree insert event");
        assert_eq!(tree_insert.kind(), WatchKind::Insert);
        assert_eq!(tree_insert.key(), &key);
        assert_eq!(tree_insert.old().expect("tree insert old"), None);
        assert_eq!(
            tree_insert.new().expect("tree insert new"),
            Some(EncodeOnceRow(1))
        );

        // One allowance: the write spends it, so the old-value encode fails.
        {
            let _encode = EncodeOnceScope::allow_one();
            tree.put(&key, EncodeOnceRow(2)).expect("tree update");
        }
        let tree_degraded = tree_rx.try_recv().expect("tree degraded update event");
        assert_eq!(
            tree_degraded.kind(),
            WatchKind::Update,
            "a failed old-value encode must not turn an update into an insert"
        );
        assert_eq!(tree_degraded.key(), &key);
        assert_eq!(tree_degraded.old().expect("tree degraded old"), None);
        assert_eq!(
            tree_degraded.new().expect("tree degraded new"),
            Some(EncodeOnceRow(2))
        );

        // Two allowances: the write and the old-value encode both succeed.
        {
            let _encode = EncodeOnceScope::allow(2);
            tree.put(&key, EncodeOnceRow(3))
                .expect("tree second update");
        }
        let tree_update = tree_rx.try_recv().expect("tree update event");
        assert_eq!(tree_update.kind(), WatchKind::Update);
        assert_eq!(tree_update.key(), &key);
        assert_eq!(
            tree_update.old().expect("tree update old"),
            Some(EncodeOnceRow(2))
        );
        assert_eq!(
            tree_update.new().expect("tree update new"),
            Some(EncodeOnceRow(3))
        );

        let map = crate::TypedMap::open_hooked(
            dir.path().join("map"),
            crate::Config::balanced().iterable(true).build(),
            EncodeOnceCodec,
            WatchHook::<EncodeOnceRow, crate::NoHook, true>::with_old(crate::NoHook),
        )
        .expect("open typed map");
        let mut map_rx = map.watch(Default::default());

        {
            let _encode = EncodeOnceScope::allow_one();
            map.put(&key, EncodeOnceRow(3)).expect("map insert");
        }
        let map_insert = map_rx.try_recv().expect("map insert event");
        assert_eq!(map_insert.kind(), WatchKind::Insert);
        assert_eq!(map_insert.key(), &key);
        assert_eq!(map_insert.old().expect("map insert old"), None);
        assert_eq!(
            map_insert.new().expect("map insert new"),
            Some(EncodeOnceRow(3))
        );

        {
            let _encode = EncodeOnceScope::allow_one();
            map.put(&key, EncodeOnceRow(4))
                .expect("map degraded update");
        }
        let map_degraded = map_rx.try_recv().expect("map degraded update event");
        assert_eq!(
            map_degraded.kind(),
            WatchKind::Update,
            "a failed old-value encode must not turn an update into an insert"
        );
        assert_eq!(map_degraded.key(), &key);
        assert_eq!(map_degraded.old().expect("map degraded old"), None);
        assert_eq!(
            map_degraded.new().expect("map degraded new"),
            Some(EncodeOnceRow(4))
        );

        {
            let _encode = EncodeOnceScope::allow(2);
            map.put(&key, EncodeOnceRow(5)).expect("map update");
        }
        let map_update = map_rx.try_recv().expect("map update event");
        assert_eq!(map_update.kind(), WatchKind::Update);
        assert_eq!(map_update.key(), &key);
        assert_eq!(
            map_update.old().expect("map update old"),
            Some(EncodeOnceRow(4))
        );
        assert_eq!(
            map_update.new().expect("map update new"),
            Some(EncodeOnceRow(5))
        );
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_zero_tree_and_map_deliver_put_update_and_delete() {
        let dir = tempdir().expect("temporary directory");
        let tree: ZeroTree<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        > = ZeroTree::open_hooked(
            dir.path().join("tree"),
            Config::test(),
            WatchHook::with_old(NoHook),
        )
        .expect("open watched zero tree");
        let map: ZeroMap<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        > = ZeroMap::open_hooked(
            dir.path().join("map"),
            watched_map_config(),
            WatchHook::with_old(NoHook),
        )
        .expect("open watched zero map");
        let key = key(1);
        let mut tree_rx = tree.watch(Default::default());
        let mut map_rx = map.watch(Default::default());

        for write in [WatchZeroRow(1), WatchZeroRow(2)] {
            tree.put(&key, &write).expect("tree write");
            map.put(&key, &write).expect("map write");
        }
        tree.delete(&key).expect("tree delete");
        map.delete(&key).expect("map delete");

        macro_rules! assert_events {
            ($rx:expr) => {{
                let rx = &mut $rx;
                let inserted = rx.try_recv().expect("insert event");
                assert_eq!(inserted.kind(), WatchKind::Insert);
                assert_eq!(inserted.old().expect("decode old"), None);
                assert_eq!(inserted.new().expect("decode new"), Some(WatchZeroRow(1)));
                let updated = rx.try_recv().expect("update event");
                assert_eq!(updated.kind(), WatchKind::Update);
                assert_eq!(updated.old().expect("decode old"), Some(WatchZeroRow(1)));
                assert_eq!(updated.new().expect("decode new"), Some(WatchZeroRow(2)));
                let deleted = rx.try_recv().expect("delete event");
                assert_eq!(deleted.kind(), WatchKind::Delete);
                assert_eq!(deleted.old().expect("decode old"), Some(WatchZeroRow(2)));
                assert_eq!(deleted.new().expect("decode new"), None);
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
            }};
        }
        assert_events!(tree_rx);
        assert_events!(map_rx);
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_zero_new_only_reports_upsert_and_delete_without_old_payload() {
        let dir = tempdir().expect("temporary directory");
        let tree: ZeroTree<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, false>,
        > = ZeroTree::open_hooked(
            dir.path().join("tree"),
            Config::test(),
            WatchHook::new_only(NoHook),
        )
        .expect("open new-only zero tree");
        let map: ZeroMap<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, false>,
        > = ZeroMap::open_hooked(
            dir.path().join("map"),
            watched_map_config(),
            WatchHook::new_only(NoHook),
        )
        .expect("open new-only zero map");
        let key = key(1);
        let mut tree_rx = tree.watch(Default::default());
        let mut map_rx = map.watch(Default::default());
        for write in [WatchZeroRow(1), WatchZeroRow(2)] {
            tree.put(&key, &write).expect("tree write");
            map.put(&key, &write).expect("map write");
        }
        tree.delete(&key).expect("tree delete");
        map.delete(&key).expect("map delete");

        macro_rules! assert_events {
            ($rx:expr) => {{
                let rx = &mut $rx;
                let inserted = rx.try_recv().expect("insert event");
                assert_eq!(inserted.kind(), WatchKind::Upsert);
                assert_eq!(inserted.old().expect("decode old"), None);
                let updated = rx.try_recv().expect("update event");
                assert_eq!(updated.kind(), WatchKind::Upsert);
                assert_eq!(updated.old().expect("decode old"), None);
                let deleted = rx.try_recv().expect("delete event");
                assert_eq!(deleted.kind(), WatchKind::Delete);
                assert_eq!(deleted.old().expect("decode old"), None);
                assert_eq!(rx.try_recv(), Err(WatchError::Empty));
            }};
        }
        assert_events!(tree_rx);
        assert_events!(map_rx);
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_zero_tree_update_many_emits_only_applied_put_and_delete() {
        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.shard_count = 1;
        let tree: ZeroTree<
            [u8; 8],
            { std::mem::size_of::<WatchZeroRow>() },
            WatchZeroRow,
            WatchHook<WatchZeroRow, NoHook, true>,
        > = ZeroTree::open_hooked(dir.path(), config, WatchHook::with_old(NoHook))
            .expect("open watched zero tree");
        let put_key = key(1);
        let delete_key = key(2);
        let keep_key = key(3);
        let mut rx = tree.watch(Default::default());
        tree.put(&delete_key, &WatchZeroRow(2))
            .expect("seed delete");
        rx.try_recv().expect("seed event");

        tree.update_many(
            vec![(put_key, 1u8), (delete_key, 2), (keep_key, 3)],
            |_, _, action| match action {
                1 => Upsert::Put(WatchZeroRow(1)),
                2 => Upsert::Delete,
                _ => Upsert::Keep,
            },
        )
        .expect("batch applies");

        assert_eq!(rx.try_recv().expect("put event").key(), &put_key);
        let deleted = rx.try_recv().expect("delete event");
        assert_eq!(deleted.key(), &delete_key);
        assert_eq!(deleted.kind(), WatchKind::Delete);
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_zero_ttl_sweep_deletes_tree_and_map_rows() {
        type TreeHook = crate::TtlHook<TtlWatchZeroRow, WatchHook<TtlWatchZeroRow, NoHook, true>>;
        type MapHook =
            crate::TtlHook<TtlWatchZeroMapRow, WatchHook<TtlWatchZeroMapRow, NoHook, true>>;
        let dir = tempdir().expect("temporary directory");
        let tree = ZeroTree::<
            [u8; 8],
            { std::mem::size_of::<TtlWatchZeroRow>() },
            TtlWatchZeroRow,
            TreeHook,
        >::open_hooked(
            dir.path().join("tree"),
            Config::test(),
            crate::TtlHook::new(WatchHook::with_old(NoHook)),
        )
        .expect("open ttl zero tree");
        let map = ZeroMap::<
            [u8; 8],
            { std::mem::size_of::<TtlWatchZeroMapRow>() },
            TtlWatchZeroMapRow,
            MapHook,
        >::open_hooked(
            dir.path().join("map"),
            watched_map_config(),
            crate::TtlHook::new(WatchHook::with_old(NoHook)),
        )
        .expect("open ttl zero map");
        tree.as_inner()
            .build_ttl_index()
            .expect("build tree ttl index");
        map.as_inner()
            .build_ttl_index()
            .expect("build map ttl index");
        let expired = key(1);
        let mut tree_rx = tree.watch(Default::default());
        let mut map_rx = map.watch(Default::default());
        tree.put(&expired, &TtlWatchZeroRow(1)).expect("tree put");
        map.put(&expired, &TtlWatchZeroMapRow(1)).expect("map put");
        tree_rx.try_recv().expect("tree seed event");
        map_rx.try_recv().expect("map seed event");

        assert_eq!(tree.sweep_expired(2, 1).expect("tree sweep").deleted, 1);
        assert_eq!(map.sweep_expired(2, 1).expect("map sweep").deleted, 1);
        assert_eq!(
            tree_rx.try_recv().expect("tree expiry").kind(),
            WatchKind::Delete
        );
        assert_eq!(
            map_rx.try_recv().expect("map expiry").kind(),
            WatchKind::Delete
        );
        assert!(tree.get(&expired).is_none());
        assert!(map.get(&expired).is_none());
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn watch_zero_transactions_deliver_only_after_commit() {
        let dir = tempdir().expect("temporary directory");
        let db = Arc::new(crate::armour::Db::open_test(dir.path()).expect("open db"));
        let tree = db
            .open_zero_tree::<WatchZeroRow, { std::mem::size_of::<WatchZeroRow>() }, _>(
                Config::test(),
                WatchHook::with_old(NoHook),
                &[],
            )
            .expect("open managed zero tree");
        let map = db
            .open_zero_map::<WatchZeroMapRow, { std::mem::size_of::<WatchZeroMapRow>() }, _>(
                watched_map_config(),
                WatchHook::with_old(NoHook),
                &[],
            )
            .expect("open managed zero map");
        let tree_key = key(1);
        let map_key = key(2);
        let mut tree_rx = tree.watch(Default::default());
        let mut map_rx = map.watch(Default::default());

        db.tx()
            .put(&tree, &tree_key, &WatchZeroRow(1))
            .expect("plan zero tree write")
            .put(&map, &map_key, &WatchZeroMapRow(2))
            .expect("plan zero map write")
            .commit()
            .expect("commit zero transaction");

        assert_eq!(tree_rx.try_recv().expect("tree event").key(), &tree_key);
        assert_eq!(map_rx.try_recv().expect("map event").key(), &map_key);
        assert_eq!(tree_rx.try_recv(), Err(WatchError::Empty));
        assert_eq!(map_rx.try_recv(), Err(WatchError::Empty));

        let rejected_key = key(3);
        let err = db
            .tx()
            .insert(&tree, &rejected_key, &WatchZeroRow(3))
            .expect("plan first zero insert")
            .insert(&tree, &rejected_key, &WatchZeroRow(4))
            .expect("plan duplicate zero insert")
            .commit()
            .expect_err("duplicate zero insert fails before the log");
        assert!(matches!(err, crate::DbError::KeyExists));
        assert_eq!(tree_rx.try_recv(), Err(WatchError::Empty));
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn watch_transaction_delivers_each_applied_row_only_after_all_unlocks() {
        use std::sync::atomic::{AtomicBool, Ordering};

        struct TouchRightOnWake {
            right: Arc<
                TypedTree<
                    [u8; 8],
                    WatchRightRow,
                    RapiraCodec,
                    crate::TtlHook<WatchRightRow, WatchHook<WatchRightRow, NoHook, true>>,
                >,
            >,
            key: [u8; 8],
            saw_right_unlocked: Arc<AtomicBool>,
        }

        impl std::task::Wake for TouchRightOnWake {
            fn wake(self: Arc<Self>) {
                self.saw_right_unlocked.store(
                    self.right.test_try_lock_writer_shard(&self.key),
                    Ordering::Release,
                );
            }
        }

        let dir = tempdir().expect("temporary directory");
        let db = Arc::new(crate::armour::Db::open_test(dir.path()).expect("open db"));
        let config = Config::test();
        let left = db
            .open_typed_tree::<WatchRow, RapiraCodec, _>(
                config.clone(),
                WatchHook::with_old(NoHook),
                &[],
            )
            .expect("open left participant");
        let right = db
            .open_typed_tree::<WatchRightRow, RapiraCodec, _>(
                config,
                WatchHook::with_old(NoHook),
                &[],
            )
            .expect("open right participant");
        let left_key = key(1);
        let right_key = key(2);
        let mut left_rx = left.watch(Default::default());
        let mut right_rx = right.watch(Default::default());
        let saw_right_unlocked = Arc::new(AtomicBool::new(false));
        let waker = Waker::from(Arc::new(TouchRightOnWake {
            right: Arc::clone(&right),
            key: right_key,
            saw_right_unlocked: Arc::clone(&saw_right_unlocked),
        }));
        let mut recv = Box::pin(left_rx.recv());
        assert!(matches!(
            Pin::as_mut(&mut recv).poll(&mut Context::from_waker(&waker)),
            Poll::Pending
        ));

        db.tx()
            .put(&left, &left_key, &WatchRow(1))
            .expect("plan left write")
            .put(&right, &right_key, &WatchRightRow(2))
            .expect("plan right write")
            .commit()
            .expect("commit watched transaction");

        assert!(
            saw_right_unlocked.load(Ordering::Acquire),
            "the left subscriber waker must run after the right participant unlocks"
        );
        drop(recv);
        assert_eq!(left_rx.try_recv().expect("left event").key(), &left_key);
        assert_eq!(right_rx.try_recv().expect("right event").key(), &right_key);
    }

    #[cfg(all(
        feature = "rapira-codec",
        feature = "var-collections",
        feature = "armour"
    ))]
    #[test]
    fn watch_pre_log_transaction_failure_emits_nothing() {
        let dir = tempdir().expect("temporary directory");
        let db = Arc::new(crate::armour::Db::open_test(dir.path()).expect("open db"));
        let tree = db
            .open_typed_tree::<WatchRow, RapiraCodec, _>(
                Config::test(),
                WatchHook::with_old(NoHook),
                &[],
            )
            .expect("open watched participant");
        let mut rx = tree.watch(Default::default());
        let watched_key = key(1);

        let err = db
            .tx()
            .insert(&tree, &watched_key, &WatchRow(1))
            .expect("plan first insert")
            .insert(&tree, &watched_key, &WatchRow(2))
            .expect("plan duplicate insert")
            .commit()
            .expect_err("duplicate insert fails before the log");

        assert!(matches!(err, crate::DbError::KeyExists));
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_update_many_emits_each_applied_mutation_but_not_keep() {
        let (tree, mut rx) = watched_typed_tree();
        let first = key(1);
        let second = key(2);
        let third = key(3);

        let applied = tree
            .update_many(
                vec![(first, 10), (second, 20), (third, 30)],
                |key, _old, value| {
                    if *key == third {
                        Upsert::Keep
                    } else {
                        Upsert::Put(WatchRow(*value))
                    }
                },
            )
            .expect("batch applies");

        assert!(matches!(applied[2].1, crate::Applied::Kept));
        assert_eq!(rx.try_recv().expect("first event").key(), &first);
        assert_eq!(rx.try_recv().expect("second event").key(), &second);
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_retain_emits_delete_for_each_removed_map_row() {
        let (map, mut rx) = watched_typed_map();
        let first = key(1);
        let second = key(2);
        map.put(&first, WatchRow(10)).expect("first insert");
        map.put(&second, WatchRow(20)).expect("second insert");
        let _ = rx.try_recv();
        let _ = rx.try_recv();

        map.iter_view()
            .expect("iterable map")
            .retain(|key, _| *key == second)
            .expect("retain");

        let event = rx.try_recv().expect("delete event");
        assert_eq!(event.key(), &first);
        assert_eq!(event.kind(), WatchKind::Delete);
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_ttl_sweep_emits_delete_after_the_row_is_gone() {
        let dir = tempdir().expect("temporary directory");
        let tree = TypedTree::open_hooked(
            dir.path(),
            Config::test(),
            RapiraCodec,
            crate::TtlHook::new(WatchHook::<TtlWatchRow, NoHook, true>::with_old(NoHook)),
        )
        .expect("open watched ttl tree");
        tree.build_ttl_index().expect("build ttl index");
        let mut rx = tree.watch(Default::default());
        let expired = key(1);
        tree.put(&expired, TtlWatchRow(1))
            .expect("insert expired row");
        let _ = rx.try_recv().expect("insert event");

        let outcome = tree.sweep_expired(2, 1).expect("sweep expired row");
        assert_eq!(outcome.deleted, 1);

        let event = rx.try_recv().expect("delete event");
        assert_eq!(event.kind(), WatchKind::Delete);
        assert!(tree.get(&expired).is_none());
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_ttl_sweep_var_typed_facades_emit_raw_deletes() {
        type Hook = crate::TtlHook<TtlWatchRow, WatchHook<TtlWatchRow, NoHook, true>>;
        let dir = tempdir().expect("temporary directory");
        let tree = VarTypedTree::<[u8; 8], TtlWatchRow, RapiraCodec, Hook>::open_hooked(
            dir.path().join("tree"),
            Config::test(),
            RapiraCodec,
            crate::TtlHook::new(WatchHook::with_old(NoHook)),
        )
        .expect("open watched ttl var tree");
        let map = VarTypedMap::<[u8; 8], TtlWatchRow, RapiraCodec, Hook>::open_hooked(
            dir.path().join("map"),
            Config::balanced().iterable(true).build(),
            RapiraCodec,
            crate::TtlHook::new(WatchHook::with_old(NoHook)),
        )
        .expect("open watched ttl var map");
        tree.as_inner()
            .build_ttl_index()
            .expect("build tree ttl index");
        map.as_inner()
            .build_ttl_index()
            .expect("build map ttl index");
        let mut tree_rx = tree.watch(Default::default());
        let mut map_rx = map.watch(Default::default());
        let expired = key(1);
        tree.put(&expired, &TtlWatchRow(1)).expect("tree insert");
        map.put(&expired, &TtlWatchRow(1)).expect("map insert");
        let _ = tree_rx.try_recv().expect("tree insert event");
        let _ = map_rx.try_recv().expect("map insert event");

        assert_eq!(tree.sweep_expired(2, 1).expect("tree sweep").deleted, 1);
        assert_eq!(map.sweep_expired(2, 1).expect("map sweep").deleted, 1);

        assert_eq!(
            tree_rx.try_recv().expect("tree delete").kind(),
            WatchKind::Delete
        );
        assert_eq!(
            map_rx.try_recv().expect("map delete").kind(),
            WatchKind::Delete
        );
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn new_only_var_typed_nohook_does_not_read_old_but_projected_still_does() {
        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.block_cache.max_size = 0;
        let plain = VarTypedTree::open_hooked(
            dir.path().join("plain"),
            config.clone(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
        )
        .expect("open new-only tree");
        let projected_path = dir.path().join("projected");
        let projected = VarTypedTree::open_hooked(
            &projected_path,
            config,
            RapiraCodec,
            WatchHook::<WatchRow, _, false>::new_only(
                crate::Projected::new(crate::IndexTargets::new(), |_, _, _| Ok(())).with(NoHook),
            ),
        )
        .expect("open projected tree");
        let key = key(1);
        plain.put(&key, &WatchRow(1)).expect("plain seed");
        projected.put(&key, &WatchRow(1)).expect("projected seed");
        plain.flush_buffers().expect("plain flush");
        projected.clean_shutdown().expect("projected shutdown");

        let before = crate::var_tree::test_locked_value_reads();
        plain.put(&key, &WatchRow(2)).expect("plain overwrite");
        assert_eq!(crate::var_tree::test_locked_value_reads() - before, 0);

        drop(projected);
        let mut reopened_config = Config::test();
        reopened_config.block_cache.max_size = 0;
        let projected = VarTypedTree::open_hooked(
            &projected_path,
            reopened_config,
            RapiraCodec,
            WatchHook::<WatchRow, _, false>::new_only(
                crate::Projected::new(crate::IndexTargets::new(), |_, _, _| Ok(())).with(NoHook),
            ),
        )
        .expect("reopen projected tree");
        let before = crate::var_tree::test_locked_value_reads();
        projected
            .put(&key, &WatchRow(2))
            .expect("projected overwrite");
        assert_eq!(crate::var_tree::test_locked_value_reads() - before, 1);
    }

    /// The companion the dormant-gate test above cannot give: with a receiver
    /// actually linked, `NEEDS_OLD_VALUE = OLD || H::NEEDS_OLD_VALUE` must make
    /// `with_old` pay one locked value read and `new_only` pay none. Without a
    /// live subscriber both modes read nothing, so the mode itself is untested.
    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn a_live_subscriber_reads_the_old_value_only_in_with_old_mode() {
        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.block_cache.max_size = 0;

        let retaining = VarTypedTree::open_hooked(
            dir.path().join("with_old"),
            config.clone(),
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
        )
        .expect("open with_old tree");
        let new_only = VarTypedTree::open_hooked(
            dir.path().join("new_only"),
            config,
            RapiraCodec,
            WatchHook::<WatchRow, NoHook, false>::new_only(NoHook),
        )
        .expect("open new_only tree");

        let key = key(1);
        retaining.put(&key, &WatchRow(1)).expect("with_old seed");
        new_only.put(&key, &WatchRow(1)).expect("new_only seed");
        retaining.flush_buffers().expect("with_old flush");
        new_only.flush_buffers().expect("new_only flush");

        let mut retaining_rx = retaining.watch(Default::default());
        let mut new_only_rx = new_only.watch(Default::default());

        let before = crate::var_tree::test_locked_value_reads();
        retaining
            .put(&key, &WatchRow(2))
            .expect("with_old overwrite");
        assert_eq!(
            crate::var_tree::test_locked_value_reads() - before,
            1,
            "a watched with_old write must read the old value"
        );

        let before = crate::var_tree::test_locked_value_reads();
        new_only
            .put(&key, &WatchRow(2))
            .expect("new_only overwrite");
        assert_eq!(
            crate::var_tree::test_locked_value_reads() - before,
            0,
            "a watched new_only write must not read the old value"
        );

        let retained = retaining_rx.try_recv().expect("with_old event");
        assert_eq!(retained.kind(), WatchKind::Update);
        assert_eq!(retained.old().expect("with_old old"), Some(WatchRow(1)));
        let plain = new_only_rx.try_recv().expect("new_only event");
        assert_eq!(plain.kind(), WatchKind::Upsert);
        assert_eq!(plain.old().expect("new_only old"), None);
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_update_many_raw_var_prefix_wakes_after_replay_on_later_error() {
        use std::sync::atomic::{AtomicBool, Ordering};

        use crate::Codec as _;

        struct MarkerHook {
            watch: WatchHook<WatchRow, NoHook, true>,
            replayed: Arc<AtomicBool>,
        }

        impl crate::TypedWriteHook<[u8; 8], WatchRow> for MarkerHook {
            const WATCHES: bool = true;
            const NEEDS_WRITE: bool = true;

            fn watch_channel(&self) -> Option<&Arc<WatchChannel<[u8; 8]>>> {
                self.watch.watch_channel()
            }

            fn watch_old(&self) -> bool {
                self.watch.watch_old()
            }

            fn on_write(&self, _key: &[u8; 8], _old: Option<&WatchRow>, _new: Option<&WatchRow>) {
                self.replayed.store(true, Ordering::Release);
            }
        }

        impl sealed::Enabled for MarkerHook {}

        struct WakeAfterReplay(Arc<AtomicBool>, Arc<AtomicBool>);

        impl std::task::Wake for WakeAfterReplay {
            fn wake(self: Arc<Self>) {
                self.0
                    .store(self.1.load(Ordering::Acquire), Ordering::Release);
            }
        }

        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.shard_count = 1;
        let replayed = Arc::new(AtomicBool::new(false));
        let tree = VarTypedTree::open_hooked(
            dir.path(),
            config,
            RapiraCodec,
            MarkerHook {
                watch: WatchHook::with_old(NoHook),
                replayed: Arc::clone(&replayed),
            },
        )
        .expect("open watched var tree");
        let mut rx = tree.watch(Default::default());
        let first = key(1);
        let second = key(2);
        let woke_after_replay = Arc::new(AtomicBool::new(false));
        let waker = Waker::from(Arc::new(WakeAfterReplay(
            Arc::clone(&woke_after_replay),
            Arc::clone(&replayed),
        )));
        let mut recv = Box::pin(rx.recv());
        assert!(matches!(
            Pin::as_mut(&mut recv).poll(&mut Context::from_waker(&waker)),
            Poll::Pending
        ));

        let _fail = crate::var_tree::UpdateManyFailAfter::after(1);
        let err = tree
            .as_inner()
            .update_many(
                vec![(first, WatchRow(1)), (second, WatchRow(2))],
                |_, _, value| {
                    Upsert::Put(ByteView::from(
                        RapiraCodec.encode(value).expect("encode test value"),
                    ))
                },
            )
            .expect_err("second raw mutation fails");
        assert!(matches!(
            err,
            crate::DbError::Internal("test: update_many injected failure")
        ));

        assert!(woke_after_replay.load(Ordering::Acquire));
        drop(recv);
        assert_eq!(rx.try_recv().expect("applied prefix event").key(), &first);
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_facade_event_is_readable_after_the_row_becomes_visible() {
        let (tree, mut rx) = watched_typed_tree();
        let key = 7u64.to_be_bytes();

        tree.put(&key, WatchRow(70)).expect("put watched row");

        let event = rx.try_recv().expect("watch event");
        assert_eq!(tree.get(&key).map(|value| value.0), Some(70));
        assert_eq!(event.new().expect("decode event"), Some(WatchRow(70)));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_atomic_replays_events_in_application_order_after_unlock() {
        let (tree, mut rx) = watched_typed_tree();
        let first = 1u64.to_be_bytes();
        let second = 2u64.to_be_bytes();

        tree.atomic(&first, |shard| {
            shard.put(&first, WatchRow(1))?;
            shard.put(&second, WatchRow(2))?;
            Ok(())
        })
        .expect("atomic watched writes");

        assert_eq!(
            [
                rx.try_recv().expect("first event").key().to_owned(),
                rx.try_recv().expect("second event").key().to_owned(),
            ],
            [first, second]
        );
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_wake_is_not_under_lock() {
        use std::sync::atomic::{AtomicBool, Ordering};

        struct ReadOnWake {
            tree: Arc<TypedTree<[u8; 8], WatchRow, RapiraCodec, WatchHook<WatchRow, NoHook, true>>>,
            key: [u8; 8],
            writer_released: Arc<AtomicBool>,
        }

        impl std::task::Wake for ReadOnWake {
            fn wake(self: Arc<Self>) {
                self.writer_released.store(
                    self.tree.test_try_lock_writer_shard(&self.key),
                    Ordering::Release,
                );
            }
        }

        let dir = tempdir().expect("temporary directory");
        let mut config = Config::test();
        config.shard_count = 2;
        let tree = Arc::new(
            TypedTree::open_hooked(
                dir.path(),
                config,
                RapiraCodec,
                WatchHook::<WatchRow, NoHook, true>::with_old(NoHook),
            )
            .expect("open watched typed tree"),
        );
        let write_key = 1u64.to_be_bytes();

        let mut rx = tree.watch(Default::default());
        let writer_released = Arc::new(AtomicBool::new(false));
        let waker = Waker::from(Arc::new(ReadOnWake {
            tree: Arc::clone(&tree),
            key: write_key,
            writer_released: Arc::clone(&writer_released),
        }));
        let mut recv = Box::pin(rx.recv());
        assert!(matches!(
            Pin::as_mut(&mut recv).poll(&mut Context::from_waker(&waker)),
            Poll::Pending
        ));

        tree.put(&write_key, WatchRow(2))
            .expect("publish watched row");
        assert!(writer_released.load(Ordering::Acquire));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_var_typed_facades_publish_raw_mutations() {
        let dir = tempdir().expect("temporary directory");
        let hook = || WatchHook::<WatchRow, NoHook, true>::with_old(NoHook);
        let tree =
            VarTypedTree::open_hooked(dir.path().join("tree"), Config::test(), RapiraCodec, hook())
                .expect("open watched var tree");
        let map = VarTypedMap::open_hooked(
            dir.path().join("map"),
            watched_map_config(),
            RapiraCodec,
            hook(),
        )
        .expect("open watched var map");
        let mut tree_rx = tree.watch(Default::default());
        let mut map_rx = map.watch(Default::default());
        let key = 9u64.to_be_bytes();

        tree.put(&key, &WatchRow(9)).expect("put var tree row");
        map.put(&key, &WatchRow(9)).expect("put var map row");

        assert_eq!(
            tree_rx
                .try_recv()
                .expect("tree event")
                .new()
                .expect("decode"),
            Some(WatchRow(9))
        );
        assert_eq!(
            map_rx.try_recv().expect("map event").new().expect("decode"),
            Some(WatchRow(9))
        );
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_ttl_wrapper_preserves_old_update_and_delete() {
        let dir = tempdir().expect("temporary directory");
        let tree = TypedTree::open_hooked(
            dir.path(),
            Config::test(),
            RapiraCodec,
            crate::TtlHook::new(WatchHook::<WatchRow, NoHook, true>::with_old(NoHook)),
        )
        .expect("open watched ttl tree");
        let mut rx = tree.watch(Default::default());
        let key = 11u64.to_be_bytes();

        tree.put(&key, WatchRow(1)).expect("insert");
        let _ = rx.try_recv().expect("insert event");
        tree.put(&key, WatchRow(2)).expect("update");
        let update = rx.try_recv().expect("update event");
        tree.delete(&key).expect("delete");
        let delete = rx.try_recv().expect("delete event");

        assert_eq!(update.kind(), WatchKind::Update);
        assert_eq!(update.old().expect("decode old"), Some(WatchRow(1)));
        assert_eq!(delete.kind(), WatchKind::Delete);
        assert_eq!(delete.old().expect("decode old"), Some(WatchRow(2)));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_projected_wrapper_preserves_old_update_and_delete() {
        let dir = tempdir().expect("temporary directory");
        let hook = crate::Projected::new(crate::IndexTargets::new(), |_, _, _| Ok(()))
            .with(WatchHook::<WatchRow, NoHook, true>::with_old(NoHook));
        let tree = TypedTree::open_hooked(dir.path(), Config::test(), RapiraCodec, hook)
            .expect("open watched projected tree");
        let mut rx = tree.watch(Default::default());
        let key = 12u64.to_be_bytes();

        tree.put(&key, WatchRow(1)).expect("insert");
        let _ = rx.try_recv().expect("insert event");
        tree.put(&key, WatchRow(2)).expect("update");
        let update = rx.try_recv().expect("update event");
        tree.delete(&key).expect("delete");
        let delete = rx.try_recv().expect("delete event");

        assert_eq!(update.kind(), WatchKind::Update);
        assert_eq!(update.old().expect("decode old"), Some(WatchRow(1)));
        assert_eq!(delete.kind(), WatchKind::Delete);
        assert_eq!(delete.old().expect("decode old"), Some(WatchRow(2)));
    }

    #[cfg(all(feature = "rapira-codec", feature = "var-collections"))]
    #[test]
    fn watch_hook_preserves_inner_no_write_and_enabled_wrappers() {
        type Hook = WatchHook<WatchRow, NoHook, true>;
        assert!(<Hook as crate::TypedWriteHook<[u8; 8], WatchRow>>::WATCHES);
        assert!(!<Hook as crate::TypedWriteHook<[u8; 8], WatchRow>>::NEEDS_WRITE);

        fn assert_enabled<H: sealed::Enabled>() {}
        assert_enabled::<crate::ttl::TtlHook<WatchRow, Hook>>();
        assert_enabled::<crate::Projected<[u8; 8], WatchRow, Hook>>();
        assert_enabled::<crate::ZeroHookAdapter<[u8; 8], WatchZeroRow, Hook>>();
        assert_enabled::<crate::VarTypedHookAdapter<[u8; 8], WatchRow, RapiraCodec, Hook>>();
    }

    struct U64Spec;
    #[derive(Clone)]
    struct U64Decoder;

    impl Default for U64Decoder {
        fn default() -> Self {
            Self
        }
    }

    impl sealed::Spec for U64Spec {}

    impl WatchDecoder<u64> for U64Decoder {
        fn decode(&self, bytes: &[u8]) -> DbResult<u64> {
            Ok(u64::from_be_bytes(
                bytes.try_into().expect("test payload length"),
            ))
        }
    }

    impl WatchSpec for U64Spec {
        type Key = [u8; 8];
        type Value = u64;
        type Decoder = U64Decoder;
    }

    fn key(value: u64) -> [u8; 8] {
        value.to_be_bytes()
    }
    fn bytes(value: u64) -> Box<[u8]> {
        value.to_be_bytes().into()
    }

    #[test]
    fn recv_timeout_reports_timeout_on_an_empty_ring_and_actually_waits() {
        let (_channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        let timeout = std::time::Duration::from_millis(60);
        let started = std::time::Instant::now();
        assert_eq!(rx.recv_timeout(timeout), Err(WatchError::Timeout));
        assert!(
            started.elapsed() >= timeout,
            "recv_timeout returned before its deadline"
        );
    }

    /// Precedence: an event already in the ring outranks an expired deadline.
    /// A zero timeout must therefore behave like `try_recv` on a non-empty
    /// ring, not like an immediate `Timeout`.
    #[test]
    fn recv_timeout_returns_a_queued_event_even_with_an_expired_deadline() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(2).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));

        let event = rx
            .recv_timeout(std::time::Duration::ZERO)
            .expect("queued event outranks the deadline");
        assert_eq!(*event.key(), key(1));
        assert_eq!(event.new().unwrap(), Some(10));
        assert_eq!(
            rx.recv_timeout(std::time::Duration::ZERO),
            Err(WatchError::Timeout)
        );
    }

    /// `Closed` outranks `Timeout`: a terminal channel must not make a caller
    /// spend its deadline waiting for events that can never arrive.
    #[test]
    fn recv_timeout_reports_closed_without_waiting_out_the_deadline() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));
        channel.close_terminal();

        assert_eq!(
            *rx.recv_timeout(std::time::Duration::ZERO).unwrap().key(),
            key(1)
        );
        let started = std::time::Instant::now();
        assert_eq!(
            rx.recv_timeout(std::time::Duration::from_secs(30)),
            Err(WatchError::Closed)
        );
        assert!(
            started.elapsed() < std::time::Duration::from_secs(5),
            "a closed channel must not wait out the deadline"
        );
    }

    /// `Lagged(n)` is a count, not a flag: every existing overflow test loses
    /// exactly one event, which cannot tell an exact count from a saturating
    /// "at least one".
    #[test]
    fn lagged_counts_every_dropped_event_not_just_the_first() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        for value in 1..=4u64 {
            channel.publish_for_test(key(value), None, Some(bytes(value * 10)));
        }

        assert_eq!(rx.try_recv(), Err(WatchError::Lagged(3)));
        let survivor = rx.try_recv().expect("the newest event survives");
        assert_eq!(*survivor.key(), key(4));
        assert_eq!(survivor.new().unwrap(), Some(40));
        assert_eq!(rx.try_recv(), Err(WatchError::Empty));

        // The gap is reported once, and the counter restarts from it.
        channel.publish_for_test(key(5), None, Some(bytes(50)));
        channel.publish_for_test(key(6), None, Some(bytes(60)));
        assert_eq!(rx.try_recv(), Err(WatchError::Lagged(1)));
        assert_eq!(*rx.try_recv().expect("post-gap event").key(), key(6));
    }

    #[test]
    fn lagged_is_reported_before_the_post_gap_event() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));
        channel.publish_for_test(key(2), None, Some(bytes(20)));

        assert_eq!(rx.try_recv(), Err(WatchError::Lagged(1)));
        let event = rx.try_recv().unwrap();
        assert_eq!(*event.key(), key(2));
        assert_eq!(event.kind(), WatchKind::Upsert);
        assert_eq!(event.new().unwrap(), Some(20));
    }

    #[test]
    fn terminal_close_drains_before_closed() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(2).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));
        channel.close_terminal();
        assert!(rx.try_recv().is_ok());
        assert_eq!(rx.try_recv(), Err(WatchError::Closed));
    }

    #[test]
    fn recv_many_keeps_a_front_gap_and_zero_max_is_a_noop() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));
        channel.publish_for_test(key(2), None, Some(bytes(20)));
        let mut events = Vec::new();
        assert_eq!(rx.recv_many(&mut events, 0), Ok(0));
        assert!(events.is_empty());
        assert_eq!(rx.recv_many(&mut events, 2), Err(WatchError::Lagged(1)));
        assert!(events.is_empty());
        assert_eq!(rx.recv_many(&mut events, 2), Ok(1));
        assert_eq!(*events.pop().unwrap().key(), key(2));
    }

    #[test]
    fn capacity_two_reports_the_gap_before_surviving_events() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(2).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));
        channel.publish_for_test(key(2), None, Some(bytes(20)));
        channel.publish_for_test(key(3), None, Some(bytes(30)));

        assert_eq!(rx.try_recv(), Err(WatchError::Lagged(1)));
        assert_eq!(*rx.try_recv().unwrap().key(), key(2));
        assert_eq!(*rx.try_recv().unwrap().key(), key(3));
    }

    #[test]
    fn capacity_three_reports_the_gap_before_all_surviving_events() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(3).unwrap());
        for value in 1..=4 {
            channel.publish_for_test(key(value), None, Some(bytes(value * 10)));
        }

        assert_eq!(rx.try_recv(), Err(WatchError::Lagged(1)));
        assert_eq!(*rx.try_recv().unwrap().key(), key(2));
        assert_eq!(*rx.try_recv().unwrap().key(), key(3));
        assert_eq!(*rx.try_recv().unwrap().key(), key(4));
    }

    #[test]
    fn recv_many_reports_a_front_gap_before_surviving_events() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(2).unwrap());
        channel.publish_for_test(key(1), None, Some(bytes(10)));
        channel.publish_for_test(key(2), None, Some(bytes(20)));
        channel.publish_for_test(key(3), None, Some(bytes(30)));

        let mut events = Vec::new();
        assert_eq!(rx.recv_many(&mut events, 2), Err(WatchError::Lagged(1)));
        assert!(events.is_empty());
        assert_eq!(rx.recv_many(&mut events, 2), Ok(2));
        assert_eq!(*events.remove(0).key(), key(2));
        assert_eq!(*events.remove(0).key(), key(3));
    }

    #[test]
    fn terminal_close_waits_for_an_entered_producer() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        let (producer_entered, release_producer) = channel.arm_before_publish();
        let (close_marked, release_close) = channel.arm_after_terminal_mark();
        let producer_channel = Arc::clone(&channel);
        let producer = std::thread::spawn(move || {
            producer_channel.publish_for_test(key(5), None, Some(bytes(50)));
        });
        producer_entered.wait();

        let close_channel = Arc::clone(&channel);
        let closer = std::thread::spawn(move || close_channel.close_terminal());
        close_marked.wait();
        release_close.wait();
        release_producer.wait();
        producer.join().unwrap();
        closer.join().unwrap();

        assert_eq!(*rx.try_recv().unwrap().key(), key(5));
        assert_eq!(rx.try_recv(), Err(WatchError::Closed));
    }

    #[test]
    fn final_deregister_during_started_producer_traversal_is_safe() {
        struct ReleaseAndJoin {
            release: Option<Arc<std::sync::Barrier>>,
            publisher: Option<std::thread::JoinHandle<()>>,
        }
        impl Drop for ReleaseAndJoin {
            fn drop(&mut self) {
                if let Some(release) = self.release.take() {
                    release.wait();
                }
                if let Some(publisher) = self.publisher.take() {
                    let _ = publisher.join();
                }
            }
        }

        let (channel, rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        let (started, release) = channel.arm_after_traversal_starts();
        let publisher = {
            let channel = Arc::clone(&channel);
            std::thread::spawn(move || channel.publish_for_test(key(8), None, Some(bytes(80))))
        };
        let mut cleanup = ReleaseAndJoin {
            release: Some(release),
            publisher: Some(publisher),
        };
        started.wait();
        drop(rx);
        assert_eq!(channel.debug_subscriber_count(), 0);
        cleanup.release.take().expect("traversal release").wait();
        cleanup.publisher.take().expect("publisher").join().unwrap();
        assert_eq!(channel.debug_subscriber_count(), 0);
    }

    #[test]
    fn terminal_close_wakes_a_polled_receiver_and_blocks_later_pushes() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct CountWake(Arc<AtomicUsize>);
        impl std::task::Wake for CountWake {
            fn wake(self: Arc<Self>) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }

        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        let wakes = Arc::new(AtomicUsize::new(0));
        let waker = Waker::from(Arc::new(CountWake(Arc::clone(&wakes))));
        let mut pending = Box::pin(rx.recv());
        assert!(matches!(
            pending.as_mut().poll(&mut Context::from_waker(&waker)),
            Poll::Pending
        ));
        channel.close_terminal();
        assert_eq!(wakes.load(Ordering::SeqCst), 1);
        drop(pending);
        channel.publish_for_test(key(9), None, Some(bytes(90)));
        assert_eq!(rx.try_recv(), Err(WatchError::Closed));
    }

    #[test]
    fn dropped_recv_future_unregisters_its_waker_and_event_remains() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        let mut future = Box::pin(rx.recv());
        assert!(matches!(
            Pin::as_mut(&mut future).poll(&mut Context::from_waker(Waker::noop())),
            Poll::Pending
        ));
        drop(future);
        channel.publish_for_test(key(3), None, Some(bytes(30)));
        assert_eq!(rx.try_recv().unwrap().new().unwrap(), Some(30));
        assert_eq!(channel.debug_registered_wakers(), 0);
    }

    #[test]
    fn blocking_receiver_observes_publish_between_empty_check_and_park() {
        let (channel, mut rx) = test_channel::<[u8; 8], U64Spec>(NonZeroUsize::new(1).unwrap());
        let (checked_empty, release) = test_support::arm_before_condvar_park();
        let join = std::thread::spawn(move || rx.recv_blocking());
        checked_empty.wait();
        channel.publish_for_test(key(4), None, Some(bytes(40)));
        release.wait();
        assert_eq!(join.join().unwrap().unwrap().new().unwrap(), Some(40));
    }
}