otel-arrow-dfe-engine 0.61.0

Async pipeline engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

//! Integration tests covering all subscription modes, ack/nack, backpressure,
//! multi-threaded correctness, topic lifecycle, and TopicSet.
//!
//! Tests are grouped by section headers. The test names follow the pattern
//! `<feature>_<scenario>` and are designed to be self-documenting.
//!
//! # Key Properties Verified
//!
//! - **Balanced**: exactly-once delivery within a group, per-subscriber ordering,
//!   no cross-group interference, backpressure blocking.
//! - **Broadcast**: all-receive, in-order delivery, lag reporting for slow
//!   subscribers, slow subscribers don't block fast ones.
//! - **Mode enforcement**: `BalancedOnly` rejects broadcast (and vice versa),
//!   `BalancedOnly` enforces single consumer group.
//! - **Ack/nack**: tracked publish outcomes, per-publisher independence,
//!   bounded in-flight tracking, disabled-when-not-tracked.
//! - **Lifecycle**: `remove_topic` closes the topic (publish fails, recv gets
//!   Closed), removed topics can be recreated independently, `close_all` shuts
//!   everything down.
//! - **TopicSet**: insert/get/remove semantics, overwrite returns previous,
//!   remove-does-not-close, clone-shares-state.

use crate::error::Error;
use crate::topic::backend::{InMemoryBackend, SubscriptionBackend};
use crate::topic::subscription::{DeliveryBackend, DeliveryStorageKind};
use crate::topic::topic::{BroadcastReadResult, FastBroadcastRing};
use crate::topic::types::{
    AckFromResult, BroadcastSubscriberId, Envelope, NackFromResult, PublishOutcome, RecvItem,
    SubscriberOptions, SubscriptionMode, TopicOptions, TopicPublishOutcomeConfig,
    TrackedPublishOutcome, TrackedPublishPermit, TrackedPublishTracker, TrackedTryPublishOutcome,
};
use crate::topic::{Delivery, RecvDelivery, Subscription, TopicBroker, TopicSet};
use otel_arrow_dfe_config::topic::{TopicBroadcastAckMode, TopicBroadcastOnLagPolicy};
use otel_arrow_dfe_config::{SubscriptionGroupName, TopicName};
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::sync::Semaphore;

// =========================================================================
// Balanced mode - single group
// =========================================================================

// Two subscribers in the same consumer group receive all 100 messages between
// them with no duplicates and no losses.
#[tokio::test]
async fn balanced_single_group_all_messages_delivered_exactly_once() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic("test", TopicOptions::default())
        .unwrap();

    let mut sub1 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut sub2 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let n = 100u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut received = HashSet::new();
    let mut order1 = Vec::new();
    let mut order2 = Vec::new();

    loop {
        tokio::select! {
            r = sub1.recv() => {
                match r {
                    Ok(RecvItem::Message(env)) => {
                        assert!(received.insert(env.id), "duplicate id={}", env.id);
                        order1.push(*env.payload);
                    }
                    Err(_) => break,
                    _ => {}
                }
            }
            r = sub2.recv() => {
                match r {
                    Ok(RecvItem::Message(env)) => {
                        assert!(received.insert(env.id), "duplicate id={}", env.id);
                        order2.push(*env.payload);
                    }
                    Err(_) => break,
                    _ => {}
                }
            }
        }
    }

    // Drain remaining from both.
    while let Ok(RecvItem::Message(env)) = sub1.recv().await {
        assert!(received.insert(env.id), "duplicate id={}", env.id);
        order1.push(*env.payload);
    }
    while let Ok(RecvItem::Message(env)) = sub2.recv().await {
        assert!(received.insert(env.id), "duplicate id={}", env.id);
        order2.push(*env.payload);
    }

    // All messages delivered.
    let all_payloads: HashSet<u64> = order1.iter().chain(order2.iter()).copied().collect();
    assert_eq!(all_payloads.len(), n as usize);
    for i in 0..n {
        assert!(all_payloads.contains(&i), "missing payload {i}");
    }
}

// Each subscriber within a consumer group receives its subset of messages in
// strictly increasing ID order.
#[tokio::test]
async fn balanced_single_group_preserves_order_per_subscriber() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic("test-order", TopicOptions::default())
        .unwrap();

    let mut sub1 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut sub2 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let n = 200u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut ids1 = Vec::new();
    let mut ids2 = Vec::new();

    while let Ok(RecvItem::Message(env)) = sub1.recv().await {
        ids1.push(env.id);
    }
    while let Ok(RecvItem::Message(env)) = sub2.recv().await {
        ids2.push(env.id);
    }

    // Each subscriber's stream must be in strictly increasing id order.
    for w in ids1.windows(2) {
        assert!(w[0] < w[1], "out of order in sub1: {} >= {}", w[0], w[1]);
    }
    for w in ids2.windows(2) {
        assert!(w[0] < w[1], "out of order in sub2: {} >= {}", w[0], w[1]);
    }
}

// Four subscribers in one group collectively receive all 500 messages with no
// duplicate IDs.
#[tokio::test]
async fn balanced_no_duplicates_within_group() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic("dup-test", TopicOptions::default())
        .unwrap();

    let num_subs = 4;
    let mut subs: Vec<_> = (0..num_subs)
        .map(|_| {
            topic
                .subscribe(
                    SubscriptionMode::Balanced {
                        group: SubscriptionGroupName::from("g1"),
                    },
                    SubscriberOptions::default(),
                )
                .unwrap()
        })
        .collect();

    let n = 500u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut all_ids = HashSet::new();
    for sub in subs.iter_mut() {
        while let Ok(RecvItem::Message(env)) = sub.recv().await {
            assert!(all_ids.insert(env.id), "duplicate id={}", env.id);
        }
    }
    assert_eq!(all_ids.len(), n as usize);
}

// =========================================================================
// Balanced mode - multiple groups
// =========================================================================

// Two consumer groups on the same topic each receive all messages independently,
// within each group delivery is split across subscribers with ordering preserved.
#[tokio::test]
async fn balanced_multiple_groups_independent() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic("multi-group", TopicOptions::default())
        .unwrap();

    let mut sub_g1_a = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("group-A"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut sub_g1_b = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("group-A"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut sub_g2 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("group-B"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let n = 100u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    // Group A: messages split between sub_g1_a and sub_g1_b.
    let mut ga_ids = HashSet::new();
    let mut ga_a_ids = Vec::new();
    let mut ga_b_ids = Vec::new();
    while let Ok(RecvItem::Message(env)) = sub_g1_a.recv().await {
        ga_a_ids.push(env.id);
        _ = ga_ids.insert(env.id);
    }
    while let Ok(RecvItem::Message(env)) = sub_g1_b.recv().await {
        ga_b_ids.push(env.id);
        assert!(ga_ids.insert(env.id), "duplicate in group-A");
    }
    assert_eq!(ga_ids.len(), n as usize);

    // Group B: sub_g2 gets all messages.
    let mut gb_ids = HashSet::new();
    let mut gb_order = Vec::new();
    while let Ok(RecvItem::Message(env)) = sub_g2.recv().await {
        _ = gb_ids.insert(env.id);
        gb_order.push(env.id);
    }
    assert_eq!(gb_ids.len(), n as usize);

    // Group B ordering preserved.
    for w in gb_order.windows(2) {
        assert!(w[0] < w[1]);
    }

    // Both groups ordered independently.
    for w in ga_a_ids.windows(2) {
        assert!(w[0] < w[1]);
    }
    for w in ga_b_ids.windows(2) {
        assert!(w[0] < w[1]);
    }
}

// =========================================================================
// Broadcast mode
// =========================================================================

// Three broadcast subscribers each receive all 100 messages in the exact
// published order.
#[tokio::test]
async fn broadcast_all_subscribers_see_all_messages_in_order() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic(
            "broadcast-test",
            TopicOptions::Mixed {
                balanced_capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
                broadcast_capacity: 1024,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
        )
        .unwrap();

    let mut sub1 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub2 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub3 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let n = 100u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    for sub in [&mut sub1, &mut sub2, &mut sub3] {
        let mut received = Vec::new();
        while let Ok(RecvItem::Message(env)) = sub.recv().await {
            received.push(*env.payload);
        }
        assert_eq!(received.len(), n as usize);
        for (i, &val) in received.iter().enumerate() {
            assert_eq!(val, i as u64);
        }
    }
}

// A slow broadcast subscriber with a small ring buffer (8 slots) receives a
// Lagged notification when the publisher overwrites unread slots.
#[tokio::test]
async fn broadcast_lag_reported_on_slow_subscriber() {
    let broker = TopicBroker::new();
    // Small broadcast buffer to force lag.
    let topic = broker
        .create_in_memory_topic(
            "broadcast-lag",
            TopicOptions::Mixed {
                balanced_capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
                broadcast_capacity: 8,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
        )
        .unwrap();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    // Publish more messages than the buffer can hold without consuming.
    let n = 50u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut messages = Vec::new();
    let mut total_lagged = 0u64;
    loop {
        match sub.recv().await {
            Ok(RecvItem::Message(env)) => messages.push(*env.payload),
            Ok(RecvItem::Lagged { missed }) => total_lagged += missed,
            Err(_) => break,
        }
    }

    // We should have fewer messages than n because some were dropped.
    assert!(
        messages.len() < n as usize,
        "expected lag but got all {} messages",
        n
    );
    assert!(total_lagged > 0, "expected lag notification");

    // The messages we did receive should be in order.
    for w in messages.windows(2) {
        assert!(w[0] < w[1], "out of order: {} >= {}", w[0], w[1]);
    }
}

// A slow subscriber that never reads does not block the publisher or prevent a
// fast subscriber from receiving every message in real time.
#[tokio::test]
async fn broadcast_slow_subscriber_does_not_block_fast_subscriber() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic(
            "broadcast-no-block",
            TopicOptions::Mixed {
                balanced_capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
                broadcast_capacity: 4,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
        )
        .unwrap();

    let _slow_sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut fast_sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    // Publish enough to overflow slow_sub buffer, but fast_sub consumes immediately.
    for i in 0..20u64 {
        topic.publish(Arc::new(i)).await.unwrap();
        // Fast subscriber consumes each message right away.
        match fast_sub.recv().await {
            Ok(RecvItem::Message(env)) => assert_eq!(*env.payload, i),
            other => panic!("unexpected: {:?}", other),
        }
    }
    // If slow_sub blocked the publisher, we'd never get here.
}

// A lagging broadcast subscriber configured with disconnect receives one final
// lag notification and is then closed on the next recv call.
#[tokio::test]
async fn broadcast_disconnects_slow_subscriber_on_lag() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "broadcast-disconnect",
            TopicOptions::BroadcastOnly {
                capacity: 8,
                on_lag: TopicBroadcastOnLagPolicy::Disconnect,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    for i in 0..50u64 {
        topic.publish(Arc::new(i)).await.unwrap();
    }

    match sub.recv().await {
        Ok(RecvItem::Lagged { missed }) => assert!(missed > 0, "expected missed count > 0"),
        other => panic!("expected lag notification before disconnect, got {other:?}"),
    }
    assert!(matches!(sub.recv().await, Err(Error::SubscriptionClosed)));
}

// In Mixed mode, async publish now waits for full topic admission. Balanced
// backpressure therefore delays both publish completion and broadcast
// visibility, while `try_publish` remains the non-blocking API.
#[tokio::test]
async fn mixed_async_publish_waits_for_balanced_admission_before_broadcast() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "mixed-bcast-priority",
            TopicOptions::Mixed {
                balanced_capacity: 1,
                broadcast_capacity: 16,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut balanced = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut broadcast = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    // Fill the balanced queue.
    topic.publish(Arc::new(1u64)).await.unwrap();

    // Second publish should block on balanced delivery, so broadcast should
    // not observe it until balanced admission succeeds.
    let topic_clone = topic.clone();
    let second_publish = tokio::spawn(async move {
        topic_clone.publish(Arc::new(2u64)).await.unwrap();
    });

    // First message.
    match broadcast.recv().await {
        Ok(RecvItem::Message(env)) => assert_eq!(*env.payload, 1),
        other => panic!("unexpected: {:?}", other),
    }

    // Second message should not arrive before balanced queue is drained.
    assert!(
        tokio::time::timeout(Duration::from_millis(200), async {
            loop {
                match broadcast.recv().await {
                    Ok(RecvItem::Message(env)) => break *env.payload,
                    Ok(RecvItem::Lagged { .. }) => continue,
                    Err(e) => panic!("unexpected recv error: {e:?}"),
                }
            }
        })
        .await
        .is_err(),
        "broadcast delivery should wait for balanced admission on async publish"
    );

    // Publisher task should still be blocked on balanced queue.
    assert!(
        !second_publish.is_finished(),
        "second publish should still be blocked by balanced backpressure"
    );

    // Drain balanced queue to unblock publisher and then observe the second
    // broadcast message.
    _ = balanced.recv().await.unwrap();
    second_publish.await.unwrap();

    let second = tokio::time::timeout(Duration::from_millis(200), async {
        loop {
            match broadcast.recv().await {
                Ok(RecvItem::Message(env)) => break *env.payload,
                Ok(RecvItem::Lagged { .. }) => continue,
                Err(e) => panic!("unexpected recv error: {e:?}"),
            }
        }
    })
    .await
    .expect("broadcast delivery should resume after balanced admission succeeds");
    assert_eq!(second, 2);

    _ = balanced.recv().await.unwrap();
    topic.close();
}

// A blocked mixed publish must not reserve capacity on balanced groups that
// were otherwise ready to admit the message.
#[tokio::test]
async fn mixed_async_publish_does_not_reserve_free_groups_while_waiting() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "mixed-no-convoy",
            TopicOptions::Mixed {
                balanced_capacity: 1,
                broadcast_capacity: 16,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut fast = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("fast"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut slow = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("slow"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    topic.publish(Arc::new(1u64)).await.unwrap();

    match fast.recv().await.unwrap() {
        RecvItem::Message(env) => assert_eq!(*env.payload, 1),
        other => panic!("unexpected first fast item: {other:?}"),
    }

    let topic_clone = topic.clone();
    let blocked_publish = tokio::spawn(async move {
        topic_clone.publish(Arc::new(2u64)).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(
        !blocked_publish.is_finished(),
        "publish should still be blocked by the slow group"
    );

    let mut permits = topic.debug_balanced_available_permits();
    permits.sort_by(|(left, _), (right, _)| left.as_ref().cmp(right.as_ref()));
    assert_eq!(
        permits,
        vec![
            (SubscriptionGroupName::from("fast"), 1),
            (SubscriptionGroupName::from("slow"), 0),
        ],
        "blocked mixed publish should not hold the fast group's permit"
    );

    match slow.recv().await.unwrap() {
        RecvItem::Message(env) => assert_eq!(*env.payload, 1),
        other => panic!("unexpected first slow item: {other:?}"),
    }

    blocked_publish.await.unwrap();

    match fast.recv().await.unwrap() {
        RecvItem::Message(env) => assert_eq!(*env.payload, 2),
        other => panic!("unexpected second fast item: {other:?}"),
    }
    match slow.recv().await.unwrap() {
        RecvItem::Message(env) => assert_eq!(*env.payload, 2),
        other => panic!("unexpected second slow item: {other:?}"),
    }

    topic.close();
}

// Dropping a blocked async mixed-topic publish must not partially publish to
// broadcast subscribers before balanced admission succeeds.
#[tokio::test]
async fn mixed_async_publish_drop_does_not_publish_to_broadcast() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "mixed-cancel-no-broadcast",
            TopicOptions::Mixed {
                balanced_capacity: 1,
                broadcast_capacity: 16,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut balanced = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut broadcast = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    topic.publish(Arc::new(1u64)).await.unwrap();

    let mut publish = Box::pin(topic.publish(Arc::new(2u64)));
    assert!(
        tokio::time::timeout(Duration::from_millis(200), publish.as_mut())
            .await
            .is_err(),
        "second publish should block while balanced capacity is full"
    );

    match broadcast.recv().await.unwrap() {
        RecvItem::Message(env) => assert_eq!(*env.payload, 1),
        other => panic!("unexpected first broadcast item: {other:?}"),
    }
    drop(publish);

    assert!(
        tokio::time::timeout(Duration::from_millis(200), async {
            loop {
                match broadcast.recv().await {
                    Ok(RecvItem::Message(env)) => break *env.payload,
                    Ok(RecvItem::Lagged { .. }) => continue,
                    Err(e) => panic!("unexpected recv error: {e:?}"),
                }
            }
        })
        .await
        .is_err(),
        "dropping a blocked publish must not leak a broadcast delivery"
    );

    match balanced.recv().await.unwrap() {
        RecvItem::Message(env) => assert_eq!(*env.payload, 1),
        other => panic!("unexpected balanced item: {other:?}"),
    }
}

// Dropping a blocked tracked publish must release the publisher's in-flight
// slot so later non-blocking attempts fail only on topic capacity, not leaked
// tracked publisher capacity.
#[tokio::test]
async fn blocked_tracked_publish_drop_releases_in_flight_capacity() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "tracked-publish-drop",
            TopicOptions::BalancedOnly { capacity: 1 },
            InMemoryBackend,
        )
        .unwrap();

    let _balanced = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    topic.publish(Arc::new(1u64)).await.unwrap();

    let tracked = topic.tracked_publisher_with_config(TopicPublishOutcomeConfig {
        max_in_flight: 1,
        timeout: Duration::from_secs(30),
    });
    let mut blocked = Box::pin(tracked.publish(Arc::new(2u64)));
    assert!(
        tokio::time::timeout(Duration::from_millis(200), blocked.as_mut())
            .await
            .is_err(),
        "tracked publish should block while balanced capacity is full"
    );
    drop(blocked);

    assert!(
        matches!(
            tracked.try_publish(Arc::new(3u64)).unwrap(),
            TrackedTryPublishOutcome::DroppedOnFull
        ),
        "dropping the blocked tracked publish should release the in-flight slot"
    );
}

// Broadcast delivery permits keep ownership of one message until the caller
// commits it, preventing the subscription from advancing past the permitted item.
#[tokio::test]
async fn broadcast_delivery_commit_advances_to_next_message() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "broadcast-delivery-permit",
            TopicOptions::BroadcastOnly {
                capacity: 16,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    topic.publish(Arc::new(1u64)).await.unwrap();
    topic.publish(Arc::new(2u64)).await.unwrap();

    let first = match sub.recv_delivery().await.unwrap() {
        RecvDelivery::Message(delivery) => delivery,
        RecvDelivery::Lagged { .. } => panic!("unexpected lag notification"),
    };
    assert_eq!(first.message_id(), 1);
    assert_eq!(*first.envelope().payload, 1);

    assert!(
        tokio::time::timeout(Duration::from_millis(200), sub.recv_delivery())
            .await
            .is_err(),
        "second delivery should stay blocked while the first delivery permit is held"
    );

    first.commit();

    let second = match sub.recv_delivery().await.unwrap() {
        RecvDelivery::Message(delivery) => delivery,
        RecvDelivery::Lagged { .. } => panic!("unexpected lag notification"),
    };
    assert_eq!(second.message_id(), 2);
    assert_eq!(*second.envelope().payload, 2);
    second.commit();
}

// Balanced deliveries from the in-memory backend use the specialized inline
// finalizer path instead of the opaque fallback.
#[tokio::test]
async fn balanced_delivery_uses_specialized_inline_storage() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "balanced-inline-delivery",
            TopicOptions::default(),
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    topic.publish(Arc::new(7u64)).await.unwrap();

    let delivery = match sub.recv_delivery().await.unwrap() {
        RecvDelivery::Message(delivery) => delivery,
        RecvDelivery::Lagged { .. } => panic!("unexpected lag notification"),
    };
    assert_eq!(delivery.storage_kind(), DeliveryStorageKind::Balanced);
    delivery.commit();
}

// Broadcast deliveries from the in-memory backend use the specialized inline
// finalizer path instead of the opaque fallback.
#[tokio::test]
async fn broadcast_delivery_uses_specialized_inline_storage() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "broadcast-inline-delivery",
            TopicOptions::BroadcastOnly {
                capacity: 16,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    topic.publish(Arc::new(11u64)).await.unwrap();

    let delivery = match sub.recv_delivery().await.unwrap() {
        RecvDelivery::Message(delivery) => delivery,
        RecvDelivery::Lagged { .. } => panic!("unexpected lag notification"),
    };
    assert_eq!(delivery.storage_kind(), DeliveryStorageKind::Broadcast);
    delivery.commit();
}

// Custom backends still work through the opaque delivery fallback even though
// the in-memory backend now uses specialized inline storage.
#[tokio::test]
async fn opaque_delivery_fallback_still_works() {
    struct OpaqueDelivery {
        envelope: Envelope<u64>,
        aborted: Arc<AtomicBool>,
    }

    impl DeliveryBackend<u64> for OpaqueDelivery {
        fn envelope(&self) -> &Envelope<u64> {
            &self.envelope
        }

        fn commit(&mut self) {}

        fn abort(&mut self, _reason: Arc<str>) -> Result<(), Error> {
            self.aborted.store(true, Ordering::SeqCst);
            Ok(())
        }

        fn abandon(&mut self) {}
    }

    struct OpaqueSubscription {
        yielded: bool,
        aborted: Arc<AtomicBool>,
    }

    impl SubscriptionBackend<u64> for OpaqueSubscription {
        fn poll_recv_delivery(
            &mut self,
            _cx: &mut Context<'_>,
        ) -> Poll<Result<RecvDelivery<u64>, Error>> {
            if self.yielded {
                Poll::Ready(Err(Error::SubscriptionClosed))
            } else {
                self.yielded = true;
                Poll::Ready(Ok(RecvDelivery::Message(Delivery::new_opaque(Box::new(
                    OpaqueDelivery {
                        envelope: Envelope {
                            id: 41,
                            payload: Arc::new(99u64),
                            tracked: false,
                        },
                        aborted: Arc::clone(&self.aborted),
                    },
                )))))
            }
        }

        fn ack(&self, _id: u64) -> Result<(), Error> {
            Ok(())
        }

        fn nack(&self, _id: u64, _reason: Arc<str>) -> Result<(), Error> {
            Ok(())
        }
    }

    let aborted = Arc::new(AtomicBool::new(false));
    let mut subscription = Subscription::new(Box::new(OpaqueSubscription {
        yielded: false,
        aborted: Arc::clone(&aborted),
    }));

    let delivery = match subscription.recv_delivery().await.unwrap() {
        RecvDelivery::Message(delivery) => delivery,
        RecvDelivery::Lagged { .. } => panic!("unexpected lag notification"),
    };
    assert_eq!(delivery.storage_kind(), DeliveryStorageKind::Opaque);
    delivery.abort("opaque fallback abort").unwrap();
    assert!(aborted.load(Ordering::SeqCst));
}

// Aborting an unforwarded tracked delivery must resolve its tracked publish as
// a Nack owned by the delivery object itself.
#[tokio::test]
async fn tracked_delivery_abort_resolves_publish_outcome() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "tracked-delivery-abort",
            TopicOptions::default(),
            InMemoryBackend,
        )
        .unwrap();

    let tracked = topic.tracked_publisher();
    let mut sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let receipt = tracked.publish(Arc::new(42u64)).await.unwrap();
    let delivery = match sub.recv_delivery().await.unwrap() {
        RecvDelivery::Message(delivery) => delivery,
        RecvDelivery::Lagged { .. } => panic!("unexpected lag notification"),
    };

    delivery
        .abort("downstream rejected before forward")
        .unwrap();
    assert_eq!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack {
            reason: Arc::from("downstream rejected before forward"),
        }
    );
}

// In Mixed mode, a lagging broadcast subscriber can be disconnected without
// affecting fast broadcast subscribers or balanced delivery.
#[tokio::test]
async fn mixed_disconnects_only_lagging_broadcast_subscriber() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_in_memory_topic(
            "mixed-broadcast-disconnect",
            TopicOptions::Mixed {
                balanced_capacity: 32,
                broadcast_capacity: 4,
                on_lag: TopicBroadcastOnLagPolicy::Disconnect,
                ack_mode: TopicBroadcastAckMode::First,
            },
        )
        .unwrap();

    let mut balanced = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("workers"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut slow_broadcast = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut fast_broadcast = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    for i in 0..20u64 {
        topic.publish(Arc::new(i)).await.unwrap();
        match fast_broadcast.recv().await {
            Ok(RecvItem::Message(env)) => assert_eq!(*env.payload, i),
            other => panic!("fast broadcast subscriber should stay current: {other:?}"),
        }
    }

    match slow_broadcast.recv().await {
        Ok(RecvItem::Lagged { missed }) => assert!(missed > 0, "expected lagged slow subscriber"),
        other => panic!("expected lag notification for slow broadcast subscriber, got {other:?}"),
    }
    assert!(matches!(
        slow_broadcast.recv().await,
        Err(Error::SubscriptionClosed)
    ));

    match balanced.recv().await {
        Ok(RecvItem::Message(env)) => assert_eq!(*env.payload, 0),
        other => panic!("balanced subscriber should still receive messages: {other:?}"),
    }
}

// =========================================================================
// Subscriber choice - publisher API identical
// =========================================================================

// A single publish call delivers the message to both a balanced and a broadcast
// subscriber, proving the publisher API is mode-agnostic.
#[tokio::test]
async fn publisher_api_identical_for_all_subscriber_modes() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic("choice-test", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    // Mix of balanced and broadcast subscribers.
    let mut balanced = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut broadcast = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    // Publisher doesn't know or care about subscriber modes.
    topic.publish(Arc::new("hello".to_string())).await.unwrap();
    topic.close();

    // Both receive the message.
    match balanced.recv().await {
        Ok(RecvItem::Message(env)) => assert_eq!(*env.payload, "hello"),
        other => panic!("unexpected: {:?}", other),
    }
    match broadcast.recv().await {
        Ok(RecvItem::Message(env)) => assert_eq!(*env.payload, "hello"),
        other => panic!("unexpected: {:?}", other),
    }
}

// =========================================================================
// Ack/Nack
// =========================================================================

// Tracked publishes resolve to the ack/nack reported by downstream subscribers.
#[tokio::test]
async fn tracked_publish_outcomes_received_when_enabled() {
    let broker = TopicBroker::new();
    let base = broker
        .create_topic("ack-test", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let topic = base.tracked_publisher();

    let mut sub = base
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let receipt1 = topic.publish(Arc::new(42u64)).await.unwrap();
    let receipt2 = topic.publish(Arc::new(43u64)).await.unwrap();

    let env1 = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };
    let env2 = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };

    sub.ack(env1.id).unwrap();
    sub.nack(env2.id, "bad data").unwrap();

    assert_eq!(
        receipt1.wait_for_outcome().await,
        TrackedPublishOutcome::Ack
    );
    assert_eq!(
        receipt2.wait_for_outcome().await,
        TrackedPublishOutcome::Nack {
            reason: Arc::from("bad data"),
        }
    );
}

// Publishing without the tracked publisher means ack/nack returns MessageNotTracked.
#[tokio::test]
async fn ack_nack_fail_when_message_is_not_tracked() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic("no-ack", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let mut sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    topic.publish(Arc::new(1)).await.unwrap();

    let env = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };

    match sub.ack(env.id) {
        Err(Error::MessageNotTracked) => {}
        other => panic!("expected MessageNotTracked, got {:?}", other),
    }
}

// Tracked publishers expose a bounded in-flight limit on try_publish.
#[tokio::test]
async fn tracked_try_publish_respects_max_in_flight() {
    let broker = TopicBroker::new();
    let base = broker
        .create_topic("ack-full", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let topic = base.tracked_publisher_with_config(TopicPublishOutcomeConfig {
        max_in_flight: 1,
        timeout: Duration::from_secs(30),
    });

    let mut sub = base
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let receipt = topic.publish(Arc::new(1u64)).await.unwrap();
    assert!(matches!(
        topic.try_publish(Arc::new(2u64)).unwrap(),
        TrackedTryPublishOutcome::MaxInFlightReached
    ));

    let env = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };
    sub.ack(env.id).unwrap();

    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

// =========================================================================
// Backpressure
// =========================================================================

// A balanced topic with capacity=2 blocks the third publish until the
// subscriber drains a message, verifying backpressure.
#[tokio::test]
async fn balanced_backpressure_blocks_publisher() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "backpressure",
            TopicOptions::Mixed {
                balanced_capacity: 2,
                broadcast_capacity: TopicOptions::DEFAULT_BROADCAST_CAPACITY,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    // Fill the buffer.
    topic.publish(Arc::new(1)).await.unwrap();
    topic.publish(Arc::new(2)).await.unwrap();

    // Next publish should block because buffer is full.
    let topic_clone = topic.clone();
    let handle = tokio::spawn(async move {
        topic_clone.publish(Arc::new(3)).await.unwrap();
    });

    // Give the publisher task a moment to block.
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(!handle.is_finished(), "publish should be blocked");

    // Consume one message to unblock.
    let _ = sub.recv().await.unwrap();

    // Now the publisher should complete.
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(handle.is_finished(), "publish should have completed");
}

// =========================================================================
// Multi-threaded correctness
// =========================================================================

// Four concurrent publisher tasks send 250 messages each; two subscribers in
// the same group collect all 1000 with no duplicates across real OS threads.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn balanced_multi_threaded_no_duplicates() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic("mt-balanced", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let num_publishers = 4;
    let msgs_per_publisher = 250;
    let total = num_publishers * msgs_per_publisher;

    // Create subscribers BEFORE publishers so the consumer group exists.
    let mut sub1 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut sub2 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    // Spawn publishers on different tasks (potentially different threads).
    let mut pub_handles = Vec::new();
    for p in 0..num_publishers {
        let t = topic.clone();
        pub_handles.push(tokio::spawn(async move {
            for i in 0..msgs_per_publisher {
                let val = (p * msgs_per_publisher + i) as u64;
                t.publish(Arc::new(val)).await.unwrap();
            }
        }));
    }

    // Wait for publishers.
    for h in pub_handles {
        h.await.unwrap();
    }
    topic.close();

    let mut all_ids = HashSet::new();
    while let Ok(RecvItem::Message(env)) = sub1.recv().await {
        assert!(all_ids.insert(env.id));
    }
    while let Ok(RecvItem::Message(env)) = sub2.recv().await {
        assert!(all_ids.insert(env.id));
    }
    assert_eq!(all_ids.len(), total);
}

// A publisher task and two subscriber tasks run on separate OS threads; both
// subscribers receive all 500 messages in order with a large enough ring buffer.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn broadcast_multi_threaded_all_receive() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "mt-broadcast",
            TopicOptions::Mixed {
                balanced_capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
                broadcast_capacity: 2048,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let n = 500u64;

    let mut sub1 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub2 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let t = topic.clone();
    let pub_handle = tokio::spawn(async move {
        for i in 0..n {
            t.publish(Arc::new(i)).await.unwrap();
        }
        t.close();
    });

    let h1 = tokio::spawn(async move {
        let mut received = Vec::new();
        loop {
            match sub1.recv().await {
                Ok(RecvItem::Message(env)) => received.push(*env.payload),
                Ok(RecvItem::Lagged { .. }) => {}
                Err(_) => break,
            }
        }
        received
    });

    let h2 = tokio::spawn(async move {
        let mut received = Vec::new();
        loop {
            match sub2.recv().await {
                Ok(RecvItem::Message(env)) => received.push(*env.payload),
                Ok(RecvItem::Lagged { .. }) => {}
                Err(_) => break,
            }
        }
        received
    });

    pub_handle.await.unwrap();
    let r1 = h1.await.unwrap();
    let r2 = h2.await.unwrap();

    // Both should receive all messages (buffer large enough).
    assert_eq!(r1.len(), n as usize);
    assert_eq!(r2.len(), n as usize);

    // In order.
    for w in r1.windows(2) {
        assert!(w[0] < w[1]);
    }
    for w in r2.windows(2) {
        assert!(w[0] < w[1]);
    }
}

// =========================================================================
// Edge: no subscribers
// =========================================================================

// Publishing to a topic with zero subscribers succeeds silently (messages are
// dropped rather than causing an error).
#[tokio::test]
async fn publish_with_no_subscribers_succeeds() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic("empty", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    // Publishing to a topic with no subscribers should succeed (messages are dropped).
    topic.publish(Arc::new(42)).await.unwrap();
}

// =========================================================================
// Edge: subscriber receives only after subscribe
// =========================================================================

// Messages published before a subscriber joins are not delivered; only messages
// published after subscribe are received.
#[tokio::test]
async fn subscriber_only_receives_messages_after_subscribe() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic("late-sub", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    // Publish before subscribing.
    topic.publish(Arc::new(1)).await.unwrap();
    topic.publish(Arc::new(2)).await.unwrap();

    let mut sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    // Publish after subscribing.
    topic.publish(Arc::new(3)).await.unwrap();
    topic.close();

    let mut received = Vec::new();
    while let Ok(RecvItem::Message(env)) = sub.recv().await {
        received.push(*env.payload);
    }
    // Should only have message 3 (published after subscribe).
    assert_eq!(received, vec![3]);
}

// =========================================================================
// BalancedOnly mode
// =========================================================================

// A BalancedOnly topic delivers 50 messages in order to a single subscriber.
#[tokio::test]
async fn balanced_only_basic_delivery() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bo-basic",
            TopicOptions::BalancedOnly {
                capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let n = 50u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut received = Vec::new();
    while let Ok(RecvItem::Message(env)) = sub.recv().await {
        received.push(*env.payload);
    }
    assert_eq!(received.len(), n as usize);
    for (i, &val) in received.iter().enumerate() {
        assert_eq!(val, i as u64);
    }
}

// A BalancedOnly topic returns BroadcastNotSupported when a broadcast
// subscription is attempted.
#[tokio::test]
async fn balanced_only_rejects_broadcast() {
    let broker: TopicBroker<u64> = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bo-no-bcast",
            TopicOptions::BalancedOnly {
                capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
            },
            InMemoryBackend,
        )
        .unwrap();

    match topic.subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default()) {
        Err(Error::SubscribeBroadcastNotSupported) => {}
        Ok(_) => panic!("expected BroadcastNotSupported, got Ok"),
        Err(e) => panic!("expected BroadcastNotSupported, got Err({e:?})"),
    }
}

// A BalancedOnly topic allows multiple subscribers in the same group but
// returns SingleGroupViolation for a second group name.
#[tokio::test]
async fn balanced_only_rejects_second_group() {
    let broker: TopicBroker<u64> = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bo-single-group",
            TopicOptions::BalancedOnly {
                capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
            },
            InMemoryBackend,
        )
        .unwrap();

    // First group succeeds.
    let _sub1 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    // Same group succeeds (adds another subscriber).
    let _sub2 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    // Different group fails.
    match topic.subscribe(
        SubscriptionMode::Balanced {
            group: SubscriptionGroupName::from("g2"),
        },
        SubscriberOptions::default(),
    ) {
        Err(Error::SubscribeSingleGroupViolation) => {}
        Ok(_) => panic!("expected SingleGroupViolation, got Ok"),
        Err(e) => panic!("expected SingleGroupViolation, got Err({e:?})"),
    }
}

// A closed BalancedOnly topic rejects new balanced subscriptions.
#[tokio::test]
async fn balanced_only_rejects_balanced_subscribe_after_close() {
    let broker: TopicBroker<u64> = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bo-closed-subscribe",
            TopicOptions::BalancedOnly {
                capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
            },
            InMemoryBackend,
        )
        .unwrap();
    topic.close();

    match topic.subscribe(
        SubscriptionMode::Balanced {
            group: SubscriptionGroupName::from("g1"),
        },
        SubscriberOptions::default(),
    ) {
        Err(Error::TopicClosed) => {}
        Ok(_) => panic!("expected TopicClosed, got Ok"),
        Err(e) => panic!("expected TopicClosed, got Err({e:?})"),
    }
}

// A closed Mixed topic rejects new balanced subscriptions.
#[tokio::test]
async fn mixed_rejects_balanced_subscribe_after_close() {
    let broker: TopicBroker<u64> = TopicBroker::new();
    let topic = broker
        .create_topic(
            "mixed-closed-subscribe",
            TopicOptions::Mixed {
                balanced_capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
                broadcast_capacity: TopicOptions::DEFAULT_BROADCAST_CAPACITY,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();
    topic.close();

    match topic.subscribe(
        SubscriptionMode::Balanced {
            group: SubscriptionGroupName::from("g1"),
        },
        SubscriberOptions::default(),
    ) {
        Err(Error::TopicClosed) => {}
        Ok(_) => panic!("expected TopicClosed, got Ok"),
        Err(e) => panic!("expected TopicClosed, got Err({e:?})"),
    }
}

// Two subscribers in a BalancedOnly topic's single group collectively receive
// all 200 messages with no duplicates.
#[tokio::test]
async fn balanced_only_no_messages_lost() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bo-no-loss",
            TopicOptions::BalancedOnly {
                capacity: TopicOptions::DEFAULT_BALANCED_CAPACITY,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub1 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut sub2 = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let n = 200u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut all_ids = HashSet::new();
    while let Ok(RecvItem::Message(env)) = sub1.recv().await {
        assert!(all_ids.insert(env.id), "duplicate id={}", env.id);
    }
    while let Ok(RecvItem::Message(env)) = sub2.recv().await {
        assert!(all_ids.insert(env.id), "duplicate id={}", env.id);
    }
    assert_eq!(all_ids.len(), n as usize);
}

// =========================================================================
// BroadcastOnly mode
// =========================================================================

// A BroadcastOnly topic delivers all 50 messages in order to each of two
// subscribers.
#[tokio::test]
async fn broadcast_only_basic_delivery() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bro-basic",
            TopicOptions::BroadcastOnly {
                capacity: 1024,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub1 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub2 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let n = 50u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    for sub in [&mut sub1, &mut sub2] {
        let mut received = Vec::new();
        while let Ok(RecvItem::Message(env)) = sub.recv().await {
            received.push(*env.payload);
        }
        assert_eq!(received.len(), n as usize);
        for (i, &val) in received.iter().enumerate() {
            assert_eq!(val, i as u64);
        }
    }
}

// A BroadcastOnly topic returns BalancedNotSupported when a balanced
// subscription is attempted.
#[tokio::test]
async fn broadcast_only_rejects_balanced() {
    let broker: TopicBroker<u64> = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bro-no-balanced",
            TopicOptions::BroadcastOnly {
                capacity: TopicOptions::DEFAULT_BROADCAST_CAPACITY,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    match topic.subscribe(
        SubscriptionMode::Balanced {
            group: SubscriptionGroupName::from("g1"),
        },
        SubscriberOptions::default(),
    ) {
        Err(Error::SubscribeBalancedNotSupported) => {}
        Ok(_) => panic!("expected BalancedNotSupported, got Ok"),
        Err(e) => panic!("expected BalancedNotSupported, got Err({e:?})"),
    }
}

// A BroadcastOnly topic with a small ring buffer (8 slots) reports lag when
// the publisher overwrites unread slots.
#[tokio::test]
async fn broadcast_only_lag_reported() {
    let broker = TopicBroker::new();
    let topic = broker
        .create_topic(
            "bro-lag",
            TopicOptions::BroadcastOnly {
                capacity: 8,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let n = 50u64;
    for i in 0..n {
        topic.publish(Arc::new(i)).await.unwrap();
    }
    topic.close();

    let mut messages = Vec::new();
    let mut total_lagged = 0u64;
    loop {
        match sub.recv().await {
            Ok(RecvItem::Message(env)) => messages.push(*env.payload),
            Ok(RecvItem::Lagged { missed }) => total_lagged += missed,
            Err(_) => break,
        }
    }

    assert!(
        messages.len() < n as usize,
        "expected lag but got all {} messages",
        n
    );
    assert!(total_lagged > 0, "expected lag notification");

    for w in messages.windows(2) {
        assert!(w[0] < w[1], "out of order: {} >= {}", w[0], w[1]);
    }
}

// =========================================================================
// Per-publisher ack routing
// =========================================================================

// Two tracked publishers can publish independently and receive separate outcomes.
#[tokio::test]
async fn tracked_publishers_resolve_independently() {
    let broker = TopicBroker::new();
    let base = broker
        .create_topic("per-pub-ack", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let handle_a = base.tracked_publisher();
    let handle_b = base.tracked_publisher();

    let mut sub = base
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let receipt_a = handle_a.publish(Arc::new(100u64)).await.unwrap();
    let receipt_b = handle_b.publish(Arc::new(200u64)).await.unwrap();

    let env1 = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };
    let env2 = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };

    // Ack both.
    sub.ack(env1.id).unwrap();
    sub.ack(env2.id).unwrap();

    assert_eq!(
        receipt_a.wait_for_outcome().await,
        TrackedPublishOutcome::Ack
    );
    assert_eq!(
        receipt_b.wait_for_outcome().await,
        TrackedPublishOutcome::Ack
    );
}

// Broadcast subscribers can acknowledge tracked publishes too.
#[tokio::test]
async fn tracked_publish_broadcast_mode() {
    let broker = TopicBroker::new();
    let base = broker
        .create_topic(
            "per-pub-bcast",
            TopicOptions::BroadcastOnly {
                capacity: 1024,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let handle = base.tracked_publisher();

    let mut sub = base
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(42u64)).await.unwrap();

    let env = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };

    sub.ack(env.id).unwrap();

    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

// =========================================================================
// Broadcast `all` (consensus) ack mode - engine behavior
//
// These exercise the broadcast-only engine end to end by constructing
// `TopicOptions::BroadcastOnly { ack_mode: All, .. }` directly.
// =========================================================================

// Build an `all`-mode broadcast-only topic with the given ring capacity and
// on-lag policy.
fn all_mode_topic(
    broker: &TopicBroker<u64>,
    name: &'static str,
    capacity: usize,
    on_lag: TopicBroadcastOnLagPolicy,
) -> crate::topic::TopicHandle<u64> {
    broker
        .create_topic(
            name,
            TopicOptions::BroadcastOnly {
                capacity,
                on_lag,
                ack_mode: TopicBroadcastAckMode::All,
            },
            InMemoryBackend,
        )
        .unwrap()
}

fn recv_message_id(item: Result<RecvItem<u64>, Error>) -> u64 {
    match item.unwrap() {
        RecvItem::Message(env) => env.id,
        RecvItem::Lagged { missed } => panic!("unexpected lag of {missed} messages"),
    }
}

/// Scenario: Two eligible broadcast subscribers receive one `all`-mode tracked message.
/// Guarantees: The upstream receipt resolves only after both subscribers acknowledge it.
#[tokio::test]
async fn broadcast_all_mode_acks_only_after_all_subscribers_ack() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-ack",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub1 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub2 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    let id1 = recv_message_id(sub1.recv().await);
    let id2 = recv_message_id(sub2.recv().await);
    assert_eq!(id1, id2);

    let outcome = tokio::spawn(receipt.wait_for_outcome());

    // First subscriber acks: consensus is not yet complete.
    sub1.ack(id1).unwrap();
    tokio::task::yield_now().await;
    assert!(
        !outcome.is_finished(),
        "upstream resolved before all subscribers acked"
    );

    // Second subscriber acks: consensus completes as Ack.
    sub2.ack(id2).unwrap();
    assert_eq!(outcome.await.unwrap(), TrackedPublishOutcome::Ack);
}

/// Scenario: One required subscriber Acks and another Nacks an `all`-mode message.
/// Guarantees: Any required subscriber's Nack resolves the upstream receipt as Nack.
#[tokio::test]
async fn broadcast_all_mode_single_nack_resolves_nack() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-ack",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub1 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub2 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    let id1 = recv_message_id(sub1.recv().await);
    let id2 = recv_message_id(sub2.recv().await);

    sub1.ack(id1).unwrap();
    sub2.nack(id2, Arc::from("downstream rejected")).unwrap();

    match receipt.wait_for_outcome().await {
        TrackedPublishOutcome::Nack { reason } => assert_eq!(&*reason, "downstream rejected"),
        other => panic!("expected Nack, got {other:?}"),
    }
}

/// Scenario: A required subscriber lag-disconnects before acknowledging a tracked message.
/// Guarantees: The outstanding upstream receipt resolves as Nack.
#[tokio::test]
async fn broadcast_all_mode_lag_disconnect_before_ack_nacks() {
    let broker = TopicBroker::<u64>::new();
    // Tiny ring so untracked publishes overwrite the tracked message's slot.
    let topic = all_mode_topic(&broker, "all-lag", 4, TopicBroadcastOnLagPolicy::Disconnect);
    let handle = topic.tracked_publisher();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    // Tracked message that requires `sub`, which never reads it.
    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    // Overwhelm the capacity-4 ring so `sub` lags past the tracked message.
    for i in 0..8u64 {
        topic.publish(Arc::new(i)).await.unwrap();
    }

    // The first delivery `sub` observes is a lag notification, which triggers
    // the disconnect that nacks the outstanding tracked message.
    match sub.recv().await.unwrap() {
        RecvItem::Lagged { .. } => {}
        RecvItem::Message(env) => panic!("expected lag, got message {}", env.id),
    }

    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
}

/// Scenario: A required `DropOldest` subscriber lags past an `all`-mode tracked message.
/// Guarantees: The unread message resolves promptly as Nack instead of timing out.
#[tokio::test]
async fn broadcast_all_mode_lag_drop_oldest_before_ack_nacks() {
    let broker = TopicBroker::<u64>::new();
    // Tiny ring so untracked publishes overwrite the tracked message's slot.
    let topic = all_mode_topic(
        &broker,
        "all-lag-drop",
        4,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    // Tracked message that requires `sub`, which never reads it.
    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    // Overwhelm the capacity-4 ring so `sub` lags past the tracked message.
    for i in 0..8u64 {
        topic.publish(Arc::new(i)).await.unwrap();
    }

    // The first delivery `sub` observes is a lag notification. Under DropOldest
    // the subscriber stays connected, but the dropped tracked message it owed an
    // ack for must still be nacked.
    match sub.recv().await.unwrap() {
        RecvItem::Lagged { .. } => {}
        RecvItem::Message(env) => panic!("expected lag, got message {}", env.id),
    }

    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
}

/// Scenario: A required subscriber is dropped before acknowledging a tracked message.
/// Guarantees: Dropping the subscriber resolves its outstanding message as Nack.
#[tokio::test]
async fn broadcast_all_mode_drop_before_ack_nacks() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-drop",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();
    let _id = recv_message_id(sub.recv().await);

    // Drop the subscriber before acking: its outstanding message is nacked.
    drop(sub);

    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
}

/// Scenario: An `all`-mode tracked message is published with no eligible subscribers.
/// Guarantees: The upstream receipt resolves immediately as Nack instead of reporting delivery.
#[tokio::test]
async fn broadcast_all_mode_zero_subscribers_nacks_immediately() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-empty",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { reason }
            if reason.as_ref() == "broadcast publish had no eligible subscribers"
    ));
}

/// Scenario: A subscriber joins after an `all`-mode tracked message is published.
/// Guarantees: The late subscriber is excluded from that message's Ack consensus.
#[tokio::test]
async fn broadcast_all_mode_late_subscriber_not_required() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-late",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut early = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    // Late subscriber joins after the publish; it is not part of the snapshot.
    let _late = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let id = recv_message_id(early.recv().await);
    early.ack(id).unwrap();

    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

/// Scenario: A subscriber Acks one of two messages and disappears before Acking the other.
/// Guarantees: Only the still-outstanding message resolves as Nack.
#[tokio::test]
async fn broadcast_all_mode_multi_message_nacks_only_unacked() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-multi",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt1 = handle.publish(Arc::new(1)).await.unwrap();
    let receipt2 = handle.publish(Arc::new(2)).await.unwrap();

    // Ack the first message (sole required subscriber) -> Ack.
    let id1 = recv_message_id(sub.recv().await);
    sub.ack(id1).unwrap();
    assert_eq!(
        receipt1.wait_for_outcome().await,
        TrackedPublishOutcome::Ack
    );

    // Receive but do not ack the second, then drop -> only the second nacks.
    let _id2 = recv_message_id(sub.recv().await);
    drop(sub);
    assert!(matches!(
        receipt2.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
}

/// Scenario: A subscriber completes consensus and then disconnects.
/// Guarantees: The completed Ack remains terminal and the later disconnect is a no-op.
#[tokio::test]
async fn broadcast_all_mode_ack_then_disconnect_keeps_ack() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-ack-then-drop",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();
    let id = recv_message_id(sub.recv().await);
    sub.ack(id).unwrap();

    // Drop after the consensus already resolved as Ack: disconnect is a no-op.
    drop(sub);

    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

/// Scenario: A required subscriber disconnects before another subscriber's late Ack.
/// Guarantees: The Nack remains terminal and the late Ack is reported as not tracked.
#[tokio::test]
async fn broadcast_all_mode_disconnect_then_ack_keeps_nack() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-drop-then-ack",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut held = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut dropped = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    let held_id = recv_message_id(held.recv().await);
    let _dropped_id = recv_message_id(dropped.recv().await);

    // The second required subscriber disappears before acking -> Nack.
    drop(dropped);

    // The surviving subscriber's late ack is rejected: the message is resolved.
    assert!(matches!(held.ack(held_id), Err(Error::MessageNotTracked)));

    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
}

/// Scenario: A subscriber Acks and then sends a late Nack for the same message.
/// Guarantees: The late Nack cannot retract its Ack or prevent consensus completion.
#[tokio::test]
async fn broadcast_all_mode_ack_then_nack_is_ignored() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-ack-then-nack",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub1 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();
    let mut sub2 = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();

    let id1 = recv_message_id(sub1.recv().await);
    let id2 = recv_message_id(sub2.recv().await);

    // sub1 acks (leaving the pending set), then nacks the same message. The Nack
    // must not override the already-counted ack.
    sub1.ack(id1).unwrap();
    sub1.nack(id1, Arc::from("late retraction")).unwrap();

    // sub2 completes the consensus -> Ack despite sub1's stray Nack.
    sub2.ack(id2).unwrap();

    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

/// Scenario: A topic closes while an `all`-mode tracked message is outstanding.
/// Guarantees: The receipt resolves as TopicClosed rather than subscriber Nack.
#[tokio::test]
async fn broadcast_all_mode_topic_close_resolves_topic_closed() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-close",
        1024,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    let mut sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    let receipt = handle.publish(Arc::new(1)).await.unwrap();
    let _id = recv_message_id(sub.recv().await);

    topic.close();

    assert_eq!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::TopicClosed
    );
}

/// Scenario: Publishing, subscribing, and acknowledging run concurrently in `all` mode.
/// Guarantees: Registry and tracker contention does not deadlock or strand receipts.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn broadcast_all_mode_concurrent_publish_subscribe_resolves() {
    let broker = TopicBroker::<u64>::new();
    let topic = all_mode_topic(
        &broker,
        "all-concurrent",
        4096,
        TopicBroadcastOnLagPolicy::DropOldest,
    );
    let handle = topic.tracked_publisher();

    const MESSAGES: u64 = 64;

    // Long-lived subscribers that ack every message they receive.
    let mut ackers = Vec::new();
    for _ in 0..3 {
        let mut sub = topic
            .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
            .unwrap();
        ackers.push(tokio::spawn(async move {
            let mut acked = 0u64;
            while acked < MESSAGES {
                match sub.recv().await {
                    Ok(RecvItem::Message(env)) => {
                        let _ = sub.ack(env.id);
                        acked += 1;
                    }
                    Ok(RecvItem::Lagged { .. }) => {}
                    Err(_) => break,
                }
            }
            // Keep the subscriber alive until every message is acked so it is
            // never the cause of a Nack.
            sub
        }));
    }

    // Subscribers joining concurrently with the publishes, each acking what it
    // receives, to exercise the subscribe-vs-publish linearization.
    let topic_for_joins = topic.clone();
    let joiner = tokio::spawn(async move {
        let mut subs = Vec::new();
        for _ in 0..MESSAGES {
            let mut sub = topic_for_joins
                .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
                .unwrap();
            // Drain without blocking forever; ack whatever is immediately ready.
            while let Ok(Ok(item)) =
                tokio::time::timeout(Duration::from_millis(1), sub.recv()).await
            {
                if let RecvItem::Message(env) = item {
                    let _ = sub.ack(env.id);
                }
            }
            subs.push(sub);
            tokio::task::yield_now().await;
        }
        subs
    });

    let mut receipts = Vec::new();
    for i in 0..MESSAGES {
        receipts.push(handle.publish(Arc::new(i)).await.unwrap());
    }

    // Every receipt must reach a terminal outcome without hanging.
    let outcomes = tokio::time::timeout(Duration::from_secs(5), async {
        let mut outcomes = Vec::new();
        for receipt in receipts {
            outcomes.push(receipt.wait_for_outcome().await);
        }
        outcomes
    })
    .await
    .expect("receipts did not resolve before timeout");

    for outcome in &outcomes {
        assert!(
            matches!(
                outcome,
                TrackedPublishOutcome::Ack | TrackedPublishOutcome::Nack { .. }
            ),
            "unexpected non-terminal outcome: {outcome:?}"
        );
    }

    // Keep subscribers alive until all outcomes are collected.
    let _ackers = ackers;
    let _joined = joiner.await.unwrap();
}

// =========================================================================
// Non-blocking publish
// =========================================================================

// try_publish reports DroppedOnFull for balanced queues without awaiting.
#[tokio::test]
async fn try_publish_balanced_only_reports_drop_on_full() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "nb-balanced",
            TopicOptions::BalancedOnly { capacity: 1 },
            InMemoryBackend,
        )
        .unwrap();

    let _sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    assert_eq!(
        topic.try_publish(Arc::new(1)).unwrap(),
        PublishOutcome::Published
    );
    assert_eq!(
        topic.try_publish(Arc::new(2)).unwrap(),
        PublishOutcome::DroppedOnFull
    );
}

// On mixed topics, try_publish is all-or-nothing across balanced and
// broadcast delivery. A balanced drop-on-full result must not leak a message
// to broadcast subscribers.
#[tokio::test]
async fn try_publish_mixed_rejects_broadcast_when_balanced_is_full() {
    let broker = TopicBroker::<u64>::new();
    let topic = broker
        .create_topic(
            "nb-mixed",
            TopicOptions::Mixed {
                balanced_capacity: 1,
                broadcast_capacity: 8,
                on_lag: TopicBroadcastOnLagPolicy::DropOldest,
                ack_mode: TopicBroadcastAckMode::First,
            },
            InMemoryBackend,
        )
        .unwrap();

    let _balanced_sub = topic
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();
    let mut broadcast_sub = topic
        .subscribe(SubscriptionMode::Broadcast, SubscriberOptions::default())
        .unwrap();

    assert_eq!(
        topic.try_publish(Arc::new(10)).unwrap(),
        PublishOutcome::Published
    );
    assert_eq!(
        topic.try_publish(Arc::new(20)).unwrap(),
        PublishOutcome::DroppedOnFull
    );

    topic.close();

    let mut received = Vec::new();
    while let Ok(item) = broadcast_sub.recv().await {
        if let RecvItem::Message(env) = item {
            received.push(*env.payload);
        }
    }
    assert_eq!(received, vec![10]);
}

// =========================================================================
// Broker lifecycle methods
// =========================================================================

// get_topic returns a handle to a previously created topic by name.
#[tokio::test]
async fn get_topic_returns_existing() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("my-topic", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    let retrieved = broker.get_topic("my-topic");
    assert!(retrieved.is_some());
    assert_eq!(retrieved.unwrap().name().as_ref(), handle.name().as_ref());
}

// get_topic returns None for a name that was never created.
#[tokio::test]
async fn get_topic_returns_none_for_missing() {
    let broker = TopicBroker::<u64>::new();
    assert!(broker.get_topic("nonexistent").is_none());
}

// get_topic_required returns UnknownTopic when missing.
#[tokio::test]
async fn get_topic_required_returns_error_for_missing() {
    let broker = TopicBroker::<u64>::new();
    let missing = "missing";
    match broker.get_topic_required(missing) {
        Err(Error::UnknownTopic { topic }) => assert_eq!(topic, missing),
        _ => panic!("expected UnknownTopic"),
    }
}

// has_topic returns false before creation and true after.
#[tokio::test]
async fn has_topic_reflects_state() {
    let broker = TopicBroker::<u64>::new();
    assert!(!broker.has_topic("t1"));
    _ = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    assert!(broker.has_topic("t1"));
}

// create_topics declares multiple topics in one call.
#[tokio::test]
async fn create_topics_batch_success() {
    let broker = TopicBroker::<u64>::new();
    let declarations = vec![
        (TopicName::parse("t-a").unwrap(), TopicOptions::default()),
        (TopicName::parse("t-b").unwrap(), TopicOptions::default()),
    ];
    let handles = broker.create_topics(declarations, InMemoryBackend).unwrap();
    assert_eq!(handles.len(), 2);
    assert!(broker.has_topic("t-a"));
    assert!(broker.has_topic("t-b"));
}

// create_topics is atomic for duplicate checks: duplicate names in the batch
// fail and no topic from the call is inserted.
#[tokio::test]
async fn create_topics_batch_duplicate_is_rejected_atomically() {
    let broker = TopicBroker::<u64>::new();
    let dup = TopicName::parse("dup").unwrap();
    let result = broker.create_topics(
        vec![
            (dup.clone(), TopicOptions::default()),
            (dup.clone(), TopicOptions::default()),
        ],
        InMemoryBackend,
    );
    match result {
        Err(Error::TopicAlreadyExists { topic }) => assert_eq!(topic, dup),
        _ => panic!("expected TopicAlreadyExists"),
    }
    assert!(!broker.has_topic("dup"));
}

// remove_topic closes the topic (publish returns Closed, recv returns Closed)
// and removes it from the broker.
#[tokio::test]
async fn remove_topic_closes_and_removes() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("removable", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let mut sub = handle
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    handle.publish(Arc::new(1)).await.unwrap();

    assert!(broker.remove_topic("removable"));
    assert!(!broker.has_topic("removable"));

    // Publish should fail with Closed.
    match handle.publish(Arc::new(2)).await {
        Err(Error::TopicClosed) => {}
        other => panic!("expected PublishError::Closed, got {:?}", other),
    }

    // Drain any buffered message, then expect Closed.
    loop {
        match sub.recv().await {
            Ok(RecvItem::Message(_)) => continue,
            Err(Error::SubscriptionClosed) => break,
            other => panic!("expected RecvError::Closed, got {:?}", other),
        }
    }
}

// remove_topic returns false when the topic does not exist.
#[tokio::test]
async fn remove_topic_returns_false_for_missing() {
    let broker = TopicBroker::<u64>::new();
    assert!(!broker.remove_topic("nonexistent"));
}

// After removing a topic, recreating it with the same name yields an
// independent topic that does not share state with the old one.
#[tokio::test]
async fn remove_topic_allows_recreation_with_same_name() {
    let broker = TopicBroker::<u64>::new();
    let old_handle = broker
        .create_topic("reuse", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    old_handle.publish(Arc::new(1)).await.unwrap();
    _ = broker.remove_topic("reuse");

    // Recreate -- should be an independent topic.
    let new_handle = broker
        .create_topic("reuse", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    let mut sub = new_handle
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    new_handle.publish(Arc::new(42)).await.unwrap();
    new_handle.close();

    let mut received = Vec::new();
    while let Ok(RecvItem::Message(env)) = sub.recv().await {
        received.push(*env.payload);
    }
    assert_eq!(received, vec![42]);
}

// topic_names returns the names of all currently registered topics.
#[tokio::test]
async fn topic_names_returns_all_names() {
    let broker = TopicBroker::<u64>::new();
    _ = broker
        .create_topic("alpha", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    _ = broker
        .create_topic("beta", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    _ = broker
        .create_topic("gamma", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let mut names: Vec<String> = broker
        .topic_names()
        .into_iter()
        .map(|n| n.to_string())
        .collect();
    names.sort();
    assert_eq!(names, vec!["alpha", "beta", "gamma"]);
}

// close_all closes every topic in the broker; subsequent publishes return
// Closed and the broker is empty.
#[tokio::test]
async fn close_all_closes_every_topic() {
    let broker = TopicBroker::<u64>::new();
    let h1 = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    let h2 = broker
        .create_topic("t2", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    broker.close_all();

    match h1.publish(Arc::new(1)).await {
        Err(Error::TopicClosed) => {}
        other => panic!("expected Closed, got {:?}", other),
    }
    match h2.publish(Arc::new(2)).await {
        Err(Error::TopicClosed) => {}
        other => panic!("expected Closed, got {:?}", other),
    }

    // Broker should be empty.
    assert!(broker.topic_names().is_empty());
}

// Registering with a closed tracker resolves immediately as TopicClosed
// instead of leaving a pending entry behind without a timeout worker.
#[tokio::test]
async fn tracked_publish_tracker_register_after_close_resolves_immediately() {
    let tracker = TrackedPublishTracker::new();
    tracker.close_all();

    let permit = TrackedPublishPermit::from_tokio_owned(
        Arc::new(Semaphore::new(1))
            .acquire_owned()
            .await
            .expect("semaphore should not be closed"),
    );

    let receipt = tracker.register(1, Duration::from_secs(30), permit);

    assert_eq!(receipt.message_id(), 1);
    assert_eq!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::TopicClosed
    );
}

// =========================================================================
// TrackedPublishTracker consensus (`all`-mode) primitives
//
// These exercise the tracker primitive directly
// =========================================================================

fn consensus_permit_from(sem: &Arc<Semaphore>) -> TrackedPublishPermit {
    TrackedPublishPermit::from_tokio_owned(
        sem.clone()
            .try_acquire_owned()
            .expect("semaphore permit available"),
    )
}

fn consensus_permit() -> TrackedPublishPermit {
    consensus_permit_from(&Arc::new(Semaphore::new(1)))
}

fn subscriber_set(ids: impl IntoIterator<Item = u64>) -> HashSet<BroadcastSubscriberId> {
    ids.into_iter().map(BroadcastSubscriberId).collect()
}

// A consensus entry resolves as Ack only once every required subscriber has acked,
// and further acks for that message are no longer tracked.
#[tokio::test]
async fn consensus_resolves_ack_only_after_all_subscribers_ack() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        7,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        7,
    );

    assert_eq!(
        tracker.resolve_ack_from(7, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );
    assert_eq!(
        tracker.resolve_ack_from(7, BroadcastSubscriberId(2)),
        AckFromResult::Resolved
    );
    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);

    assert_eq!(
        tracker.resolve_ack_from(7, BroadcastSubscriberId(1)),
        AckFromResult::NotTracked
    );
}

// A repeated ack from the same subscriber must not falsely complete the consensus.
#[tokio::test]
async fn consensus_duplicate_ack_does_not_complete() {
    let tracker = TrackedPublishTracker::new();
    let _receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        1,
    );

    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(2)),
        AckFromResult::Resolved
    );
}

/// Scenario: A non-member acknowledges a consensus entry before its required members.
/// Guarantees: The unrelated Ack does not advance or falsely complete consensus.
#[tokio::test]
async fn consensus_ack_from_non_member_does_not_advance() {
    let tracker = TrackedPublishTracker::new();
    let _receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        1,
    );

    // A non-member ack is a no-op and does not advance consensus.
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(99)),
        AckFromResult::StillPending
    );

    // Both genuine members must still ack for the entry to resolve.
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(2)),
        AckFromResult::Resolved
    );
}

/// Scenario: Required, already-Acked, and unknown subscribers Nack consensus entries.
/// Guarantees: Nack results distinguish Resolved, NotRequired, and NotTracked cases.
#[tokio::test]
async fn consensus_nack_from_respects_pending_membership() {
    let tracker = TrackedPublishTracker::new();
    let _receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        1,
    );

    // Subscriber 1 acks, leaving the pending set {2}.
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );

    // Subscriber 1's later Nack is ignored: it no longer requires the message.
    assert_eq!(
        tracker.resolve_nack_from(1, BroadcastSubscriberId(1), Arc::from("retraction")),
        NackFromResult::NotRequired
    );

    // Subscriber 2 still requires the message: its Nack resolves the entry.
    assert_eq!(
        tracker.resolve_nack_from(1, BroadcastSubscriberId(2), Arc::from("rejected")),
        NackFromResult::Resolved
    );

    // Once resolved (and removed) the message id is no longer tracked.
    assert_eq!(
        tracker.resolve_nack_from(1, BroadcastSubscriberId(2), Arc::from("again")),
        NackFromResult::NotTracked
    );
    assert_eq!(
        tracker.resolve_nack_from(999, BroadcastSubscriberId(1), Arc::from("unknown")),
        NackFromResult::NotTracked
    );

    let first_receipt = tracker.register(2, Duration::from_secs(30), consensus_permit());
    assert_eq!(
        tracker.resolve_nack_from(2, BroadcastSubscriberId(1), Arc::from("wrong mode")),
        NackFromResult::NotTracked
    );
    assert!(tracker.resolve(2, TrackedPublishOutcome::Ack));
    assert_eq!(
        first_receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Ack
    );
}

/// Scenario: Consensus registration receives an empty eligible-subscriber set.
/// Guarantees: The receipt Nacks immediately without leaving a tracked entry.
#[tokio::test]
async fn consensus_empty_set_resolves_nack_immediately() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        HashSet::new(),
        1,
    );

    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { reason }
            if reason.as_ref() == "broadcast publish had no eligible subscribers"
    ));
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::NotTracked
    );
}

// Acking an unknown message id is reported as not-tracked.
#[tokio::test]
async fn consensus_resolve_ack_from_unknown_message_not_tracked() {
    let tracker = TrackedPublishTracker::new();
    assert_eq!(
        tracker.resolve_ack_from(99, BroadcastSubscriberId(1)),
        AckFromResult::NotTracked
    );
}

// resolve_ack_from is consensus-only: a first-wins (`First`-kind) entry reports
// not-tracked and is left pending, so the first-wins resolve path still works.
#[tokio::test]
async fn resolve_ack_from_first_kind_entry_is_not_tracked() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register(1, Duration::from_secs(30), consensus_permit());

    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::NotTracked
    );
    // Still pending: the first-wins path resolves it.
    assert!(tracker.resolve(1, TrackedPublishOutcome::Ack));
    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

// A required subscriber disappearing nacks its outstanding consensus entries.
#[tokio::test]
async fn consensus_subscriber_disappearance_nacks_outstanding() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        5,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        5,
    );

    tracker.nack_pending_for_subscriber(
        BroadcastSubscriberId(2),
        Arc::from("subscriber disconnected"),
    );

    match receipt.wait_for_outcome().await {
        TrackedPublishOutcome::Nack { reason } => assert_eq!(&*reason, "subscriber disconnected"),
        other => panic!("expected Nack, got {other:?}"),
    }
    assert_eq!(
        tracker.resolve_ack_from(5, BroadcastSubscriberId(1)),
        AckFromResult::NotTracked
    );
}

// Disconnecting a subscriber only nacks entries that still require it.
#[tokio::test]
async fn consensus_disappearance_only_nacks_entries_requiring_subscriber() {
    let tracker = TrackedPublishTracker::new();
    let r1 = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1]),
        1,
    );
    let r2 = tracker.register_consensus(
        2,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([2]),
        2,
    );

    tracker.nack_pending_for_subscriber(BroadcastSubscriberId(1), Arc::from("gone"));

    assert!(matches!(
        r1.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
    assert_eq!(
        tracker.resolve_ack_from(2, BroadcastSubscriberId(2)),
        AckFromResult::Resolved
    );
    assert_eq!(r2.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

/// Scenario: A lag threshold divides one subscriber's skipped and readable messages.
/// Guarantees: Only required messages below the sequence threshold resolve as Nack.
#[tokio::test]
async fn consensus_nack_owed_before_respects_seq_threshold() {
    let tracker = TrackedPublishTracker::new();
    // Message at seq 3 requires subscriber 1 and was skipped by the lag.
    let skipped = tracker.register_consensus(
        10,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1]),
        3,
    );
    // Message at the threshold also requires subscriber 1 but is still readable.
    let readable = tracker.register_consensus(
        11,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1]),
        5,
    );

    // Subscriber 1 lagged: its next read position is seq 5, so only seq < 5 is
    // unrecoverable.
    tracker.nack_owed_before(
        BroadcastSubscriberId(1),
        5,
        Arc::from("lagged past message"),
    );

    match skipped.wait_for_outcome().await {
        TrackedPublishOutcome::Nack { reason } => assert_eq!(&*reason, "lagged past message"),
        other => panic!("expected Nack for skipped message, got {other:?}"),
    }

    // The readable entry is untouched and still resolves on ack.
    assert_eq!(
        tracker.resolve_ack_from(11, BroadcastSubscriberId(1)),
        AckFromResult::Resolved
    );
    assert_eq!(
        readable.wait_for_outcome().await,
        TrackedPublishOutcome::Ack
    );
}
/// Scenario: The generic resolver Nacks an entry after one consensus Ack.
/// Guarantees: A terminal generic Nack overrides the still-pending consensus.
#[tokio::test]
async fn consensus_single_resolve_nack_overrides_consensus() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        1,
    );

    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );
    assert!(tracker.resolve(
        1,
        TrackedPublishOutcome::Nack {
            reason: Arc::from("boom")
        }
    ));
    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(2)),
        AckFromResult::NotTracked
    );
}

// First terminal transition wins: an ack that completes the consensus makes a
// later disconnect of the (already satisfied) subscriber a no-op.
#[tokio::test]
async fn consensus_ack_completion_beats_late_disconnect() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1]),
        1,
    );

    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::Resolved
    );
    tracker.nack_pending_for_subscriber(BroadcastSubscriberId(1), Arc::from("late"));
    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

// Registering a consensus entry against a closed tracker resolves immediately.
#[tokio::test]
async fn consensus_register_after_close_resolves_topic_closed() {
    let tracker = TrackedPublishTracker::new();
    tracker.close_all();
    let receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1]),
        1,
    );
    assert_eq!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::TopicClosed
    );
}

// The in-flight permit is released exactly once the consensus entry resolves.
#[tokio::test]
async fn consensus_releases_permit_on_resolution() {
    let sem = Arc::new(Semaphore::new(1));
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit_from(&sem),
        subscriber_set([1]),
        1,
    );

    assert_eq!(sem.available_permits(), 0);
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::Resolved
    );
    let _ = receipt.wait_for_outcome().await;
    assert_eq!(sem.available_permits(), 1);
}

// =========================================================================
// TopicSet
// =========================================================================

// Inserting a handle into a TopicSet and retrieving it by local name returns
// the correct underlying topic.
#[tokio::test]
async fn topic_set_insert_and_get() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("pipeline-1");
    _ = set.insert("output", handle);

    let retrieved = set.get("output");
    assert!(retrieved.is_some());
    assert_eq!(retrieved.unwrap().name().as_ref(), "t1");
}

// Getting a name that was never inserted into the TopicSet returns None.
#[tokio::test]
async fn topic_set_get_missing_returns_none() {
    let set = TopicSet::<u64>::new("empty-set");
    assert!(set.get("nonexistent").is_none());
}

// get_required on TopicSet returns UnknownTopic when local alias is missing.
#[tokio::test]
async fn topic_set_get_required_returns_error_for_missing() {
    let set = TopicSet::<u64>::new("empty-set");
    let missing = "missing-local";
    match set.get_required(missing) {
        Err(Error::UnknownTopic { topic }) => assert_eq!(topic, missing),
        _ => panic!("expected UnknownTopic"),
    }
}

// Removing an entry from a TopicSet returns the handle and makes subsequent
// get calls return None.
#[tokio::test]
async fn topic_set_remove() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("p1");
    _ = set.insert("output", handle);
    assert!(set.contains("output"));

    let removed = set.remove("output");
    assert!(removed.is_some());
    assert!(!set.contains("output"));
}

// Removing a topic from a TopicSet does not close the underlying topic; the
// original handle can still publish.
#[tokio::test]
async fn topic_set_remove_does_not_close_topic() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("p1");
    _ = set.insert("output", handle.clone());

    // Remove from set.
    _ = set.remove("output");

    // Topic should still be usable via the original handle.
    handle.publish(Arc::new(42)).await.unwrap();
}

// Inserting a second handle under the same local name replaces the first and
// returns the previous handle.
#[tokio::test]
async fn topic_set_insert_overwrites() {
    let broker = TopicBroker::<u64>::new();
    let h1 = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    let h2 = broker
        .create_topic("t2", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("p1");
    assert!(set.insert("output", h1).is_none());

    let prev = set.insert("output", h2);
    assert!(prev.is_some());
    assert_eq!(prev.unwrap().name().as_ref(), "t1");

    // Current should point to t2.
    assert_eq!(set.get("output").unwrap().name().as_ref(), "t2");
}

// topic_names on a TopicSet returns the local alias names, not the underlying
// topic names.
#[tokio::test]
async fn topic_set_topic_names() {
    let broker = TopicBroker::<u64>::new();
    let h1 = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();
    let h2 = broker
        .create_topic("t2", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("p1");
    _ = set.insert("alpha", h1);
    _ = set.insert("beta", h2);

    let mut names: Vec<String> = set
        .topic_names()
        .into_iter()
        .map(|n| n.to_string())
        .collect();
    names.sort();
    assert_eq!(names, vec!["alpha", "beta"]);
}

// Handles fetched from a TopicSet can still create tracked publishers.
#[tokio::test]
async fn topic_set_tracked_publisher() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("p1");
    _ = set.insert("output", handle);

    let handle = set.get("output").unwrap();
    let pub_handle = handle.tracked_publisher();

    let mut sub = handle
        .subscribe(
            SubscriptionMode::Balanced {
                group: SubscriptionGroupName::from("g1"),
            },
            SubscriberOptions::default(),
        )
        .unwrap();

    let receipt = pub_handle.publish(Arc::new(99u64)).await.unwrap();

    let env = match sub.recv().await.unwrap() {
        RecvItem::Message(e) => e,
        _ => panic!(),
    };

    sub.ack(env.id).unwrap();

    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}

// A TopicSet's name matches the value provided at construction.
#[tokio::test]
async fn topic_set_name() {
    let set = TopicSet::<u64>::new("my-pipeline");
    assert_eq!(set.name(), "my-pipeline");
}

// Cloning a TopicSet shares the underlying state: an insert on one clone is
// visible from the other.
#[tokio::test]
async fn topic_set_clone_shares_state() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set1 = TopicSet::new("p1");
    let set2 = set1.clone();

    _ = set1.insert("output", handle);

    // set2 should see the insert from set1.
    assert!(set2.contains("output"));
    assert_eq!(set2.len(), 1);
}

// len() and is_empty() accurately reflect the number of entries in the
// TopicSet.
#[tokio::test]
async fn topic_set_len_and_is_empty() {
    let broker = TopicBroker::<u64>::new();
    let handle = broker
        .create_topic("t1", TopicOptions::default(), InMemoryBackend)
        .unwrap();

    let set = TopicSet::new("p1");
    assert!(set.is_empty());
    assert_eq!(set.len(), 0);

    _ = set.insert("output", handle);
    assert!(!set.is_empty());
    assert_eq!(set.len(), 1);
}

/// Scenario: A delayed tracked publisher commits after the ring wraps onto its slot.
/// Guarantees: The stale message cannot overwrite newer data and resolves promptly as Nack.
#[tokio::test]
async fn broadcast_ring_stale_commit_does_not_overwrite_newer_wrapped_sequence() {
    let ring = FastBroadcastRing::new(2);
    let stale_seq = ring.reserve_seq();
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        stale_seq,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1]),
        stale_seq,
    );

    let next_seq = ring.reserve_seq();
    assert!(ring.commit_slot(
        next_seq,
        Envelope {
            id: next_seq,
            tracked: false,
            payload: Arc::new(next_seq),
        },
    ));

    let wrapped_seq = ring.reserve_seq();
    assert!(ring.commit_slot(
        wrapped_seq,
        Envelope {
            id: wrapped_seq,
            tracked: false,
            payload: Arc::new(wrapped_seq),
        },
    ));

    let committed = ring.commit_slot(
        stale_seq,
        Envelope {
            id: stale_seq,
            tracked: true,
            payload: Arc::new(stale_seq),
        },
    );
    assert!(!committed);
    if !committed {
        let _ = tracker.resolve(
            stale_seq,
            TrackedPublishOutcome::Nack {
                reason: Arc::from("broadcast message was overtaken before ring commit"),
            },
        );
    }

    match ring.try_read(wrapped_seq) {
        BroadcastReadResult::Ready(envelope) => {
            assert_eq!(envelope.id, wrapped_seq);
            assert_eq!(*envelope.payload, wrapped_seq);
        }
        _ => panic!("wrapped sequence should remain readable"),
    }
    assert!(matches!(
        receipt.wait_for_outcome().await,
        TrackedPublishOutcome::Nack { .. }
    ));
}

/// Scenario: One member Acks while another member still keeps consensus pending.
/// Guarantees: A later disconnect cannot Nack the member's completed contribution.
#[tokio::test]
async fn consensus_disconnect_does_not_nack_completed_ack() {
    let tracker = TrackedPublishTracker::new();
    let receipt = tracker.register_consensus(
        1,
        Duration::from_secs(30),
        consensus_permit(),
        subscriber_set([1, 2]),
        1,
    );

    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(1)),
        AckFromResult::StillPending
    );
    tracker.nack_pending_for_subscriber(BroadcastSubscriberId(1), Arc::from("disconnected"));
    assert_eq!(
        tracker.resolve_ack_from(1, BroadcastSubscriberId(2)),
        AckFromResult::Resolved
    );
    assert_eq!(receipt.wait_for_outcome().await, TrackedPublishOutcome::Ack);
}