moq-net 0.2.16

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

use futures::{FutureExt, StreamExt, stream::FuturesUnordered};

use crate::{
	AsPath, Error, Timescale, Timestamp,
	coding::{Stream, Writer},
	ietf::{self, Control, EndLocation, FetchHeader, FetchType, Filter, GroupOrder, Location, RequestId},
	track::Subscription,
	util::{MaybeBoxedExt, MaybeSendBox},
};

use super::{Message, Version, cluster, peer};

/// A broadcast whose route table is watched for changes in what we advertise: the
/// namespace becoming (un)advertisable, or its path or cost moving.
struct Watched {
	broadcast: crate::broadcast::Consumer,
	/// Demand edges re-price the serving route without a route change (see
	/// [`crate::broadcast::outgoing_cost`]), so the loop watches this too.
	demand: crate::broadcast::Demand,
	/// What the peer currently holds for this namespace, or [`Advert::None`] while it
	/// is filtered. A selection that differs is worth a wire message; one that matches
	/// is not.
	sent: Advert,
	/// When demand drained while a zero cost was advertised. Restoring the cold cost is
	/// deferred by [`crate::broadcast::COST_LINGER`] past this, so viewer churn does not
	/// flap routing across the mesh; demand returning in the window cancels it.
	idle_at: Option<web_async::time::Instant>,
	/// Set once the broadcast errors, so a dead entry stops being polled.
	dead: bool,
	/// The peer should hold this namespace but does not: it refused the request, or we
	/// could not get a stream to make it on. Nothing about that clears on its own, so the
	/// loop comes back to it on a timer.
	deferred: bool,
	/// What the peer's refusal said about coming back, which outranks that timer.
	refused: Refused,
}

/// What a refusal said about re-offering the namespace.
///
/// A peer answers a request it declines with a retry interval ({{moqt}} REQUEST_ERROR),
/// and ignoring it is how a permanent refusal (unauthorized, uninterested) turns into a
/// request every few seconds for the life of the session.
/// What a group has next for [`Publisher::run_group`]: a batch of complete frames
/// waiting in the buffer, a consumer for the in-flight tail, or the end of the group.
enum Step {
	/// The buffer was refilled; its frames are the next ones to send.
	Batch,
	/// Nothing is complete yet, so stream the open tail chunk by chunk.
	Partial(frame::Consumer),
	/// The group ended.
	Done,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Refused {
	/// Never refused, or refused on a draft whose error carries no interval, so our own
	/// backoff is the only guidance there is.
	#[default]
	No,
	/// Refused with a minimum wait before re-offering.
	Until(web_async::time::Instant),
	/// Refused with an interval of 0: the peer does not want this offered again.
	Never,
}

impl Refused {
	/// Whether a fresh offer may go out now.
	///
	/// The single gate, consulted on every reconciliation rather than only on the retry
	/// sweep: a route change re-prices an advertisement but does not excuse us from a
	/// wait the peer asked for, nor make a refused namespace a different one.
	fn offerable(&self, now: web_async::time::Instant) -> bool {
		match self {
			Self::No => true,
			Self::Until(at) => now >= *at,
			Self::Never => false,
		}
	}

	/// Whether the loop should keep coming back at all. Only a refusal that forbids
	/// retrying ends it; a wait still has to arm the timer that counts it out.
	fn pending(&self) -> bool {
		*self != Self::Never
	}
}

impl Watched {
	fn new(broadcast: crate::broadcast::Consumer) -> Self {
		Self {
			demand: broadcast.demand(),
			broadcast,
			sent: Advert::None,
			idle_at: None,
			dead: false,
			deferred: false,
			refused: Refused::No,
		}
	}

	/// Record what the peer now holds, retiring any linger the old advertisement armed.
	///
	/// Only a discounted advertisement has a cost to restore. Leaving `idle_at` set past
	/// one that isn't would keep [`Publisher::linger_deadline`] handing back an expired
	/// instant that nothing ever clears, and the announce loops would spin on it.
	fn set_sent(&mut self, sent: Advert) {
		if !sent.discounted() {
			self.idle_at = None;
		}
		self.sent = sent;
	}
}

/// What to advertise to this peer for one broadcast.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
enum Advert {
	/// Nothing: every route loops through the peer or us, or none is announced.
	#[default]
	None,
	/// The namespace, with no routing information: the peer did not negotiate the MoQ
	/// Cluster extension, so there is nowhere to put a path or a cost.
	Plain,
	/// The namespace, with the path it traversed and that path's accumulated cost.
	Cluster(cluster::Advert),
}

impl Advert {
	/// Whether the peer should hold this namespace at all.
	fn wanted(&self) -> bool {
		!matches!(self, Self::None)
	}

	/// The parameters to put on the wire, as the message structs carry them.
	fn params(&self) -> Option<cluster::Advert> {
		match self {
			Self::Cluster(advert) => Some(advert.clone()),
			_ => None,
		}
	}

	/// Whether this advertisement carries a zero cost, which is what the serving-route
	/// discount produces and what the linger is watching to restore.
	fn discounted(&self) -> bool {
		matches!(self, Self::Cluster(advert) if advert.cost == 0)
	}
}

/// What a watched broadcast reported.
enum Watch {
	/// Its route table or demand moved; re-run the selection.
	Changed(crate::PathOwned),
	/// Demand just drained while a discounted cost was advertised. The cold cost is
	/// restored once the linger expires, not now, so viewer churn does not flap routing.
	Idle(crate::PathOwned),
}

/// How long to wait for a stream to advertise one namespace on.
///
/// Only reached when the peer has granted no more, which on this path means it is holding
/// every advertisement we already sent. Long enough that a merely slow peer is not given
/// up on, short enough that the loop resumes and can retire something.
const ADVERTISE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// First wait before re-offering a namespace we could not get up.
const RETRY_BASE: std::time::Duration = std::time::Duration::from_millis(100);

/// Ceiling on that wait. The loop retries for the life of the session, so it must settle
/// into a slow poll rather than a spin.
const RETRY_MAX: std::time::Duration = std::time::Duration::from_secs(5);

/// Spread a retry over half its window, so every namespace on a busy relay does not come
/// back at the same instant.
fn jitter(delay: std::time::Duration) -> std::time::Duration {
	use rand::RngExt;
	delay.mul_f64(0.5 + rand::rng().random::<f64>() / 2.0)
}

/// Where one announce loop's advertisements go.
enum Target<S: web_transport_trait::Session> {
	/// Inline NAMESPACE entries on the SUBSCRIBE_NAMESPACE stream that asked for them
	/// (draft-16+).
	Inline(Stream<S, Version>),
	/// Each advertisement on its own PUBLISH_NAMESPACE request. Unsolicited when there
	/// is no stream; draft-14/15 answer a SUBSCRIBE_NAMESPACE this way, since they
	/// predate NAMESPACE, and hold onto its stream to end with the subscription.
	Requests(Option<Stream<S, Version>>),
}

impl<S: web_transport_trait::Session> Target<S> {
	/// The SUBSCRIBE_NAMESPACE stream this loop answers, if any.
	fn stream(&mut self) -> Option<&mut Stream<S, Version>> {
		match self {
			Self::Inline(stream) | Self::Requests(Some(stream)) => Some(stream),
			Self::Requests(None) => None,
		}
	}

	/// Resolves when the peer ends this loop by closing the stream it asked on.
	///
	/// An unsolicited loop has no stream of its own to watch and parks here: the
	/// session driver polling it is what drops it when the session ends.
	async fn closed(&mut self) -> Result<(), Error> {
		match self.stream() {
			Some(stream) => stream.reader.closed().await,
			None => std::future::pending().await,
		}
	}
}

/// One announce loop's state: where its advertisements go, and what the peer holds.
struct Namespaces<S: web_transport_trait::Session> {
	/// What the peer declared in its SETUP, which decides what an advertisement carries.
	peer: cluster::Peer,
	target: Target<S>,
	/// Every announced broadcast under this loop's prefix.
	watched: HashMap<crate::PathOwned, Watched>,
	/// The open PUBLISH_NAMESPACE request carrying each advertised namespace. Empty when
	/// the entries ride a SUBSCRIBE_NAMESPACE stream inline.
	requests: HashMap<crate::PathOwned, NamespaceRequest<S>>,
}

impl<S: web_transport_trait::Session> Namespaces<S> {
	fn new(peer: cluster::Peer, target: Target<S>) -> Self {
		Self {
			peer,
			target,
			watched: HashMap::new(),
			requests: HashMap::new(),
		}
	}
}

/// What woke an announce-forwarding loop.
enum NamespaceEvent {
	/// The session or stream ended, with the result to surface.
	Closed(Result<(), Error>),
	/// An origin-level (un)announce, `None` once the announce stream ends.
	Update(Option<crate::announce::Update>),
	/// A watched broadcast's route table or demand moved; re-run the selection.
	Routes(crate::PathOwned),
	/// A watched broadcast's demand drained; start its linger.
	Idle(crate::PathOwned),
	/// The linger sleep fired without an expired entry (it was canceled, or a later
	/// deadline remains): restart the turn so the next deadline arms a fresh sleep.
	Linger,
	/// The retry sleep fired: re-offer whatever the peer should be holding and isn't.
	Retry,
}

#[derive(Clone)]
pub(super) struct Publisher<S: web_transport_trait::Session> {
	session: S,
	// Traffic stats are attributed through this tagged origin handle.
	origin: origin::Consumer,
	control: Control,
	// Our own Hop ID, stamped onto every advertisement we forward. Taken from the
	// origin we consume so it matches the local relay identity across every session,
	// which is what makes cross-session loop detection work.
	self_origin: crate::Origin,
	// The identity assigned to the peer by the caller (`Client::with_peer_origin`, or
	// the per-session default a server hands every request), used when the peer declares
	// none itself. A peer that negotiates the MoQ Cluster extension declares its own,
	// which wins unless it withheld it as the reserved 0.
	peer_origin: Option<crate::Origin>,
	// What the peer declared in its SETUP, filled when that stream is read.
	peer_setup: peer::PeerSetup,
	version: Version,
}

impl<S: web_transport_trait::Session> Publisher<S> {
	pub fn new(
		session: S,
		origin: origin::Consumer,
		control: Control,
		peer_origin: Option<crate::Origin>,
		peer_setup: peer::PeerSetup,
		version: Version,
	) -> Self {
		Self {
			session,
			self_origin: *origin,
			origin,
			control,
			peer_origin,
			peer_setup,
			version,
		}
	}

	/// What the peer declared in its SETUP, or the default (extension off) on a version
	/// that cannot negotiate it.
	///
	/// Blocks until the peer's SETUP arrives, because the extension changes the NAMESPACE
	/// encoding: nothing can be advertised until we know whether the peer speaks it.
	async fn peer(&self) -> cluster::Peer {
		match cluster::supported(self.version) {
			true => self.peer_setup.get().await.cluster,
			false => cluster::Peer::default(),
		}
	}

	/// Whether the peer requires advertisements to be solicited, from the same SETUP.
	///
	/// Blocks on it for the same reason [`Self::peer`] does: this decides whether the
	/// first advertisement is sent unasked, so it cannot be guessed and corrected later.
	async fn requires_solicitation(&self) -> bool {
		self.peer_setup.get().await.solicit.unwrap_or(false)
	}

	/// The origin to serve this peer's subscriptions from: sources whose hop chain flows
	/// through the peer are excluded, so a subscription is never handed data that already
	/// flowed through the subscriber.
	///
	/// The same exclusion the announce path applies (see [`Self::select`]), which is what
	/// keeps advertised paths truthful and prevents subscription cycles of any length.
	async fn serving_origin(&self) -> origin::Consumer {
		self.excluding(&self.peer().await)
	}

	/// Our origin handle with [`Self::exclude`] applied, the view both the data plane
	/// and the announce loops read this peer's routes through.
	fn excluding(&self, peer: &cluster::Peer) -> origin::Consumer {
		match self.exclude(peer) {
			crate::Origin::UNKNOWN => self.origin.clone(),
			exclude => self.origin.clone().excluding(exclude),
		}
	}

	/// The Hop ID whose paths must not be advertised (or served) back to this peer.
	///
	/// A peer that declared an identity supplies its own; otherwise fall back to the one
	/// we assigned it (`Client::with_peer_origin` when dialing, `Request::with_peer_origin`
	/// or a fresh per-session id when accepting), since moq-transport carries no identity
	/// of its own. A peer that declared the reserved 0 declared no identity, so it takes
	/// the fallback like any other anonymous peer.
	fn exclude(&self, peer: &cluster::Peer) -> crate::Origin {
		peer.identity().or(self.peer_origin).unwrap_or(crate::Origin::UNKNOWN)
	}

	/// Pick what to advertise to this peer for one broadcast.
	///
	/// A same-path source can splice in or detach without an origin-level (un)announce,
	/// and demand can re-price the serving route in place, so the announce loops watch
	/// every announced broadcast (see [`Watched`]) and re-run this when either moves.
	fn select(&self, watch: &Watched, peer: &cluster::Peer) -> Advert {
		let routes = watch.broadcast.routes();
		let exclude = self.exclude(peer);

		for (route, serving) in crate::broadcast::advertisable_routes(&routes, self.self_origin, exclude) {
			if !peer.negotiated() {
				return Advert::Plain;
			}

			let cost = crate::broadcast::outgoing_cost(&watch.demand, route, serving);
			// Our own Hop ID is always the last entry, so the peer reconstructs the full
			// path. A chain with no room left is a loop in all but name; try the next route.
			match cluster::Advert::forward(&route.hops, cost, self.self_origin) {
				Ok(advert) => return Advert::Cluster(advert),
				Err(_) => continue,
			}
		}

		Advert::None
	}

	/// Poll every watched broadcast for a change in what it should advertise, reporting
	/// the first changed path.
	///
	/// Two things move it: the route table (a failover, a standby attaching, a
	/// re-price) and demand on the serving route (which switches the discount on and
	/// off). `fired` is the linger deadline's verdict for this turn.
	fn poll_watched(
		watched: &mut HashMap<crate::PathOwned, Watched>,
		fired: Option<web_async::time::Instant>,
		waiter: &kio::Waiter,
	) -> Poll<Watch> {
		for (path, watch) in watched.iter_mut() {
			if watch.dead {
				continue;
			}
			match watch.broadcast.poll_routes_changed(waiter) {
				Poll::Ready(Ok(())) => return Poll::Ready(Watch::Changed(path.clone())),
				// A dying broadcast has no further route changes; the origin's
				// unannounce is what removes the entry.
				Poll::Ready(Err(_)) => {
					watch.dead = true;
					continue;
				}
				Poll::Pending => {}
			}

			// Only a cost-carrying advertisement re-prices on demand; a plain one has
			// nowhere to put the discount, so watching demand would fire forever.
			if !matches!(watch.sent, Advert::Cluster(_)) {
				continue;
			}

			if !watch.sent.discounted() {
				// Not discounted: demand arriving is what applies the discount.
				if let Poll::Ready(Ok(())) = watch.demand.poll_used(waiter) {
					return Poll::Ready(Watch::Changed(path.clone()));
				}
				continue;
			}

			match watch.idle_at {
				// Demand coming back within the linger cancels the restore; fall through
				// to re-arm the unused watch.
				Some(_) if watch.demand.is_used() => watch.idle_at = None,
				// The linger expired: restore the cold cost.
				Some(at) if fired.is_some_and(|now| now >= at + crate::broadcast::COST_LINGER) => {
					watch.idle_at = None;
					return Poll::Ready(Watch::Changed(path.clone()));
				}
				// Still lingering: the sleep owns the wakeup, and `poll_used` re-arms
				// the cancel check above.
				Some(_) => {
					let _ = watch.demand.poll_used(waiter);
					continue;
				}
				None => {}
			}

			// Demand just drained. Start the linger rather than re-pricing now, and end
			// the turn so the caller arms a deadline for it.
			if let Poll::Ready(Ok(())) = watch.demand.poll_unused(waiter) {
				return Poll::Ready(Watch::Idle(path.clone()));
			}
		}
		Poll::Pending
	}

	/// The earliest deferred cost-restore across every watched broadcast.
	fn linger_deadline(watched: &HashMap<crate::PathOwned, Watched>) -> Option<web_async::time::Instant> {
		watched
			.values()
			.filter_map(|watch| watch.idle_at)
			.min()
			.map(|at| at + crate::broadcast::COST_LINGER)
	}

	/// Handle an incoming bidi stream dispatched by the session.
	pub fn handle_stream(
		&self,
		id: u64,
		mut data: bytes::Bytes,
		stream: Stream<S, Version>,
	) -> Result<MaybeSendBox<'static, ()>, Error> {
		let this = self.clone();
		let task = match id {
			ietf::Subscribe::ID => {
				let msg = ietf::Subscribe::decode_msg(&mut data, this.version)?;
				if !data.is_empty() {
					return Err(Error::WrongSize);
				}
				tracing::debug!(message = ?msg, "received subscribe");
				async move {
					if let Err(err) = this.run_subscribe_stream(stream, msg).await {
						tracing::debug!(%err, "subscribe stream error");
					}
				}
				.maybe_boxed()
			}
			ietf::Fetch::ID => {
				let msg = ietf::Fetch::decode_msg(&mut data, this.version)?;
				if !data.is_empty() {
					return Err(Error::WrongSize);
				}
				tracing::debug!(message = ?msg, "received fetch");
				async move {
					if let Err(err) = this.run_fetch_stream(stream, msg).await {
						tracing::debug!(%err, "fetch stream error");
					}
				}
				.maybe_boxed()
			}
			// Draft-18 SUBSCRIBE_NAMESPACE (0x50) and the legacy 0x11 message decode
			// to the same request_id + namespace; the legacy Subscribe Options field
			// is ignored (moq-lite never subscribes to tracks).
			ietf::SubscribeNamespace::ID | ietf::SubscribeNamespaceLegacy::ID => {
				let msg = if id == ietf::SubscribeNamespace::ID {
					ietf::SubscribeNamespace::decode_msg(&mut data, this.version)?
				} else {
					let legacy = ietf::SubscribeNamespaceLegacy::decode_msg(&mut data, this.version)?;
					ietf::SubscribeNamespace {
						request_id: legacy.request_id,
						namespace: legacy.namespace,
					}
				};
				if !data.is_empty() {
					return Err(Error::WrongSize);
				}
				tracing::debug!(message = ?msg, "received subscribe_namespace");
				async move {
					if let Err(err) = this.run_subscribe_namespace_stream(stream, msg).await {
						tracing::debug!(%err, "subscribe_namespace stream error");
					}
				}
				.maybe_boxed()
			}
			ietf::TrackStatus::ID => {
				tracing::warn!("TrackStatus not supported");
				async {}.maybe_boxed()
			}
			_ => {
				tracing::warn!(id, "unexpected bidi stream type for publisher");
				return Err(Error::UnexpectedStream);
			}
		};
		Ok(task)
	}

	/// Handle a SUBSCRIBE on its bidi stream.
	async fn run_subscribe_stream(self, mut stream: Stream<S, Version>, msg: ietf::Subscribe<'_>) -> Result<(), Error> {
		let request_id = msg.request_id;
		let track_name = msg.track_name.clone();
		let absolute = self.origin.absolute(&msg.track_namespace).to_owned();

		tracing::info!(id = %request_id, broadcast = %absolute, track = %track_name, "subscribe started");

		// Stats (subscriptions, viewer refcount, groups/frames/bytes) are counted in
		// the model, through the tagged `origin::Consumer` the broadcast resolves from.

		// We just received a subscribe for this exact namespace, so the peer must have already
		// seen the announcement. `request_broadcast` resolves it immediately, or falls back to
		// an `origin::Dynamic` handler if one is registered.
		let broadcast = match self
			.serving_origin()
			.await
			.request_broadcast(&msg.track_namespace)
			.await
		{
			Ok(broadcast) => broadcast,
			Err(_) => {
				return self
					.reject_subscribe(stream, request_id, 404, "Broadcast not found")
					.await;
			}
		};

		let track = match broadcast.track(&msg.track_name) {
			Ok(track) => track,
			Err(err) => {
				return self.reject_subscribe(stream, request_id, 404, &err.to_string()).await;
			}
		};

		let priority = super::priority::from_wire(msg.subscriber_priority);

		// Subscribe before resolving the filter: on a routed broadcast the live edge only
		// becomes readable once the subscription's demand attaches a route, so the edge
		// snapshot has to come after. The resolved range is applied to the preference
		// right below, before anything is served.
		let (cache, mut track) = {
			let subscription = Subscription {
				priority,
				..Default::default()
			};
			match track.subscribe(subscription).await {
				Ok(subscribed) => (track, subscribed),
				Err(err) => {
					return self.reject_subscribe(stream, request_id, 404, &err.to_string()).await;
				}
			}
		};

		// The filter and any fill are relative to the live edge, so snapshot it once:
		// the fill ends exactly where a Next Object subscription begins, which is what
		// lets the draft's current-group join (Next Object plus a StartGroup=1 fill)
		// cover the group with no gap and no overlap.
		let edge = live_edge(&cache);
		let range = subscribe_range(&msg, edge, self.version);
		let _ = track.update(Subscription {
			priority,
			group_start: range.start.map(|start| start.group),
			group_end: range.end.map(|end| end.group),
			..Default::default()
		});

		// A fill reads the group cache through its own consumer, independent of the
		// subscription's cursor.
		let fill = msg
			.fill
			.filter(|_| Filter::is_draft20(self.version))
			.map(|fill| (fill_range(fill, msg.filter, edge.largest), cache));

		// Send SubscribeOk on the stream
		stream.writer.encode(&ietf::SubscribeOk::ID).await?;
		stream
			.writer
			.encode(&ietf::SubscribeOk {
				request_id: match self.version {
					Version::Draft14 | Version::Draft15 | Version::Draft16 => Some(request_id),
					_ => None,
				},
				track_alias: request_id.0,
				// Required once the track has content; a fill-requesting subscriber
				// sizes its backfill against this.
				largest: edge.largest,
				properties: match msg.properties_wanted {
					// Declaring the timescale is what opts the track into timestamps; every
					// object Timestamp below is in these units.
					// We serve the newest group first, matching moq-lite.
					true => ietf::Properties {
						timescale: Some(track.info().timescale),
						group_order: Some(GroupOrder::Descending),
					},
					// INCLUDE_PROPERTIES=0. The field stays present but empty, which also
					// means the track opts out of timestamps for this subscriber.
					false => ietf::Properties::default(),
				},
			})
			.await?;

		// Run the track, cancelling on reader close (Unsubscribe or stream close).
		// The fill (when one was requested) runs alongside on its own fetch stream;
		// its failures reset that stream and never touch the subscription.
		let res = {
			let serve = async {
				match fill {
					Some((fill, cache)) => {
						let fill = self.run_fill(request_id, priority, fill, cache);
						let (res, ()) = futures::join!(self.run_track(track, request_id, range), fill);
						res
					}
					None => self.run_track(track, request_id, range).await,
				}
			};
			let mut serve = std::pin::pin!(serve);
			let mut reader_closed = std::pin::pin!(stream.reader.closed());
			let mut session_closed = std::pin::pin!(self.session.closed());
			kio::wait(|waiter| {
				if let Poll::Ready(res) = waiter.poll_future(serve.as_mut()) {
					return Poll::Ready(res);
				}
				if waiter.poll_future(reader_closed.as_mut()).is_ready()
					|| waiter.poll_future(session_closed.as_mut()).is_ready()
				{
					return Poll::Ready(Ok(()));
				}
				Poll::Pending
			})
			.await
		};

		// Send PublishDone
		let (status, reason) = match &res {
			Ok(()) => (ietf::PublishDoneStatus::TrackEnded, "track ended"),
			Err(_) => (ietf::PublishDoneStatus::InternalError, "internal error"),
		};
		let _ = stream.writer.encode(&ietf::PublishDone::ID).await;
		let _ = stream
			.writer
			.encode(&ietf::PublishDone {
				request_id: match self.version {
					Version::Draft14 | Version::Draft15 | Version::Draft16 => Some(request_id),
					_ => None,
				},
				status_code: status.code(self.version),
				stream_count: 0,
				reason_phrase: reason.into(),
			})
			.await;

		// PUBLISH_DONE is the last thing on this stream, so it needs the acknowledgement too.
		let _ = stream.writer.close().await;

		res
	}

	/// Reject a SUBSCRIBE, ending the request stream.
	///
	/// Takes the whole stream because delivering the error is the other half of the job:
	/// [`Writer`] resets on drop, and a reset discards data the peer has not acknowledged, so
	/// returning here without [`Writer::close`] leaves the subscriber waiting on a request we
	/// already refused.
	async fn reject_subscribe(
		&self,
		mut stream: Stream<S, Version>,
		request_id: RequestId,
		error_code: u64,
		reason: &str,
	) -> Result<(), Error> {
		self.write_subscribe_error(&mut stream.writer, request_id, error_code, reason)
			.await?;

		// The peer dropping the stream once it has the rejection is a normal end, not our failure.
		let _ = stream.writer.close().await;
		Ok(())
	}

	/// Write a subscribe error on the bidi stream writer.
	async fn write_subscribe_error(
		&self,
		writer: &mut Writer<S::SendStream, Version>,
		request_id: RequestId,
		error_code: u64,
		reason: &str,
	) -> Result<(), Error> {
		match self.version {
			Version::Draft14 => {
				writer.encode(&ietf::SubscribeError::ID).await?;
				writer
					.encode(&ietf::SubscribeError {
						request_id,
						error_code,
						reason_phrase: reason.into(),
					})
					.await?;
			}
			Version::Draft15 | Version::Draft16 => {
				writer.encode(&ietf::RequestError::ID).await?;
				writer
					.encode(&ietf::RequestError {
						request_id: Some(request_id),
						error_code,
						reason_phrase: reason.into(),
						retry_interval: 0,
					})
					.await?;
			}
			_ => {
				writer.encode(&ietf::RequestError::ID).await?;
				writer
					.encode(&ietf::RequestError {
						request_id: None,
						error_code,
						reason_phrase: reason.into(),
						retry_interval: 0,
					})
					.await?;
			}
		}
		Ok(())
	}

	/// Serve a track using FuturesUnordered for unlimited concurrent groups.
	async fn run_track(
		&self,
		mut track: track::Subscriber,
		request_id: RequestId,
		range: ServeRange,
	) -> Result<(), Error> {
		// The subscription range is a preference for what the publisher should keep
		// available; the cursor is what this subscriber actually reads, and setting one does
		// not move the other. A requested start is used as given, including one past the
		// live edge, where waiting for that group is the point. Only an absent start falls
		// back to the live edge, since a fresh cursor starts at the oldest cached group and
		// would otherwise replay the whole retained history at once.
		match range.start {
			Some(start) => track.start_at(start.group),
			None => {
				if let Some(latest) = track.latest() {
					track.start_at(latest);
				}
			}
		}
		track.end_at(range.end.map(|end| end.group));

		let mut tasks = FuturesUnordered::new();

		loop {
			// Await the next group while driving the in-flight group futures.
			let group = {
				kio::wait(|waiter| {
					let mut cx = std::task::Context::from_waker(waiter.waker());
					while let std::task::Poll::Ready(Some(())) = tasks.poll_next_unpin(&mut cx) {}
					track.poll_recv_group(waiter)
				})
				.await
			};

			let Some(group) = group? else {
				// Track finished: drain the in-flight group futures, then FIN.
				while tasks.next().await.is_some() {}
				return Ok(());
			};

			let sequence = group.sequence;
			tracing::debug!(subscribe = %request_id, track = %track.name(), sequence, "serving group");

			// Trim the boundary groups to the filter's object bounds, so nothing outside
			// the requested range is sent. Interior groups are served whole.
			let slice = GroupSlice {
				skip: match range.start {
					Some(start) if start.group == sequence => start.object,
					_ => 0,
				},
				until: match range.end {
					Some(end) if end.group == sequence => end.object.map(|object| object.saturating_add(1)),
					_ => None,
				},
			};

			let msg = ietf::GroupHeader {
				track_alias: request_id.0,
				group_id: sequence,
				sub_group_id: 0,
				publisher_priority: 0,
				// Carry per-object timestamps as extension headers (the Timestamp Object
				// Property) so moq-transport peers get the real PTS. The units are the
				// track's, declared once in SUBSCRIBE_OK.
				flags: ietf::GroupFlags {
					has_extensions: true,
					// Only honest when the stream really starts at the group's first
					// object; a trimmed head starts partway through.
					first_object: slice.skip == 0,
					..Default::default()
				},
			};

			let priority = track.subscription().priority;
			let timescale = track.info().timescale;
			tasks.push(
				Self::run_group(
					self.session.clone(),
					msg,
					priority,
					group,
					timescale,
					self.version,
					slice,
				)
				.map(|_| ()),
			);
		}
	}

	async fn run_group(
		session: S,
		msg: ietf::GroupHeader,
		priority: u8,
		mut group: group::Consumer,
		timescale: Timescale,
		version: Version,
		slice: GroupSlice,
	) -> Result<(), Error> {
		let stream = session.open_uni().await.map_err(Error::from_transport)?;

		let mut stream = Writer::new(stream, version);
		stream.set_priority(priority);

		stream.encode(&msg).await?;

		// The next object id to read. Ids below `slice.skip` are consumed without being
		// written, and the first written id goes on the wire as its absolute delta, so
		// the peer sees the true numbering rather than a silently renumbered group.
		let mut index: u64 = 0;
		let mut first_written = true;

		// A subscriber catching up on a cached group takes the whole backlog under one
		// lock; at the live edge the batch comes up empty and the open tail streams
		// chunk by chunk, so forwarding never waits for a frame to complete.
		let mut buf: frame::Buffer = frame::Buffer::new();
		'serve: loop {
			// The filter ends inside this group: everything at `until` and beyond is
			// outside the requested range, so stop without waiting for the group's end.
			if slice.until.is_some_and(|until| index >= until) {
				break;
			}
			// Wait for whatever the group has next, bailing if the peer closes first.
			let step = {
				let mut closed = std::pin::pin!(stream.closed());
				kio::wait(|waiter| {
					if waiter.poll_future(closed.as_mut()).is_ready() {
						return Poll::Ready(Err(Error::Cancel));
					}
					match group.poll_read_frames(waiter, &mut buf) {
						Poll::Pending => group
							.poll_next_frame(waiter)
							.map_ok(|frame| frame.map_or(Step::Done, Step::Partial)),
						res => res.map_ok(|count| if count == 0 { Step::Done } else { Step::Batch }),
					}
				})
				.await
			};

			match step? {
				Step::Batch => {
					for i in 0..buf.filled().len() {
						if slice.until.is_some_and(|until| index >= until) {
							break 'serve;
						}
						let frame = buf.filled()[i].clone();
						if index >= slice.skip {
							let delta = if std::mem::take(&mut first_written) { index } else { 0 };
							Self::write_object_header(&mut stream, &msg, delta, frame.timestamp, timescale, version)
								.await?;
							stream.encode(&(frame.payload.len() as u64)).await?;
							if frame.payload.is_empty() {
								// Have to write the object status too.
								stream.encode(&0u8).await?;
							} else {
								stream.write_chunk(frame.payload).await?;
							}
						}
						index += 1;
						// The fill stamped the group once. A flow-controlled peer can
						// take longer than `latency_max` to accept one batch, so keep
						// stamping or the rest of the group expires mid-serve.
						group.keep_alive();
					}
				}
				Step::Partial(mut frame) => {
					if index < slice.skip {
						// A skipped frame still has to be drained to advance the cursor.
						loop {
							let chunk = {
								let mut closed = std::pin::pin!(stream.closed());
								kio::wait(|waiter| {
									if waiter.poll_future(closed.as_mut()).is_ready() {
										return Poll::Ready(Err(Error::Cancel));
									}
									frame.poll_read_chunk(waiter)
								})
								.await
							};
							if chunk?.is_none() {
								break;
							}
						}
						index += 1;
						continue;
					}

					let delta = if std::mem::take(&mut first_written) { index } else { 0 };
					Self::write_object_header(&mut stream, &msg, delta, frame.timestamp, timescale, version).await?;
					index += 1;

					// Write the size of the frame.
					stream.encode(&frame.size).await?;

					if frame.size == 0 {
						// Have to write the object status too.
						stream.encode(&0u8).await?;
					} else {
						// Stream each chunk of the frame.
						loop {
							let chunk = {
								let mut closed = std::pin::pin!(stream.closed());
								kio::wait(|waiter| {
									if waiter.poll_future(closed.as_mut()).is_ready() {
										return Poll::Ready(Err(Error::Cancel));
									}
									frame.poll_read_chunk(waiter)
								})
								.await
							};

							match chunk? {
								Some(chunk) => {
									stream.write_chunk(chunk).await?;
								}
								None => break,
							}
						}
					}
				}
				Step::Done => break,
			}
		}

		// Consume the writer: close() waits for the peer to acknowledge everything,
		// and taking ownership disarms the Drop fallback that would otherwise reset
		// the finished stream with a spurious Cancel.
		stream.close().await?;

		tracing::debug!(sequence = %msg.group_id, "finished group");

		Ok(())
	}

	/// Write one object's header: the id delta and, when the group carries extensions,
	/// the presentation timestamp.
	///
	/// The first object's delta is its absolute Object ID; every later one is the prior
	/// ID plus the delta plus one, so a contiguous group is a zero delta throughout.
	async fn write_object_header(
		stream: &mut Writer<S::SendStream, Version>,
		msg: &ietf::GroupHeader,
		delta: u64,
		timestamp: Timestamp,
		timescale: Timescale,
		version: Version,
	) -> Result<(), Error> {
		stream.encode(&delta).await?;

		// Per-object extension headers carry the frame's presentation timestamp.
		if msg.flags.has_extensions {
			let mut ext = bytes::BytesMut::new();
			ietf::encode_object_time(&mut ext, timestamp, timescale, version)?;
			stream.encode(&(ext.len() as u64)).await?;
			stream.write_chunk(ext.freeze()).await?;
		}

		Ok(())
	}

	/// Serve a draft-20 fill on its own fetch stream: the requested range, read from the
	/// group cache, capped at the Largest Object snapshot.
	///
	/// A fill is a promise once requested. An empty range opens no stream, but a range we
	/// cannot serve still opens one and resets it right after the FETCH_HEADER, the
	/// draft's fill-failure signal. Nothing here touches the subscription either way.
	async fn run_fill(&self, request_id: RequestId, priority: u8, fill: FillServe, track: track::Consumer) {
		if matches!(fill, FillServe::Empty) {
			return;
		}

		let stream = match self.session.open_uni().await {
			Ok(stream) => stream,
			Err(err) => {
				tracing::debug!(err = %Error::from_transport(err), fill = %request_id, "fill stream failed to open");
				return;
			}
		};
		let mut stream = Writer::new(stream, self.version);
		stream.set_priority(priority);

		let res = async {
			stream.encode(&FetchHeader::TYPE).await?;
			stream.encode(&FetchHeader { request_id }).await?;

			let FillServe::Group { sequence, skip, until } = fill else {
				return Err(Error::Unsupported);
			};

			let group = track.fetch_group(sequence, group::Fetch { priority }).await?;
			Self::write_fill_group(&mut stream, group, sequence, skip, until, self.version).await
		}
		.await;

		match res {
			Ok(()) => {
				// Close waits for the acknowledgement, and consuming the writer disarms
				// the Drop fallback that would reset a finished stream.
				if let Err(err) = stream.close().await {
					tracing::debug!(%err, fill = %request_id, "fill stream close failed");
				} else {
					tracing::debug!(fill = %request_id, "fill complete");
				}
			}
			Err(err) => {
				tracing::debug!(%err, fill = %request_id, "fill failed, resetting its stream");
				stream.abort(&err);
			}
		}
	}

	/// Write one group's frames as draft-20 fetch objects (section 11.4.4).
	///
	/// The first object carries its absolute Group and Object IDs plus the priority;
	/// every later one inherits them and increments the Object ID, so only the
	/// properties (the timestamp) and the payload go on the wire. A fetch object has no
	/// status field: a zero payload length is simply an empty object.
	async fn write_fill_group(
		stream: &mut Writer<S::SendStream, Version>,
		mut group: group::Consumer,
		sequence: u64,
		skip: u64,
		until: Option<u64>,
		version: Version,
	) -> Result<(), Error> {
		let timescale = group.timescale();
		let mut index: u64 = 0;
		let mut first = true;

		let mut buf: frame::Buffer = frame::Buffer::new();
		'serve: loop {
			// The cap is the Largest Object snapshot: the group may keep growing, but
			// everything past the snapshot belongs to the subscription, not the fill.
			if until.is_some_and(|until| index >= until) {
				break;
			}

			let step = {
				let mut closed = std::pin::pin!(stream.closed());
				kio::wait(|waiter| {
					if waiter.poll_future(closed.as_mut()).is_ready() {
						return Poll::Ready(Err(Error::Cancel));
					}
					match group.poll_read_frames(waiter, &mut buf) {
						Poll::Pending => group
							.poll_next_frame(waiter)
							.map_ok(|frame| frame.map_or(Step::Done, Step::Partial)),
						res => res.map_ok(|count| if count == 0 { Step::Done } else { Step::Batch }),
					}
				})
				.await
			};

			match step? {
				Step::Batch => {
					for i in 0..buf.filled().len() {
						if until.is_some_and(|until| index >= until) {
							break 'serve;
						}
						let frame = buf.filled()[i].clone();
						if index >= skip {
							Self::write_fill_object(
								stream,
								sequence,
								index,
								std::mem::take(&mut first),
								frame.timestamp,
								timescale,
								version,
							)
							.await?;
							stream.encode(&(frame.payload.len() as u64)).await?;
							if !frame.payload.is_empty() {
								stream.write_chunk(frame.payload).await?;
							}
						}
						index += 1;
						group.keep_alive();
					}
				}
				Step::Partial(mut frame) => {
					if index < skip {
						// A skipped frame still has to be drained to advance the cursor.
						loop {
							let chunk = {
								let mut closed = std::pin::pin!(stream.closed());
								kio::wait(|waiter| {
									if waiter.poll_future(closed.as_mut()).is_ready() {
										return Poll::Ready(Err(Error::Cancel));
									}
									frame.poll_read_chunk(waiter)
								})
								.await
							};
							if chunk?.is_none() {
								break;
							}
						}
						index += 1;
						continue;
					}

					Self::write_fill_object(
						stream,
						sequence,
						index,
						std::mem::take(&mut first),
						frame.timestamp,
						timescale,
						version,
					)
					.await?;
					index += 1;

					stream.encode(&frame.size).await?;
					loop {
						let chunk = {
							let mut closed = std::pin::pin!(stream.closed());
							kio::wait(|waiter| {
								if waiter.poll_future(closed.as_mut()).is_ready() {
									return Poll::Ready(Err(Error::Cancel));
								}
								frame.poll_read_chunk(waiter)
							})
							.await
						};

						match chunk? {
							Some(chunk) => stream.write_chunk(chunk).await?,
							None => break,
						}
					}
				}
				Step::Done => break,
			}
		}

		Ok(())
	}

	/// Write one fetch object's header: the Serialization Flags, the fields they
	/// declare, and the properties block carrying the timestamp.
	async fn write_fill_object(
		stream: &mut Writer<S::SendStream, Version>,
		sequence: u64,
		object: u64,
		first: bool,
		timestamp: Timestamp,
		timescale: Timescale,
		version: Version,
	) -> Result<(), Error> {
		// Serialization Flags: the two low bits encode the subgroup (00 = subgroup
		// zero), then per-field presence bits.
		const OBJECT_ID: u64 = 0x04;
		const GROUP_ID: u64 = 0x08;
		const PRIORITY: u64 = 0x10;
		const PROPERTIES: u64 = 0x20;

		if first {
			// The first object must carry its absolute Group and Object IDs. Include the
			// priority too: "same as the prior object" has no prior to refer to.
			stream.encode(&(GROUP_ID | OBJECT_ID | PRIORITY | PROPERTIES)).await?;
			stream.encode(&sequence).await?;
			stream.encode(&object).await?;
			stream.encode(&0u8).await?;
		} else {
			// Same group and priority; the Object ID is the prior one plus one.
			stream.encode(&PROPERTIES).await?;
		}

		let mut ext = bytes::BytesMut::new();
		ietf::encode_object_time(&mut ext, timestamp, timescale, version)?;
		stream.encode(&(ext.len() as u64)).await?;
		stream.write_chunk(ext.freeze()).await?;

		Ok(())
	}

	/// Handle a FETCH on its bidi stream.
	async fn run_fetch_stream(self, mut stream: Stream<S, Version>, msg: ietf::Fetch<'_>) -> Result<(), Error> {
		let _subscribe_id = match msg.fetch_type {
			FetchType::Standalone { .. } => {
				return self.reject_fetch(stream, msg.request_id, 500, "not supported").await;
			}
			FetchType::RelativeJoining {
				subscriber_request_id,
				group_offset,
			} => {
				if group_offset != 0 {
					return self.reject_fetch(stream, msg.request_id, 500, "not supported").await;
				}
				subscriber_request_id
			}
			FetchType::AbsoluteJoining { .. } => {
				return self.reject_fetch(stream, msg.request_id, 500, "not supported").await;
			}
		};

		// Send FetchOk/RequestOk
		self.write_fetch_ok(&mut stream.writer, msg.request_id).await?;

		// Create a uni stream with just a FetchHeader and FIN it
		let uni = self.session.open_uni().await.map_err(Error::from_transport)?;
		let mut writer = Writer::new(uni, self.version);
		writer.encode(&FetchHeader::TYPE).await?;
		writer
			.encode(&FetchHeader {
				request_id: msg.request_id,
			})
			.await?;
		writer.close().await?;

		Ok(())
	}

	async fn write_fetch_ok(
		&self,
		writer: &mut Writer<S::SendStream, Version>,
		request_id: RequestId,
	) -> Result<(), Error> {
		match self.version {
			Version::Draft14 => {
				writer.encode(&ietf::FetchOk::ID).await?;
				writer
					.encode(&ietf::FetchOk {
						request_id: Some(request_id),
						group_order: GroupOrder::Descending,
						end_of_track: false,
						end_location: Location { group: 0, object: 0 },
					})
					.await?;
			}
			Version::Draft15 | Version::Draft16 => {
				writer.encode(&ietf::RequestOk::ID).await?;
				writer
					.encode(&ietf::RequestOk {
						request_id: Some(request_id),
					})
					.await?;
			}
			_ => {
				writer.encode(&ietf::RequestOk::ID).await?;
				writer.encode(&ietf::RequestOk { request_id: None }).await?;
			}
		}
		Ok(())
	}

	/// Reject a FETCH, ending the request stream. See [`Self::reject_subscribe`] for why the
	/// close is not optional.
	async fn reject_fetch(
		&self,
		mut stream: Stream<S, Version>,
		request_id: RequestId,
		error_code: u64,
		reason: &str,
	) -> Result<(), Error> {
		self.write_fetch_error(&mut stream.writer, request_id, error_code, reason)
			.await?;

		let _ = stream.writer.close().await;
		Ok(())
	}

	async fn write_fetch_error(
		&self,
		writer: &mut Writer<S::SendStream, Version>,
		request_id: RequestId,
		error_code: u64,
		reason: &str,
	) -> Result<(), Error> {
		match self.version {
			Version::Draft14 => {
				writer.encode(&ietf::FetchError::ID).await?;
				writer
					.encode(&ietf::FetchError {
						request_id,
						error_code,
						reason_phrase: reason.into(),
					})
					.await?;
			}
			Version::Draft15 | Version::Draft16 => {
				writer.encode(&ietf::RequestError::ID).await?;
				writer
					.encode(&ietf::RequestError {
						request_id: Some(request_id),
						error_code,
						reason_phrase: reason.into(),
						retry_interval: 0,
					})
					.await?;
			}
			_ => {
				writer.encode(&ietf::RequestError::ID).await?;
				writer
					.encode(&ietf::RequestError {
						request_id: None,
						error_code,
						reason_phrase: reason.into(),
						retry_interval: 0,
					})
					.await?;
			}
		}
		Ok(())
	}

	/// Bring the peer's view of one namespace in line with the current selection.
	///
	/// A loop writing inline (draft-16+ answering a SUBSCRIBE_NAMESPACE) re-sends
	/// NAMESPACE on that stream, which the receiver treats as a replacement, and
	/// retracts with NAMESPACE_DONE. Otherwise each advertisement rides its own
	/// PUBLISH_NAMESPACE request: an update re-sends PUBLISH_NAMESPACE **on the stream
	/// that already carries it**, since a second stream would leave two claiming one
	/// namespace, and a withdrawal closes the request with PUBLISH_NAMESPACE_DONE.
	async fn sync_namespace(
		&self,
		ns: &mut Namespaces<S>,
		suffix: &crate::PathOwned,
		path: &crate::PathOwned,
	) -> Result<(), Error> {
		let Namespaces {
			peer,
			target,
			watched,
			requests,
		} = ns;

		let Some(watch) = watched.get(suffix) else {
			return Ok(());
		};
		let advert = self.select(watch, peer);
		let refused = watch.refused;
		let wanted = advert.wanted();
		let held = watch.sent.wanted();
		let unchanged = advert == watch.sent;

		if unchanged {
			// Nothing to send. A namespace that is no longer advertisable is no longer
			// pending either, and leaving that set would keep the retry timer armed
			// forever for a wire message that can never happen.
			if !wanted && let Some(watch) = watched.get_mut(suffix) {
				watch.deferred = false;
			}
			return Ok(());
		}

		// A fresh offer waits for what the refusal asked for, whatever brought us back.
		// Only withdrawing and re-announcing clears it, since that builds a fresh entry.
		if wanted && !held && !refused.offerable(web_async::time::Instant::now()) {
			return Ok(());
		}

		let absolute = self.origin.absolute(path).to_owned();
		// Only a fresh PUBLISH_NAMESPACE request can be refused; everything else below
		// either rides a stream the peer already accepted or says nothing at all.
		let mut refused = watch.refused;
		let sent = match target {
			Target::Requests(_) => {
				match (advert.wanted(), requests.get_mut(suffix)) {
					(false, _) => {
						if held {
							tracing::debug!(broadcast = %absolute, "namespace_done");
						}
						self.withdraw_namespace(target, requests, suffix.clone()).await?;
					}
					(true, Some(request)) => {
						tracing::debug!(broadcast = %absolute, "announce update");
						request.stream.writer.encode(&ietf::PublishNamespace::ID).await?;
						request
							.stream
							.writer
							.encode(&ietf::PublishNamespace {
								request_id: request.request_id,
								track_namespace: request.path.as_path(),
								cluster: advert.params(),
							})
							.await?;
					}
					(true, None) => {
						tracing::debug!(broadcast = %absolute, "publish_namespace");
						refused = self
							.advertise_namespace(requests, path, suffix.clone(), advert.params())
							.await?;
					}
				}
				// The peer can reject a fresh PUBLISH_NAMESPACE, which leaves no request
				// behind. Record what it actually holds, so a later route change retries
				// instead of believing the namespace is already advertised.
				match requests.contains_key(suffix) {
					true => advert,
					false => Advert::None,
				}
			}
			Target::Inline(stream) => {
				match (advert.wanted(), held) {
					(true, _) => {
						tracing::debug!(broadcast = %absolute, "namespace");
						stream.writer.encode(&ietf::Namespace::ID).await?;
						stream
							.writer
							.encode(&ietf::Namespace {
								suffix: suffix.as_path(),
								cluster: advert.params(),
							})
							.await?;
					}
					(false, true) => {
						tracing::debug!(broadcast = %absolute, "namespace_done");
						stream.writer.encode(&ietf::NamespaceDone::ID).await?;
						stream
							.writer
							.encode(&ietf::NamespaceDone {
								suffix: suffix.as_path(),
							})
							.await?;
					}
					// Never advertised and still not advertisable: nothing to say.
					(false, false) => {}
				}
				advert
			}
		};

		if let Some(watch) = watched.get_mut(suffix) {
			// A peer that asked not to be offered this again outranks the retry timer;
			// anything else it should hold and does not comes back on one.
			watch.refused = refused;
			watch.deferred = wanted && !sent.wanted() && refused.pending();
			watch.set_sent(sent);
		}
		Ok(())
	}

	/// Open a PUBLISH_NAMESPACE request for one namespace, recording it in `requests`
	/// so an update or withdrawal reuses the same stream. A declined request records
	/// nothing: a peer that wants none of this rejects each one and stays connected.
	///
	/// Returns what the refusal, if any, said about coming back.
	async fn advertise_namespace(
		&self,
		requests: &mut HashMap<crate::PathOwned, NamespaceRequest<S>>,
		path: &crate::PathOwned,
		suffix: crate::PathOwned,
		cluster: Option<cluster::Advert>,
	) -> Result<Refused, Error> {
		let request_id = self.control.next_request_id().await?;

		// Bounded, because an advertisement holds its stream for as long as the namespace
		// lives: a peer whose concurrent-stream limit we have filled makes this open block,
		// and the withdrawals queued behind it are the only thing that would free a slot.
		// Giving up records nothing, so the namespace is simply retried later.
		let Some(request) = self.open_request().await? else {
			tracing::debug!(broadcast = %self.origin.absolute(path), "no stream for the advertisement");
			return Ok(Refused::No);
		};
		let mut request = request;

		request.writer.encode(&ietf::PublishNamespace::ID).await?;
		request
			.writer
			.encode(&ietf::PublishNamespace {
				request_id,
				track_namespace: path.as_path(),
				cluster,
			})
			.await?;

		// Bounded for the same reason the open is: a peer that takes the stream and answers
		// nothing would park this loop forever, and every withdrawal queued behind it.
		let Some((type_id, mut data)) = Self::read_response(&mut request).await? else {
			tracing::debug!(broadcast = %self.origin.absolute(path), "no answer to the advertisement");
			return Ok(Refused::No);
		};

		match (self.version, type_id) {
			(Version::Draft14, ietf::PublishNamespaceOk::ID) => {
				let msg = ietf::PublishNamespaceOk::decode_msg(&mut data, self.version)?;
				tracing::debug!(message = ?msg, "publish namespace ok");
			}
			(Version::Draft14, ietf::PublishNamespaceError::ID) => {
				let msg = ietf::PublishNamespaceError::decode_msg(&mut data, self.version)?;
				tracing::warn!(message = ?msg, "publish namespace error");
				// Draft-14's error carries no retry interval, so our own backoff stands.
				return Ok(Refused::No);
			}
			(_, ietf::RequestOk::ID) => {
				let msg = ietf::RequestOk::decode_msg(&mut data, self.version)?;
				tracing::debug!(message = ?msg, "publish namespace ok");
			}
			(_, ietf::RequestError::ID) => {
				let msg = ietf::RequestError::decode_msg(&mut data, self.version)?;
				tracing::warn!(message = ?msg, "publish namespace error");
				return Ok(self.refusal(msg.retry_interval));
			}
			_ => return Err(Error::UnexpectedMessage),
		}

		requests.insert(
			suffix,
			NamespaceRequest {
				path: path.clone(),
				request_id,
				stream: request,
			},
		);
		Ok(Refused::No)
	}

	/// How to read a refusal's retry interval, in milliseconds.
	///
	/// Draft-14/15 errors carry no interval, so a decoded 0 there says nothing and our own
	/// backoff stands. Everywhere else 0 is the peer asking not to be offered this again,
	/// which is what keeps a permanent refusal (unauthorized, uninterested) from becoming
	/// a request every few seconds for the life of the session.
	fn refusal(&self, retry_interval: u64) -> Refused {
		match (self.version, retry_interval) {
			(Version::Draft14 | Version::Draft15, _) => Refused::No,
			(_, 0) => Refused::Never,
			(_, ms) => Refused::Until(web_async::time::Instant::now() + std::time::Duration::from_millis(ms)),
		}
	}

	/// Open a stream for one advertisement, or `None` if the peer did not give us one in
	/// time.
	///
	/// The announce loop is single-threaded over origin updates, so an open that parks
	/// forever parks everything, including the unannounces that release the streams the
	/// peer is waiting on us to retire. Failing instead keeps the loop moving.
	async fn open_request(&self) -> Result<Option<Stream<S, Version>>, Error> {
		let mut open = std::pin::pin!(Stream::open(&self.session, self.version));
		let mut timeout = kio::time::Deadline::after(ADVERTISE_TIMEOUT);

		kio::wait(|waiter| {
			if let Poll::Ready(res) = waiter.poll_future(open.as_mut()) {
				return Poll::Ready(res.map(Some));
			}
			if timeout.poll(waiter).is_ready() {
				return Poll::Ready(Ok(None));
			}
			Poll::Pending
		})
		.await
	}

	/// Read the peer's answer to one advertisement, or `None` if it did not answer in time.
	///
	/// Bounded for the same reason [`Self::open_request`] is, and it is the same peer
	/// behavior seen a step later: a stream the peer accepts and never answers on holds the
	/// loop just as effectively as one it never grants. Giving up records nothing, so the
	/// namespace stays outstanding and the retry re-offers it.
	async fn read_response(request: &mut Stream<S, Version>) -> Result<Option<(u64, bytes::Bytes)>, Error> {
		let mut read = std::pin::pin!(async {
			let type_id: u64 = request.reader.decode().await?;
			let size: u16 = request.reader.decode().await?;
			let data = request.reader.read_exact(size as usize).await?;
			Ok::<_, Error>((type_id, data))
		});
		let mut timeout = kio::time::Deadline::after(ADVERTISE_TIMEOUT);

		kio::wait(|waiter| {
			if let Poll::Ready(res) = waiter.poll_future(read.as_mut()) {
				return Poll::Ready(res.map(Some));
			}
			if timeout.poll(waiter).is_ready() {
				return Poll::Ready(Ok(None));
			}
			Poll::Pending
		})
		.await
	}

	/// Withdraw an advertised namespace: NAMESPACE_DONE inline, or PUBLISH_NAMESPACE_DONE
	/// closing the request that carried it.
	async fn withdraw_namespace(
		&self,
		target: &mut Target<S>,
		requests: &mut HashMap<crate::PathOwned, NamespaceRequest<S>>,
		suffix: crate::PathOwned,
	) -> Result<(), Error> {
		match target {
			Target::Requests(_) => {
				if let Some(mut request) = requests.remove(&suffix) {
					// Draft-17+ removed PUBLISH_NAMESPACE_DONE: the FIN below is the whole
					// withdrawal. Sending it anyway puts the type on the wire before the
					// body fails to encode, and a receiver reading 0x09 there has no choice
					// but to treat it as a protocol violation (see
					// `Subscriber::terminal_publish_namespace`).
					if matches!(self.version, Version::Draft14 | Version::Draft15 | Version::Draft16) {
						// Best effort: the peer may already be gone.
						let _ = request
							.stream
							.writer
							.encode_message(&ietf::PublishNamespaceDone {
								track_namespace: request.path.as_path(),
								request_id: request.request_id,
							})
							.await;
					}

					// The withdrawal rides this request's own stream, which drops with it, so
					// it needs the acknowledgement before the drop-time reset can discard it.
					let _ = request.stream.writer.close().await;
				}
			}
			Target::Inline(stream) => {
				stream.writer.encode(&ietf::NamespaceDone::ID).await?;
				stream
					.writer
					.encode(&ietf::NamespaceDone {
						suffix: suffix.as_path(),
					})
					.await?;
			}
		}
		Ok(())
	}

	/// Close out every open PUBLISH_NAMESPACE request. A no-op for a loop whose entries
	/// ride the SUBSCRIBE_NAMESPACE stream itself, which retracts them by ending.
	async fn withdraw_requests(
		&self,
		target: &mut Target<S>,
		requests: &mut HashMap<crate::PathOwned, NamespaceRequest<S>>,
	) {
		let suffixes: Vec<crate::PathOwned> = requests.keys().cloned().collect();
		for suffix in suffixes {
			let _ = self.withdraw_namespace(target, requests, suffix).await;
		}
	}

	/// Advertise every namespace we can, without waiting to be asked.
	///
	/// moq-transport itself says nothing about which of the two discovery messages a peer
	/// expects, and the peers that never send SUBSCRIBE_NAMESPACE are exactly the ones
	/// expecting a publisher to announce itself, so the default has to be to announce. A
	/// peer that would rather ask says so with the MoQ Solicit extension
	/// ([`solicit`](super::solicit)),
	/// and then this loop does nothing and
	/// [`Self::run_subscribe_namespace_stream`] carries the advertisements instead.
	/// Exactly one of the two is live, which is what keeps the peer from hearing a
	/// namespace twice.
	pub async fn run_publish_namespaces(self) -> Result<(), Error> {
		if self.requires_solicitation().await {
			return Ok(());
		}

		// The cluster extension changes what an advertisement carries, so nothing can be
		// sent until the peer's SETUP says whether it speaks it.
		let peer = self.peer().await;

		// Split horizon, as the solicited loop applies it: never advertise a route back
		// to the peer it came from.
		let origin = self.excluding(&peer);

		let ns = Namespaces::new(peer, Target::Requests(None));
		self.run_namespaces(origin, crate::Path::empty().to_owned(), ns).await
	}

	/// Handle a SUBSCRIBE_NAMESPACE on its bidi stream.
	///
	/// All the announce state is local to this task (mirroring `lite::Publisher`'s
	/// announce handling): whatever this subscription advertised is withdrawn
	/// when its stream ends. It only advertises anything when the peer asked to be told
	/// on request; otherwise [`Self::run_publish_namespaces`] has already said it all.
	async fn run_subscribe_namespace_stream(
		self,
		mut stream: Stream<S, Version>,
		msg: ietf::SubscribeNamespace<'_>,
	) -> Result<(), Error> {
		let prefix = msg.namespace.to_owned();

		tracing::debug!(prefix = %self.origin.absolute(&prefix), "subscribe_namespace stream");

		// A prefix outside our scope (empty origin, or a token that doesn't grant it)
		// just means we have nothing to announce; respond with an empty set rather than
		// erroring, which would look fatal to the peer.
		let origin = self
			.origin
			.scope(&[prefix.as_path()])
			.unwrap_or_else(|| self.origin.empty());

		// Send OK response
		match self.version {
			Version::Draft14 => {
				stream.writer.encode(&ietf::SubscribeNamespaceOk::ID).await?;
				stream
					.writer
					.encode(&ietf::SubscribeNamespaceOk {
						request_id: msg.request_id,
					})
					.await?;
			}
			Version::Draft15 | Version::Draft16 => {
				stream.writer.encode(&ietf::RequestOk::ID).await?;
				stream
					.writer
					.encode(&ietf::RequestOk {
						request_id: Some(msg.request_id),
					})
					.await?;
			}
			_ => {
				stream.writer.encode(&ietf::RequestOk::ID).await?;
				stream.writer.encode(&ietf::RequestOk { request_id: None }).await?;
			}
		}

		// The extension changes what an advertisement carries, so nothing can be
		// sent until the peer's SETUP says whether it speaks it.
		let peer = self.peer().await;
		// Register the split-horizon peer on the announce cursor too. The origin
		// model uses this exposure to park a reflected copy before it can replace
		// the source we are currently advertising to that peer.
		let origin = match self.exclude(&peer) {
			crate::Origin::UNKNOWN => origin,
			exclude => origin.excluding(exclude),
		};

		// Draft-14/15 predate NAMESPACE, so they answer with their own PUBLISH_NAMESPACE
		// requests and keep this stream open for the subscription's lifetime.
		let target = match self.version {
			Version::Draft14 | Version::Draft15 => Target::Requests(Some(stream)),
			_ => Target::Inline(stream),
		};

		// Unless the peer asked to be told only on request, it has already heard all of
		// this as unsolicited PUBLISH_NAMESPACE. Repeating it here would leave it holding
		// two sources for one namespace, so this stream carries nothing and simply stays
		// open until the peer is done with it.
		let origin = match self.requires_solicitation().await {
			true => origin,
			false => origin.empty(),
		};

		let ns = Namespaces::new(peer, target);
		self.run_namespaces(origin, prefix, ns).await
	}

	/// Forward origin (un)announces to the peer until the loop ends.
	///
	/// Shared by both announce paths: they differ in where the advertisements go
	/// ([`Target`]) and where the origin is rooted (`prefix`, empty when nothing asked
	/// for a subset).
	async fn run_namespaces(
		&self,
		origin: origin::Consumer,
		prefix: crate::PathOwned,
		mut ns: Namespaces<S>,
	) -> Result<(), Error> {
		let mut announced = origin.announced();

		let mut linger = kio::time::Deadline::new();

		// When to re-offer whatever the peer should hold and doesn't, and how long to wait
		// the next time that fails. Jittered so a relay's namespaces don't all come back on
		// the same tick.
		let mut retry = kio::time::Deadline::new();
		let mut retry_at: Option<web_async::time::Instant> = None;
		let mut retry_delay = RETRY_BASE;

		// Stream updates (origin (un)announces plus watched route and demand
		// changes), bailing if the peer closes its side first.
		let res = loop {
			linger.set(Self::linger_deadline(&ns.watched));

			match ns.watched.values().any(|watch| watch.deferred) {
				// Arm on the edge, so a turn that changes nothing else doesn't push the
				// deadline out forever.
				true => retry_at = retry_at.or_else(|| Some(web_async::time::Instant::now() + jitter(retry_delay))),
				false => {
					retry_at = None;
					retry_delay = RETRY_BASE;
				}
			}
			retry.set(retry_at);

			let event = {
				let mut closed = std::pin::pin!(ns.target.closed());
				let watched = &mut ns.watched;
				kio::wait(|waiter| {
					if let Poll::Ready(res) = waiter.poll_future(closed.as_mut()) {
						return Poll::Ready(NamespaceEvent::Closed(res));
					}
					if let Poll::Ready(update) = announced.poll_next(waiter) {
						return Poll::Ready(NamespaceEvent::Update(update));
					}
					if retry.poll(waiter).is_ready() {
						return Poll::Ready(NamespaceEvent::Retry);
					}
					// Stamped per poll rather than kept: the turn always ends in a
					// `Ready` below once it fires, so it never has to survive.
					let fired = linger.poll(waiter).is_ready().then(web_async::time::Instant::now);
					match Self::poll_watched(watched, fired, waiter) {
						Poll::Ready(Watch::Changed(path)) => return Poll::Ready(NamespaceEvent::Routes(path)),
						Poll::Ready(Watch::Idle(path)) => return Poll::Ready(NamespaceEvent::Idle(path)),
						Poll::Pending => {}
					}
					match fired.is_some() {
						true => Poll::Ready(NamespaceEvent::Linger),
						false => Poll::Pending,
					}
				})
				.await
			};

			match event {
				NamespaceEvent::Closed(res) => break res,
				NamespaceEvent::Linger => continue,
				NamespaceEvent::Retry => {
					retry_at = None;
					retry_delay = (retry_delay * 2).min(RETRY_MAX);

					// A minimum wait the peer named is enforced by `sync_namespace`, which
					// every path goes through, so a namespace still inside one simply
					// makes no offer this turn. The next sweep is at most RETRY_MAX away.
					let deferred: Vec<crate::PathOwned> = ns
						.watched
						.iter()
						.filter(|(_, watch)| watch.deferred)
						.map(|(suffix, _)| suffix.clone())
						.collect();

					for suffix in deferred {
						let path = prefix.join(&suffix);
						self.sync_namespace(&mut ns, &suffix, &path).await?;
					}
				}
				NamespaceEvent::Update(None) => {
					// The origin is gone: withdraw everything, then finish the
					// stream and wait for delivery.
					self.withdraw_requests(&mut ns.target, &mut ns.requests).await;
					let Some(stream) = ns.target.stream() else {
						return Ok(());
					};
					stream.writer.finish()?;
					return stream.writer.closed().await;
				}
				NamespaceEvent::Update(Some(crate::announce::Update { path, broadcast })) => {
					let suffix = path
						.strip_prefix(&prefix)
						.expect("origin returned invalid path")
						.to_owned();
					let path = path.to_owned();

					match broadcast {
						Some(broadcast) => {
							ns.watched.insert(suffix.clone(), Watched::new(broadcast));
							self.sync_namespace(&mut ns, &suffix, &path).await?;
						}
						None => {
							// Only close out namespaces the peer actually saw.
							let held = ns.watched.remove(&suffix).is_some_and(|watch| watch.sent.wanted());
							if held {
								tracing::debug!(broadcast = %self.origin.absolute(&path), "namespace_done");
								self.withdraw_namespace(&mut ns.target, &mut ns.requests, suffix)
									.await?;
							}
						}
					}
				}
				NamespaceEvent::Routes(suffix) => {
					let path = prefix.join(&suffix);
					self.sync_namespace(&mut ns, &suffix, &path).await?;
				}
				NamespaceEvent::Idle(suffix) => {
					if let Some(watch) = ns.watched.get_mut(&suffix) {
						watch.idle_at = Some(web_async::time::Instant::now());
					}
				}
			}
		};

		// This loop's advertisements die with it.
		self.withdraw_requests(&mut ns.target, &mut ns.requests).await;

		res
	}
}

/// One draft-14/15 advertisement: the PUBLISH_NAMESPACE request it rode on and
/// what closes it out with PUBLISH_NAMESPACE_DONE.
struct NamespaceRequest<S: web_transport_trait::Session> {
	path: crate::PathOwned,
	request_id: RequestId,
	stream: Stream<S, Version>,
}

#[cfg(test)]
mod group_priority_test {
	use super::*;
	use crate::lite::test_transport::SinkSession;

	/// The model's `Subscription::priority` is higher-first ("higher values preempt
	/// lower ones"), matching the transport trait's send order, so a group stream must
	/// receive the model value unchanged. An inversion here would transmit the
	/// LOWEST-priority track first under contention.
	#[tokio::test]
	async fn group_stream_preserves_model_priority() {
		let log = crate::lite::test_transport::Log::default();
		let session = SinkSession::new(log.clone());

		let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "test", None);
		let mut group = track.create_group(group::Info { sequence: 0 }).unwrap();
		group
			.write_frame(crate::Timestamp::from_millis(0).unwrap(), b"hello".as_slice())
			.unwrap();
		let consumer = group.consume();
		group.finish().unwrap();

		let msg = ietf::GroupHeader {
			track_alias: 0,
			group_id: 0,
			sub_group_id: 0,
			publisher_priority: 0,
			flags: Default::default(),
		};

		Publisher::<SinkSession>::run_group(
			session,
			msg,
			200,
			consumer,
			Timescale::default(),
			Version::Draft14,
			GroupSlice::default(),
		)
		.await
		.unwrap();

		assert_eq!(
			log.priorities(),
			vec![200],
			"model priority must pass through unchanged"
		);
	}

	/// `run_group` takes two routes to the wire: complete frames come out of a batch
	/// read, while an in-flight frame streams chunk by chunk. The two must encode
	/// identically, or a subscriber catching up sees different bytes than one at the
	/// live edge.
	#[tokio::test]
	async fn batched_and_streamed_frames_encode_identically() {
		const FRAMES: usize = 12;
		const PAYLOAD: usize = 7;

		fn header() -> ietf::GroupHeader {
			ietf::GroupHeader {
				track_alias: 0,
				group_id: 0,
				sub_group_id: 0,
				publisher_priority: 0,
				flags: Default::default(),
			}
		}

		fn payload(i: usize) -> Vec<u8> {
			vec![i as u8; PAYLOAD]
		}

		fn timestamp(i: usize) -> crate::Timestamp {
			crate::Timestamp::from_millis(i as u64 * 10).unwrap()
		}

		// Every frame complete before serving starts: the batch read takes them all.
		let batched = {
			let log = crate::lite::test_transport::Log::default();
			let session = SinkSession::new(log.clone());
			let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "test", None);
			let mut group = track.create_group(group::Info { sequence: 0 }).unwrap();
			for i in 0..FRAMES {
				group.write_frame(timestamp(i), payload(i).as_slice()).unwrap();
			}
			let consumer = group.consume();
			group.finish().unwrap();

			Publisher::<SinkSession>::run_group(
				session,
				header(),
				0,
				consumer,
				Timescale::default(),
				Version::Draft14,
				GroupSlice::default(),
			)
			.await
			.unwrap();
			log.writes.lock().unwrap().clone()
		};

		// Every frame still open when the publisher reaches it, so each one streams a
		// chunk at a time down the `Step::Partial` path.
		let streamed = {
			let log = crate::lite::test_transport::Log::default();
			let session = SinkSession::new(log.clone());
			let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "test", None);
			let mut group = track.create_group(group::Info { sequence: 0 }).unwrap();
			let consumer = group.consume();

			let mut serve = std::pin::pin!(Publisher::<SinkSession>::run_group(
				session,
				header(),
				0,
				consumer,
				Timescale::default(),
				Version::Draft14,
				GroupSlice::default(),
			));
			// Past the group header, parked with nothing to send.
			assert!(futures::poll!(serve.as_mut()).is_pending());

			for i in 0..FRAMES {
				{
					let mut frame = group
						.create_frame(crate::frame::Info {
							size: PAYLOAD as u64,
							timestamp: timestamp(i),
						})
						.unwrap();
					// The publisher is parked on this frame, so each chunk is forwarded
					// before the next one is written.
					for byte in payload(i) {
						frame.write(&[byte][..]).unwrap();
						assert!(futures::poll!(serve.as_mut()).is_pending());
					}
					frame.finish().unwrap();
				}
				assert!(futures::poll!(serve.as_mut()).is_pending());
			}

			group.finish().unwrap();
			serve.await.unwrap();
			log.writes.lock().unwrap().clone()
		};

		assert!(!batched.is_empty(), "the group produced no bytes");
		assert_eq!(batched, streamed, "batched and streamed writes must encode the same");
	}

	/// A frame still being written must reach the wire as it fills rather than waiting
	/// for the whole thing: the batch read has to yield to the open tail.
	#[tokio::test]
	async fn an_open_frame_streams_before_it_completes() {
		let log = crate::lite::test_transport::Log::default();
		let session = SinkSession::new(log.clone());

		let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "test", None);
		let mut group = track.create_group(group::Info { sequence: 0 }).unwrap();
		let consumer = group.consume();

		// A large frame, opened but far from complete.
		let mut frame = group
			.create_frame(crate::frame::Info {
				size: 4096,
				timestamp: crate::Timestamp::from_millis(0).unwrap(),
			})
			.unwrap();
		frame.write(&[7u8; 512][..]).unwrap();

		let msg = ietf::GroupHeader {
			track_alias: 0,
			group_id: 0,
			sub_group_id: 0,
			publisher_priority: 0,
			flags: Default::default(),
		};

		let mut serving = std::pin::pin!(Publisher::<SinkSession>::run_group(
			session,
			msg,
			0,
			consumer,
			Timescale::default(),
			Version::Draft14,
			GroupSlice::default(),
		));
		// Let it run until it blocks on the rest of the frame.
		assert!(futures::poll!(serving.as_mut()).is_pending());

		let written = log.writes.lock().unwrap().len();
		assert!(
			written >= 512,
			"the open frame's first chunk must be forwarded before it completes, wrote {written}"
		);
	}
}

#[cfg(test)]
mod subscribe_cursor_test {
	use super::*;
	use crate::lite::test_transport::{Log, SinkSession};

	/// A subscription's cursor starts at the oldest cached group, so serving it verbatim
	/// replays every retained group at once, each on its own stream. Relays reject the burst
	/// and players skip straight back to the live edge, so the catch-up is pure waste.
	#[tokio::test]
	async fn a_subscribe_is_served_from_the_live_edge() {
		let log = Log::default();
		let session = SinkSession::new(log.clone());

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let peer_setup = peer::PeerSetup::default();
		peer_setup.set(peer::Peer::default());

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			peer_setup,
			Version::Draft16,
		);

		let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "video", None);
		for sequence in 0..4 {
			let mut group = track.create_group(group::Info { sequence }).unwrap();
			group
				.write_frame(crate::Timestamp::from_millis(0).unwrap(), b"frame".as_slice())
				.unwrap();
			group.finish().unwrap();
		}

		let subscriber = track.subscribe(None);
		track.finish().unwrap();

		publisher
			.run_track(subscriber, RequestId(1), ServeRange::default())
			.await
			.unwrap();

		// `run_group` sets the priority once per stream it opens, so this counts groups served.
		assert_eq!(log.priorities().len(), 1, "only group 3 should have been served");
	}
}

#[cfg(test)]
mod serve_tests {
	use super::*;
	use crate::lite::test_transport::{Log, ScriptedSession, SinkSession};

	fn occurrences(log: &Log, needle: &[u8]) -> usize {
		let writes = log.writes.lock().unwrap();
		writes.windows(needle.len()).filter(|window| *window == needle).count()
	}

	fn timestamp() -> crate::Timestamp {
		crate::Timestamp::from_millis(0).unwrap()
	}

	/// A publisher whose origin serves one broadcast ("room") with one track ("video").
	struct Serve {
		publisher: Publisher<ScriptedSession>,
		session: ScriptedSession,
		log: Log,
		track: track::Producer,
		_origin: origin::Producer,
		_broadcast: crate::broadcast::Producer,
	}

	fn serve(version: Version) -> Serve {
		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let mut broadcast = origin
			.create_broadcast("room", crate::broadcast::Route::new().with_announce(true))
			.unwrap();
		let track = broadcast.create_track("video", None).unwrap();

		let session = ScriptedSession::per_stream(vec![Vec::new()]);
		let log = session.log.clone();

		let peer_setup = peer::PeerSetup::default();
		peer_setup.set(peer::Peer::default());

		let publisher = Publisher::new(
			session.clone(),
			origin.consume(),
			Control::new(None, false),
			None,
			peer_setup,
			version,
		);

		Serve {
			publisher,
			session,
			log,
			track,
			_origin: origin,
			_broadcast: broadcast,
		}
	}

	/// A distinctive request id, so `[FetchHeader::TYPE, REQUEST_ID]` is a usable needle.
	const REQUEST_ID: u64 = 0x2B;

	fn subscribe(filter: Filter, fill: Option<ietf::Fill>) -> ietf::Subscribe<'static> {
		ietf::Subscribe {
			request_id: RequestId(REQUEST_ID),
			track_namespace: crate::Path::new("room"),
			track_name: "video".into(),
			subscriber_priority: 128,
			group_order: GroupOrder::Descending,
			filter,
			fill,
			properties_wanted: true,
		}
	}

	/// The bytes that begin every fill fetch stream.
	const FETCH_STREAM: &[u8] = &[FetchHeader::TYPE as u8, REQUEST_ID as u8];

	/// Serve `msg` against the live track, then finish the track so the subscription
	/// completes. Subscribing after the finish would be rejected instead of served.
	async fn run_live(h: &mut Serve, msg: ietf::Subscribe<'static>) {
		// `create_broadcast` registers the broadcast from a spawned task, so yield to the
		// runtime before subscribing or the lookup 404s.
		tokio::time::sleep(std::time::Duration::from_millis(1)).await;

		let stream = Stream::open(&h.session, h.publisher.version).await.unwrap();
		let mut serve = std::pin::pin!(h.publisher.clone().run_subscribe_stream(stream, msg));

		// Everything cached serves immediately; the subscription then parks at the live
		// edge, which is where the track is allowed to finish.
		for _ in 0..200 {
			assert!(
				futures::poll!(serve.as_mut()).is_pending(),
				"subscription ended before the track finished"
			);
		}

		h.track.finish().unwrap();
		serve.await.unwrap();
	}

	/// The draft's canonical current-group join: a Next Object subscription plus a
	/// StartGroup=1 fill. The published head arrives exactly once, on a fetch stream,
	/// and the subscription starts past the snapshot, so nothing is duplicated and
	/// nothing outside the requested range is sent.
	#[tokio::test]
	async fn canonical_join_serves_the_head_on_a_fetch_stream() {
		let mut h = serve(Version::Draft20);

		let mut group = h.track.create_group(group::Info { sequence: 0 }).unwrap();
		for payload in [b"head-0", b"head-1", b"head-2"] {
			group.write_frame(timestamp(), payload.as_slice()).unwrap();
		}
		group.finish().unwrap();

		run_live(
			&mut h,
			subscribe(
				Filter::NextObject,
				Some(ietf::Fill {
					filter: Some(Filter::Relative(1)),
					range_filters: false,
				}),
			),
		)
		.await;

		assert_eq!(occurrences(&h.log, FETCH_STREAM), 1, "expected one fill fetch stream");
		for payload in [b"head-0", b"head-1", b"head-2"] {
			assert_eq!(
				occurrences(&h.log, payload),
				1,
				"each object exactly once, via the fill"
			);
		}
		assert!(h.log.resets().is_empty(), "a served fill must not reset");
	}

	/// moq-lite's own join over draft-20: Relative(1) names the start of the current
	/// group, so the cache replays the whole group on the subscription stream.
	#[tokio::test]
	async fn relative_one_replays_the_current_group() {
		let mut h = serve(Version::Draft20);

		let mut group = h.track.create_group(group::Info { sequence: 0 }).unwrap();
		for payload in [b"head-0", b"head-1", b"head-2"] {
			group.write_frame(timestamp(), payload.as_slice()).unwrap();
		}
		group.finish().unwrap();

		run_live(&mut h, subscribe(Filter::Relative(1), None)).await;

		assert_eq!(occurrences(&h.log, FETCH_STREAM), 0, "no fill was requested");
		for payload in [b"head-0", b"head-1", b"head-2"] {
			assert_eq!(occurrences(&h.log, payload), 1, "the whole group replays in range");
		}
	}

	/// A Next Object subscription never receives the already-published head of the
	/// current group: everything below the snapshot is outside the requested range.
	#[tokio::test]
	async fn next_object_does_not_replay_the_head() {
		let mut h = serve(Version::Draft20);

		let mut group = h.track.create_group(group::Info { sequence: 0 }).unwrap();
		for payload in [b"head-0", b"head-1", b"head-2"] {
			group.write_frame(timestamp(), payload.as_slice()).unwrap();
		}
		group.finish().unwrap();

		run_live(&mut h, subscribe(Filter::NextObject, None)).await;

		for payload in [b"head-0", b"head-1", b"head-2"] {
			assert_eq!(
				occurrences(&h.log, payload),
				0,
				"the head is outside the requested range"
			);
		}
	}

	/// A fill spanning several groups is refused by resetting the fetch stream right
	/// after the FETCH_HEADER, the draft's fill-failure signal; the subscription itself
	/// is untouched and still completes.
	#[tokio::test]
	async fn a_multi_group_fill_resets_its_stream() {
		let mut h = serve(Version::Draft20);

		for sequence in 0..2 {
			let mut group = h.track.create_group(group::Info { sequence }).unwrap();
			group.write_frame(timestamp(), b"frame".as_slice()).unwrap();
			group.finish().unwrap();
		}

		run_live(
			&mut h,
			subscribe(
				Filter::NextObject,
				Some(ietf::Fill {
					filter: Some(Filter::Relative(2)),
					range_filters: false,
				}),
			),
		)
		.await;

		assert_eq!(occurrences(&h.log, FETCH_STREAM), 1, "the promised stream still opens");
		assert_eq!(h.log.resets().len(), 1, "and is reset as the failure signal");
	}

	/// A fill against an empty track has an empty range: no fetch stream is owed.
	#[tokio::test]
	async fn an_empty_track_opens_no_fill_stream() {
		let mut h = serve(Version::Draft20);

		run_live(
			&mut h,
			subscribe(
				Filter::NextObject,
				Some(ietf::Fill {
					filter: Some(Filter::Relative(1)),
					range_filters: false,
				}),
			),
		)
		.await;

		assert_eq!(occurrences(&h.log, FETCH_STREAM), 0);
		assert!(h.log.resets().is_empty());
	}

	/// The filter's object bounds trim what `run_group` writes: the skipped head is not
	/// sent, the first written object's delta is its absolute id, and a capped tail stops
	/// early. Extensions are off so the wire is just deltas, sizes, and payloads.
	#[tokio::test]
	async fn run_group_honors_the_slice() {
		fn header() -> ietf::GroupHeader {
			ietf::GroupHeader {
				track_alias: 0,
				group_id: 0,
				sub_group_id: 0,
				publisher_priority: 0,
				flags: ietf::GroupFlags {
					first_object: false,
					..Default::default()
				},
			}
		}

		async fn serve_slice(slice: GroupSlice) -> Vec<u8> {
			let log = Log::default();
			let session = SinkSession::new(log.clone());
			let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "test", None);
			let mut group = track.create_group(group::Info { sequence: 0 }).unwrap();
			for payload in [b"aa", b"bb", b"cc", b"dd"] {
				group.write_frame(timestamp(), payload.as_slice()).unwrap();
			}
			let consumer = group.consume();
			group.finish().unwrap();

			Publisher::<SinkSession>::run_group(
				session,
				header(),
				0,
				consumer,
				Timescale::default(),
				Version::Draft20,
				slice,
			)
			.await
			.unwrap();

			log.writes.lock().unwrap().clone()
		}

		// Skip 2: the head is dropped and the first delta is the absolute id 2.
		let trimmed = serve_slice(GroupSlice { skip: 2, until: None }).await;
		assert!(
			trimmed.ends_with(&[0x02, 0x02, b'c', b'c', 0x00, 0x02, b'd', b'd']),
			"expected delta 2 then cc, delta 0 then dd, got {trimmed:x?}"
		);

		// Until 2: only the head is written, stopping before the cap.
		let capped = serve_slice(GroupSlice {
			skip: 0,
			until: Some(2),
		})
		.await;
		assert!(
			capped.ends_with(&[0x00, 0x02, b'a', b'a', 0x00, 0x02, b'b', b'b']),
			"expected aa then bb only, got {capped:x?}"
		);
		assert_eq!(
			capped.windows(2).filter(|w| *w == b"cc").count(),
			0,
			"the cap excludes cc"
		);
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::lite::test_transport::SinkSession;

	async fn settle() {
		tokio::time::sleep(std::time::Duration::from_millis(1)).await;
	}

	fn occurrences(log: &crate::lite::test_transport::Log, needle: &[u8]) -> usize {
		let writes = log.writes.lock().unwrap();
		writes.windows(needle.len()).filter(|window| *window == needle).count()
	}

	/// A SETUP slot already filled with what the peer declared. The announce loops block
	/// on it, so a test that leaves it empty is a test that never advertises.
	fn declared(solicit: Option<bool>) -> peer::PeerSetup {
		let slot = peer::PeerSetup::default();
		slot.set(peer::Peer {
			solicit,
			..Default::default()
		});
		slot
	}

	/// A peer that requires solicitation, which is what hands the advertisements to the
	/// SUBSCRIBE_NAMESPACE stream.
	fn requires_solicitation() -> peer::PeerSetup {
		declared(Some(true))
	}

	/// A publisher for a peer assigned `assigned`, over an origin holding two
	/// broadcasts: `from/peer`, whose only route flows through `assigned`, and
	/// `from/us`, which does not. The producers are returned so the routes outlive
	/// the assertions.
	async fn echo_harness(
		assigned: crate::Origin,
	) -> (
		Publisher<SinkSession>,
		origin::Consumer,
		Vec<crate::broadcast::Producer>,
	) {
		let other = crate::Origin::new(778).unwrap();
		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let consumer = origin.consume();

		let session = crate::lite::test_transport::SinkSession::new(Default::default());
		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			Some(assigned),
			peer::PeerSetup::default(),
			Version::Draft16,
		);

		let mut echoed_hops = crate::OriginList::new();
		echoed_hops.push(assigned).unwrap();
		let echoed = origin
			.create_broadcast(
				"from/peer",
				crate::broadcast::Route::new()
					.with_hops(echoed_hops)
					.with_announce(true),
			)
			.unwrap();

		let mut local_hops = crate::OriginList::new();
		local_hops.push(other).unwrap();
		let local = origin
			.create_broadcast(
				"from/us",
				crate::broadcast::Route::new().with_hops(local_hops).with_announce(true),
			)
			.unwrap();

		// Broadcast visibility is deferred until the executor ticks.
		tokio::time::sleep(std::time::Duration::from_millis(1)).await;

		(publisher, consumer, vec![echoed, local])
	}

	/// A broadcast whose every route flows through the peer's assigned identity
	/// (`Client::with_peer_origin`) is never advertised to that peer; it would only
	/// echo the peer's own content back at it. A broadcast with an independent
	/// route still is.
	#[tokio::test(start_paused = true)]
	async fn assigned_peer_origin_filters_echoed_announces() {
		let assigned = crate::Origin::new(777).unwrap();
		let (publisher, consumer, _routes) = echo_harness(assigned).await;

		let peer = cluster::Peer::default();

		let echoed = consumer.get_broadcast("from/peer").unwrap();
		assert!(!publisher.select(&Watched::new(echoed), &peer).wanted());

		let local = consumer.get_broadcast("from/us").unwrap();
		assert_eq!(publisher.select(&Watched::new(local), &peer), Advert::Plain);
	}

	/// Declaring the reserved 0 turns the extension on while naming nobody, so the
	/// identity we assigned stands in, exactly as for a peer that never negotiated.
	/// Asserted on the resolution itself rather than through an advertisement: a
	/// negotiated peer always sends its own HOP_PATH, so a route attributed to the
	/// assigned identity is a state this peer class cannot reach; see
	/// [`a_declared_zero_chain_is_still_advertised_back`] for what it gets instead.
	#[tokio::test(start_paused = true)]
	async fn withheld_peer_origin_falls_back_to_assigned() {
		let assigned = crate::Origin::new(777).unwrap();
		let declared = crate::Origin::new(9).unwrap();
		let (publisher, _consumer, _routes) = echo_harness(assigned).await;

		let withheld = cluster::Peer {
			origin: Some(crate::Origin::UNKNOWN),
			cost: None,
		};
		assert!(withheld.negotiated(), "the extension is on");
		assert_eq!(publisher.exclude(&withheld), assigned, "0 names nobody, so we do");

		let absent = cluster::Peer::default();
		assert_eq!(publisher.exclude(&absent), assigned, "so does declaring nothing");

		let named = cluster::Peer {
			origin: Some(declared),
			cost: None,
		};
		assert_eq!(publisher.exclude(&named), declared, "a declared identity wins");
	}

	/// A peer that negotiated the extension MUST send a HOP_PATH on every advertisement,
	/// and one that declared 0 names itself 0 there. An arriving chain is not rewritten,
	/// so the route carries 0, the assigned identity appears nowhere in it, and the
	/// split-horizon filter has nothing to match: the peer is advertised its own route
	/// back.
	#[tokio::test(start_paused = true)]
	async fn a_declared_zero_chain_is_still_advertised_back() {
		let assigned = crate::Origin::new(777).unwrap();
		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let consumer = origin.consume();

		let publisher = Publisher::new(
			crate::lite::test_transport::SinkSession::new(Default::default()),
			origin.consume(),
			Control::new(None, false),
			Some(assigned),
			peer::PeerSetup::default(),
			Version::Draft16,
		);

		// The chain as ingress stores it: the peer named itself 0.
		let mut hops = crate::OriginList::new();
		hops.push(crate::Origin::UNKNOWN).unwrap();
		let _echoed = origin
			.create_broadcast(
				"from/peer",
				crate::broadcast::Route::new().with_hops(hops).with_announce(true),
			)
			.unwrap();
		tokio::time::sleep(std::time::Duration::from_millis(1)).await;

		let peer = cluster::Peer {
			origin: Some(crate::Origin::UNKNOWN),
			cost: None,
		};
		let echoed = consumer.get_broadcast("from/peer").unwrap();
		assert!(
			publisher.select(&Watched::new(echoed), &peer).wanted(),
			"known gap: the assigned identity is not in the chain, so nothing filters it",
		);
	}

	/// A drained broadcast arms a linger so the cold cost is restored after a grace
	/// period. If the advertisement stops being discounted before that fires, the
	/// linger must go with it: an expired deadline that nothing clears makes
	/// `linger_deadline` hand back the same instant every turn, and the announce loops
	/// spin on it forever.
	#[tokio::test]
	async fn linger_clears_when_the_advert_stops_being_discounted() {
		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let broadcast = origin
			.clone()
			.create_broadcast("cam", crate::broadcast::Route::announced())
			.unwrap();

		let mut watch = Watched::new(broadcast.consume());
		let hops = crate::OriginList::try_from(vec![crate::Origin::new(7).unwrap()]).unwrap();

		// Discounted (cost 0) and drained: the linger is running.
		watch.set_sent(Advert::Cluster(cluster::Advert {
			hops: cluster::HopPath::new(hops.clone()),
			cost: 0,
		}));
		watch.idle_at = Some(web_async::time::Instant::now());
		let watched = HashMap::from([(crate::Path::new("cam").to_owned(), watch)]);
		assert!(Publisher::<SinkSession>::linger_deadline(&watched).is_some());

		// A re-priced advertisement has a cost to advertise, so there is nothing left
		// to restore.
		let mut watch = watched.into_values().next().unwrap();
		watch.set_sent(Advert::Cluster(cluster::Advert {
			hops: cluster::HopPath::new(hops),
			cost: 9,
		}));
		let watched = HashMap::from([(crate::Path::new("cam").to_owned(), watch)]);
		assert_eq!(
			Publisher::<SinkSession>::linger_deadline(&watched),
			None,
			"a non-discounted advert must not leave a deadline behind"
		);

		// So does one that stopped being advertisable at all.
		let mut watch = watched.into_values().next().unwrap();
		watch.idle_at = Some(web_async::time::Instant::now());
		watch.set_sent(Advert::None);
		let watched = HashMap::from([(crate::Path::new("cam").to_owned(), watch)]);
		assert_eq!(Publisher::<SinkSession>::linger_deadline(&watched), None);
	}

	/// A same-path source can splice into (or detach from) an existing broadcast
	/// without an origin-level (un)announce, silently flipping `advertisable`.
	/// Namespace forwarding must follow: advertise when a clean route appears,
	/// withdraw when the last one detaches.
	#[tokio::test]
	async fn namespace_follows_route_eligibility_changes() {
		let assigned = crate::Origin::new(777).unwrap();
		let clean_publisher = crate::Origin::new(778).unwrap();
		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();

		let gate = kio::Producer::new(true);
		let session = SinkSession::gated_bi(gate.consume());
		let log = session.log.clone();
		let publisher = Publisher::new(
			session.clone(),
			origin.consume(),
			Control::new(None, false),
			Some(assigned),
			requires_solicitation(),
			Version::Draft16,
		);

		// The broadcast starts with only a route through the assigned peer.
		let mut tainted_hops = crate::OriginList::new();
		tainted_hops.push(assigned).unwrap();
		let _tainted = origin
			.create_broadcast(
				"route-flip-cam",
				crate::broadcast::Route::new()
					.with_hops(tainted_hops)
					.with_announce(true),
			)
			.unwrap();
		settle().await;

		let stream = Stream::open(&session, Version::Draft16).await.unwrap();
		let msg = ietf::SubscribeNamespace {
			request_id: RequestId(1),
			namespace: crate::Path::new(""),
		};
		let mut run = std::pin::pin!(publisher.run_subscribe_namespace_stream(stream, msg));

		// Initial set: the tainted-only broadcast is filtered, nothing but the OK
		// response on the wire.
		assert!(futures::poll!(run.as_mut()).is_pending());
		assert_eq!(occurrences(&log, b"route-flip-cam"), 0);

		// A clean source splices in: no origin announce fires, only the route table
		// changes. The namespace must now be advertised.
		let mut clean_hops = crate::OriginList::new();
		clean_hops.push(clean_publisher).unwrap();
		let clean = origin
			.create_broadcast(
				"route-flip-cam",
				crate::broadcast::Route::new().with_hops(clean_hops).with_announce(true),
			)
			.unwrap();
		settle().await;
		assert!(futures::poll!(run.as_mut()).is_pending());
		assert_eq!(
			occurrences(&log, b"route-flip-cam"),
			1,
			"NAMESPACE after a clean route joins"
		);

		// The clean source detaches, leaving only the tainted route: withdrawn.
		drop(clean);
		settle().await;
		assert!(futures::poll!(run.as_mut()).is_pending());
		assert_eq!(
			occurrences(&log, b"route-flip-cam"),
			2,
			"NAMESPACE_DONE after the last clean route detaches"
		);
	}

	/// The peer's OK to a PUBLISH_NAMESPACE, framed exactly as the announce path
	/// reads it -- built with the crate's own writer so the framing can't drift
	/// from the encoder under test.
	/// A REQUEST_ERROR declining an advertisement, with the retry interval the peer asked
	/// for in milliseconds. Zero means it does not want the namespace offered again.
	async fn publish_namespace_error(version: Version, retry_interval: u64) -> Vec<u8> {
		let log = crate::lite::test_transport::Log::default();
		let mut writer = crate::coding::Writer::new(crate::lite::test_transport::SinkSend::new(log.clone()), version);

		writer.encode(&ietf::RequestError::ID).await.unwrap();
		writer
			.encode(&ietf::RequestError {
				request_id: matches!(version, Version::Draft15 | Version::Draft16).then_some(RequestId(1)),
				error_code: 403,
				reason_phrase: "no".into(),
				retry_interval,
			})
			.await
			.unwrap();

		log.writes.lock().unwrap().clone()
	}

	/// A peer that refuses an advertisement with a retry interval of 0 is asking not to be
	/// offered it again. Coming back anyway turns a permanent refusal (unauthorized,
	/// uninterested) into a request every few seconds for the life of the session.
	#[tokio::test(start_paused = true)]
	async fn a_refusal_that_forbids_retrying_is_not_retried() {
		const VERSION: Version = Version::Draft17;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let _cam = origin
			.create_broadcast("lonely-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Every stream is answered with the same refusal, so a retry would show up as a
		// second occurrence on the wire.
		let refusal = publish_namespace_error(VERSION, 0).await;
		let session =
			crate::lite::test_transport::ScriptedSession::per_stream(vec![refusal.clone(), refusal.clone(), refusal]);
		let log = session.log.clone();

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			declared(Some(false)),
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"lonely-cam") > 0 {
				break;
			}
			settle().await;
		}
		assert_eq!(occurrences(&log, b"lonely-cam"), 1, "the advertisement never went out");

		// Well past every retry the loop would otherwise take.
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			tick().await;
		}

		assert_eq!(
			occurrences(&log, b"lonely-cam"),
			1,
			"re-offered a namespace the peer asked not to be offered again"
		);
	}

	async fn publish_namespace_ok(version: Version) -> Vec<u8> {
		let log = crate::lite::test_transport::Log::default();
		let mut writer = crate::coding::Writer::new(crate::lite::test_transport::SinkSend::new(log.clone()), version);

		match version {
			Version::Draft14 => {
				writer.encode(&ietf::PublishNamespaceOk::ID).await.unwrap();
				writer
					.encode(&ietf::PublishNamespaceOk {
						request_id: RequestId(1),
					})
					.await
					.unwrap();
			}
			Version::Draft15 | Version::Draft16 => {
				writer.encode(&ietf::RequestOk::ID).await.unwrap();
				writer
					.encode(&ietf::RequestOk {
						request_id: Some(RequestId(1)),
					})
					.await
					.unwrap();
			}
			// Draft-17+ dropped the request id: the response rides the request's stream.
			_ => {
				writer.encode(&ietf::RequestOk::ID).await.unwrap();
				writer.encode(&ietf::RequestOk { request_id: None }).await.unwrap();
			}
		}

		let writes = log.writes.lock().unwrap();
		writes.clone()
	}

	/// Draft-14/15 predate the NAMESPACE message, so a SUBSCRIBE_NAMESPACE is
	/// answered with one PUBLISH_NAMESPACE request per matching namespace over the
	/// control stream, and PUBLISH_NAMESPACE_DONE withdraws it. The state is local
	/// to the subscription's task, mirroring lite's announce handling.
	#[tokio::test]
	async fn v14_subscribe_namespace_is_answered_with_publish_namespace() {
		const VERSION: Version = Version::Draft14;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let consumer = origin.consume();

		// Announced before the peer subscribes: it must only hit the wire after.
		let early = origin
			.create_broadcast("early-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Stream 1 is the peer's SUBSCRIBE_NAMESPACE (the peer stays quiet after);
		// streams 2 and 3 answer our two PUBLISH_NAMESPACE requests.
		let ok = publish_namespace_ok(VERSION).await;
		let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![Vec::new(), ok.clone(), ok]);
		let log = session.log.clone();

		let publisher = Publisher::new(
			session.clone(),
			consumer,
			Control::new(None, false),
			None,
			requires_solicitation(),
			VERSION,
		);

		let stream = Stream::open(&session, VERSION).await.unwrap();
		let msg = ietf::SubscribeNamespace {
			request_id: RequestId(1),
			namespace: crate::Path::new(""),
		};
		let mut run = std::pin::pin!(publisher.run_subscribe_namespace_stream(stream, msg));

		// The subscription solicits the already-announced namespace.
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"early-cam") >= 1 {
				break;
			}
			settle().await;
		}
		assert_eq!(
			occurrences(&log, b"early-cam"),
			1,
			"PUBLISH_NAMESPACE after subscribing"
		);

		// A later announce reaches the same subscription.
		let _late = origin
			.create_broadcast("late-cam", crate::broadcast::Route::announced())
			.unwrap();
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"late-cam") >= 1 {
				break;
			}
			settle().await;
		}
		assert_eq!(
			occurrences(&log, b"late-cam"),
			1,
			"PUBLISH_NAMESPACE for a live announce"
		);

		// An unannounce closes out its own request with PUBLISH_NAMESPACE_DONE.
		drop(early);
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"early-cam") >= 2 {
				break;
			}
			settle().await;
		}
		assert_eq!(
			occurrences(&log, b"early-cam"),
			2,
			"PUBLISH_NAMESPACE_DONE on unannounce"
		);

		// One stream for the subscription itself, one per PUBLISH_NAMESPACE: the
		// withdrawal rode the announce's own request, not a new stream.
		assert_eq!(log.bi_opens(), 3, "no extra stream for the withdrawal");
	}

	/// A peer that declared nothing is told without being asked. Relays that never send
	/// SUBSCRIBE_NAMESPACE hear nothing otherwise, and every third-party one behaves
	/// that way: a publisher is expected to announce itself.
	#[tokio::test]
	async fn a_peer_that_declared_nothing_is_told_unsolicited() {
		const VERSION: Version = Version::Draft17;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let _local = origin
			.create_broadcast("local-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// The only stream is the PUBLISH_NAMESPACE request we open ourselves.
		let session =
			crate::lite::test_transport::ScriptedSession::per_stream(vec![publish_namespace_ok(VERSION).await]);
		let log = session.log.clone();

		let peer_setup = peer::PeerSetup::default();
		peer_setup.set(peer::Peer::default());

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			peer_setup,
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"local-cam") >= 1 {
				break;
			}
			settle().await;
		}

		assert_eq!(
			occurrences(&log, b"local-cam"),
			1,
			"PUBLISH_NAMESPACE without a SUBSCRIBE_NAMESPACE"
		);
		assert_eq!(log.bi_opens(), 1, "one request stream");
	}

	/// Drive both announce loops at once against a peer that declared `solicit`,
	/// returning how many times the namespace hit the wire and how many bidi streams
	/// were opened. One stream means the entry rode the subscription inline; two means
	/// it went out as its own PUBLISH_NAMESPACE request.
	async fn advertise_both_ways(solicit: Option<bool>) -> (usize, usize) {
		const VERSION: Version = Version::Draft17;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let _cam = origin
			.create_broadcast("cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Stream 1 is the peer's SUBSCRIBE_NAMESPACE; stream 2, if opened at all, is our
		// PUBLISH_NAMESPACE request.
		let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![
			Vec::new(),
			publish_namespace_ok(VERSION).await,
		]);
		let log = session.log.clone();

		let publisher = Publisher::new(
			session.clone(),
			origin.consume(),
			Control::new(None, false),
			None,
			declared(solicit),
			VERSION,
		);

		let stream = Stream::open(&session, VERSION).await.unwrap();
		let msg = ietf::SubscribeNamespace {
			request_id: RequestId(1),
			namespace: crate::Path::new(""),
		};
		let mut solicited = std::pin::pin!(publisher.clone().run_subscribe_namespace_stream(stream, msg));
		let mut unsolicited = std::pin::pin!(publisher.run_publish_namespaces());

		// Poll well past the first advertisement, so a second one from the other loop
		// would show up rather than being missed by an early break. The unsolicited loop
		// finishes immediately when the peer requires solicitation, and a completed
		// future must not be polled again.
		let mut quiet = false;
		for _ in 0..100 {
			assert!(futures::poll!(solicited.as_mut()).is_pending());
			if !quiet {
				quiet = futures::poll!(unsolicited.as_mut()).is_ready();
			}
			settle().await;
		}

		(occurrences(&log, b"cam"), log.bi_opens())
	}

	/// The regression that made announces solicited in the first place: a namespace sent
	/// as both PUBLISH_NAMESPACE and NAMESPACE leaves the peer holding two sources for
	/// one broadcast, and whichever arrives second replaces the one the first attached.
	/// The peer's SETUP picks which loop carries it, so the other stays quiet and the
	/// namespace goes out exactly once either way.
	#[tokio::test]
	async fn each_namespace_is_advertised_exactly_once() {
		let (unsolicited, streams) = advertise_both_ways(Some(false)).await;
		assert_eq!(unsolicited, 1, "a peer that required nothing is told once");
		assert_eq!(streams, 2, "on its own PUBLISH_NAMESPACE request");

		let (solicited, streams) = advertise_both_ways(Some(true)).await;
		assert_eq!(solicited, 1, "a peer that asked to be told on request is told once");
		assert_eq!(streams, 1, "inline on the SUBSCRIBE_NAMESPACE stream it asked on");
	}

	/// A peer out of stream credit parks the open. That must not wedge the loop, because
	/// the withdrawals queued behind it are the only thing that frees a slot: an open that
	/// never gives up is a deadlock, not a delay.
	///
	/// Draft-14 so the withdrawal names its namespace on the wire, which is what makes the
	/// loop's progress visible while every open is blocked.
	#[tokio::test(start_paused = true)]
	async fn a_parked_open_still_lets_a_namespace_be_withdrawn() {
		const VERSION: Version = Version::Draft14;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let first = origin
			.create_broadcast("first-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Open: the peer still has credit for the first advertisement, and answers it.
		let gate = kio::Producer::new(true);
		let ok = publish_namespace_ok(VERSION).await;
		let session = crate::lite::test_transport::ScriptedSession::gated_open(vec![ok.clone(), ok], gate.consume());
		let log = session.log.clone();

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			declared(Some(false)),
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"first-cam") > 0 {
				break;
			}
			settle().await;
		}
		assert_eq!(
			occurrences(&log, b"first-cam"),
			1,
			"the first advertisement never went out"
		);

		// Credit runs out, and a second namespace wants a stream we cannot get.
		set_gate(&gate, false);
		let _second = origin
			.create_broadcast("second-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Retiring the first frees a slot and needs no new stream, so the loop has to reach
		// it despite the open above.
		drop(first);

		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"first-cam") >= 2 {
				break;
			}
			tick().await;
		}
		assert_eq!(
			occurrences(&log, b"first-cam"),
			2,
			"PUBLISH_NAMESPACE_DONE never sent: the open wedged the loop"
		);

		// Credit returns, and nothing else about the origin changes.
		set_gate(&gate, true);

		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"second-cam") > 0 {
				break;
			}
			tick().await;
		}
		assert_eq!(
			occurrences(&log, b"second-cam"),
			1,
			"never retried once credit returned"
		);
	}

	/// A namespace nobody can advertise any more is not pending, whatever happened before.
	/// `deferred` outliving the want would arm the retry timer forever for a wire message
	/// that can never happen: not a spin, but a session that never sleeps.
	#[tokio::test(start_paused = true)]
	async fn a_namespace_that_stops_being_advertisable_stops_being_deferred() {
		let assigned = crate::Origin::new(777).unwrap();

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();

		// Every route flows through the peer's own identity, so split horizon says this
		// must never be advertised back to it: `select` wants nothing, which is what the
		// peer already holds.
		let mut hops = crate::OriginList::new();
		hops.push(assigned).unwrap();
		let _echoed = origin
			.create_broadcast(
				"from/peer",
				crate::broadcast::Route::new().with_hops(hops).with_announce(true),
			)
			.unwrap();
		settle().await;

		let session = crate::lite::test_transport::SinkSession::new(Default::default());
		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			Some(assigned),
			declared(Some(false)),
			Version::Draft17,
		);

		// The state a refused or failed offer leaves behind: the peer holds nothing, and
		// the loop is coming back to it on a timer.
		let suffix: crate::PathOwned = crate::Path::new("from/peer").to_owned();
		let broadcast = origin.consume().get_broadcast("from/peer").unwrap();
		let mut watch = Watched::new(broadcast);
		watch.deferred = true;

		let mut ns = Namespaces::new(cluster::Peer::default(), Target::Requests(None));
		ns.watched.insert(suffix.clone(), watch);

		publisher.sync_namespace(&mut ns, &suffix, &suffix).await.unwrap();

		assert!(
			!ns.watched[&suffix].deferred,
			"the retry timer stays armed for a namespace that can never be advertised"
		);
	}

	/// A minimum wait binds every path back to the namespace, not just the retry sweep.
	/// A route change re-prices the advertisement; it does not excuse us from the wait the
	/// peer asked for.
	#[tokio::test(start_paused = true)]
	async fn a_route_change_still_waits_out_a_refusal() {
		const VERSION: Version = Version::Draft17;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let cam = origin
			.create_broadcast("solo-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Refused with a wait far longer than any backoff the loop would take on its own.
		let refusal = publish_namespace_error(VERSION, 600_000).await;
		let session =
			crate::lite::test_transport::ScriptedSession::per_stream(vec![refusal.clone(), refusal.clone(), refusal]);
		let log = session.log.clone();

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			declared(Some(false)),
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"solo-cam") > 0 {
				break;
			}
			settle().await;
		}
		assert_eq!(occurrences(&log, b"solo-cam"), 1, "the advertisement never went out");

		// A second route makes the advertisement worth re-pricing, which is a path back
		// into the reconciliation that does not go through the retry timer.
		let _standby = origin
			.create_broadcast("solo-cam", crate::broadcast::Route::announced())
			.unwrap();

		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			tick().await;
		}

		assert_eq!(
			occurrences(&log, b"solo-cam"),
			1,
			"re-offered inside the wait the peer asked for"
		);

		drop(cam);
	}

	/// Draft-17+ has no PUBLISH_NAMESPACE_DONE, so a withdrawal there is the FIN and
	/// nothing else. Writing the message anyway puts its type on the wire before the body
	/// fails to encode, which the receiver can only read as a protocol violation, so every
	/// unannounce would kill an otherwise healthy session.
	///
	/// Only reachable through the unsolicited loop, which is what this branch made the
	/// default: the solicited path answers inline and never opens a request per namespace.
	#[tokio::test]
	async fn a_modern_withdrawal_is_the_fin_alone() {
		const VERSION: Version = Version::Draft17;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let cam = origin
			.create_broadcast("solo-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		let session =
			crate::lite::test_transport::ScriptedSession::per_stream(vec![publish_namespace_ok(VERSION).await]);
		let log = session.log.clone();

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			declared(None),
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"solo-cam") > 0 {
				break;
			}
			settle().await;
		}
		assert_eq!(occurrences(&log, b"solo-cam"), 1, "the advertisement never went out");

		let advertised = log.writes.lock().unwrap().len();

		// Unannounce, which retires the request the advertisement opened.
		drop(cam);
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			settle().await;
		}

		assert_eq!(
			log.writes.lock().unwrap().len(),
			advertised,
			"a draft-17+ withdrawal wrote a message; the FIN alone retracts"
		);
	}

	/// The peer granting a stream is only half the exchange. One it accepts and then never
	/// answers on wedges the loop exactly as a parked open does, so the response is bounded
	/// too: everything queued behind it is otherwise stranded for the session.
	///
	/// Draft-14 so each advertisement names its namespace on the wire.
	#[tokio::test(start_paused = true)]
	async fn a_silent_answer_still_lets_the_next_namespace_be_advertised() {
		const VERSION: Version = Version::Draft14;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let _first = origin
			.create_broadcast("first-cam", crate::broadcast::Route::announced())
			.unwrap();
		let _second = origin
			.create_broadcast("second-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Every stream opens and then goes silent: an exhausted script parks rather than
		// reporting EOF, which is the peer that takes the request and answers nothing.
		let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![Vec::new(), Vec::new()]);
		let log = session.log.clone();

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			declared(Some(false)),
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());
		for _ in 0..200 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"first-cam") > 0 && occurrences(&log, b"second-cam") > 0 {
				break;
			}
			tick().await;
		}

		// Whichever went first is the one that stalled, so both having reached the wire is
		// the proof: the loop gave up on the answer and carried on.
		assert!(
			occurrences(&log, b"first-cam") > 0,
			"the first advertisement never went out"
		);
		assert!(
			occurrences(&log, b"second-cam") > 0,
			"the silent answer wedged the loop: the second namespace never went out"
		);
	}

	/// Credit returning raises no signal of its own: no announce, no route change, nothing
	/// the loop is watching. Only a retry brings the namespace back, and without one it
	/// stays undiscoverable for the life of the session.
	#[tokio::test(start_paused = true)]
	async fn a_namespace_refused_a_stream_is_retried_on_its_own() {
		const VERSION: Version = Version::Draft14;

		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let _cam = origin
			.create_broadcast("lonely-cam", crate::broadcast::Route::announced())
			.unwrap();
		settle().await;

		// Closed from the start: the peer has granted nothing.
		let gate = kio::Producer::new(false);
		let ok = publish_namespace_ok(VERSION).await;
		let session = crate::lite::test_transport::ScriptedSession::gated_open(vec![ok], gate.consume());
		let log = session.log.clone();

		let publisher = Publisher::new(
			session,
			origin.consume(),
			Control::new(None, false),
			None,
			declared(Some(false)),
			VERSION,
		);

		let mut run = std::pin::pin!(publisher.run_publish_namespaces());

		// Well past the point where the open gives up.
		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			tick().await;
		}
		assert_eq!(occurrences(&log, b"lonely-cam"), 0, "advertised without a stream");

		// Credit returns. Nothing else changes: no publish, no unannounce, no route move.
		set_gate(&gate, true);

		for _ in 0..100 {
			assert!(futures::poll!(run.as_mut()).is_pending());
			if occurrences(&log, b"lonely-cam") > 0 {
				break;
			}
			tick().await;
		}
		assert_eq!(occurrences(&log, b"lonely-cam"), 1, "never came back on its own");
	}

	/// Advance far enough that a parked open gives up and its retry comes due, without
	/// making the test wait: time is paused, so this only moves the clock the loop reads.
	async fn tick() {
		tokio::time::advance(std::time::Duration::from_millis(200)).await;
	}

	fn set_gate(gate: &kio::Producer<bool>, open: bool) {
		let Ok(mut gate) = gate.write() else {
			panic!("gate closed")
		};
		*gate = open;
	}

	/// A publisher talking to a scripted peer that never answers, over one bidi stream.
	struct Harness {
		publisher: Publisher<crate::lite::test_transport::ScriptedSession>,
		session: crate::lite::test_transport::ScriptedSession,
		log: crate::lite::test_transport::Log,
		/// Keeps the origin alive; the publisher only holds a consumer.
		_origin: origin::Producer,
	}

	fn harness(version: Version) -> Harness {
		let origin = crate::origin::Info::new(crate::Origin::new(1).unwrap()).produce();
		let session = crate::lite::test_transport::ScriptedSession::per_stream(vec![Vec::new()]);
		let log = session.log.clone();

		// Serving a request blocks on the peer's SETUP, which no scripted peer sends here.
		let peer_setup = peer::PeerSetup::default();
		peer_setup.set(peer::Peer::default());

		let publisher = Publisher::new(
			session.clone(),
			origin.consume(),
			Control::new(None, false),
			None,
			peer_setup,
			version,
		);

		Harness {
			publisher,
			session,
			log,
			_origin: origin,
		}
	}

	/// Subscribe to a path nothing publishes, returning what the peer would read off the
	/// request stream plus the reset codes the stream recorded.
	async fn subscribe_missing(version: Version) -> (Vec<u8>, Vec<u32>) {
		let h = harness(version);

		let stream = Stream::open(&h.session, version).await.unwrap();
		h.publisher
			.clone()
			.run_subscribe_stream(
				stream,
				ietf::Subscribe {
					request_id: RequestId(1),
					track_namespace: crate::Path::new("nothing/here"),
					track_name: "video".into(),
					subscriber_priority: 128,
					group_order: GroupOrder::Descending,
					filter: Filter::NextObject,
					fill: None,
					properties_wanted: true,
				},
			)
			.await
			.unwrap();

		let writes = h.log.writes.lock().unwrap().clone();
		(writes, h.log.resets())
	}

	/// Send a FETCH we don't implement, returning the same pair.
	async fn fetch_unsupported(version: Version, fetch_type: FetchType<'_>) -> (Vec<u8>, Vec<u32>) {
		let h = harness(version);

		let stream = Stream::open(&h.session, version).await.unwrap();
		h.publisher
			.clone()
			.run_fetch_stream(
				stream,
				ietf::Fetch {
					request_id: RequestId(1),
					subscriber_priority: 128,
					group_order: GroupOrder::Descending,
					fetch_type,
				},
			)
			.await
			.unwrap();

		let writes = h.log.writes.lock().unwrap().clone();
		(writes, h.log.resets())
	}

	/// A SUBSCRIBE for a path with no publisher is refused with REQUEST_ERROR, and the refusal
	/// has to survive the trip. `Writer` resets the stream on drop, and a reset that races the
	/// write discards the bytes the peer has not read yet, which leaves the subscriber waiting
	/// on a request we already refused. Finishing first makes the drop-time reset a no-op.
	#[tokio::test]
	async fn missing_broadcast_is_refused_without_resetting_the_stream() {
		for version in [Version::Draft17, Version::Draft18, Version::Draft19, Version::Draft20] {
			let (writes, resets) = subscribe_missing(version).await;

			assert!(!writes.is_empty(), "{version}: nothing was sent");
			assert_eq!(
				writes[0],
				ietf::RequestError::ID as u8,
				"{version}: not a REQUEST_ERROR"
			);
			assert!(resets.is_empty(), "{version}: stream reset, discarding the error");
		}
	}

	/// Every FETCH we refuse goes out through its own error encoder, so it needs the same
	/// finish: a reset there loses the rejection the same way.
	#[tokio::test]
	async fn unsupported_fetch_is_refused_without_resetting_the_stream() {
		let unsupported = || {
			[
				(
					"standalone",
					FetchType::Standalone {
						namespace: crate::Path::new("nothing/here"),
						track: "video".into(),
						start: Location { group: 0, object: 0 },
						end: Location { group: 1, object: 0 },
					},
				),
				(
					"relative joining with an offset",
					FetchType::RelativeJoining {
						subscriber_request_id: RequestId(3),
						group_offset: 1,
					},
				),
				(
					"absolute joining",
					FetchType::AbsoluteJoining {
						subscriber_request_id: RequestId(3),
						group_id: 7,
					},
				),
			]
		};

		for version in [Version::Draft17, Version::Draft18, Version::Draft19, Version::Draft20] {
			for (label, fetch_type) in unsupported() {
				let (writes, resets) = fetch_unsupported(version, fetch_type).await;

				assert!(!writes.is_empty(), "{version} {label}: nothing was sent");
				assert_eq!(
					writes[0],
					ietf::RequestError::ID as u8,
					"{version} {label}: not a REQUEST_ERROR"
				);
				assert!(
					resets.is_empty(),
					"{version} {label}: stream reset, discarding the error"
				);
			}
		}
	}
}

/// The live edge a SUBSCRIBE resolves against, snapshotted once so the subscription
/// floor, the fill cap, and the advertised LARGEST_OBJECT all agree on where it is.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
struct LiveEdge {
	/// The newest group sequence, `None` before any group exists.
	latest: Option<u64>,
	/// The precise Largest Object. `None` when the track is empty, or when the newest
	/// group's frames cannot be read right now (none written yet, or a spliced track
	/// between segments), in which case nothing is advertised and no fill is servable.
	largest: Option<Location>,
	/// One past the Largest Object, which is where a Next Object subscription begins.
	/// When the edge is imprecise this falls back to the next group boundary: never below
	/// the true Next Object, at worst under-delivering the current group's tail.
	next: Option<Location>,
}

/// Snapshot the live edge of a track.
fn live_edge(track: &track::Consumer) -> LiveEdge {
	let Some(latest) = track.latest() else {
		return LiveEdge::default();
	};

	match track.peek_latest() {
		Some(group) if group.sequence == latest => {
			let count = group.frame_count() as u64;
			let largest = match count.checked_sub(1) {
				Some(object) => Some(Location { group: latest, object }),
				// A group with no frames yet has no objects, so the largest sits in an
				// earlier group. Walk back through the cache to find it, or a peer that
				// subscribes in the instant between a group's creation and its first
				// frame is told the track is empty and gets no fill.
				None => largest_before(track, latest),
			};
			// One past the edge, even when the edge sits below the newest group: a group
			// may keep writing after a newer one exists, and a floor above the true Next
			// Object would strand those objects between the fill cap and the
			// subscription. With no readable object anywhere, the newest group's start
			// excludes nothing the cache can still name.
			let next = match largest {
				Some(largest) => Location {
					group: largest.group,
					object: largest.object.saturating_add(1),
				},
				None => Location {
					group: latest,
					object: 0,
				},
			};
			LiveEdge {
				latest: Some(latest),
				largest,
				next: Some(next),
			}
		}
		_ => LiveEdge {
			latest: Some(latest),
			largest: None,
			next: Some(Location {
				group: latest.saturating_add(1),
				object: 0,
			}),
		},
	}
}

/// The last object below `sequence`: the nearest earlier cached group that has started a
/// frame, walked in cache order so legal gaps in the group numbering are crossed. Empty
/// groups exist for at most the instant between creation and first frame, so the walk is
/// one step in practice. A group evicted from the cache is not visible, which is fine:
/// Largest Object is the track from this publisher's perspective, and that is the cache.
fn largest_before(track: &track::Consumer, sequence: u64) -> Option<Location> {
	let mut sequence = sequence;
	loop {
		let group = track.peek_before(sequence)?;
		if let Some(object) = (group.frame_count() as u64).checked_sub(1) {
			return Some(Location {
				group: group.sequence,
				object,
			});
		}
		sequence = group.sequence;
	}
}

/// The Locations a SUBSCRIBE's Location Filter selects, resolved against the live edge.
///
/// `start: None` joins at the beginning of the latest group, which is what moq-lite means
/// by joining a live track. An explicit start is honored down to the object: the start
/// group is served from `start.object` and the end group up to `end.object`, so a filter
/// is never widened into objects the subscriber excluded.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
struct ServeRange {
	/// The first Location to serve, or `None` for the start of the latest group.
	start: Option<Location>,
	/// Where the range ends, inclusive. `None` is open ended. The subscription stays
	/// open once the range is exhausted; draft-20 removed the notion of a filter ending
	/// a subscription.
	end: Option<EndLocation>,
}

/// The slice of one group a subscription's [`ServeRange`] selects.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
struct GroupSlice {
	/// Frames dropped from the front; also the first written object's absolute id.
	skip: u64,
	/// One past the last object to write, when the filter ends inside this group.
	until: Option<u64>,
}

/// Resolve a SUBSCRIBE's Location Filter into the range to serve.
///
/// Only draft-20 is honored. Earlier drafts have a Filter Type tag whose absolute forms we
/// never served, and starting to interpret them now would change what an existing peer
/// receives; draft-20 is also the first version whose relative forms can name a past group
/// without the subscriber knowing Largest Object.
fn subscribe_range(msg: &ietf::Subscribe<'_>, edge: LiveEdge, version: Version) -> ServeRange {
	if !Filter::is_draft20(version) {
		if !matches!(msg.filter, Filter::NextObject | Filter::Unfiltered) {
			tracing::warn!(filter = ?msg.filter, "filter not supported before draft-20, ignoring");
		}
		return ServeRange::default();
	}

	filter_range(msg.filter, edge)
}

/// The Locations a single Location Filter selects, resolved against the live edge.
fn filter_range(filter: Filter, edge: LiveEdge) -> ServeRange {
	match filter {
		// No restriction. moq-lite starts at the beginning of the latest group, which is
		// the join point it is built around; a subscription passes objects as they are
		// published, so an absent filter is not a request to replay history.
		Filter::Unfiltered => ServeRange::default(),
		// `{Largest.Group, Largest.Object + 1}`. Everything below it, including the
		// already-published head of the current group, is outside the requested range,
		// so the join is mid-group by construction. The draft pairs this with a fill
		// when the subscriber wants the head; see `run_fill`.
		Filter::NextObject => ServeRange {
			start: edge.next,
			end: None,
		},
		// `{Largest.Group + 1 - groups, 0}`: 0 is the next group and 1 is the current one.
		// Counted from `Largest.Group`, which sits below the newest group while that
		// group has no objects yet; only with no largest at all does the newest group
		// stand in for it.
		Filter::Relative(groups) => ServeRange {
			start: edge
				.largest
				.map(|largest| largest.group)
				.or(edge.latest)
				.map(|group| Location {
					group: group.saturating_add(1).saturating_sub(groups),
					object: 0,
				}),
			end: None,
		},
		Filter::Absolute { start, end } => ServeRange {
			start: Some(start),
			end,
		},
	}
}

/// What a draft-20 fill request resolves to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FillServe {
	/// The range is empty, so no fetch stream is opened at all.
	Empty,
	/// A single group served from the cache: `skip` frames dropped from the front, and
	/// delivery stopping before `until` when set (the current group is capped at the
	/// Largest Object snapshot; a whole past group reads to its end).
	Group {
		sequence: u64,
		skip: u64,
		until: Option<u64>,
	},
	/// A range spanning several groups, which we do not serve: multi-group fetch
	/// serialization depends on a negotiated group order we do not implement, so the
	/// stream is reset instead, the draft's fill-failure signal.
	Unsupported,
}

/// Resolve a fill request using the Fetch rules: relative to Largest Object and never
/// extending beyond it. An omitted Location Filter inherits the subscription's.
fn fill_range(fill: ietf::Fill, subscription: Filter, largest: Option<Location>) -> FillServe {
	// A Range Filter narrows which objects pass, which we do not implement; serving the
	// unfiltered range instead would deliver objects the peer excluded, so refuse it.
	if fill.range_filters {
		return FillServe::Unsupported;
	}
	let filter = fill.filter.unwrap_or(subscription);

	// Nothing published (or no precise edge to cap at) means no fill is servable; an
	// empty range opens no stream.
	let Some(largest) = largest else {
		return FillServe::Empty;
	};

	let start = match filter {
		// A Fetch without a filter is the whole track up to Largest Object.
		Filter::Unfiltered => Location { group: 0, object: 0 },
		// One past the edge, which for a Fetch is always empty.
		Filter::NextObject => return FillServe::Empty,
		Filter::Relative(groups) => Location {
			group: largest.group.saturating_add(1).saturating_sub(groups),
			object: 0,
		},
		Filter::Absolute { start, .. } => start,
	};

	// Cap the requested end at Largest Object.
	let end = match filter {
		Filter::Absolute { end: Some(end), .. }
			if end.group < largest.group
				|| (end.group == largest.group && end.object.is_some_and(|object| object < largest.object)) =>
		{
			end
		}
		_ => EndLocation {
			group: largest.group,
			object: Some(largest.object),
		},
	};

	if start.group > end.group || (start.group == end.group && end.object.is_some_and(|object| object < start.object)) {
		return FillServe::Empty;
	}
	if start.group != end.group {
		return FillServe::Unsupported;
	}

	FillServe::Group {
		sequence: start.group,
		skip: start.object,
		until: end.object.map(|object| object.saturating_add(1)),
	}
}

#[cfg(test)]
mod range_tests {
	use super::*;
	use crate::ietf::EndLocation;

	fn subscribe(filter: Filter) -> ietf::Subscribe<'static> {
		ietf::Subscribe {
			request_id: RequestId(1),
			track_namespace: crate::Path::new("broadcast"),
			track_name: "video".into(),
			subscriber_priority: 128,
			group_order: GroupOrder::Descending,
			filter,
			fill: None,
			properties_wanted: true,
		}
	}

	/// A live edge of group 100 whose current group has objects 0 through 4.
	const EDGE: LiveEdge = LiveEdge {
		latest: Some(100),
		largest: Some(Location { group: 100, object: 4 }),
		next: Some(Location { group: 100, object: 5 }),
	};

	/// A start past the live edge is what the subscriber asked for, so it is used as given.
	/// Clamping it to the live edge would serve a group outside the requested range.
	#[tokio::test]
	async fn a_future_start_is_not_clamped_to_the_live_edge() {
		let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "video", None);
		track
			.create_group(group::Info { sequence: 7 })
			.unwrap()
			.finish()
			.unwrap();
		track
			.create_group(group::Info { sequence: 8 })
			.unwrap()
			.finish()
			.unwrap();

		// Next Group against a live edge of 8 asks for 9, which does not exist yet.
		let mut subscriber = track.subscribe(None);
		subscriber.start_at(9);
		assert!(
			futures::poll!(std::pin::pin!(subscriber.recv_group())).is_pending(),
			"a future start must wait for its group rather than serving the live edge"
		);

		// The group it asked for is what it gets once published.
		track
			.create_group(group::Info { sequence: 9 })
			.unwrap()
			.finish()
			.unwrap();
		let group = subscriber.recv_group().await.unwrap().expect("group 9");
		assert_eq!(group.sequence, 9);
	}

	/// Earlier drafts never had their absolute filters served, so honoring one now would
	/// change what an existing peer receives.
	#[test]
	fn older_drafts_are_ignored() {
		let msg = subscribe(Filter::Absolute {
			start: Location { group: 4, object: 0 },
			end: Some(EndLocation { group: 9, object: None }),
		});
		assert_eq!(subscribe_range(&msg, EDGE, Version::Draft19), ServeRange::default());
	}

	/// An absent filter is "no restriction on what is forwarded", not a request for
	/// history, so it joins at the live edge.
	#[test]
	fn an_unfiltered_subscription_stays_live() {
		let msg = subscribe(Filter::Unfiltered);
		assert_eq!(subscribe_range(&msg, EDGE, Version::Draft20), ServeRange::default());
	}

	/// Next Object starts one past the Largest Object, mid-group. Everything below it,
	/// including the current group's head, is outside the requested range.
	#[test]
	fn next_object_starts_past_the_largest_object() {
		let msg = subscribe(Filter::NextObject);
		assert_eq!(
			subscribe_range(&msg, EDGE, Version::Draft20),
			ServeRange {
				start: Some(Location { group: 100, object: 5 }),
				end: None,
			}
		);
	}

	/// When the edge cannot be read precisely, Next Object falls back to the next group
	/// boundary: never below the true Next Object, so nothing already published is sent.
	#[test]
	fn next_object_without_a_precise_edge_waits_for_the_next_group() {
		let edge = LiveEdge {
			latest: Some(100),
			largest: None,
			next: Some(Location { group: 101, object: 0 }),
		};
		let msg = subscribe(Filter::NextObject);
		assert_eq!(
			subscribe_range(&msg, edge, Version::Draft20),
			ServeRange {
				start: Some(Location { group: 101, object: 0 }),
				end: None,
			}
		);
	}

	/// `{Largest.Group + 1 - groups, 0}`: one is the current group, zero is the next one,
	/// and larger values reach further back.
	#[test]
	fn relative_counts_back_from_the_next_group() {
		for (groups, expected) in [(0, 101), (1, 100), (2, 99), (5, 96)] {
			let msg = subscribe(Filter::Relative(groups));
			assert_eq!(
				subscribe_range(&msg, EDGE, Version::Draft20),
				ServeRange {
					start: Some(Location {
						group: expected,
						object: 0,
					}),
					end: None,
				},
				"{groups} groups back"
			);
		}
	}

	/// Relative counts from `Largest.Group`, which is below the newest group while that
	/// group has no objects yet, so a current-group join still reaches the content.
	#[test]
	fn relative_counts_from_the_largest_group_over_an_empty_newest_group() {
		let edge = LiveEdge {
			latest: Some(1),
			largest: Some(Location { group: 0, object: 2 }),
			next: Some(Location { group: 0, object: 3 }),
		};
		let msg = subscribe(Filter::Relative(1));
		assert_eq!(
			subscribe_range(&msg, edge, Version::Draft20),
			ServeRange {
				start: Some(Location { group: 0, object: 0 }),
				end: None,
			}
		);
	}

	/// Counting back further than the track goes lands at its start rather than wrapping.
	#[test]
	fn relative_saturates_at_the_start() {
		let msg = subscribe(Filter::Relative(500));
		assert_eq!(
			subscribe_range(&msg, EDGE, Version::Draft20),
			ServeRange {
				start: Some(Location { group: 0, object: 0 }),
				end: None,
			}
		);
	}

	/// Nothing published yet means there is no edge to count back from.
	#[test]
	fn relative_without_an_edge_stays_live() {
		let msg = subscribe(Filter::Relative(3));
		assert_eq!(
			subscribe_range(&msg, LiveEdge::default(), Version::Draft20),
			ServeRange::default()
		);
	}

	/// A group created but not yet written has no objects, so the largest sits in an
	/// earlier group. Losing it would tell a fill-requesting peer the track is empty, and
	/// a floor above the true Next Object would strand a late object of the earlier group
	/// between the fill cap and the subscription: a group may keep writing after a newer
	/// one exists, so the earlier group is deliberately left unfinished here.
	#[tokio::test]
	async fn an_empty_newest_group_walks_back_for_the_largest() {
		let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "video", None);
		let mut first = track.create_group(group::Info { sequence: 0 }).unwrap();
		for _ in 0..3 {
			first
				.write_frame(crate::Timestamp::from_millis(0).unwrap(), b"frame".as_slice())
				.unwrap();
		}
		let _open = track.create_group(group::Info { sequence: 1 }).unwrap();

		let edge = live_edge(&track.consume());
		assert_eq!(edge.latest, Some(1));
		assert_eq!(
			edge.largest,
			Some(Location { group: 0, object: 2 }),
			"the largest object is the previous group's last frame"
		);
		assert_eq!(
			edge.next,
			Some(Location { group: 0, object: 3 }),
			"the floor is one past the largest, so a late object of group 0 is not stranded"
		);
	}

	/// Group numbering may legally skip sequences, so the walk follows the cache's own
	/// order rather than decrementing by one.
	#[tokio::test]
	async fn the_walkback_crosses_a_gap_in_the_numbering() {
		let mut track = track::Producer::new(std::sync::Arc::new(crate::broadcast::Info::default()), "video", None);
		let mut first = track.create_group(group::Info { sequence: 0 }).unwrap();
		first
			.write_frame(crate::Timestamp::from_millis(0).unwrap(), b"frame".as_slice())
			.unwrap();
		first.finish().unwrap();
		// Sequence 1 never exists; the newest group is empty.
		let _open = track.create_group(group::Info { sequence: 2 }).unwrap();

		let edge = live_edge(&track.consume());
		assert_eq!(edge.latest, Some(2));
		assert_eq!(edge.largest, Some(Location { group: 0, object: 0 }));
		assert_eq!(edge.next, Some(Location { group: 0, object: 1 }));
	}

	/// Both ends carry through, object bounds included, so the boundary groups can be
	/// trimmed rather than widened.
	#[test]
	fn absolute_carries_both_ends() {
		let msg = subscribe(Filter::Absolute {
			start: Location { group: 4, object: 3 },
			end: Some(EndLocation {
				group: 9,
				object: Some(6),
			}),
		});
		assert_eq!(
			subscribe_range(&msg, EDGE, Version::Draft20),
			ServeRange {
				start: Some(Location { group: 4, object: 3 }),
				end: Some(EndLocation {
					group: 9,
					object: Some(6)
				}),
			}
		);
	}
}

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

	/// Objects 0 through 4 of group 100 are published.
	const LARGEST: Option<Location> = Some(Location { group: 100, object: 4 });

	/// A fill with an explicit Location Filter and no range filters.
	fn fill(filter: Filter) -> ietf::Fill {
		ietf::Fill {
			filter: Some(filter),
			range_filters: false,
		}
	}

	/// The canonical current-group join: a fill one group back covers the published head
	/// of the current group, capped at the Largest Object snapshot.
	#[test]
	fn current_group_fill() {
		assert_eq!(
			fill_range(fill(Filter::Relative(1)), Filter::NextObject, LARGEST),
			FillServe::Group {
				sequence: 100,
				skip: 0,
				until: Some(5),
			}
		);
	}

	/// A fill of the next group starts past the Largest Object, which for a Fetch is
	/// always empty, as is an explicit Next Object.
	#[test]
	fn a_future_fill_is_empty() {
		assert_eq!(
			fill_range(fill(Filter::Relative(0)), Filter::NextObject, LARGEST),
			FillServe::Empty
		);
		assert_eq!(
			fill_range(fill(Filter::NextObject), Filter::NextObject, LARGEST),
			FillServe::Empty
		);
	}

	/// Nothing published means every fill range is empty; no stream is owed.
	#[test]
	fn no_content_means_no_fill() {
		assert_eq!(
			fill_range(fill(Filter::Relative(1)), Filter::NextObject, None),
			FillServe::Empty
		);
		assert_eq!(
			fill_range(fill(Filter::Unfiltered), Filter::NextObject, None),
			FillServe::Empty
		);
	}

	/// A whole past group is served to its end; only the current group is capped.
	#[test]
	fn a_past_group_is_served_whole() {
		assert_eq!(
			fill_range(
				fill(Filter::Absolute {
					start: Location { group: 7, object: 0 },
					end: Some(EndLocation { group: 7, object: None }),
				}),
				Filter::NextObject,
				LARGEST
			),
			FillServe::Group {
				sequence: 7,
				skip: 0,
				until: None,
			}
		);
	}

	/// Object bounds inside the group carry through to the served slice.
	#[test]
	fn object_bounds_trim_the_group() {
		assert_eq!(
			fill_range(
				fill(Filter::Absolute {
					start: Location { group: 7, object: 2 },
					end: Some(EndLocation {
						group: 7,
						object: Some(5)
					}),
				}),
				Filter::NextObject,
				LARGEST
			),
			FillServe::Group {
				sequence: 7,
				skip: 2,
				until: Some(6),
			}
		);
	}

	/// An end past the edge is capped at the Largest Object, per the Fetch rules.
	#[test]
	fn the_end_is_capped_at_the_largest_object() {
		assert_eq!(
			fill_range(
				fill(Filter::Absolute {
					start: Location { group: 100, object: 0 },
					end: Some(EndLocation {
						group: 100,
						object: Some(1000),
					}),
				}),
				Filter::NextObject,
				LARGEST
			),
			FillServe::Group {
				sequence: 100,
				skip: 0,
				until: Some(5),
			}
		);
	}

	/// A range spanning several groups is refused rather than served in an order the
	/// peer may not expect; the reset is the draft's fill-failure signal.
	#[test]
	fn a_multi_group_fill_is_unsupported() {
		assert_eq!(
			fill_range(fill(Filter::Relative(3)), Filter::NextObject, LARGEST),
			FillServe::Unsupported
		);
		assert_eq!(
			fill_range(fill(Filter::Unfiltered), Filter::NextObject, LARGEST),
			FillServe::Unsupported
		);
		assert_eq!(
			fill_range(
				fill(Filter::Absolute {
					start: Location { group: 7, object: 0 },
					end: Some(EndLocation { group: 9, object: None }),
				}),
				Filter::NextObject,
				LARGEST
			),
			FillServe::Unsupported
		);
	}

	/// A Range Filter narrows which objects pass; refusing beats serving objects the
	/// peer excluded.
	#[test]
	fn a_range_filtered_fill_is_unsupported() {
		let fill = ietf::Fill {
			filter: Some(Filter::Relative(1)),
			range_filters: true,
		};
		assert_eq!(fill_range(fill, Filter::NextObject, LARGEST), FillServe::Unsupported);
	}

	/// An omitted Location Filter inherits the subscription's, per the draft: a fill
	/// scope carries only the settings that differ.
	#[test]
	fn an_omitted_filter_inherits_the_subscription() {
		let empty = ietf::Fill::default();
		// A Next Object subscription inherited into a Fetch is always empty.
		assert_eq!(fill_range(empty, Filter::NextObject, LARGEST), FillServe::Empty);
		// A current-group subscription inherited into the fill covers its head.
		assert_eq!(
			fill_range(empty, Filter::Relative(1), LARGEST),
			FillServe::Group {
				sequence: 100,
				skip: 0,
				until: Some(5),
			}
		);
	}

	/// A backwards range is empty, not an error.
	#[test]
	fn a_backwards_range_is_empty() {
		assert_eq!(
			fill_range(
				fill(Filter::Absolute {
					start: Location { group: 7, object: 5 },
					end: Some(EndLocation {
						group: 7,
						object: Some(2)
					}),
				}),
				Filter::NextObject,
				LARGEST
			),
			FillServe::Empty
		);
	}

	/// The whole track fits in one group only when the track has exactly one group.
	#[test]
	fn unfiltered_with_one_group_is_the_canonical_fill() {
		assert_eq!(
			fill_range(
				fill(Filter::Unfiltered),
				Filter::NextObject,
				Some(Location { group: 0, object: 9 })
			),
			FillServe::Group {
				sequence: 0,
				skip: 0,
				until: Some(10),
			}
		);
	}
}