wse 3.2.0

WebSocket engine for reactive user interfaces: topics with message recovery, presence, clustering without a broker, JWT, end-to-end encryption and signed messages.
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
use bytes::Bytes;
use dashmap::DashMap;
use std::collections::VecDeque;
use std::mem::size_of;
use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

/// Global counter to guarantee unique epochs even for rapid buffer re-creation.
static EPOCH_COUNTER: AtomicU32 = AtomicU32::new(0);

// ---------------------------------------------------------------------------
// RecoveryResult
// ---------------------------------------------------------------------------

pub(crate) enum RecoveryResult {
    /// Successfully recovered messages after the requested offset.
    Recovered {
        publications: Vec<Bytes>,
        epoch: u32,
        offset: u64,
    },
    /// Epoch mismatch or offset too old -- client must re-subscribe.
    NotRecovered { epoch: u32, offset: u64 },
    /// No history buffer exists for the requested topic.
    NoHistory,
}

// ---------------------------------------------------------------------------
// RecoveryConfig
// ---------------------------------------------------------------------------

pub(crate) struct RecoveryConfig {
    /// Power-of-two exponent for the per-topic message limit (default 7 = 128
    /// msgs). Clamped to `MAX_BUFFER_SIZE_BITS`.
    pub(crate) buffer_size_bits: u32,
    /// How long (seconds) an idle topic buffer lives before cleanup evicts it.
    pub(crate) history_ttl_secs: u64,
    /// Maximum number of messages returned in a single recovery response.
    pub(crate) max_recovery_messages: usize,
    /// Global memory budget across all topic buffers (bytes).
    pub(crate) global_memory_budget: usize,
}

impl Default for RecoveryConfig {
    fn default() -> Self {
        Self {
            buffer_size_bits: 7,   // 128 slots
            history_ttl_secs: 300, // 5 minutes
            max_recovery_messages: 500,
            global_memory_budget: 256 * 1024 * 1024, // 256 MB
        }
    }
}

/// How often expired and over-budget buffers are removed.
pub(crate) const CLEANUP_INTERVAL: Duration = Duration::from_secs(30);

/// How often the arrival order is marked, and how many marks are kept at
/// most (a day of them).
pub(crate) const MARK_INTERVAL: Duration = Duration::from_secs(1);
const MAX_MARKS: usize = 86_400;

/// How much before a peer's interest began the messages it is sent go back:
/// a mark's interval, and the time its request took to come.
const LATELY_MARGIN: Duration = Duration::from_secs(3);

/// Most topics with no buffer left whose removed history is kept, for the
/// peers that may ask after a lost link; past them, any topic counts as one.
/// As many relayed streams with no buffer have where this node stands in
/// them kept.
const MAX_UNKEPT_TOPICS: usize = 100_000;

/// Largest per-topic message limit: 2^16 = 65536 messages.
pub(crate) const MAX_BUFFER_SIZE_BITS: u32 = 16;

/// Bytes charged to the memory budget for a buffer's struct, its map entry and
/// bookkeeping, on top of its topic key and its message slots.
const BUFFER_OVERHEAD: usize = 128;

// ---------------------------------------------------------------------------
// RecoveryEntry -- single message stored in the foreign ring buffer
// ---------------------------------------------------------------------------

struct RecoveryEntry {
    /// Pre-framed WebSocket bytes (Arc-shared with broadcast path -- zero-copy).
    data: Bytes,
    /// Monotonic offset within this topic buffer.
    offset: u64,
    /// Its place in this node's arrival order (`RecoveryManager::arrival`).
    seq: u64,
}

/// A stored message and its place in this node's arrival order.
type Arrived = (u64, Bytes);

/// The streams' messages in one list: each stream in its own order, the
/// streams interleaved by when their messages arrived here.
fn interleave(streams: Vec<Vec<Arrived>>) -> Vec<Bytes> {
    let mut out = Vec::with_capacity(streams.iter().map(Vec::len).sum());
    let mut streams: Vec<_> = streams
        .into_iter()
        .map(|stream| stream.into_iter().peekable())
        .collect();
    while let Some((_, i)) = streams
        .iter_mut()
        .enumerate()
        .filter_map(|(i, stream)| stream.peek().map(|(seq, _)| (*seq, i)))
        .min()
    {
        if let Some((_, data)) = streams[i].next() {
            out.push(data);
        }
    }
    out
}

/// The topic of a foreign buffer's key (`topic\0epoch`).
fn foreign_topic(key: &str) -> &str {
    key.split_once('\0').map_or(key, |(topic, _)| topic)
}

// ---------------------------------------------------------------------------
// TopicRecoveryBuffer -- per-topic ring buffer
// ---------------------------------------------------------------------------

struct TopicRecoveryBuffer {
    /// Stored messages in offset order; the front holds `tail_offset()`. The
    /// queue grows as messages arrive, so a topic that has seen a handful of
    /// messages does not pay for `capacity` slots.
    entries: VecDeque<(Bytes, u64)>,
    /// Maximum number of messages kept; the oldest is evicted beyond it.
    capacity: usize,
    /// The latest arrival number evicted (0: none): every message that
    /// arrived after it is still here.
    evicted_through: u64,
    /// Next offset to be written (one past the newest entry).
    head_offset: u64,
    /// Random epoch generated on creation -- changes on server restart.
    epoch: u32,
    /// Total bytes of all stored entries' data.
    total_bytes: usize,
    /// Length of the topic key this buffer is stored under.
    key_len: usize,
    /// Timestamp of the most recent push.
    last_write: Instant,
}

impl TopicRecoveryBuffer {
    /// Create an empty buffer that keeps at most `1 << capacity_bits` messages.
    fn new(capacity_bits: u32, key_len: usize) -> Self {
        // Generate a unique epoch: time + PID + counter (no external rand dependency).
        // Counter guarantees uniqueness even for rapid buffer re-creation within same process.
        let epoch = (SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as u32)
            .wrapping_add(std::process::id())
            .wrapping_add(EPOCH_COUNTER.fetch_add(1, Ordering::Relaxed));

        Self {
            entries: VecDeque::new(),
            capacity: 1usize << capacity_bits.min(MAX_BUFFER_SIZE_BITS),
            evicted_through: 0,
            head_offset: 0,
            epoch,
            total_bytes: 0,
            key_len,
            last_write: Instant::now(),
        }
    }

    /// Oldest offset still in the buffer (equals `head_offset` when empty).
    fn tail_offset(&self) -> u64 {
        self.head_offset - self.entries.len() as u64
    }

    /// Bytes this buffer costs: payloads, allocated queue slots, the key and
    /// fixed overhead. This, not just the payload size, is what the memory
    /// budget is checked against.
    fn footprint(&self) -> usize {
        self.total_bytes
            + self.entries.capacity() * size_of::<(Bytes, u64)>()
            + self.key_len
            + BUFFER_OVERHEAD
    }

    /// Push a message into the buffer. Returns the assigned offset.
    ///
    /// When the buffer is full, the oldest entry is evicted.
    fn push(&mut self, data: Bytes, seq: u64) -> u64 {
        if self.entries.len() >= self.capacity
            && let Some((old, old_seq)) = self.entries.pop_front()
        {
            self.total_bytes -= old.len();
            self.evicted_through = self.evicted_through.max(old_seq);
        }

        let offset = self.head_offset;
        self.total_bytes += data.len();
        self.entries.push_back((data, seq));
        self.head_offset += 1;
        self.last_write = Instant::now();

        offset
    }

    /// Recover messages with offset strictly greater than `after_offset`.
    ///
    /// Returns `None` if `after_offset` is older than the tail (gap too large).
    /// Results are capped at `max_messages`.
    fn recover_since(&self, after_offset: u64, max_messages: usize) -> Option<Vec<Arrived>> {
        // If the first message we need (after_offset + 1) is before the tail,
        // those messages have been evicted -- gap too large.
        let start = match after_offset.checked_add(1) {
            Some(s) => s,
            None => return Some(Vec::new()), // u64::MAX means fully up-to-date
        };

        let tail = self.tail_offset();
        if self.head_offset > 0 && start < tail {
            return None;
        }
        if start >= self.head_offset {
            // Nothing to recover -- client is up to date.
            return Some(Vec::new());
        }

        let count = ((self.head_offset - start) as usize).min(max_messages);
        let first = (start - tail) as usize;
        Some(
            self.entries
                .iter()
                .skip(first)
                .take(count)
                .map(|(data, seq)| (*seq, data.clone()))
                .collect(),
        )
    }

    /// The arrival number of the message at `offset`, if it is still here.
    fn seq_at(&self, offset: u64) -> Option<u64> {
        let tail = self.tail_offset();
        (offset >= tail && offset < self.head_offset)
            .then(|| self.entries[(offset - tail) as usize].1)
    }

    /// Where the client's last message (`offset`) stands in this node's
    /// arrival order: its own number, the last evicted one's when it was
    /// that, or the newest's when the client has everything here.
    fn anchor_seq(&self, offset: u64) -> Option<u64> {
        self.seq_at(offset)
            .or_else(|| {
                (offset.checked_add(1) == Some(self.tail_offset()) && self.evicted_through > 0)
                    .then_some(self.evicted_through)
            })
            .or_else(|| {
                (offset.saturating_add(1) >= self.head_offset)
                    .then(|| self.entries.back().map(|(_, seq)| *seq))
                    .flatten()
            })
    }

    /// The whole stream, when this node holds all of it (nothing evicted)
    /// and every message arrived after `seq`.
    fn whole_after(&self, seq: u64) -> Option<Vec<Arrived>> {
        (self.evicted_through == 0 && self.entries.iter().all(|(_, s)| *s > seq)).then(|| {
            self.entries
                .iter()
                .map(|(data, s)| (*s, data.clone()))
                .collect()
        })
    }

    /// The latest arrival number among what it holds or evicted (0: none).
    fn last_seq(&self) -> u64 {
        self.entries
            .back()
            .map_or(self.evicted_through, |(_, seq)| *seq)
    }

    /// From offset `from` on, the messages held: each one's offset,
    /// arrival number and bytes.
    fn held_from(&self, from: u64) -> impl Iterator<Item = (u64, u64, &Bytes)> {
        let tail = self.tail_offset();
        let from = from.max(tail);
        self.entries
            .iter()
            .skip(usize::try_from(from - tail).unwrap_or(usize::MAX))
            .zip(from..)
            .map(|((data, seq), offset)| (offset, *seq, data))
    }

    /// The messages that arrived after `seq`; None when one of them was
    /// evicted already.
    fn arrived_after(&self, seq: u64) -> Option<Vec<Arrived>> {
        if self.evicted_through > seq {
            return None;
        }
        Some(
            self.entries
                .iter()
                .filter(|(_, s)| *s > seq)
                .map(|(data, s)| (*s, data.clone()))
                .collect(),
        )
    }
}

// ---------------------------------------------------------------------------
// ForeignRecoveryBuffer -- stores messages from other cluster nodes
// ---------------------------------------------------------------------------
//
// When a cluster peer publishes a message, it attaches its local (epoch, offset).
// This buffer stores those messages keyed by the origin node's epoch so that a
// client reconnecting to *this* node can recover using the original epoch/offset
// even though the messages originated elsewhere.

/// What this node no longer holds of a topic: the latest arrival among it,
/// when the last of it went, and the latest arrival among what it published
/// to other nodes (0: none of that).
#[derive(Clone, Copy)]
struct Removed {
    through: u64,
    at: Instant,
    shared_through: u64,
}

impl Removed {
    fn note(&mut self, seq: u64, shared: bool) {
        self.through = self.through.max(seq);
        self.at = Instant::now();
        if shared {
            self.shared_through = self.shared_through.max(seq);
        }
    }

    fn none() -> Self {
        Self {
            through: 0,
            at: Instant::now(),
            shared_through: 0,
        }
    }
}

/// Where this node stands in a stream relayed to it that it holds no buffer
/// of (no room to make one, or it was removed): every offset up to
/// `through` was delivered, and of the 64 after it, each `above` has a bit
/// for. A peer whose link was lost is asked after `through`, and what it
/// sends again of them is not delivered twice.
struct Delivered {
    epoch: u32,
    through: u64,
    above: u64,
    at: Instant,
}

impl Delivered {
    fn first(epoch: u32, offset: u64) -> Self {
        Self {
            epoch,
            through: offset,
            above: 0,
            at: Instant::now(),
        }
    }

    /// Where a buffer removed stood: what it held, and what it let go of.
    fn of(buf: &ForeignRecoveryBuffer) -> Option<Self> {
        if !buf.initialized {
            return None;
        }
        let through = buf
            .contiguous_through()
            .or_else(|| buf.head_offset.checked_sub(1))?;
        let above = buf
            .entries
            .iter()
            .flatten()
            .filter(|entry| entry.offset > through && entry.offset - through <= 64)
            .fold(0u64, |above, entry| {
                above | 1 << (entry.offset - through - 1)
            });
        Some(Self {
            epoch: buf.epoch,
            through,
            above,
            at: buf.last_write,
        })
    }

    /// `offset` is delivered: false when it was already. One more than 64
    /// past `through` moves the window on, and gives up on what it leaves
    /// behind undelivered.
    fn deliver(&mut self, offset: u64) -> bool {
        self.at = Instant::now();
        if offset <= self.through {
            return false;
        }
        let mut ahead = offset - self.through - 1;
        if ahead >= 64 {
            let shift = ahead - 63;
            self.above = self.above.checked_shr(shift.min(64) as u32).unwrap_or(0);
            self.through += shift;
            ahead = 63;
        }
        let bit = 1u64 << ahead;
        if self.above & bit != 0 {
            return false;
        }
        self.above |= bit;
        let run = self.above.trailing_ones();
        self.through += u64::from(run);
        self.above = self.above.checked_shr(run).unwrap_or(0);
        true
    }

    fn has(&self, offset: u64) -> bool {
        offset <= self.through || {
            let ahead = offset - self.through - 1;
            ahead < 64 && self.above & (1 << ahead) != 0
        }
    }

    /// Something after `offset` was delivered.
    fn any_after(&self, offset: u64) -> bool {
        if offset < self.through {
            return true;
        }
        let ahead = offset - self.through;
        ahead < 64 && self.above.checked_shr(ahead as u32).unwrap_or(0) != 0
    }
}

struct ForeignRecoveryBuffer {
    entries: Box<[Option<RecoveryEntry>]>,
    mask: u64,
    head_offset: u64,
    tail_offset: u64,
    /// The originating node's epoch (not ours).
    epoch: u32,
    total_bytes: usize,
    /// Length of the "topic\0epoch" key this buffer is stored under.
    key_len: usize,
    last_write: Instant,
    initialized: bool,
    /// The latest arrival number evicted (0: none).
    evicted_through: u64,
}

impl ForeignRecoveryBuffer {
    fn new(capacity_bits: u32, epoch: u32, key_len: usize) -> Self {
        let capacity = 1u64 << capacity_bits.min(MAX_BUFFER_SIZE_BITS);
        let mut entries = Vec::with_capacity(capacity as usize);
        entries.resize_with(capacity as usize, || None);
        Self {
            entries: entries.into_boxed_slice(),
            mask: capacity - 1,
            head_offset: 0,
            tail_offset: 0,
            epoch,
            total_bytes: 0,
            key_len,
            last_write: Instant::now(),
            initialized: false,
            evicted_through: 0,
        }
    }

    /// Bytes this buffer costs (the ring's slots are allocated up front,
    /// because peer offsets can arrive with gaps and out of order).
    fn footprint(&self) -> usize {
        self.total_bytes
            + self.entries.len() * size_of::<Option<RecoveryEntry>>()
            + self.key_len
            + BUFFER_OVERHEAD
    }

    /// Insert at the origin node's offset. Handles gaps and out-of-order
    /// arrival. False when it is here already, or older than what is kept:
    /// nothing new for this node.
    fn push_at(&mut self, data: Bytes, origin_offset: u64, seq: u64) -> bool {
        let capacity = self.mask + 1;

        // First message sets the baseline (handles origin_offset = 0 correctly).
        if !self.initialized {
            self.tail_offset = origin_offset;
            self.head_offset = origin_offset;
            self.initialized = true;
        }

        // Skip if already stored (duplicate or behind tail).
        if origin_offset < self.tail_offset || self.seq_at(origin_offset).is_some() {
            return false;
        }

        // Advance head if this is a new high-water mark.
        if origin_offset >= self.head_offset {
            let new_tail = origin_offset.saturating_sub(capacity - 1);
            if new_tail.saturating_sub(self.tail_offset) >= capacity {
                // The jump leaves the whole ring behind: drop everything in one
                // pass. Walking offset by offset would spin for as long as the
                // jump is wide - up to 2^64 steps for a hostile peer's offset.
                for slot in self.entries.iter_mut() {
                    if let Some(old) = slot.take() {
                        self.total_bytes -= old.data.len();
                        self.evicted_through = self.evicted_through.max(old.seq);
                    }
                }
                self.tail_offset = new_tail;
            } else {
                while self.tail_offset < new_tail {
                    let evict_idx = (self.tail_offset & self.mask) as usize;
                    if let Some(old) = self.entries[evict_idx].take() {
                        self.total_bytes -= old.data.len();
                        self.evicted_through = self.evicted_through.max(old.seq);
                    }
                    self.tail_offset += 1;
                }
            }
            self.head_offset = origin_offset.saturating_add(1);
        }

        let idx = (origin_offset & self.mask) as usize;
        let data_len = data.len();

        // Evict any existing entry at this slot (shouldn't happen, but defensive).
        if let Some(old) = self.entries[idx].take() {
            self.total_bytes -= old.data.len();
            self.evicted_through = self.evicted_through.max(old.seq);
        }

        self.entries[idx] = Some(RecoveryEntry {
            data,
            offset: origin_offset,
            seq,
        });
        self.total_bytes += data_len;
        self.last_write = Instant::now();
        true
    }

    /// The last offset held with nothing missing between it and the oldest
    /// kept: what a peer is asked to send after, once its link is back.
    /// None for a buffer that holds nothing to anchor on.
    fn contiguous_through(&self) -> Option<u64> {
        if !self.initialized || self.head_offset <= self.tail_offset {
            return None;
        }
        let mut offset = self.tail_offset;
        while offset < self.head_offset && self.seq_at(offset).is_some() {
            offset += 1;
        }
        offset.checked_sub(1)
    }

    /// Recover messages after `after_offset`, same logic as TopicRecoveryBuffer.
    fn recover_since(&self, after_offset: u64, max_messages: usize) -> Option<Vec<Arrived>> {
        let start = match after_offset.checked_add(1) {
            Some(s) => s,
            None => return Some(Vec::new()),
        };

        if self.head_offset > self.tail_offset && start < self.tail_offset {
            return None;
        }
        if start >= self.head_offset {
            return Some(Vec::new());
        }

        let count = ((self.head_offset - start) as usize).min(max_messages);
        let mut result = Vec::with_capacity(count);

        for i in 0..count {
            let offset = start + i as u64;
            let idx = (offset & self.mask) as usize;
            if let Some(entry) = &self.entries[idx] {
                if entry.offset == offset {
                    result.push((entry.seq, entry.data.clone()));
                } else {
                    // Gap in foreign buffer (missed cluster message) -- can't recover.
                    return None;
                }
            } else {
                return None;
            }
        }

        Some(result)
    }

    /// The arrival number of the message at `offset`, if it is here.
    fn seq_at(&self, offset: u64) -> Option<u64> {
        self.entries[(offset & self.mask) as usize]
            .as_ref()
            .filter(|entry| entry.offset == offset)
            .map(|entry| entry.seq)
    }

    /// Where the client's last message (`offset`) stands in this node's
    /// arrival order: its own number; the last evicted one's when it was
    /// that; just before the next one here when it never came here; the
    /// newest's when the client has everything here.
    fn anchor_seq(&self, offset: u64) -> Option<u64> {
        if let Some(seq) = self.seq_at(offset) {
            return Some(seq);
        }
        let next = offset.saturating_add(1);
        if next == self.tail_offset && self.evicted_through > 0 {
            return Some(self.evicted_through);
        }
        if next >= self.head_offset {
            return self.entries.iter().flatten().map(|entry| entry.seq).max();
        }
        self.entries
            .iter()
            .flatten()
            .filter(|entry| entry.offset > offset)
            .min_by_key(|entry| entry.offset)
            .map(|entry| entry.seq.saturating_sub(1))
    }

    /// The whole stream, when this node holds all of it from its first
    /// offset without a hole (nothing evicted) and every message arrived
    /// after `seq`.
    fn whole_after(&self, seq: u64) -> Option<Vec<Arrived>> {
        if !self.initialized || self.tail_offset != 0 || self.evicted_through != 0 {
            return None;
        }
        if self.head_offset > 0 && self.contiguous_through() != Some(self.head_offset - 1) {
            return None;
        }
        let mut held: Vec<&RecoveryEntry> = self.entries.iter().flatten().collect();
        if held.iter().any(|entry| entry.seq <= seq) {
            return None;
        }
        held.sort_unstable_by_key(|entry| entry.offset);
        Some(
            held.into_iter()
                .map(|entry| (entry.seq, entry.data.clone()))
                .collect(),
        )
    }

    /// The latest arrival number among what it holds or evicted (0: none).
    fn last_seq(&self) -> u64 {
        self.entries
            .iter()
            .flatten()
            .map(|entry| entry.seq)
            .max()
            .unwrap_or(0)
            .max(self.evicted_through)
    }

    /// The messages that arrived after `seq`; None when one of them was
    /// evicted already, or one never came (shed on the way, or relayed while
    /// this node had no interest): a hole among them.
    fn arrived_after(&self, seq: u64) -> Option<Vec<Arrived>> {
        if self.evicted_through > seq {
            return None;
        }
        let mut after: Vec<&RecoveryEntry> = self
            .entries
            .iter()
            .flatten()
            .filter(|entry| entry.seq > seq)
            .collect();
        after.sort_unstable_by_key(|entry| entry.offset);
        if let Some(first) = after.first() {
            // What came before them is here (or evicted, or the stream's
            // start): nothing is missing in between.
            let before = first.offset.checked_sub(1);
            let held = before
                .is_none_or(|before| before < self.tail_offset || self.seq_at(before).is_some());
            let contiguous = after.windows(2).all(|w| w[1].offset == w[0].offset + 1);
            if !held || !contiguous {
                return None;
            }
        }
        Some(
            after
                .into_iter()
                .map(|entry| (entry.seq, entry.data.clone()))
                .collect(),
        )
    }
}

// ---------------------------------------------------------------------------
// RecoveryManager -- thread-safe manager for all topic buffers
// ---------------------------------------------------------------------------

pub(crate) struct RecoveryManager {
    /// This node's own stream of each topic: what it publishes to the whole
    /// cluster.
    buffers: DashMap<String, TopicRecoveryBuffer>,
    /// And of what it publishes to its own subscribers only: a stream of its
    /// own, never sent to another node, so the other one has neither its
    /// offsets nor its room.
    local_buffers: DashMap<String, TopicRecoveryBuffer>,
    /// Foreign buffers: keyed by "topic:epoch" to support multiple origin epochs.
    foreign_buffers: DashMap<String, ForeignRecoveryBuffer>,
    /// The origin epochs each topic has a foreign buffer for: a topic
    /// published on several nodes recovers from all of them.
    foreign_epochs: DashMap<String, Vec<u32>>,
    /// The order messages arrive in on this node, whatever node published
    /// them: a recovery replays every stream of a topic after the client's
    /// last message, in this order.
    arrival: AtomicU64,
    /// Where in that order this node's current, unbroken interest in each
    /// topic began, and when: other nodes relay a topic only while this node
    /// has it, so the relayed streams are whole from there on only.
    interest_since: DashMap<String, (u64, Instant)>,
    /// The arrival order once a second, back to the oldest message this
    /// node holds of its own streams: what it published since a moment is
    /// found by it.
    marks: parking_lot::Mutex<VecDeque<(Instant, u64)>>,
    /// Per topic, the latest arrival among the messages of it this node no
    /// longer holds (expired, or over the budget), and when: a client whose
    /// last message came before it may have missed them, in a stream it never
    /// heard from. Kept while the topic has buffers, and for the history's
    /// lifetime after: a peer that comes back after a lost link is told of
    /// what was not kept meanwhile.
    removed_through: DashMap<String, Removed>,
    /// The latest arrival not kept of a topic that found no room among
    /// `MAX_UNKEPT_TOPICS`, and when: it counts for every topic.
    removed_any: parking_lot::Mutex<Option<Removed>>,
    /// The latest arrival, among what this node published to other nodes,
    /// of the records of what it no longer holds that it let go (0: none):
    /// what a peer that did not hear of it may have missed is not known.
    forgotten: AtomicU64,
    /// Per relayed stream with no buffer here ("topic\0epoch"), where this
    /// node stands in it.
    relayed_unkept: DashMap<String, Delivered>,
    config: RecoveryConfig,
    total_bytes: AtomicUsize,
}

impl RecoveryManager {
    pub(crate) fn new(config: RecoveryConfig) -> Self {
        Self {
            buffers: DashMap::new(),
            local_buffers: DashMap::new(),
            foreign_buffers: DashMap::new(),
            foreign_epochs: DashMap::new(),
            arrival: AtomicU64::new(1),
            interest_since: DashMap::new(),
            marks: parking_lot::Mutex::new(VecDeque::new()),
            removed_through: DashMap::new(),
            removed_any: parking_lot::Mutex::new(None),
            forgotten: AtomicU64::new(0),
            relayed_unkept: DashMap::new(),
            config,
            total_bytes: AtomicUsize::new(0),
        }
    }

    /// Reserve this message's `(epoch, offset)`, build the stored bytes from them
    /// via `build`, push, and return the stored bytes.
    ///
    /// The epoch/offset read and the push happen under the SAME DashMap shard
    /// write lock, so the offset handed to `build` is exactly the offset the
    /// message is stored at -- race-free even with concurrent pushers. This lets
    /// the caller weave the recovery coordinates INTO the payload before it is
    /// framed/encrypted, so the live copy and any replayed copy are byte-identical
    /// and the client can dedup / detect gaps from the message itself.
    ///
    /// None when the topic has no buffer and the memory budget is used up: a
    /// new buffer allocates its slots up front, and an application may
    /// publish to any number of new topics between two cleanups. The message
    /// then goes unstamped; its topic is recoverable once there is room.
    #[cfg(test)]
    pub(crate) fn push_stamped<F>(&self, topic: &str, build: F) -> Option<Bytes>
    where
        F: FnOnce(u32, u64) -> Bytes,
    {
        self.stamp(topic, false, build).0
    }

    /// `push_stamped` for a message published to this node's subscribers
    /// only: kept for them in a stream of its own, never sent to another
    /// node.
    #[cfg(test)]
    pub(crate) fn push_stamped_local<F>(&self, topic: &str, build: F) -> Option<Bytes>
    where
        F: FnOnce(u32, u64) -> Bytes,
    {
        self.stamp(topic, true, build).0
    }

    /// `push_stamped` or `push_stamped_local`, with the message's place in
    /// this node's arrival order: the number other nodes hear it by.
    pub(crate) fn stamp<F>(&self, topic: &str, local_only: bool, build: F) -> (Option<Bytes>, u64)
    where
        F: FnOnce(u32, u64) -> Bytes,
    {
        let buffers = if local_only {
            &self.local_buffers
        } else {
            &self.buffers
        };
        let mut created = false;
        // A topic that has a buffer is found without making a key.
        let mut entry = match buffers.get_mut(topic) {
            Some(entry) => entry,
            None if self.total_bytes.load(Ordering::Relaxed)
                >= self.config.global_memory_budget =>
            {
                // Not kept: a client whose last message of the topic came
                // before it cannot be told it missed nothing.
                let seq = self.arrival.fetch_add(1, Ordering::Relaxed);
                self.note_removed(topic, seq, !local_only);
                return (None, seq);
            }
            None => buffers.entry(topic.to_owned()).or_insert_with(|| {
                created = true;
                TopicRecoveryBuffer::new(self.config.buffer_size_bits, topic.len())
            }),
        };

        let buf = entry.value_mut();
        let epoch = buf.epoch;
        let offset = buf.head_offset; // the offset buf.push() is about to assign
        let data = build(epoch, offset);

        let old_bytes = if created { 0 } else { buf.footprint() };
        let seq = self.arrival.fetch_add(1, Ordering::Relaxed);
        buf.push(data.clone(), seq);
        let new_bytes = buf.footprint();

        // Update global byte counter with the delta (accounts for evictions).
        // DashMap entry API holds the shard write lock for this entire block,
        // so cleanup() cannot remove this buffer between the read and update.
        if new_bytes > old_bytes {
            self.total_bytes
                .fetch_add(new_bytes - old_bytes, Ordering::AcqRel);
        } else if old_bytes > new_bytes {
            let _ = self
                .total_bytes
                .try_update(Ordering::AcqRel, Ordering::Acquire, |cur| {
                    Some(cur.saturating_sub(old_bytes - new_bytes))
                });
        }
        (Some(data), seq)
    }

    /// Push a pre-built message (recovery coordinates already woven in, or none).
    /// Test-only convenience over push_stamped; production stamps via push_stamped.
    #[cfg(test)]
    pub(crate) fn push(&self, topic: &str, data: Bytes) {
        self.push_stamped(topic, move |_epoch, _offset| data);
    }

    /// Store a message received from a cluster peer in a foreign recovery buffer.
    ///
    /// The epoch and offset belong to the originating node. This lets clients
    /// recover using the original epoch/offset from any node in the cluster.
    /// False when this node has it already: a peer sends what a lost link
    /// missed again, and only what is new here is delivered.
    pub(crate) fn push_foreign(
        &self,
        topic: &str,
        data: Bytes,
        origin_epoch: u32,
        origin_offset: u64,
    ) -> bool {
        // Key: "topic\0epoch" -- null byte separator is safe (never in topic
        // names). Written into this thread's buffer: a buffer that exists is
        // found without allocating a key.
        thread_local! {
            static KEY: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
        }
        KEY.with_borrow_mut(|key| {
            use std::fmt::Write;
            key.clear();
            let _ = write!(key, "{topic}\0{origin_epoch}");
            self.push_foreign_at(key, data, origin_epoch, origin_offset)
        })
    }

    fn push_foreign_at(
        &self,
        key: &str,
        data: Bytes,
        origin_epoch: u32,
        origin_offset: u64,
    ) -> bool {
        let mut created = false;
        let mut entry = match self.foreign_buffers.get_mut(key) {
            Some(entry) => entry,
            // Over the memory budget no new buffer is made: each one
            // allocates its slots up front, and a peer can name any number of
            // fresh (topic, epoch) pairs between two cleanups. The message is
            // still delivered live; only its recovery copy is skipped, and a
            // client whose last message came before it cannot be told it
            // missed nothing.
            None if self.total_bytes.load(Ordering::Relaxed)
                >= self.config.global_memory_budget =>
            {
                if !self.deliver_unkept(key, origin_epoch, origin_offset) {
                    return false;
                }
                let seq = self.arrival.fetch_add(1, Ordering::Relaxed);
                self.note_removed(foreign_topic(key), seq, false);
                return true;
            }
            // Delivered before, with no buffer to hold it then: not again,
            // and no buffer yet while some of what was delivered comes after
            // it (a buffer begun here would take them for new).
            None if let Some(mut delivered) = self.relayed_unkept.get_mut(key)
                && (delivered.has(origin_offset) || delivered.any_after(origin_offset)) =>
            {
                if !delivered.deliver(origin_offset) {
                    return false;
                }
                drop(delivered);
                let seq = self.arrival.fetch_add(1, Ordering::Relaxed);
                self.note_removed(foreign_topic(key), seq, false);
                return true;
            }
            None => self
                .foreign_buffers
                .entry(key.to_owned())
                .or_insert_with(|| {
                    created = true;
                    ForeignRecoveryBuffer::new(
                        self.config.buffer_size_bits,
                        origin_epoch,
                        key.len(),
                    )
                }),
        };

        if created {
            // The buffer stands where it was, from now on.
            self.relayed_unkept.remove(key);
        }
        if created && let Some((topic, _)) = key.split_once('\0') {
            let mut epochs = self.foreign_epochs.entry(topic.to_owned()).or_default();
            if !epochs.contains(&origin_epoch) {
                epochs.push(origin_epoch);
            }
        }
        let buf = entry.value_mut();
        let old_bytes = if created { 0 } else { buf.footprint() };
        let new = buf.push_at(
            data,
            origin_offset,
            self.arrival.fetch_add(1, Ordering::Relaxed),
        );
        let new_bytes = buf.footprint();

        if new_bytes > old_bytes {
            self.total_bytes
                .fetch_add(new_bytes - old_bytes, Ordering::AcqRel);
        } else if old_bytes > new_bytes {
            let _ = self
                .total_bytes
                .try_update(Ordering::AcqRel, Ordering::Acquire, |cur| {
                    Some(cur.saturating_sub(old_bytes - new_bytes))
                });
        }
        new
    }

    /// Where this node stands in each stream relayed to it: (topic, origin
    /// epoch, the last offset held with nothing missing before it). A peer
    /// whose link was lost sends what came after it once the link is back.
    pub(crate) fn foreign_positions(&self) -> Vec<(String, u32, u64)> {
        let held = self.foreign_buffers.iter().filter_map(|entry| {
            let (topic, _) = entry.key().split_once('\0')?;
            let through = entry.value().contiguous_through()?;
            Some((topic.to_owned(), entry.value().epoch, through))
        });
        let unkept = self.relayed_unkept.iter().filter_map(|entry| {
            let (topic, _) = entry.key().split_once('\0')?;
            Some((topic.to_owned(), entry.value().epoch, entry.value().through))
        });
        held.chain(unkept).collect()
    }

    /// A message of a relayed stream with no buffer here, and no room for
    /// one: false when it was delivered already.
    fn deliver_unkept(&self, key: &str, epoch: u32, offset: u64) -> bool {
        if let Some(mut delivered) = self.relayed_unkept.get_mut(key) {
            return delivered.deliver(offset);
        }
        if self.relayed_unkept.len() >= MAX_UNKEPT_TOPICS {
            return true;
        }
        match self.relayed_unkept.entry(key.to_owned()) {
            dashmap::Entry::Occupied(mut delivered) => delivered.get_mut().deliver(offset),
            dashmap::Entry::Vacant(slot) => {
                slot.insert(Delivered::first(epoch, offset));
                true
            }
        }
    }

    /// What this node published to `topic` in its stream `epoch` after
    /// `after`, oldest first, for a peer that missed it: from the oldest kept
    /// when some of it is gone, nothing when the stream is not this node's.
    pub(crate) fn published_after(&self, topic: &str, epoch: u32, after: u64) -> Vec<(u64, Bytes)> {
        let Some(buf) = self.buffers.get(topic) else {
            return Vec::new();
        };
        if buf.epoch != epoch {
            return Vec::new();
        }
        buf.held_from(after.saturating_add(1))
            .map(|(offset, _, data)| (offset, data.clone()))
            .collect()
    }

    /// This node's own stream of `topic` whose epoch is `epoch`: the one it
    /// publishes to the cluster, or the one of what it publishes to its own
    /// subscribers only.
    fn own_stream(
        &self,
        topic: &str,
        epoch: u32,
    ) -> Option<dashmap::mapref::one::Ref<'_, String, TopicRecoveryBuffer>> {
        self.buffers
            .get(topic)
            .filter(|buf| buf.epoch == epoch)
            .or_else(|| {
                self.local_buffers
                    .get(topic)
                    .filter(|buf| buf.epoch == epoch)
            })
    }

    /// This node's own streams of `topic`, one at a time: `each` sees the
    /// cluster's, then the local one.
    fn each_own<R>(
        &self,
        topic: &str,
        mut each: impl FnMut(&TopicRecoveryBuffer) -> Option<R>,
    ) -> Option<R> {
        for own in [&self.buffers, &self.local_buffers] {
            if let Some(buf) = own.get(topic)
                && let Some(found) = each(&buf)
            {
                return Some(found);
            }
        }
        None
    }

    /// Attempt to recover messages for a topic after a given offset.
    ///
    /// First checks the local buffer. If the epoch matches, recovers from local.
    /// If the epoch doesn't match local, checks foreign buffers (cluster-replicated).
    /// This allows clients to recover from any node, even after reconnecting to a
    /// different node than the one that originally published the messages.
    pub(crate) fn recover(&self, topic: &str, epoch: u32, after_offset: u64) -> RecoveryResult {
        let max = self.config.max_recovery_messages;
        // The stream of the client's last message: the local one, or one
        // relayed from another node, by its epoch. What it missed there, and
        // where that last message stands in this node's arrival order.
        let anchored = if let Some(buf) = self.own_stream(topic, epoch) {
            let missed = buf
                .head_offset
                .saturating_sub(after_offset.saturating_add(1)) as usize;
            Some((
                if missed <= max {
                    buf.recover_since(after_offset, max)
                } else {
                    None
                },
                buf.anchor_seq(after_offset),
                buf.head_offset,
            ))
        } else if let Some(fbuf) = self.foreign_buffers.get(&format!("{topic}\0{epoch}"))
            && fbuf.epoch == epoch
        {
            let missed = fbuf
                .head_offset
                .saturating_sub(after_offset.saturating_add(1)) as usize;
            Some((
                if missed <= max {
                    fbuf.recover_since(after_offset, max)
                } else {
                    None
                },
                fbuf.anchor_seq(after_offset),
                fbuf.head_offset,
            ))
        } else {
            None
        };
        let Some((own, anchor_seq, head)) = anchored else {
            // No matching buffer found at all.
            return match self.each_own(topic, |buf| Some((buf.epoch, buf.head_offset))) {
                // Local buffer exists but with different epoch -- tell client to re-subscribe.
                Some((epoch, offset)) => RecoveryResult::NotRecovered { epoch, offset },
                None => RecoveryResult::NoHistory,
            };
        };
        let not_recovered = RecoveryResult::NotRecovered {
            epoch,
            offset: head,
        };
        // A history of the topic removed, or a message not kept, from after
        // the client's last message: what it missed there is gone.
        if let Some(removed) = self.removed_after(topic)
            && anchor_seq.is_none_or(|seq| removed > seq)
        {
            return not_recovered;
        }
        let Some(mut publications) = own else {
            return not_recovered;
        };
        // Relayed streams are whole only within this node's unbroken
        // interest in the topic: one that began after the client's last
        // message may have missed what other nodes published in between.
        let relayed_whole = |seq: Option<u64>| {
            let since = self
                .interest_since
                .get(topic)
                .map_or(u64::MAX, |since| since.0);
            seq.is_some_and(|seq| seq >= since)
        };
        let anchored_relayed = self.own_stream(topic, epoch).is_none();
        let relays = self
            .foreign_epochs
            .get(topic)
            .is_some_and(|epochs| !epochs.is_empty());
        if (anchored_relayed || relays) && !relayed_whole(anchor_seq) {
            return not_recovered;
        }
        // The topic's other streams (published here, or on other nodes):
        // what arrived after the client's last message, which each of them
        // must still hold whole. Without that message here, nothing places
        // them: a stream with anything in it then cannot be recovered.
        let mut streams: Vec<Option<Vec<Arrived>>> = Vec::new();
        self.each_own(topic, |buf| {
            if buf.epoch != epoch {
                streams.push(match anchor_seq {
                    Some(seq) => buf.arrived_after(seq),
                    None => buf.entries.is_empty().then(Vec::new),
                });
            }
            None::<()>
        });
        let others: Vec<u32> = self
            .foreign_epochs
            .get(topic)
            .map(|epochs| epochs.iter().copied().filter(|e| *e != epoch).collect())
            .unwrap_or_default();
        for other in others {
            if let Some(fbuf) = self.foreign_buffers.get(&format!("{topic}\0{other}")) {
                streams.push(match anchor_seq {
                    Some(seq) => fbuf.arrived_after(seq),
                    None => fbuf.arrived_after(u64::MAX),
                });
            }
        }
        let mut merged = false;
        for stream in streams {
            let Some(mut more) = stream else {
                return not_recovered;
            };
            merged |= !more.is_empty();
            publications.append(&mut more);
        }
        if publications.len() > max {
            return not_recovered;
        }
        if merged {
            // In the order they arrived here.
            publications.sort_unstable_by_key(|(seq, _)| *seq);
        }
        RecoveryResult::Recovered {
            publications: publications.into_iter().map(|(_, data)| data).collect(),
            epoch,
            offset: head.saturating_sub(1),
        }
    }

    /// Recover for a client that names the last offset it holds of each
    /// stream of `topic` (`named`: epoch, offset), and its last message
    /// (`anchor`).
    ///
    /// Each named stream comes from its own offset, so the order the streams
    /// arrived in on the client's last node does not matter. A stream it does
    /// not name comes only whole: held here from its first message, every
    /// one of which arrived after the anchor. Anything else is not
    /// recovered, because nothing here proves what the client missed: a
    /// named stream this node does not hold, or holds with a hole or only
    /// since its interest in the topic began again; an unnamed one with a
    /// message from before the anchor; a buffer of the topic removed with
    /// messages from after it; more than `max_recovery_messages`.
    pub(crate) fn recover_streams(
        &self,
        topic: &str,
        anchor: (u32, u64),
        named: &[(u32, u64)],
    ) -> RecoveryResult {
        let max = self.config.max_recovery_messages;
        let not_recovered = RecoveryResult::NotRecovered {
            epoch: anchor.0,
            offset: anchor.1,
        };
        let position = |epoch: u32| named.iter().find(|(e, _)| *e == epoch).map(|(_, o)| *o);
        let since = self.interest_since.get(topic).map(|since| since.0);
        let foreign_epochs: Vec<u32> = self
            .foreign_epochs
            .get(topic)
            .map(|epochs| epochs.clone())
            .unwrap_or_default();

        // Where the client's last message stands in this node's arrival
        // order, if it is here.
        let local_anchor = self
            .own_stream(topic, anchor.0)
            .map(|buf| buf.seq_at(anchor.1));
        let anchor_seq = match local_anchor {
            Some(seq) => seq,
            None => self
                .foreign_buffers
                .get(&format!("{topic}\0{}", anchor.0))
                .and_then(|fbuf| fbuf.seq_at(anchor.1)),
        };
        if let Some(removed) = self.removed_after(topic)
            && anchor_seq.is_none_or(|seq| removed > seq)
        {
            return not_recovered;
        }

        let mut streams: Vec<Vec<Arrived>> = Vec::with_capacity(foreign_epochs.len() + 1);
        let mut missed = 0usize;
        let mut head = anchor.1.saturating_add(1);
        let mut seen: Vec<u32> = Vec::with_capacity(foreign_epochs.len() + 1);

        let failed = self.each_own(topic, |buf| {
            seen.push(buf.epoch);
            if buf.epoch == anchor.0 {
                head = head.max(buf.head_offset);
            }
            let more = match position(buf.epoch) {
                Some(offset) => {
                    missed += buf.head_offset.saturating_sub(offset.saturating_add(1)) as usize;
                    if missed > max {
                        return Some(());
                    }
                    buf.recover_since(offset, max)
                }
                None => anchor_seq.and_then(|seq| buf.whole_after(seq)),
            };
            let Some(more) = more else {
                return Some(());
            };
            streams.push(more);
            None
        });
        if failed.is_some() {
            return not_recovered;
        }

        for epoch in foreign_epochs {
            let Some(fbuf) = self.foreign_buffers.get(&format!("{topic}\0{epoch}")) else {
                continue;
            };
            seen.push(epoch);
            if epoch == anchor.0 {
                head = head.max(fbuf.head_offset);
            }
            // Relayed here only while this node has the topic: whole only
            // from where its current interest began.
            let more = match position(epoch) {
                Some(offset) => {
                    // The first message it needs, or with none, the newest
                    // here: everything after it came while this node had
                    // the topic.
                    let first = offset.saturating_add(1);
                    let from = if first >= fbuf.head_offset {
                        fbuf.seq_at(fbuf.head_offset.saturating_sub(1))
                    } else {
                        fbuf.seq_at(first)
                    };
                    let covered = from.is_some_and(|seq| since.is_some_and(|since| seq >= since));
                    missed += fbuf.head_offset.saturating_sub(first) as usize;
                    if !covered || missed > max {
                        return not_recovered;
                    }
                    fbuf.recover_since(offset, max)
                }
                None => anchor_seq
                    .filter(|_| {
                        fbuf.entries
                            .iter()
                            .flatten()
                            .map(|entry| entry.seq)
                            .min()
                            .is_none_or(|first| since.is_some_and(|since| first >= since))
                    })
                    .and_then(|seq| fbuf.whole_after(seq)),
            };
            let Some(more) = more else {
                return not_recovered;
            };
            streams.push(more);
        }

        // A stream the client names that this node does not hold.
        if named.iter().any(|(epoch, _)| !seen.contains(epoch)) {
            return not_recovered;
        }
        if streams.iter().map(Vec::len).sum::<usize>() > max {
            return not_recovered;
        }
        RecoveryResult::Recovered {
            publications: interleave(streams),
            epoch: anchor.0,
            offset: head.saturating_sub(1),
        }
    }

    /// What the streams of `topic` hold beyond `before` (each one's last
    /// offset at some moment; a stream not in it, from its first message),
    /// in arrival order: what was published since. None past
    /// `max_recovery_messages`, or when a stream no longer holds all of it.
    pub(crate) fn published_since(&self, topic: &str, before: &[(u32, u64)]) -> Option<Vec<Bytes>> {
        let max = self.config.max_recovery_messages;
        let last = |epoch: u32| before.iter().find(|(e, _)| *e == epoch).map(|(_, o)| *o);
        let mut streams: Vec<Vec<Arrived>> = Vec::new();
        let mut total = 0u64;
        let gone = self.each_own(topic, |buf| {
            let more = match last(buf.epoch) {
                Some(offset) => {
                    total += buf.head_offset.saturating_sub(offset.saturating_add(1));
                    buf.recover_since(offset, max)
                }
                None => {
                    total += buf.head_offset;
                    buf.whole_after(0)
                }
            };
            match more {
                Some(more) => {
                    streams.push(more);
                    None
                }
                None => Some(()),
            }
        });
        if gone.is_some() {
            return None;
        }
        let foreign_epochs: Vec<u32> = self
            .foreign_epochs
            .get(topic)
            .map(|epochs| epochs.clone())
            .unwrap_or_default();
        for epoch in foreign_epochs {
            let Some(fbuf) = self.foreign_buffers.get(&format!("{topic}\0{epoch}")) else {
                continue;
            };
            let more = match last(epoch) {
                Some(offset) => {
                    total += fbuf.head_offset.saturating_sub(offset.saturating_add(1));
                    fbuf.recover_since(offset, max)?
                }
                None => {
                    total += fbuf.head_offset;
                    fbuf.whole_after(0)?
                }
            };
            streams.push(more);
        }
        let held = streams.iter().map(Vec::len).sum::<usize>();
        if total > max as u64 || held as u64 != total {
            return None;
        }
        Some(interleave(streams))
    }

    /// The streams this node holds of `topic`: each one's epoch and the last
    /// offset here. Read once a connection subscribed, it is where the
    /// connection starts in each: what comes after reaches it live.
    pub(crate) fn streams(&self, topic: &str) -> Vec<(u32, u64)> {
        let mut streams = Vec::new();
        self.each_own(topic, |buf| {
            if buf.head_offset > 0 {
                streams.push((buf.epoch, buf.head_offset - 1));
            }
            None::<()>
        });
        let foreign_epochs: Vec<u32> = self
            .foreign_epochs
            .get(topic)
            .map(|epochs| epochs.clone())
            .unwrap_or_default();
        for epoch in foreign_epochs {
            if let Some(fbuf) = self.foreign_buffers.get(&format!("{topic}\0{epoch}"))
                && fbuf.initialized
                && fbuf.head_offset > 0
            {
                streams.push((epoch, fbuf.head_offset - 1));
            }
        }
        streams
    }

    /// Get the current (epoch, head_offset) for a topic, if a buffer exists.
    pub(crate) fn get_position(&self, topic: &str) -> Option<(u32, u64)> {
        self.each_own(topic, |buf| Some((buf.epoch, buf.head_offset)))
    }

    /// Evict stale topic buffers based on TTL and global memory budget.
    ///
    /// First pass: remove any buffer whose `last_write` is older than the TTL.
    /// Second pass (if still over budget): collect remaining buffers sorted by
    /// `last_write` (oldest first) and remove them until under budget.
    /// Both local and foreign buffers are cleaned up.
    pub(crate) fn cleanup(&self) {
        // Compare ages, not `now - ttl`: that subtraction panics when the TTL is
        // longer than the machine's uptime (e.g. a service started at boot on
        // Windows), and a panic here would stop all eviction for good.
        let ttl = Duration::from_secs(self.config.history_ttl_secs);

        // First pass: remove TTL-expired own buffers, the cluster's and the
        // local ones.
        for (own, shared) in [(&self.buffers, true), (&self.local_buffers, false)] {
            let expired: Vec<String> = own
                .iter()
                .filter(|entry| entry.value().last_write.elapsed() > ttl)
                .map(|entry| entry.key().clone())
                .collect();
            for key in &expired {
                if let Some((_, removed)) = own.remove(key) {
                    self.removed_own(key, &removed, shared);
                }
            }
        }

        // First pass: remove TTL-expired foreign buffers.
        let mut foreign_to_remove = Vec::new();
        for entry in self.foreign_buffers.iter() {
            if entry.value().last_write.elapsed() > ttl {
                foreign_to_remove.push(entry.key().clone());
            }
        }
        for key in &foreign_to_remove {
            if let Some(removed) = self.remove_foreign(key) {
                self.note_removed(foreign_topic(key), removed.last_seq(), false);
                let _ = self
                    .total_bytes
                    .try_update(Ordering::Relaxed, Ordering::Relaxed, |cur| {
                        Some(cur.saturating_sub(removed.footprint()))
                    });
            }
        }

        // Second pass: if still over budget, evict LRU across own and foreign.
        if self.total_bytes.load(Ordering::Relaxed) > self.config.global_memory_budget {
            /// Which map a candidate is in.
            #[derive(Clone, Copy)]
            enum Held {
                Shared,
                Local,
                Foreign,
            }
            let mut candidates: Vec<(String, Instant, Held)> = Vec::new();
            for (own, held) in [
                (&self.buffers, Held::Shared),
                (&self.local_buffers, Held::Local),
            ] {
                for e in own.iter() {
                    candidates.push((e.key().clone(), e.value().last_write, held));
                }
            }
            for e in self.foreign_buffers.iter() {
                candidates.push((e.key().clone(), e.value().last_write, Held::Foreign));
            }

            // Sort by last_write ascending (oldest first).
            candidates.sort_by_key(|(_, lw, _)| *lw);

            for (key, _, held) in candidates {
                if self.total_bytes.load(Ordering::Relaxed) <= self.config.global_memory_budget {
                    break;
                }
                match held {
                    Held::Shared | Held::Local => {
                        let (own, shared) = match held {
                            Held::Shared => (&self.buffers, true),
                            _ => (&self.local_buffers, false),
                        };
                        if let Some((_, removed)) = own.remove(&key) {
                            self.removed_own(&key, &removed, shared);
                        }
                    }
                    Held::Foreign => {
                        if let Some(removed) = self.remove_foreign(&key) {
                            self.note_removed(foreign_topic(&key), removed.last_seq(), false);
                            let _ = self.total_bytes.try_update(
                                Ordering::Relaxed,
                                Ordering::Relaxed,
                                |cur| Some(cur.saturating_sub(removed.footprint())),
                            );
                        }
                    }
                }
            }
        }

        // A topic with no buffer left recovers nothing here: what was removed
        // of it matters to a peer that asks after a lost link, within the
        // history's lifetime. One let go of what went to the cluster is
        // remembered as forgotten: a peer that did not hear of it cannot be
        // told what it missed.
        let gone: Vec<String> = self
            .removed_through
            .iter()
            .filter(|entry| {
                let topic = entry.key();
                entry.value().at.elapsed() > ttl
                    && !self.buffers.contains_key(topic)
                    && !self.local_buffers.contains_key(topic)
                    && !self.foreign_epochs.contains_key(topic)
            })
            .map(|entry| entry.key().clone())
            .collect();
        for topic in gone {
            if let Some((_, removed)) = self.removed_through.remove(&topic) {
                self.forgotten
                    .fetch_max(removed.shared_through, Ordering::Relaxed);
            }
        }
        let mut any = self.removed_any.lock();
        if let Some(removed) = *any
            && removed.at.elapsed() > ttl
        {
            self.forgotten
                .fetch_max(removed.shared_through, Ordering::Relaxed);
            *any = None;
        }
        drop(any);
        self.relayed_unkept
            .retain(|_, delivered| delivered.at.elapsed() <= ttl);
        self.trim_marks();
    }

    /// An own buffer of `topic` went (expired, or over the budget): what it
    /// held is no longer here, and its bytes are given back.
    fn removed_own(&self, topic: &str, removed: &TopicRecoveryBuffer, shared: bool) {
        self.note_removed(topic, removed.last_seq(), shared);
        let _ = self
            .total_bytes
            .try_update(Ordering::Relaxed, Ordering::Relaxed, |cur| {
                Some(cur.saturating_sub(removed.footprint()))
            });
    }

    /// The latest arrival of `topic` this node no longer holds, the one of
    /// any topic among it.
    fn removed_after(&self, topic: &str) -> Option<u64> {
        let own = self
            .removed_through
            .get(topic)
            .map(|removed| removed.through);
        let any = self.removed_any.lock().map(|removed| removed.through);
        own.max(any)
    }

    /// The topics a peer that has `topic` (a name, or a pattern of them)
    /// must hear this node no longer holds, or never could, a message it
    /// published to the cluster after arrival `after` of: none, the topic,
    /// each topic the pattern matches, or the pattern itself when what was
    /// let go counts for every topic.
    pub(crate) fn lost_after(&self, topic: &str, after: u64) -> Vec<String> {
        let any = self
            .removed_any
            .lock()
            .map_or(0, |removed| removed.shared_through);
        if any.max(self.forgotten.load(Ordering::Relaxed)) > after {
            return vec![topic.to_owned()];
        }
        if crate::server::is_pattern(topic) {
            let mut lost: Vec<String> = self
                .removed_through
                .iter()
                .filter(|entry| entry.value().shared_through > after)
                .filter(|entry| crate::server::glob_match(topic, entry.key()))
                .map(|entry| entry.key().clone())
                .chain(
                    self.buffers
                        .iter()
                        .filter(|entry| entry.value().evicted_through > after)
                        .filter(|entry| crate::server::glob_match(topic, entry.key()))
                        .map(|entry| entry.key().clone()),
                )
                .collect();
            lost.sort_unstable();
            lost.dedup();
            return lost;
        }
        let removed = self
            .removed_through
            .get(topic)
            .is_some_and(|removed| removed.shared_through > after);
        let evicted = self
            .buffers
            .get(topic)
            .is_some_and(|buf| buf.evicted_through > after);
        if removed || evicted {
            vec![topic.to_owned()]
        } else {
            Vec::new()
        }
    }

    /// A node this one heard from is gone without a word, and another took
    /// its place: what it published that this node did not hear of is gone,
    /// in any topic this node has or holds a stream of.
    pub(crate) fn lost_everything(&self) {
        // Every topic a client here can have a position in: one of this
        // node's own included, a pattern's as much as one named.
        let mut topics: Vec<String> = self
            .interest_since
            .iter()
            .map(|entry| entry.key().clone())
            .chain(self.foreign_epochs.iter().map(|entry| entry.key().clone()))
            .chain(
                self.relayed_unkept
                    .iter()
                    .map(|entry| foreign_topic(entry.key()).to_owned()),
            )
            .chain(self.buffers.iter().map(|entry| entry.key().clone()))
            .chain(self.local_buffers.iter().map(|entry| entry.key().clone()))
            .filter(|topic| !crate::server::is_pattern(topic))
            .collect();
        topics.sort_unstable();
        topics.dedup();
        for topic in &topics {
            self.not_kept(topic);
        }
    }

    /// A peer said messages of `topic` (or, a pattern, of each topic here it
    /// matches) were published that no node holds.
    pub(crate) fn lost(&self, topic: &str) {
        if !crate::server::is_pattern(topic) {
            self.not_kept(topic);
            return;
        }
        let mut matched: Vec<String> = self
            .buffers
            .iter()
            .map(|entry| entry.key().clone())
            .chain(self.local_buffers.iter().map(|entry| entry.key().clone()))
            .chain(self.foreign_epochs.iter().map(|entry| entry.key().clone()))
            .chain(self.interest_since.iter().map(|entry| entry.key().clone()))
            .filter(|name| {
                !crate::server::is_pattern(name) && crate::server::glob_match(topic, name)
            })
            .collect();
        matched.sort_unstable();
        matched.dedup();
        for name in &matched {
            self.not_kept(name);
        }
    }

    /// Messages of `topic` up to arrival `seq` are not held here (a buffer
    /// removed, or a message with no room to keep it), `shared` when some
    /// of them this node published to other nodes.
    fn note_removed(&self, topic: &str, seq: u64, shared: bool) {
        if seq == 0 {
            return;
        }
        if let Some(mut removed) = self.removed_through.get_mut(topic) {
            removed.note(seq, shared);
            return;
        }
        // No room for another topic's: it counts for every topic.
        if self.removed_through.len() >= MAX_UNKEPT_TOPICS {
            self.removed_any
                .lock()
                .get_or_insert_with(Removed::none)
                .note(seq, shared);
            return;
        }
        self.removed_through
            .entry(topic.to_owned())
            .or_insert_with(Removed::none)
            .note(seq, shared);
    }

    /// A message of `topic` came, relayed with no position: the node it was
    /// published on had no room to keep it, and no node holds it.
    pub(crate) fn not_kept(&self, topic: &str) {
        let seq = self.arrival.fetch_add(1, Ordering::Relaxed);
        self.note_removed(topic, seq, false);
    }

    /// This node took an interest in `topic` (its first local subscriber,
    /// none lingering): other nodes relay it from now on.
    pub(crate) fn interest_began(&self, topic: &str) {
        self.interest_since.insert(
            topic.to_owned(),
            (self.arrival.load(Ordering::Relaxed), Instant::now()),
        );
    }

    /// The topics this node has, each with how long ago its current interest
    /// began (milliseconds): a node it links to again sends what it
    /// published to them since, the streams it did not name included.
    pub(crate) fn interests(&self) -> Vec<(String, u64)> {
        self.interest_since
            .iter()
            .map(|entry| {
                let age = entry.value().1.elapsed().as_millis();
                (entry.key().clone(), u64::try_from(age).unwrap_or(u64::MAX))
            })
            .collect()
    }

    /// Marks where the arrival order stands now, unless nothing arrived
    /// since the last mark; called once a second.
    pub(crate) fn mark(&self) {
        let next = self.arrival.load(Ordering::Relaxed);
        let mut marks = self.marks.lock();
        if marks.back().is_some_and(|(_, last)| *last == next) {
            return;
        }
        if marks.len() == MAX_MARKS {
            marks.pop_front();
        }
        marks.push_back((Instant::now(), next));
    }

    /// Lets go the marks from before the oldest message this node holds of
    /// its own streams, but the last of them.
    fn trim_marks(&self) {
        let oldest = self
            .buffers
            .iter()
            .filter_map(|buf| buf.entries.front().map(|(_, seq)| *seq))
            .min()
            .unwrap_or(u64::MAX);
        let mut marks = self.marks.lock();
        while marks.len() > 1 && marks[1].1 <= oldest {
            marks.pop_front();
        }
    }

    /// The first arrival number given out after `at`, to a mark: 0 before
    /// the first.
    fn arrival_at(&self, at: Instant) -> u64 {
        let marks = self.marks.lock();
        let after = marks.partition_point(|(mark, _)| *mark <= at);
        after.checked_sub(1).map_or(0, |i| marks[i].1)
    }

    /// The topics of this node's own streams that `pattern` matches.
    pub(crate) fn own_topics_matching(&self, pattern: &str) -> Vec<String> {
        self.buffers
            .iter()
            .filter(|entry| crate::server::glob_match(pattern, entry.key()))
            .map(|entry| entry.key().clone())
            .collect()
    }

    /// What this node published to the cluster of `topic` after arrival
    /// `after`, with its stream's epoch and each message's offset, for a peer
    /// that did not hear it: None when this node publishes none to it, or the
    /// peer named the stream (`named`).
    pub(crate) fn published_unheard(
        &self,
        topic: &str,
        after: u64,
        named: impl Fn(u32) -> bool,
    ) -> Option<(u32, Vec<(u64, Bytes)>)> {
        let buf = self.buffers.get(topic)?;
        if named(buf.epoch) {
            return None;
        }
        let messages = buf
            .held_from(0)
            .filter(|(_, seq, _)| *seq > after)
            .map(|(offset, _, data)| (offset, data.clone()))
            .collect();
        Some((buf.epoch, messages))
    }

    /// The last arrival number given out: everything up to it is in this
    /// node's history, or was let go of and recorded so.
    pub(crate) fn arrived_through(&self) -> u64 {
        self.arrival.load(Ordering::Acquire).saturating_sub(1)
    }

    /// The last arrival number given out before `age` ago (and a little
    /// before it), to a mark: what a peer whose interest began then could
    /// not have heard of comes after it.
    pub(crate) fn arrived_before(&self, age: Duration) -> u64 {
        Instant::now()
            .checked_sub(age.saturating_add(LATELY_MARGIN))
            .map_or(0, |at| self.arrival_at(at).saturating_sub(1))
    }

    /// This node no longer has `topic`: its relayed streams stop.
    pub(crate) fn interest_ended(&self, topic: &str) {
        self.interest_since.remove(topic);
    }

    /// How long a topic stays of interest after its last local subscriber
    /// left: what other nodes publish meanwhile is still relayed here, for
    /// the client that comes back within the history's lifetime.
    pub(crate) fn interest_linger(&self) -> Duration {
        // A history kept "forever" lingers ten years: an instant that far
        // out is still one the clock can name.
        const MAX_LINGER_SECS: u64 = 10 * 365 * 86_400;
        Duration::from_secs(self.config.history_ttl_secs.min(MAX_LINGER_SECS))
    }

    /// Removes the foreign buffer `key` (`topic\0epoch`) and its epoch from
    /// its topic's streams at once: a relay that makes the buffer anew
    /// meanwhile waits for both, then names the stream again. The buffer's
    /// lock is taken before the streams', as a relay takes them.
    fn remove_foreign(&self, key: &str) -> Option<ForeignRecoveryBuffer> {
        let (key, removed) = self.foreign_buffers.remove_if(key, |key, removed| {
            #[cfg(test)]
            REMOVING.with_borrow(|hook| hook.as_ref().map(|hook| hook()));
            self.forget_foreign(key, removed.epoch);
            true
        })?;
        // What it delivered is not delivered again.
        if let Some(delivered) = Delivered::of(&removed)
            && self.relayed_unkept.len() < MAX_UNKEPT_TOPICS
        {
            self.relayed_unkept.insert(key, delivered);
        }
        Some(removed)
    }

    /// A foreign buffer (`topic\0epoch`) is gone: its topic no longer
    /// recovers from that epoch.
    fn forget_foreign(&self, key: &str, epoch: u32) {
        if let Some((topic, _)) = key.split_once('\0') {
            if let Some(mut epochs) = self.foreign_epochs.get_mut(topic) {
                epochs.retain(|e| *e != epoch);
            }
            self.foreign_epochs
                .remove_if(topic, |_, epochs| epochs.is_empty());
        }
    }

    /// How long, in seconds, a stream that receives nothing is still kept
    /// here (its history's lifetime, until the next cleanup): a client that
    /// heard nothing of a stream for longer can forget it.
    pub(crate) fn history_secs(&self) -> u64 {
        self.config
            .history_ttl_secs
            .saturating_add(CLEANUP_INTERVAL.as_secs())
    }

    /// Return the number of topic buffers currently held.
    pub(crate) fn topic_count(&self) -> usize {
        self.buffers.len()
    }

    /// Return the number of buffers holding messages relayed by cluster peers
    /// (one per origin topic and epoch).
    #[cfg(test)]
    pub(crate) fn foreign_buffer_count(&self) -> usize {
        self.foreign_buffers.len()
    }

    /// Return the memory charged to recovery: payloads plus buffer overhead,
    /// for local and foreign buffers.
    pub(crate) fn total_bytes(&self) -> usize {
        self.total_bytes.load(Ordering::Relaxed)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
thread_local! {
    /// Runs as a foreign buffer is removed: a test does there what another
    /// worker may do at that point.
    static REMOVING: std::cell::RefCell<Option<Box<dyn Fn()>>> = const { std::cell::RefCell::new(None) };
}

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

    #[test]
    fn a_foreign_stream_made_again_as_cleanup_removes_it_is_still_recovered() {
        let mgr = std::sync::Arc::new(RecoveryManager::new(RecoveryConfig {
            history_ttl_secs: 0, // immediate expiry
            ..RecoveryConfig::default()
        }));
        mgr.interest_began("topic");
        mgr.push_foreign("topic", make_data("old"), 77, 0);
        std::thread::sleep(std::time::Duration::from_millis(5));
        // As cleanup removes the stream's buffer, a relay of the stream comes
        // on another worker.
        let pushing = std::sync::Arc::new(std::sync::Mutex::new(None));
        let (relay, slot) = (std::sync::Arc::clone(&mgr), std::sync::Arc::clone(&pushing));
        REMOVING.with_borrow_mut(|hook| {
            *hook = Some(Box::new(move || {
                let relay = std::sync::Arc::clone(&relay);
                let pushed = std::thread::spawn(move || {
                    relay.push_foreign("topic", make_data("new"), 77, 1);
                    relay.push_foreign("topic", make_data("later"), 77, 2);
                });
                std::thread::sleep(std::time::Duration::from_millis(50));
                *slot.lock().unwrap() = Some(pushed);
            }));
        });
        mgr.cleanup();
        REMOVING.with_borrow_mut(|hook| *hook = None);
        let pushed = pushing
            .lock()
            .unwrap()
            .take()
            .expect("cleanup removed the buffer");
        pushed.join().unwrap();
        // The new buffer is one of the topic's streams: a client that asks
        // from before it is told what it holds, never that nothing came.
        assert_eq!(mgr.streams("topic"), vec![(77, 2)]);
    }

    fn make_data(s: &str) -> Bytes {
        Bytes::from(s.to_owned())
    }

    // --- TopicRecoveryBuffer tests ---

    #[test]
    fn test_push_recover_roundtrip() {
        let mut buf = TopicRecoveryBuffer::new(4, 0); // 16 slots
        for i in 0..5 {
            buf.push(make_data(&format!("msg{i}")), i + 1);
        }

        // Recover from offset 2 (should get messages at offsets 3 and 4).
        let recovered = buf.recover_since(2, 500).unwrap();
        assert_eq!(recovered.len(), 2);
        assert_eq!(&recovered[0].1[..], b"msg3");
        assert_eq!(&recovered[1].1[..], b"msg4");
    }

    #[test]
    fn test_buffer_overflow() {
        let mut buf = TopicRecoveryBuffer::new(2, 0); // 4 slots
        for i in 0..10 {
            buf.push(make_data(&format!("msg{i}")), i + 1);
        }

        // Tail should have advanced. head=10, tail=6.
        assert_eq!(buf.head_offset, 10);
        assert_eq!(buf.tail_offset(), 6);

        // Trying to recover from offset 3 (well before tail=6) should return None.
        assert!(buf.recover_since(3, 500).is_none());

        // Boundary: after_offset=5, start=6 which IS the tail -- should succeed.
        let boundary = buf.recover_since(5, 500).unwrap();
        assert_eq!(boundary.len(), 4); // offsets 6, 7, 8, 9
        assert_eq!(&boundary[0].1[..], b"msg6");

        // Recover from offset 7 should return msgs 8 and 9.
        let recovered = buf.recover_since(7, 500).unwrap();
        assert_eq!(recovered.len(), 2);
        assert_eq!(&recovered[0].1[..], b"msg8");
        assert_eq!(&recovered[1].1[..], b"msg9");
    }

    #[test]
    fn test_epoch_mismatch() {
        let config = RecoveryConfig::default();
        let mgr = RecoveryManager::new(config);

        mgr.push("topic1", make_data("hello"));

        let (real_epoch, _) = mgr.get_position("topic1").unwrap();
        let wrong_epoch = real_epoch.wrapping_add(1);

        match mgr.recover("topic1", wrong_epoch, 0) {
            RecoveryResult::NotRecovered { epoch, offset } => {
                assert_eq!(epoch, real_epoch);
                assert_eq!(offset, 1); // head_offset after one push
            }
            _ => panic!("expected NotRecovered for epoch mismatch"),
        }
    }

    #[test]
    fn test_empty_buffer() {
        let config = RecoveryConfig::default();
        let mgr = RecoveryManager::new(config);

        match mgr.recover("nonexistent", 0, 0) {
            RecoveryResult::NoHistory => {}
            _ => panic!("expected NoHistory for missing topic"),
        }
    }

    #[test]
    fn test_ttl_cleanup() {
        let config = RecoveryConfig {
            history_ttl_secs: 0, // immediate expiry
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);

        mgr.push("topic1", make_data("data"));
        assert_eq!(mgr.topic_count(), 1);

        // Sleep a tiny bit so last_write is definitely older than TTL=0.
        std::thread::sleep(std::time::Duration::from_millis(5));

        mgr.cleanup();
        assert_eq!(mgr.topic_count(), 0);
        assert_eq!(mgr.total_bytes(), 0);
    }

    #[test]
    fn test_global_budget_eviction() {
        let config = RecoveryConfig {
            global_memory_budget: 10, // tiny budget: 10 bytes
            history_ttl_secs: 3600,   // don't TTL-expire
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);

        // Push data that exceeds budget across multiple topics.
        mgr.push("t1", make_data("aaaaaaa")); // 7 bytes
        std::thread::sleep(std::time::Duration::from_millis(2));
        mgr.push("t2", make_data("bbbbbbb")); // 7 bytes
        std::thread::sleep(std::time::Duration::from_millis(2));
        mgr.push("t3", make_data("ccccccc")); // 7 bytes

        // Total is 21 bytes, well over the 10-byte budget.
        assert!(mgr.total_bytes() > 10);

        mgr.cleanup();

        // After cleanup, should be at or under budget. At least one topic evicted.
        assert!(mgr.total_bytes() <= 10);
        assert!(mgr.topic_count() < 3);
    }

    #[test]
    fn test_get_position() {
        let config = RecoveryConfig::default();
        let mgr = RecoveryManager::new(config);

        assert!(mgr.get_position("topic1").is_none());

        mgr.push("topic1", make_data("msg0"));
        mgr.push("topic1", make_data("msg1"));
        mgr.push("topic1", make_data("msg2"));

        let (_epoch, offset) = mgr.get_position("topic1").unwrap();
        assert_eq!(offset, 3); // head_offset after 3 pushes
    }

    #[test]
    fn over_the_budget_a_new_topic_goes_unstamped() {
        let mgr = RecoveryManager::new(RecoveryConfig {
            global_memory_budget: 1,
            ..RecoveryConfig::default()
        });
        assert!(mgr.push_stamped("first", |_, _| make_data("a")).is_some());
        // The budget is used up: a topic with a buffer keeps it, a new one
        // gets none.
        assert!(mgr.push_stamped("first", |_, _| make_data("b")).is_some());
        assert!(mgr.push_stamped("second", |_, _| make_data("c")).is_none());
    }

    #[test]
    fn push_stamped_offset_matches_storage_and_recover() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        let mut reserved = Vec::new();
        for _ in 0..3 {
            let stored = mgr
                .push_stamped("topic1", |epoch, offset| {
                    reserved.push((epoch, offset));
                    make_data(&format!("o={offset}"))
                })
                .unwrap();
            // The returned bytes are exactly what was built for the reserved offset.
            let (_, off) = *reserved.last().unwrap();
            assert_eq!(&stored[..], format!("o={off}").as_bytes());
        }
        // Offsets are assigned 0,1,2 and the epoch is stable across pushes -- i.e.
        // the offset handed to the builder is exactly the storage offset.
        assert_eq!(
            reserved.iter().map(|(_, o)| *o).collect::<Vec<_>>(),
            vec![0, 1, 2]
        );
        assert!(reserved.iter().all(|(e, _)| *e == reserved[0].0));

        // recover() returns the stamped bytes at the offsets they were stored at.
        let (epoch, _) = mgr.get_position("topic1").unwrap();
        match mgr.recover("topic1", epoch, 0) {
            RecoveryResult::Recovered { publications, .. } => {
                assert_eq!(&publications[0][..], b"o=1");
                assert_eq!(&publications[1][..], b"o=2");
            }
            _ => panic!("expected Recovered"),
        }
    }

    #[test]
    fn test_recover_cap() {
        let config = RecoveryConfig {
            max_recovery_messages: 3,
            buffer_size_bits: 5, // 32 slots
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);

        for i in 0..20 {
            mgr.push("topic1", make_data(&format!("msg{i}")));
        }

        let (epoch, _) = mgr.get_position("topic1").unwrap();

        // 14 messages after offset 5, but cap is 3 -- should return NotRecovered
        // (matches Centrifugo: truncated recovery = incomplete = must re-fetch)
        match mgr.recover("topic1", epoch, 5) {
            RecoveryResult::NotRecovered {
                epoch: ep,
                offset: off,
            } => {
                assert_eq!(ep, epoch);
                assert_eq!(off, 20); // head_offset
            }
            _ => panic!("expected NotRecovered when cap truncates"),
        }

        // But if the gap is within the cap (e.g., after_offset=17, 2 messages to recover)
        match mgr.recover("topic1", epoch, 17) {
            RecoveryResult::Recovered { publications, .. } => {
                assert_eq!(publications.len(), 2); // offsets 18, 19
                assert_eq!(&publications[0][..], b"msg18");
                assert_eq!(&publications[1][..], b"msg19");
            }
            _ => panic!("expected Recovered when within cap"),
        }
    }

    // --- ForeignRecoveryBuffer tests ---

    #[test]
    fn test_foreign_push_recover() {
        let config = RecoveryConfig::default();
        let mgr = RecoveryManager::new(config);
        // This node has the topic: other nodes relay it here.
        mgr.interest_began("topic1");

        let foreign_epoch: u32 = 42;

        // Simulate receiving 5 messages from a cluster peer.
        for i in 0u64..5 {
            mgr.push_foreign("topic1", make_data(&format!("fmsg{i}")), foreign_epoch, i);
        }

        // Recover using the foreign epoch -- should succeed.
        match mgr.recover("topic1", foreign_epoch, 2) {
            RecoveryResult::Recovered {
                publications,
                epoch,
                offset,
            } => {
                assert_eq!(epoch, foreign_epoch);
                assert_eq!(offset, 4); // head_offset - 1 = 5 - 1
                assert_eq!(publications.len(), 2);
                assert_eq!(&publications[0][..], b"fmsg3");
                assert_eq!(&publications[1][..], b"fmsg4");
            }
            other => panic!(
                "expected Recovered, got {:?}",
                match other {
                    RecoveryResult::NotRecovered { .. } => "NotRecovered",
                    RecoveryResult::NoHistory => "NoHistory",
                    _ => "unknown",
                }
            ),
        }
    }

    #[test]
    fn a_relayed_message_held_already_is_not_new() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        assert!(mgr.push_foreign("t", make_data("m0"), 7, 0));
        assert!(mgr.push_foreign("t", make_data("m1"), 7, 1));
        // Sent again by a peer catching this node up: held, so not delivered.
        assert!(!mgr.push_foreign("t", make_data("m1"), 7, 1));
        assert!(!mgr.push_foreign("t", make_data("m0"), 7, 0));
        // Past a hole, then the hole itself: both new.
        assert!(mgr.push_foreign("t", make_data("m3"), 7, 3));
        assert!(mgr.push_foreign("t", make_data("m2"), 7, 2));
        assert!(!mgr.push_foreign("t", make_data("m2"), 7, 2));
    }

    #[test]
    fn a_node_asks_from_its_first_hole_in_each_relayed_stream() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        for offset in [0, 1, 2, 4, 5] {
            mgr.push_foreign("a", make_data("x"), 7, offset);
        }
        for offset in 10..13 {
            mgr.push_foreign("b", make_data("y"), 9, offset);
        }
        let mut points = mgr.foreign_positions();
        points.sort();
        assert_eq!(
            points,
            vec![("a".to_owned(), 7, 2), ("b".to_owned(), 9, 12)]
        );
        // The hole filled: from the newest on.
        mgr.push_foreign("a", make_data("x"), 7, 3);
        assert!(mgr.foreign_positions().contains(&("a".to_owned(), 7, 5)));
    }

    #[test]
    fn an_own_stream_that_let_go_what_a_client_missed_is_not_recovered_by_streams() {
        // Four slots: away for ten, the first six are gone.
        let mgr = RecoveryManager::new(RecoveryConfig {
            buffer_size_bits: 2,
            ..RecoveryConfig::default()
        });
        mgr.push("prices", make_data("0"));
        let (epoch, _) = mgr.get_position("prices").unwrap();
        for n in 1..=10 {
            mgr.push("prices", make_data(&n.to_string()));
        }
        assert!(not_recovered(&mgr.recover_streams(
            "prices",
            (epoch, 0),
            &[(epoch, 0)]
        )));
        assert!(not_recovered(&mgr.recover("prices", epoch, 0)));
        // From what is still held: recovered.
        let RecoveryResult::Recovered { publications, .. } =
            mgr.recover_streams("prices", (epoch, 7), &[(epoch, 7)])
        else {
            panic!("not recovered");
        };
        assert_eq!(publications.len(), 3);
        // The same of a local stream.
        mgr.push_stamped_local("local", |_, _| make_data("0"));
        let (local, _) = mgr.get_position("local").unwrap();
        for n in 1..=10 {
            mgr.push_stamped_local("local", |_, _| make_data(&n.to_string()));
        }
        assert!(not_recovered(&mgr.recover_streams(
            "local",
            (local, 0),
            &[(local, 0)]
        )));
    }

    #[test]
    fn a_window_of_delivered_offsets_tells_what_is_new() {
        let mut delivered = Delivered::first(7, 5);
        assert!(!delivered.deliver(5) && !delivered.deliver(0));
        assert!(delivered.deliver(7), "a hole at 6");
        assert_eq!((delivered.through, delivered.above), (5, 0b10));
        assert!(!delivered.deliver(7));
        assert!(delivered.any_after(6) && !delivered.any_after(7));
        assert!(delivered.deliver(6));
        assert_eq!((delivered.through, delivered.above), (7, 0));
        // Far ahead: the window moves on, and gives up on the hole behind.
        assert!(delivered.deliver(200));
        assert_eq!(delivered.through, 136);
        assert!(delivered.has(200) && !delivered.has(199));
        assert!(!delivered.deliver(200));
        assert!(delivered.deliver(137));
        assert_eq!(delivered.through, 137);
        let mut edge = Delivered::first(7, u64::MAX - 1);
        assert!(edge.deliver(u64::MAX) && !edge.deliver(u64::MAX));
    }

    #[test]
    fn a_stream_relayed_with_no_room_to_keep_it_is_not_delivered_twice() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.push("setup", make_data("s"));
        let budget = mgr.total_bytes();
        let mgr = with_budget(mgr, budget);
        assert!(mgr.push_foreign("prices:open", make_data("0"), 7, 0));
        assert!(mgr.foreign_buffers.is_empty());
        // A peer is asked after it, and sends it again all the same.
        assert!(
            mgr.foreign_positions()
                .contains(&("prices:open".to_owned(), 7, 0))
        );
        assert!(!mgr.push_foreign("prices:open", make_data("0"), 7, 0));
        assert!(mgr.push_foreign("prices:open", make_data("2"), 7, 2));
        // Room again: what was delivered after a message is no buffer's yet.
        let mgr = with_budget(mgr, usize::MAX);
        assert!(mgr.push_foreign("prices:open", make_data("1"), 7, 1));
        assert!(mgr.foreign_buffers.is_empty());
        assert!(!mgr.push_foreign("prices:open", make_data("2"), 7, 2));
        assert!(mgr.push_foreign("prices:open", make_data("3"), 7, 3));
        assert_eq!(mgr.foreign_buffers.len(), 1);
        assert!(mgr.relayed_unkept.is_empty());
        assert!(!mgr.push_foreign("prices:open", make_data("1"), 7, 1));
    }

    #[test]
    fn a_relayed_buffer_removed_leaves_where_this_node_stood() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        for offset in [0, 1, 3] {
            mgr.push_foreign("a", make_data("x"), 7, offset);
        }
        // Over the budget: the buffer goes.
        let mgr = with_budget(mgr, 0);
        mgr.cleanup();
        assert!(mgr.foreign_buffers.is_empty());
        assert!(mgr.foreign_positions().contains(&("a".to_owned(), 7, 1)));
        for offset in [0, 1, 3] {
            assert!(!mgr.push_foreign("a", make_data("x"), 7, offset));
        }
        assert!(mgr.push_foreign("a", make_data("x"), 7, 2));
    }

    #[test]
    fn a_peer_gets_what_this_node_published_after_its_position() {
        let mgr = RecoveryManager::new(RecoveryConfig {
            buffer_size_bits: 2, // 4 kept
            ..RecoveryConfig::default()
        });
        for i in 0..6 {
            mgr.push("t", make_data(&format!("m{i}")));
        }
        let (epoch, head) = mgr.get_position("t").unwrap();
        assert_eq!(head, 6);
        let sent = |after| -> Vec<(u64, String)> {
            mgr.published_after("t", epoch, after)
                .into_iter()
                .map(|(offset, data)| (offset, String::from_utf8(data.to_vec()).unwrap()))
                .collect()
        };
        assert_eq!(sent(3), vec![(4, "m4".to_owned()), (5, "m5".to_owned())]);
        // What is gone is skipped: from the oldest kept (offset 2).
        assert_eq!(sent(0).first(), Some(&(2, "m2".to_owned())));
        assert_eq!(sent(0).len(), 4);
        assert!(sent(5).is_empty());
        assert!(sent(u64::MAX).is_empty());
        // Another node's stream, or another epoch: nothing.
        assert!(
            mgr.published_after("t", epoch.wrapping_add(1), 0)
                .is_empty()
        );
        assert!(mgr.published_after("other", epoch, 0).is_empty());
    }

    #[test]
    fn test_foreign_epoch_mismatch() {
        let config = RecoveryConfig::default();
        let mgr = RecoveryManager::new(config);

        let foreign_epoch: u32 = 42;
        mgr.push_foreign("topic1", make_data("data"), foreign_epoch, 0);

        // Try to recover with wrong epoch -- no matching buffer.
        let wrong_epoch = 99;
        match mgr.recover("topic1", wrong_epoch, 0) {
            RecoveryResult::NoHistory => {}
            _ => panic!("expected NoHistory for unmatched foreign epoch"),
        }
    }

    #[test]
    fn test_foreign_buffer_eviction() {
        let config = RecoveryConfig {
            global_memory_budget: 20,
            history_ttl_secs: 3600,
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);

        // Push local data (7 bytes).
        mgr.push("t_local", make_data("aaaaaaa"));
        std::thread::sleep(std::time::Duration::from_millis(2));

        // Push foreign data (7 bytes).
        mgr.push_foreign("t_foreign", make_data("bbbbbbb"), 42, 0);
        std::thread::sleep(std::time::Duration::from_millis(2));

        // Push more foreign data (7 bytes) -- total now 21, over budget of 20.
        mgr.push_foreign("t_foreign2", make_data("ccccccc"), 43, 0);

        assert!(mgr.total_bytes() > 20);

        mgr.cleanup();

        // After cleanup, should be at or under budget.
        assert!(mgr.total_bytes() <= 20);
    }

    #[test]
    fn fresh_foreign_epochs_stop_at_the_budget() {
        let config = RecoveryConfig {
            global_memory_budget: 64 * 1024,
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);
        // This node has the topic: other nodes relay it here.
        mgr.interest_began("t");
        // A peer naming a new epoch with every message.
        for epoch in 0..10_000u32 {
            mgr.push_foreign("t", make_data("x"), epoch, 0);
        }
        let one_buffer = ForeignRecoveryBuffer::new(mgr.config.buffer_size_bits, 0, 8).footprint();
        assert!(
            mgr.total_bytes() <= 64 * 1024 + one_buffer,
            "{}",
            mgr.total_bytes()
        );
        assert!(mgr.foreign_buffers.len() < 10_000);
        // An existing buffer still takes messages.
        mgr.push_foreign("t", make_data("y"), 0, 1);
        assert!(mgr.streams("t").contains(&(0, 1)));
        // What came past the budget is not kept: a client from before it is
        // not told it missed nothing.
        assert!(not_recovered(&mgr.recover("t", 0, 0)));
    }

    #[test]
    fn test_foreign_ttl_cleanup() {
        let config = RecoveryConfig {
            history_ttl_secs: 0, // immediate expiry
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);

        mgr.push_foreign("topic1", make_data("data"), 42, 0);

        std::thread::sleep(std::time::Duration::from_millis(5));

        mgr.cleanup();
        assert_eq!(mgr.total_bytes(), 0);
        assert_eq!(mgr.foreign_buffers.len(), 0);
    }

    #[test]
    fn test_foreign_and_local_coexist() {
        let config = RecoveryConfig::default();
        let mgr = RecoveryManager::new(config);
        // This node has the topic: other nodes relay it here.
        mgr.interest_began("topic1");

        // Local messages on topic1.
        mgr.push("topic1", make_data("local0"));
        mgr.push("topic1", make_data("local1"));
        let (local_epoch, _) = mgr.get_position("topic1").unwrap();

        // Foreign messages on same topic, different epoch.
        let foreign_epoch: u32 = 77;
        mgr.push_foreign("topic1", make_data("foreign0"), foreign_epoch, 0);
        mgr.push_foreign("topic1", make_data("foreign1"), foreign_epoch, 1);

        // The client last had local0: everything after it, from both
        // streams, in the order it arrived here.
        match mgr.recover("topic1", local_epoch, 0) {
            RecoveryResult::Recovered { publications, .. } => {
                let got: Vec<&[u8]> = publications.iter().map(|p| &p[..]).collect();
                assert_eq!(got, [&b"local1"[..], b"foreign0", b"foreign1"]);
            }
            _ => panic!("expected Recovered from both streams"),
        }

        // The client last had foreign0: only foreign1 came after it.
        match mgr.recover("topic1", foreign_epoch, 0) {
            RecoveryResult::Recovered { publications, .. } => {
                assert_eq!(publications.len(), 1);
                assert_eq!(&publications[0][..], b"foreign1");
            }
            _ => panic!("expected Recovered from foreign buffer"),
        }
    }

    #[test]
    fn two_nodes_interleaved_recover_in_arrival_order() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        // This node has the topic: other nodes relay it here.
        mgr.interest_began("room");
        let other: u32 = 0xa;
        mgr.push_foreign("room", make_data("a1"), other, 0);
        mgr.push("room", make_data("b1"));
        mgr.push_foreign("room", make_data("a2"), other, 1);
        mgr.push("room", make_data("b2"));
        let (epoch, _) = mgr.get_position("room").unwrap();
        mgr.push_foreign("room", make_data("a3"), other, 2);
        mgr.push("room", make_data("b3"));
        mgr.push_foreign("room", make_data("a4"), other, 3);
        mgr.push("room", make_data("b4"));
        match mgr.recover("room", epoch, 1) {
            RecoveryResult::Recovered { publications, .. } => {
                let got: Vec<&[u8]> = publications.iter().map(|p| &p[..]).collect();
                assert_eq!(got, [&b"a3"[..], b"b3", b"a4", b"b4"]);
            }
            _ => panic!("expected Recovered from both streams"),
        }
    }

    #[test]
    fn a_relayed_stream_with_a_hole_after_the_anchor_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("b0"), 7, 0);
        mgr.push("room", make_data("a0"));
        let (epoch, _) = mgr.get_position("room").unwrap();
        mgr.push_foreign("room", make_data("b1"), 7, 1);
        // b2 was shed on the way here.
        mgr.push_foreign("room", make_data("b3"), 7, 3);
        assert!(matches!(
            mgr.recover("room", epoch, 0),
            RecoveryResult::NotRecovered { .. }
        ));
    }

    #[test]
    fn a_stream_that_lost_what_came_after_the_anchor_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig {
            buffer_size_bits: 1, // 2 slots
            ..RecoveryConfig::default()
        });
        mgr.push_foreign("room", make_data("b0"), 7, 0);
        mgr.push("room", make_data("a0"));
        let (epoch, _) = mgr.get_position("room").unwrap();
        // Three more from the other node: one of them is evicted already.
        for (i, text) in ["b1", "b2", "b3"].iter().enumerate() {
            mgr.push_foreign("room", make_data(text), 7, i as u64 + 1);
        }
        assert!(matches!(
            mgr.recover("room", epoch, 0),
            RecoveryResult::NotRecovered { .. }
        ));
    }

    /// The texts of a recovery, or None when it did not recover.
    fn replayed(result: RecoveryResult) -> Option<Vec<String>> {
        match result {
            RecoveryResult::Recovered { publications, .. } => Some(
                publications
                    .iter()
                    .map(|p| String::from_utf8(p.to_vec()).unwrap())
                    .collect(),
            ),
            _ => None,
        }
    }

    #[test]
    fn a_client_from_a_node_that_saw_the_streams_in_another_order_loses_nothing() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        let (a, b) = (0xa, 0xb);
        mgr.push_foreign("room", make_data("a0"), a, 0);
        mgr.push_foreign("room", make_data("b0"), b, 0);
        // This node had b1 before a1; the client's node had a1 first, and
        // the client got a1 only.
        mgr.push_foreign("room", make_data("b1"), b, 1);
        mgr.push_foreign("room", make_data("a1"), a, 1);
        assert_eq!(
            replayed(mgr.recover_streams("room", (a, 1), &[(a, 1), (b, 0)])),
            Some(vec!["b1".to_owned()])
        );
    }

    #[test]
    fn every_named_stream_comes_from_its_own_offset() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push("room", make_data("l0"));
        mgr.push_foreign("room", make_data("f0"), 7, 0);
        mgr.push("room", make_data("l1"));
        mgr.push_foreign("room", make_data("f1"), 7, 1);
        mgr.push("room", make_data("l2"));
        let (local, _) = mgr.get_position("room").unwrap();
        // In this node's arrival order.
        assert_eq!(
            replayed(mgr.recover_streams("room", (local, 0), &[(local, 0), (7, 0)])),
            Some(vec!["l1".to_owned(), "f1".to_owned(), "l2".to_owned()])
        );
        // Up to date in both: nothing.
        assert_eq!(
            replayed(mgr.recover_streams("room", (local, 2), &[(local, 2), (7, 1)])),
            Some(vec![])
        );
    }

    #[test]
    fn a_named_stream_this_node_does_not_hold_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0), (0xc, 4)])),
            None
        );
    }

    #[test]
    fn a_named_stream_with_a_hole_after_the_position_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        // a1 was shed on the way here.
        mgr.push_foreign("room", make_data("a2"), 0xa, 2);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0)])),
            None
        );
    }

    #[test]
    fn an_unnamed_stream_that_came_before_the_last_message_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        // c0 came here before a0: whether the client should have had it
        // nothing here says.
        mgr.push_foreign("room", make_data("c0"), 0xc, 0);
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0)])),
            None
        );
    }

    #[test]
    fn an_unnamed_stream_that_came_after_the_last_message_is_replayed() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        mgr.push_foreign("room", make_data("c0"), 0xc, 0);
        mgr.push_foreign("room", make_data("c1"), 0xc, 1);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0)])),
            Some(vec!["c0".to_owned(), "c1".to_owned()])
        );
    }

    #[test]
    fn an_unnamed_stream_held_from_its_middle_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        // What came of c before c5 this node never had.
        mgr.push_foreign("room", make_data("c5"), 0xc, 5);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0)])),
            None
        );
    }

    #[test]
    fn a_stream_removed_after_the_last_message_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        mgr.push_foreign("room", make_data("c0"), 0xc, 0);
        std::thread::sleep(Duration::from_millis(2));
        mgr.push_foreign("room", make_data("a1"), 0xa, 1);
        // Over the memory budget the oldest buffer goes: c, with what the
        // client missed.
        let budget = mgr.total_bytes() - 1;
        let mgr = RecoveryManager {
            config: RecoveryConfig {
                global_memory_budget: budget,
                ..RecoveryConfig::default()
            },
            ..mgr
        };
        mgr.cleanup();
        assert!(!mgr.streams("room").iter().any(|(epoch, _)| *epoch == 0xc));
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0)])),
            None
        );
    }

    /// The same manager with its memory budget at `budget`.
    fn with_budget(mgr: RecoveryManager, budget: usize) -> RecoveryManager {
        RecoveryManager {
            config: RecoveryConfig {
                global_memory_budget: budget,
                ..RecoveryConfig::default()
            },
            ..mgr
        }
    }

    fn not_recovered(result: &RecoveryResult) -> bool {
        matches!(result, RecoveryResult::NotRecovered { .. })
    }

    /// A node gone without a word, another in its place: a client whose
    /// last message came from this node's own stream, published to the
    /// cluster or to its own subscribers only, is not told it missed nothing
    /// either (a pattern of its may have covered what the gone one sent).
    #[test]
    fn a_node_lost_anew_leaves_no_topic_here_said_whole() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.push("news", make_data("0"));
        mgr.push_stamped_local("local", |_, _| make_data("0"));
        let (news, _) = mgr.get_position("news").unwrap();
        let (local, _) = mgr.get_position("local").unwrap();
        assert!(!not_recovered(&mgr.recover("news", news, 0)));
        assert!(!not_recovered(&mgr.recover("local", local, 0)));
        mgr.lost_everything();
        assert!(not_recovered(&mgr.recover("news", news, 0)));
        assert!(not_recovered(&mgr.recover_streams(
            "news",
            (news, 0),
            &[(news, 0)]
        )));
        assert!(not_recovered(&mgr.recover("local", local, 0)));
        assert!(not_recovered(&mgr.recover_streams(
            "local",
            (local, 0),
            &[(local, 0)]
        )));
    }

    #[test]
    fn a_client_with_one_position_is_not_told_a_removed_stream_was_replayed() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        // The client's last message, this node's own; then another node's,
        // then this node's again.
        mgr.push("room", make_data("l0"));
        let (local, _) = mgr.get_position("room").unwrap();
        std::thread::sleep(Duration::from_millis(2));
        mgr.push_foreign("room", make_data("f0"), 0xf, 0);
        std::thread::sleep(Duration::from_millis(2));
        mgr.push("room", make_data("l1"));
        // Over the budget the oldest buffer goes: the other node's.
        let budget = mgr.total_bytes() - 1;
        let mgr = with_budget(mgr, budget);
        mgr.cleanup();
        assert!(mgr.streams("room").iter().all(|(epoch, _)| *epoch == local));
        // A client before 3.1 names its last message only: f0 is gone.
        assert!(not_recovered(&mgr.recover("room", local, 0)));
    }

    #[test]
    fn a_relayed_message_with_no_room_to_keep_it_is_never_recovered_as_nothing() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push("room", make_data("l0"));
        let (local, _) = mgr.get_position("room").unwrap();
        // Over the budget: another node's new stream gets no buffer, and its
        // message goes out live only.
        let budget = mgr.total_bytes();
        let mgr = with_budget(mgr, budget);
        assert!(mgr.push_foreign("room", make_data("f0"), 0xf, 0));
        assert!(mgr.streams("room").iter().all(|(epoch, _)| *epoch == local));
        // A client whose last message came before it may have missed it.
        assert!(not_recovered(&mgr.recover("room", local, 0)));
        assert_eq!(
            replayed(mgr.recover_streams("room", (local, 0), &[(local, 0)])),
            None
        );
    }

    #[test]
    fn a_message_published_with_no_room_to_keep_it_is_never_recovered_as_nothing() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("f0"), 0xf, 0);
        let budget = mgr.total_bytes();
        let mgr = with_budget(mgr, budget);
        // This node's new stream gets no buffer: the message goes unstamped.
        assert!(mgr.push_stamped("room", |_, _| make_data("l0")).is_none());
        assert!(not_recovered(&mgr.recover("room", 0xf, 0)));
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xf, 0), &[(0xf, 0)])),
            None
        );
    }

    #[test]
    fn a_message_relayed_with_no_position_is_never_recovered_as_nothing() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.push("room", make_data("l0"));
        let (local, _) = mgr.get_position("room").unwrap();
        // Another node had no room to keep its message: it came with no
        // position, and no node holds it.
        mgr.not_kept("room");
        assert!(not_recovered(&mgr.recover("room", local, 0)));
        assert_eq!(
            replayed(mgr.recover_streams("room", (local, 0), &[(local, 0)])),
            None
        );
        // A client whose last message came after it missed nothing.
        mgr.push("room", make_data("l1"));
        assert!(!not_recovered(&mgr.recover("room", local, 1)));
    }

    #[test]
    fn a_peer_hears_what_it_did_not_hear_of_and_this_node_no_longer_holds() {
        // No room for any history.
        let mgr = with_budget(RecoveryManager::new(RecoveryConfig::default()), 0);
        let heard = mgr.arrived_through();
        for topic in ["news", "prices:a"] {
            assert!(mgr.push_stamped(topic, |_, _| make_data("x")).is_none());
        }
        // Published to this node's subscribers only, relayed here, or told
        // of by a peer: not this node's to tell.
        assert!(
            mgr.push_stamped_local("mine", |_, _| make_data("x"))
                .is_none()
        );
        mgr.push_foreign("theirs", make_data("x"), 0xf, 0);
        mgr.not_kept("told");
        assert_eq!(mgr.lost_after("news", heard), ["news"]);
        assert_eq!(mgr.lost_after("prices:*", heard), ["prices:a"]);
        for topic in ["other", "mine", "theirs", "told"] {
            assert!(mgr.lost_after(topic, heard).is_empty(), "{topic}");
        }
        // A peer that heard of everything up to now: nothing to say.
        assert!(mgr.lost_after("news", mgr.arrived_through()).is_empty());
    }

    #[test]
    fn a_message_the_ring_let_go_before_a_peer_heard_of_it_is_told() {
        // Two slots a topic: the first of three goes.
        let mgr = RecoveryManager::new(RecoveryConfig {
            buffer_size_bits: 1,
            ..RecoveryConfig::default()
        });
        let heard = mgr.arrived_through();
        for text in ["a", "b", "c"] {
            mgr.push("news", make_data(text));
        }
        assert_eq!(mgr.lost_after("news", heard), ["news"]);
        assert_eq!(mgr.lost_after("n*", heard), ["news"]);
        // One that heard of "a": nothing it missed is gone.
        assert!(mgr.lost_after("news", heard + 1).is_empty());
    }

    #[test]
    fn a_record_let_go_counts_for_every_topic_a_peer_did_not_hear_of_it_by() {
        let mgr = RecoveryManager::new(RecoveryConfig {
            history_ttl_secs: 0,
            global_memory_budget: 0,
            ..RecoveryConfig::default()
        });
        let heard = mgr.arrived_through();
        assert!(mgr.push_stamped("news", |_, _| make_data("x")).is_none());
        // The history's lifetime is over: the record goes, and is forgotten.
        std::thread::sleep(Duration::from_millis(5));
        mgr.cleanup();
        assert!(!mgr.removed_through.contains_key("news"));
        assert_eq!(mgr.lost_after("other", heard), ["other"]);
        assert!(mgr.lost_after("other", mgr.arrived_through()).is_empty());
    }

    #[test]
    fn a_buffer_removed_is_told_to_peers_when_they_had_some_of_it() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        let heard = mgr.arrived_through();
        mgr.push("news", make_data("x"));
        mgr.push_stamped_local("mine", |_, _| make_data("x"));
        let mgr = with_budget(mgr, 0);
        mgr.cleanup();
        assert_eq!(mgr.topic_count(), 0);
        assert_eq!(mgr.lost_after("news", heard), ["news"]);
        assert!(mgr.lost_after("mine", heard).is_empty());
    }

    #[test]
    fn what_was_published_to_this_nodes_subscribers_only_is_a_stream_of_its_own() {
        // Two slots a stream.
        let mgr = RecoveryManager::new(RecoveryConfig {
            buffer_size_bits: 1,
            ..RecoveryConfig::default()
        });
        mgr.push("news", make_data("s0"));
        let (shared, _) = mgr.get_position("news").unwrap();
        // Three local ones: in their own stream, which takes none of the
        // cluster stream's offsets or room.
        for text in ["l0", "l1", "l2"] {
            mgr.push_stamped_local("news", |_, _| make_data(text));
        }
        mgr.push("news", make_data("s1"));
        let streams = mgr.streams("news");
        assert_eq!(streams.len(), 2);
        assert!(streams.contains(&(shared, 1)));
        let (local, _) = *streams.iter().find(|(e, _)| *e != shared).unwrap();
        assert_eq!(
            mgr.published_after("news", shared, 0),
            vec![(1, make_data("s1"))]
        );
        assert!(mgr.published_after("news", local, 0).is_empty());
        let (epoch, all) = mgr.published_unheard("news", 0, |_| false).unwrap();
        assert_eq!(epoch, shared);
        assert_eq!(all, vec![(0, make_data("s0")), (1, make_data("s1"))]);
        // Its own subscribers recover both streams, in the order they came:
        // from where they stand in each; by one position, not once the
        // local stream let "l0" go after it.
        assert!(not_recovered(&mgr.recover("news", shared, 0)));
        let named = [(shared, 0), (local, 1)];
        let RecoveryResult::Recovered { publications, .. } =
            mgr.recover_streams("news", (shared, 0), &named)
        else {
            panic!("not recovered");
        };
        assert_eq!(publications, vec![make_data("l2"), make_data("s1")]);
    }

    #[test]
    fn a_topic_not_kept_with_no_room_to_name_it_counts_for_every_topic() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        for n in 0..MAX_UNKEPT_TOPICS {
            mgr.removed_through.insert(format!("t{n}"), Removed::none());
        }
        mgr.push("room", make_data("l0"));
        let (local, _) = mgr.get_position("room").unwrap();
        let heard = mgr.arrived_through();
        mgr.not_kept("unnamed");
        assert!(!mgr.removed_through.contains_key("unnamed"));
        // Each topic a client asks of.
        assert!(not_recovered(&mgr.recover("room", local, 0)));
        // And each a peer has, of what this node published to other nodes.
        assert!(mgr.lost_after("other", heard).is_empty());
        let mgr = with_budget(mgr, 0);
        assert!(mgr.push_stamped("unnamed", |_, _| make_data("x")).is_none());
        assert_eq!(mgr.lost_after("other", heard), ["other"]);
        assert_eq!(mgr.lost_after("prices:*", heard), ["prices:*"]);
    }

    #[test]
    fn a_peer_saying_a_pattern_lost_marks_each_topic_here_it_matches() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.push("prices:a", make_data("a0"));
        mgr.push_foreign("prices:b", make_data("b0"), 0xf, 0);
        mgr.interest_began("prices:c");
        mgr.push("other", make_data("o0"));
        let (local, _) = mgr.get_position("prices:a").unwrap();
        let (other, _) = mgr.get_position("other").unwrap();
        mgr.lost("prices:*");
        assert!(not_recovered(&mgr.recover("prices:a", local, 0)));
        assert!(not_recovered(&mgr.recover("prices:b", 0xf, 0)));
        assert!(mgr.removed_through.contains_key("prices:c"));
        assert!(!mgr.removed_through.contains_key("prices:*"));
        assert!(!not_recovered(&mgr.recover("other", other, 0)));
        // A topic it names: that one.
        mgr.lost("other");
        assert!(not_recovered(&mgr.recover("other", other, 0)));
    }

    #[test]
    fn a_pattern_matches_the_topics_of_this_nodes_own_streams() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        for topic in ["prices:a", "prices:b", "other"] {
            mgr.push(topic, make_data("x"));
        }
        mgr.push_foreign("prices:c", make_data("f"), 0xf, 0);
        let mut matched = mgr.own_topics_matching("prices:*");
        matched.sort();
        assert_eq!(matched, ["prices:a", "prices:b"]);
        assert!(mgr.own_topics_matching("none:*").is_empty());
    }

    #[test]
    fn a_peer_gets_what_this_node_published_after_what_it_heard_of() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.push("news", make_data("old"));
        let (epoch, _) = mgr.get_position("news").unwrap();
        // A minute ago the arrival order stood after "old".
        let minute_ago = Instant::now().checked_sub(Duration::from_secs(60)).unwrap();
        mgr.marks
            .lock()
            .push_back((minute_ago, mgr.arrival.load(Ordering::Relaxed)));
        let heard = mgr.arrived_through();
        mgr.push("news", make_data("new"));
        // An interest of 30 s began after "old": before it, nothing was
        // relayed; one older than every mark: everything.
        assert_eq!(mgr.arrived_before(Duration::from_secs(30)), heard);
        assert_eq!(mgr.arrived_before(Duration::from_secs(120)), 0);
        let (sent_epoch, sent) = mgr.published_unheard("news", heard, |_| false).unwrap();
        assert_eq!(sent_epoch, epoch);
        assert_eq!(sent, vec![(1, make_data("new"))]);
        let (_, all) = mgr.published_unheard("news", 0, |_| false).unwrap();
        assert_eq!(all.len(), 2);
        // A stream the peer named, or none here: nothing this way.
        assert!(mgr.published_unheard("news", 0, |e| e == epoch).is_none());
        assert!(mgr.published_unheard("other", 0, |_| false).is_none());
    }

    #[test]
    fn the_marks_go_back_as_far_as_this_node_holds_its_messages() {
        // Two slots a topic.
        let mgr = RecoveryManager::new(RecoveryConfig {
            buffer_size_bits: 1,
            ..RecoveryConfig::default()
        });
        for text in ["a", "b", "c"] {
            mgr.mark();
            mgr.push("news", make_data(text));
        }
        mgr.mark();
        mgr.mark();
        let marks = |mgr: &RecoveryManager| -> Vec<u64> {
            mgr.marks.lock().iter().map(|(_, next)| *next).collect()
        };
        assert_eq!(marks(&mgr), [1, 2, 3, 4], "none while nothing came");
        // "a" is gone: of the marks before "b", the last stays.
        mgr.cleanup();
        assert_eq!(marks(&mgr), [2, 3, 4]);
    }

    #[test]
    fn more_than_the_recovery_limit_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig {
            max_recovery_messages: 2,
            ..RecoveryConfig::default()
        });
        mgr.interest_began("room");
        for i in 0..2 {
            mgr.push_foreign("room", make_data("a"), 0xa, i);
            mgr.push_foreign("room", make_data("b"), 0xb, i);
        }
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0), (0xb, 0)])),
            Some(vec!["a".to_owned(), "b".to_owned()])
        );
        mgr.push_foreign("room", make_data("b"), 0xb, 2);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0), (0xb, 0)])),
            None
        );
    }

    #[test]
    fn a_named_stream_relayed_before_the_topic_came_back_here_is_not_recovered() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        mgr.push_foreign("room", make_data("a1"), 0xa, 1);
        assert!(replayed(mgr.recover_streams("room", (0xa, 1), &[(0xa, 1)])).is_some());
        // The topic left this node and came back: what was published in
        // between was not relayed here.
        mgr.interest_ended("room");
        mgr.interest_began("room");
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 1), &[(0xa, 1)])),
            None
        );
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0)])),
            None
        );
    }

    #[test]
    fn a_stream_relayed_out_of_order_is_replayed_in_its_own_order() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        mgr.push_foreign("room", make_data("a0"), 0xa, 0);
        mgr.push_foreign("room", make_data("b0"), 0xb, 0);
        mgr.push_foreign("room", make_data("b2"), 0xb, 2);
        mgr.push_foreign("room", make_data("a1"), 0xa, 1);
        mgr.push_foreign("room", make_data("b1"), 0xb, 1);
        assert_eq!(
            replayed(mgr.recover_streams("room", (0xa, 0), &[(0xa, 0), (0xb, 0)])),
            Some(vec!["a1".to_owned(), "b1".to_owned(), "b2".to_owned()])
        );
    }

    #[test]
    fn the_streams_of_a_topic_are_what_this_node_holds_at_their_last_offsets() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        mgr.interest_began("room");
        assert!(mgr.streams("room").is_empty());
        mgr.push("room", make_data("l0"));
        mgr.push("room", make_data("l1"));
        mgr.push_foreign("room", make_data("f3"), 7, 3);
        let (local, _) = mgr.get_position("room").unwrap();
        let mut streams = mgr.streams("room");
        streams.sort_unstable();
        let mut expected = vec![(local, 1), (7, 3)];
        expected.sort_unstable();
        assert_eq!(streams, expected);
    }

    #[test]
    fn test_foreign_buffer_overflow() {
        let config = RecoveryConfig {
            buffer_size_bits: 2, // 4 slots
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(config);
        // This node has the topic: other nodes relay it here.
        mgr.interest_began("topic1");

        let epoch: u32 = 50;
        // Push 10 messages -- only last 4 should survive (offsets 6-9).
        for i in 0u64..10 {
            mgr.push_foreign("topic1", make_data(&format!("fm{i}")), epoch, i);
        }

        // Recovery from offset 4 (start=5, before tail=6) should fail.
        match mgr.recover("topic1", epoch, 4) {
            RecoveryResult::NotRecovered { .. } => {}
            _ => panic!("expected NotRecovered for gap too large"),
        }

        // Recovery from offset 5 (start=6 = tail) should succeed with 4 messages.
        match mgr.recover("topic1", epoch, 5) {
            RecoveryResult::Recovered { publications, .. } => {
                assert_eq!(publications.len(), 4);
                assert_eq!(&publications[0][..], b"fm6");
            }
            _ => panic!("expected Recovered at boundary"),
        }

        // Recovery from offset 7 should get messages 8, 9.
        match mgr.recover("topic1", epoch, 7) {
            RecoveryResult::Recovered { publications, .. } => {
                assert_eq!(publications.len(), 2);
                assert_eq!(&publications[0][..], b"fm8");
                assert_eq!(&publications[1][..], b"fm9");
            }
            _ => panic!("expected Recovered"),
        }
    }

    #[test]
    fn foreign_offset_jump_is_bounded() {
        let mgr = RecoveryManager::new(RecoveryConfig::default());
        // This node has the topic: other nodes relay it here.
        mgr.interest_began("t");
        mgr.push_foreign("t", make_data("a"), 7, 0);
        let started = Instant::now();
        mgr.push_foreign("t", make_data("b"), 7, 1u64 << 62);
        assert!(started.elapsed() < Duration::from_secs(1));
        // Only the newest message is left; anything older is a gap.
        match mgr.recover("t", 7, (1u64 << 62) - 1) {
            RecoveryResult::Recovered { publications, .. } => {
                assert_eq!(publications.len(), 1);
                assert_eq!(&publications[0][..], b"b");
            }
            _ => panic!("expected Recovered"),
        }
        assert!(matches!(
            mgr.recover("t", 7, 0),
            RecoveryResult::NotRecovered { .. }
        ));
    }

    #[test]
    fn local_buffer_memory_grows_with_use() {
        let cfg = RecoveryConfig {
            buffer_size_bits: 16, // allows 65536 messages per topic
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(cfg);
        mgr.push("room:1", make_data("hello"));
        // One small message must not cost the 65536-slot maximum (~2 MiB).
        assert!(
            mgr.total_bytes() < 4096,
            "charged {} bytes",
            mgr.total_bytes()
        );
    }

    #[test]
    fn budget_accounting_returns_to_zero() {
        let cfg = RecoveryConfig {
            history_ttl_secs: 0,
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(cfg);
        for i in 0..200 {
            mgr.push(&format!("topic-{}", i % 7), make_data("payload"));
            mgr.push_foreign(&format!("f-{}", i % 5), make_data("payload"), 9, i);
        }
        assert!(mgr.total_bytes() > 0);
        std::thread::sleep(Duration::from_millis(5));
        mgr.cleanup();
        assert_eq!(mgr.topic_count(), 0);
        assert_eq!(mgr.foreign_buffer_count(), 0);
        assert_eq!(mgr.total_bytes(), 0);
    }

    #[test]
    fn ttl_longer_than_uptime_does_not_panic() {
        let cfg = RecoveryConfig {
            history_ttl_secs: u64::MAX / 4,
            ..RecoveryConfig::default()
        };
        let mgr = RecoveryManager::new(cfg);
        mgr.push("t", make_data("x"));
        mgr.cleanup();
        assert_eq!(mgr.topic_count(), 1);
    }

    mod properties {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(1000))]

            /// Whatever the history and the client's position, recovery returns
            /// exactly the missing suffix in order, or says it cannot.
            #[test]
            fn recovery_returns_exactly_the_missing_suffix(
                bits in 1u32..6,
                pushed in 0usize..200,
                after in 0u64..210,
                max_messages in 1usize..300,
            ) {
                let cfg = RecoveryConfig {
                    buffer_size_bits: bits,
                    max_recovery_messages: max_messages,
                    ..RecoveryConfig::default()
                };
                let mgr = RecoveryManager::new(cfg);
                for i in 0..pushed {
                    mgr.push("t", make_data(&format!("m{i}")));
                }
                let Some((epoch, head)) = mgr.get_position("t") else {
                    prop_assert_eq!(pushed, 0);
                    return Ok(());
                };
                prop_assert_eq!(head, pushed as u64);
                let capacity = 1u64 << bits;
                let tail = head.saturating_sub(capacity);
                match mgr.recover("t", epoch, after) {
                    RecoveryResult::Recovered { publications, offset, .. } => {
                        let start = after + 1;
                        prop_assert!(start >= tail);
                        prop_assert_eq!(offset, head - 1);
                        let expected: Vec<String> =
                            (start..head).map(|o| format!("m{o}")).collect();
                        let got: Vec<String> = publications
                            .iter()
                            .map(|b| String::from_utf8(b.to_vec()).unwrap())
                            .collect();
                        prop_assert_eq!(got, expected);
                    }
                    RecoveryResult::NotRecovered { .. } => {
                        let missing = head.saturating_sub(after + 1);
                        prop_assert!(after + 1 < tail || missing > max_messages as u64);
                    }
                    RecoveryResult::NoHistory => prop_assert!(false, "history exists"),
                }
            }
        }
    }
}