moq-net 0.3.2

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
use crate::runtime::Timers as _;
use crate::{frame, group, origin, track};
use std::{
	collections::HashMap,
	sync::{Arc, atomic},
	task::{Poll, ready},
	time::Duration,
};

use crate::{
	AsPath, Error, Path, PathOwned, Timescale, Timestamp, bandwidth,
	coding::{Decode, Reader, Stream},
	lite,
	track::{Position, Subscription},
};

use super::Version;

use kio::Lock;

pub(super) struct SubscriberConfig<S: crate::transport::poll::Session> {
	pub runtime: crate::time::Clock,
	pub session: S,
	/// The origin into which remote broadcasts are inserted. Traffic stats are
	/// attributed through this handle: tag it with [`origin::Producer::with_stats`]
	/// first.
	pub origin: origin::Producer,
	/// Receiver-side bandwidth producer for PROBE feedback. None disables the
	/// feature (used by versions that don't carry probe streams).
	pub recv_bandwidth: Option<bandwidth::Producer>,
	pub version: Version,
	/// Shared slot for the peer's SETUP (lite-05+). Written when the peer's Setup
	/// stream is read; the probe stream waits on it before opening.
	pub peer_setup: super::PeerSetup,
	/// The origin (hop) id assigned to the peer, used whenever the peer doesn't
	/// declare one itself. See `Client::with_peer_hop`.
	pub peer_hop: Option<crate::Hop>,
	/// Local policy for what pulling from this peer costs, overriding whatever it
	/// declared in its SETUP. `None` charges the peer's declared price.
	pub cost: Option<u64>,
	/// Set once the peer sends a GOAWAY; new request streams are then rejected
	/// with [`Error::GoingAway`] (the peer told us to stop asking).
	pub going_away: crate::goaway::GoingAway,
}

#[derive(Clone)]
pub(super) struct Subscriber<S: crate::transport::poll::Session> {
	runtime: crate::time::Clock,
	session: S,

	origin: origin::Producer,
	recv_bandwidth: Option<bandwidth::Producer>,
	// Session-level origin id shared with the Publisher. Used to drop reflected
	// announces: any incoming announce whose hop chain already passed through us
	// has looped, so it is neither used as a route nor forwarded. On lite-04/05
	// we also ask the peer to filter them out (AnnounceRequest.exclude_hop) so
	// they never hit the wire, but this check is what makes it correct.
	self_origin: crate::Hop,
	// The origin stored as `Route.via` for broadcasts from versions that don't
	// carry real hop ids on the wire (Lite01/02/03), and for a peer that reports
	// 0 in AnnounceOk. Lite03 placeholders stay 0 and count as anonymous.
	//
	// This is the peer's assigned identity (`peer_hop`) when the caller gave
	// it one. Otherwise it is `Hop::UNKNOWN` (0), the reserved "no identity" value.
	//
	// Assigning one is the caller's call, not this layer's: a server gives every
	// accepted session a fresh id so its routes are at least distinguishable from
	// another session's, while a client only assigns one it knows out of band. The
	// assigned id stays local and is never written into a hop chain.
	session_origin: crate::Hop,
	subscribes: Lock<HashMap<u64, TrackEntry>>,
	next_id: Arc<atomic::AtomicU64>,
	version: Version,
	/// The peer's advertised SETUP (lite-05+), set when its Setup stream is read.
	peer_setup: super::PeerSetup,
	/// Local policy overriding the peer's declared egress price. See `poll_link_cost`.
	cost: Option<u64>,
	/// Sources created by the announce half, drained by the driver into
	/// [`SourceServe`] machines.
	sources: kio::Queue<(PathOwned, crate::broadcast::Dynamic)>,
	going_away: crate::goaway::GoingAway,
}

#[derive(Clone)]
struct TrackEntry {
	producer: track::Producer,
	/// Timestamp scale from this track's TRACK_INFO, known before the SUBSCRIBE is
	/// even opened, so group streams decode frames without blocking.
	timescale: Option<Timescale>,
}

impl<S: crate::transport::poll::Session> Subscriber<S> {
	pub fn new(config: SubscriberConfig<S>) -> Self {
		// Identity for incoming-hop loop detection. Derived from the local
		// origin we publish into so it matches the relay identity across
		// every session sharing that origin, required for cross-session
		// loop detection.
		let self_origin = config.origin.hop();
		Self {
			session: config.session,
			runtime: config.runtime,
			origin: config.origin,
			recv_bandwidth: config.recv_bandwidth,
			self_origin,
			session_origin: config.peer_hop.unwrap_or(crate::Hop::UNKNOWN),
			subscribes: Default::default(),
			next_id: Default::default(),
			version: config.version,
			peer_setup: config.peer_setup,
			cost: config.cost,
			sources: kio::Queue::new(),
			going_away: config.going_away,
		}
	}

	/// Reject a new request once the peer has sent a GOAWAY: it told us to stop
	/// opening streams on this session (existing subscriptions keep flowing).
	fn check_going_away(&self) -> Result<(), Error> {
		if self.going_away.is_set() {
			return Err(Error::GoingAway);
		}
		Ok(())
	}

	/// What pulling content across this session's link costs, added to the route cost
	/// of every announcement received over it.
	///
	/// A locally configured price wins, since what we charge our own routing is local
	/// policy. Otherwise we charge what the peer declared, which is how a server prices
	/// a link at all: it cannot tell a sibling from a stranger, so the dialer that chose
	/// the peer declares the price for both of them. Falls back to
	/// [`super::DEFAULT_COST`] when neither priced it, and to `0` on a version that
	/// carries no cost at all, whose routes rank on hop count alone.
	///
	/// Our own price short-circuits the peer's, so a session that configured one never
	/// blocks on a SETUP to start routing.
	fn poll_link_cost(&self, waiter: &kio::Waiter) -> Poll<u64> {
		// Older versions carry no cost on the wire, so nothing is charged and their
		// routes rank on hop count alone. Returning early also avoids blocking on a
		// SETUP that versions without a Setup Stream never send.
		if !self.version.has_route_cost() {
			return Poll::Ready(0);
		}
		match self.cost {
			Some(cost) => Poll::Ready(cost),
			None => self
				.peer_setup
				.poll_cost(waiter)
				.map(|cost| cost.unwrap_or(super::DEFAULT_COST)),
		}
	}

	/// Apply one received announce message to the origin and the per-stream
	/// bookkeeping in `run`.
	fn handle_announce(
		&mut self,
		prefix: &PathOwned,
		announce: lite::AnnounceBroadcast<'_>,
		run: &mut PrefixRun,
	) -> Result<(), Error> {
		match announce {
			lite::AnnounceBroadcast::Active { suffix, hops, cost } => {
				let path = prefix.join(&suffix);
				if self.version.has_announce_id() {
					// Every `active` assigns the next ordinal, even ones we drop locally.
					run.announced_by_id.insert(run.next_announce_id, path.clone());
					run.next_announce_id += 1;
				}
				if lite::restart_supported(self.version)
					&& !self.version.has_announce_id()
					&& run.announced.contains(&path)
				{
					// lite-05 only: a duplicate ANNOUNCE for an already-announced path is a RESTART;
					// atomically replace the broadcast. Lite06+ restarts by announce id, and older
					// versions never defined restarts, so both fall through to start_announce, which
					// rejects the duplicate (Error::ProtocolViolation).
					self.restart_announce(
						path,
						hops,
						cost,
						run.link_cost,
						run.responder_origin,
						&mut run.announced,
					)?;
				} else {
					self.start_announce(
						path,
						hops,
						cost,
						run.link_cost,
						run.responder_origin,
						&mut run.announced,
					)?;
				}
			}
			lite::AnnounceBroadcast::Ended { suffix, .. } => {
				let path = prefix.join(&suffix);
				tracing::debug!(broadcast = %self.log_path(&path), "unannounced");
				run.announced.retire(&path);
			}
			lite::AnnounceBroadcast::EndedId { id } => {
				// Resolve and retire the id; an unknown or already-retired id is a
				// protocol violation.
				let Some(path) = run.announced_by_id.remove(&id) else {
					return Err(Error::ProtocolViolation);
				};
				tracing::debug!(broadcast = %self.log_path(&path), "unannounced");
				run.announced.retire(&path);
			}
			lite::AnnounceBroadcast::Restart { id, hops, cost } => {
				// Resolve the id; it stays live (the replacement reuses it). An unknown
				// or retired id is a protocol violation.
				let Some(path) = run.announced_by_id.get(&id).cloned() else {
					return Err(Error::ProtocolViolation);
				};
				self.restart_announce(
					path,
					hops,
					cost,
					run.link_cost,
					run.responder_origin,
					&mut run.announced,
				)?;
			}
			lite::AnnounceBroadcast::Skipped => {}
		}
		Ok(())
	}

	/// Records the advertisement either way. Returns `Ok(true)` if it was accepted
	/// and attached a route, or `Ok(false)` if it was declined locally.
	fn start_announce(
		&mut self,
		path: PathOwned,
		mut hops: crate::Hops,
		// The route cost off the wire, i.e. as the peer advertised it.
		// [`Cost::UNKNOWN`] before lite-06, leaving the hop chain as the only
		// routing input as before.
		cost: crate::origin::Cost,
		// This link's price, added to the wire cost.
		link_cost: u64,
		// Lite05+: the announce sender's origin id (from AnnounceOk). The sender no
		// longer stamps itself onto the chain, so we append it here to reconstruct
		// the full `[src...sender]` chain Lite04 stored. None for older versions,
		// where the sender already appended itself.
		responder_origin: Option<crate::Hop>,
		announced: &mut Announced,
	) -> Result<bool, Error> {
		// One current advertisement per prefix per stream. Test what the peer
		// advertised, not only what we accepted locally.
		if announced.contains(&path) {
			return Err(Error::ProtocolViolation);
		}

		// The peer holds this prefix now. Everything below either accepts the announcement,
		// replacing this, or declines it and leaves it exactly as reserved.
		announced.reserve(path.clone());

		if let Some(responder) = responder_origin {
			// A chain already naming the sender came back through it: a reflection, and
			// appending the sender again would name it twice. That is legal in a lite
			// chain but a PROTOCOL_VIOLATION for an IETF peer we forward it to, so it
			// must not enter the model at all. Zero names nobody, so it may repeat.
			if responder != crate::Hop::UNKNOWN && hops.contains(&responder) {
				tracing::debug!(route = %self.log_path(&path), "dropping announce reflected by its sender");
				return Ok(false);
			}
			// If the chain is already full, drop the announce. This is the same decision
			// the Lite04 sender makes at its push site.
			if hops.push(responder).is_err() {
				tracing::warn!(
					route = %self.log_path(&path),
					"dropping announce; hop chain at MAX_HOPS (possible loop)",
				);
				return Ok(false);
			}
		}

		// Drop announces that already passed through us. This connection is
		// a reflection, not a new path. Lite04/05 peers filter these out for us
		// via AnnounceRequest.exclude_hop, but that is only an optimization:
		// this is the authoritative cluster-loop check, and the only one on
		// every other version.
		if hops.contains(&self.self_origin) {
			tracing::debug!(route = %self.log_path(&path), "dropping reflected announce");
			return Ok(false);
		}

		// Lite03 carries its hop count as UNKNOWN placeholders rather than real
		// ids; they stay 0 and count as anonymous. Lite01/02 send no list at all.
		// Either way the chain must have at least the anonymous mark so a
		// downstream hop can see that this path passed through an unidentified hop.
		if hops.is_empty() {
			hops.push(crate::Hop::UNKNOWN)
				.expect("an empty hop chain always has room for one entry, and repeats nothing");
		}

		tracing::debug!(route = %self.log_path(&path), hops = hops.len(), "announce");

		// Announce this session's route into the origin: paths under the prefix
		// resolve through this session on demand. An error means the prefix is
		// outside our scope, so don't serve it. Reflections are already
		// filtered above.
		let route = self.announced_route(hops, cost, link_cost, responder_origin);
		let Ok(dynamic) = self.origin.dynamic(&path, route.clone()) else {
			return Ok(false);
		};

		announced.attach(path, AnnouncedRoute::new(route, dynamic));

		Ok(true)
	}

	/// The route to announce for a prefix this peer advertised, charging our
	/// link's price on top of the cost it advertised.
	///
	/// Once the peer has sent a GOAWAY every route it announces starts out draining,
	/// including a restart of one already attached: a connection on its way out must
	/// not win selection, however good the path it advertises looks.
	fn announced_route(
		&self,
		hops: crate::Hops,
		cost: crate::origin::Cost,
		link_cost: u64,
		responder: Option<crate::Hop>,
	) -> crate::origin::Route {
		let mut route = crate::origin::Route::default()
			.with_hops(hops)
			.with_cost(cost.charged(link_cost))
			.with_via(self.via(responder));

		if self.going_away.is_set() {
			route.cost = crate::origin::Cost::DRAIN;
		}

		route
	}

	/// The announcing session's declared or assigned identity, for split-horizon.
	///
	/// A non-zero AnnounceOk origin is the declared id. Otherwise the caller-assigned
	/// identity stands in, locally: it is never written into the hop chain.
	fn via(&self, responder: Option<crate::Hop>) -> crate::Hop {
		responder
			.filter(|hop| *hop != crate::Hop::UNKNOWN)
			.unwrap_or(self.session_origin)
	}

	/// Handle a RESTART (an explicit restart status, or a duplicate ANNOUNCE on lite-05).
	///
	/// The first hop of the chain identifies the original publisher. When it matches
	/// the prior advertisement and is a real identity, the broadcast is the same
	/// content on a new path: this session's route metadata updates in place,
	/// in-flight tracks keep flowing, and the origin only hands over if the winner
	/// changed. Consumers observe nothing. When the first hop differs, or is
	/// [`Hop::UNKNOWN`](crate::Hop::UNKNOWN), the old route detaches gracefully
	/// and a fresh one attaches, so downstream sees a real Ended + Active.
	/// The advertisement is already live, so this can attach a route even when the
	/// original advertisement was declined locally.
	///
	/// Returns `Ok(false)` if the new hop chain is a reflected loop (this session's
	/// route is now gone), `Ok(true)` otherwise.
	fn restart_announce(
		&mut self,
		path: PathOwned,
		mut hops: crate::Hops,
		// The route cost off the wire and this link's price. See `start_announce`.
		cost: crate::origin::Cost,
		link_cost: u64,
		// Lite05+: the announce sender's origin id (from AnnounceOk), appended here to
		// rebuild the full chain since the sender no longer stamps itself. None for older
		// versions. See `start_announce`.
		responder_origin: Option<crate::Hop>,
		announced: &mut Announced,
	) -> Result<bool, Error> {
		// Reflected loop (or a full chain): detach its route but keep the advertisement live.
		let reflected = match responder_origin {
			// A chain already naming the sender came back through it; see `start_announce`.
			Some(responder) => {
				(responder != crate::Hop::UNKNOWN && hops.contains(&responder))
					|| hops.push(responder).is_err()
					|| hops.contains(&self.self_origin)
			}
			None => hops.contains(&self.self_origin),
		};
		if reflected {
			tracing::debug!(route = %self.log_path(&path), "dropping reflected restart");
			announced.declined(path);
			return Ok(false);
		}

		if hops.is_empty() {
			hops.push(crate::Hop::UNKNOWN)
				.expect("an empty hop chain always has room for one entry, and repeats nothing");
		}

		tracing::debug!(route = %self.log_path(&path), hops = hops.len(), "restart");
		let metadata = self.announced_route(hops, cost, link_cost, responder_origin);

		// A restart is a metadata update: the route keeps its prefix (and its
		// served paths) and re-prices in place. In-flight tracks keep flowing.
		if let Some(entry) = announced.attached(&path) {
			entry.update(metadata);
			return Ok(true);
		}

		let Ok(dynamic) = self.origin.dynamic(&path, metadata.clone()) else {
			announced.declined(path);
			return Ok(false);
		};
		announced.attach(path, AnnouncedRoute::new(metadata, dynamic));

		Ok(true)
	}

	/// Remove a subscription, releasing the session's handle on its producer.
	fn remove_subscribe(&self, id: u64) {
		self.subscribes.lock().remove(&id);
	}

	/// Decode one datagram body and hand it to the matching subscription's producer.
	fn route_datagram(&self, payload: bytes::Bytes) -> Result<(), Error> {
		let mut buf = payload;
		let dg = lite::Datagram::decode(&mut buf, self.version)?;

		// Write through the map rather than cloning the entry out: a `TrackEntry` clone
		// is a handful of atomic bumps on every datagram, and a producer held past its
		// removal would keep the track (its cached groups, its stats subscription) alive.
		// The group path already writes to a producer under this lock.
		let mut subscribes = self.subscribes.lock();
		let Some(entry) = subscribes.get_mut(&dg.subscribe) else {
			// Unknown or already-closed subscription: drop the datagram.
			return Ok(());
		};

		// Datagrams are lite-05+, which always negotiates a timescale; default defensively.
		let scale = entry.timescale.unwrap_or_default();
		let timestamp =
			Timestamp::new(dg.timestamp, scale).map_err(|_| Error::BoundsExceeded(crate::coding::BoundsExceeded))?;

		entry.producer.insert_datagram(dg.sequence, timestamp, dg.payload)?;
		Ok(())
	}

	fn log_path(&self, path: impl AsPath) -> Path<'_> {
		self.origin.root().join(path)
	}
}

/// The subscriber half's driver: the announce prefixes, the uni-stream accept
/// loop, PROBE feedback, datagrams, and the per-source serve machines. Only an
/// error ends it.
// Owns the active subscriptions for exactly as long as the driver. A dropped
// driver is how a cancelled session unwinds, so cleanup cannot depend on any
// poll returning Ready.
struct SubscriptionCleanup(Lock<HashMap<u64, TrackEntry>>);

impl Drop for SubscriptionCleanup {
	fn drop(&mut self) {
		// Group machines own their cancellation cleanup independently. This records
		// session cancellation as the track's terminal state.
		for (_, entry) in self.0.lock().drain() {
			let _ = entry.producer.abort(Error::Cancel);
		}
	}
}

pub(super) struct SubscriberDriver<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	/// Aborts whatever is still subscribed when the driver is dropped.
	_cleanup: SubscriptionCleanup,
	/// One machine per permitted prefix. Only an error ends the session; a
	/// prefix finishing cleanly (publisher FIN) just retires.
	prefixes: Vec<AnnouncePrefix<S>>,
	uni: UniAccept<S>,
	/// PROBE feedback; finishes quietly when unsupported or given up on.
	bandwidth: Option<RecvBandwidth<S>>,
	/// Datagram receive; inert on a version or transport without datagrams.
	datagrams: Option<DatagramRecv<S>>,
	/// One machine per announced source, serving the origin's track requests.
	sources: kio::Tasks<SourceServe<S>>,
}

impl<S: crate::transport::poll::Session> SubscriberDriver<S> {
	pub fn new(subscriber: Subscriber<S>) -> Self {
		// The wire speaks announce interest by prefix: ask for each granted
		// pattern's literal head and let the origin's scope filter what arrives.
		let prefixes = crate::model::interest_prefixes(&subscriber.origin.allowed())
			.into_iter()
			.map(|prefix| AnnouncePrefix::new(subscriber.clone(), prefix))
			.collect();

		Self {
			prefixes,
			_cleanup: SubscriptionCleanup(subscriber.subscribes.clone()),
			uni: UniAccept::new(subscriber.clone()),
			bandwidth: Some(RecvBandwidth::new(subscriber.clone())),
			datagrams: Some(DatagramRecv::new(subscriber.clone())),
			sources: kio::Tasks::new(),
			subscriber,
		}
	}

	pub fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		let mut i = 0;
		while i < self.prefixes.len() {
			match self.prefixes[i].poll(waiter) {
				Poll::Ready(Ok(())) => {
					self.prefixes.swap_remove(i);
				}
				Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
				Poll::Pending => i += 1,
			}
		}
		if let Poll::Ready(res) = self.uni.poll(waiter) {
			return Poll::Ready(res);
		}
		if let Some(bandwidth) = &mut self.bandwidth {
			match bandwidth.poll(waiter) {
				Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
				Poll::Ready(Ok(())) => self.bandwidth = None,
				Poll::Pending => {}
			}
		}
		if let Some(datagrams) = &mut self.datagrams {
			match datagrams.poll(waiter) {
				Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
				Poll::Ready(Ok(())) => self.datagrams = None,
				Poll::Pending => {}
			}
		}

		// Sources created by the announce half; their completion never ends the
		// session (the origin delivers the unannounce itself).
		while let Poll::Ready(Ok((path, dynamic))) = self.subscriber.sources.poll_pop(waiter) {
			self.sources
				.push(SourceServe::new(self.subscriber.clone(), path, dynamic));
		}
		let _ = self.sources.poll(waiter);

		Poll::Pending
	}
}

/// Accepts incoming uni streams (GROUP data plus the peer's SETUP) and drives
/// each as a child machine. Resolves only on a transport error.
struct UniAccept<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	// A dedicated accept handle: the poll interface takes `&mut self`.
	accept: S,
	children: kio::Tasks<UniServe<S>>,
}

impl<S: crate::transport::poll::Session> UniAccept<S> {
	fn new(subscriber: Subscriber<S>) -> Self {
		let accept = subscriber.session.clone();
		Self {
			subscriber,
			accept,
			children: kio::Tasks::new(),
		}
	}

	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		let _ = self.children.poll(waiter);

		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match self.accept.poll_accept_uni(&mut cx) {
				Poll::Ready(Ok(stream)) => {
					self.children.push(UniServe {
						subscriber: self.subscriber.clone(),
						state: UniState::Start {
							reader: Reader::new(stream, self.subscriber.version),
						},
					});
				}
				Poll::Ready(Err(err)) => return Poll::Ready(Err(Error::from_transport(err))),
				Poll::Pending => break,
			}
		}

		// Newly accepted children start now rather than on the next wake.
		let _ = self.children.poll(waiter);
		Poll::Pending
	}
}

/// One accepted uni stream, dispatched on its first varint.
struct UniServe<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	state: UniState<S>,
}

// A state machine's enum is its storage: one transient instance per stream, so the
// big variant is the working state, not padding held in bulk.
#[allow(clippy::large_enum_variant)]
enum UniState<S: crate::transport::poll::Session> {
	/// Reading the stream's type.
	Start {
		reader: Reader<S::RecvStream, Version>,
	},
	/// Reading the peer's single SETUP message, recorded so capability-gated
	/// streams (PROBE) can consult it. lite-05+ only.
	Setup {
		reader: Reader<S::RecvStream, Version>,
	},
	Group(GroupRecv<S>),
	Done,
}

impl<S: crate::transport::poll::Session> kio::Task for UniServe<S> {
	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
		if let Err(err) = ready!(self.poll_serve(waiter)) {
			tracing::debug!(%err, "error running uni stream");
		}
		Poll::Ready(())
	}
}

impl<S: crate::transport::poll::Session> UniServe<S> {
	/// Abort the stream with the given error, wherever the reader currently lives.
	fn abort(&mut self, err: &Error) {
		match &mut self.state {
			UniState::Start { reader } | UniState::Setup { reader } => reader.abort(err),
			UniState::Group(recv) => recv.reader.abort(err),
			UniState::Done => {}
		}
	}

	fn poll_serve(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		loop {
			match &mut self.state {
				UniState::Start { reader } => {
					let mut cx = std::task::Context::from_waker(waiter.waker());
					// A decode error here is only logged; the peer hung up or spoke garbage
					// before the stream had a type.
					let kind = ready!(reader.poll_decode::<lite::DataType>(&mut cx))?;
					let UniState::Start { reader } = std::mem::replace(&mut self.state, UniState::Done) else {
						unreachable!()
					};
					self.state = match kind {
						lite::DataType::Group => UniState::Group(GroupRecv::new(self.subscriber.clone(), reader)),
						lite::DataType::Setup => UniState::Setup { reader },
					};
				}
				UniState::Setup { reader } => {
					if !self.subscriber.version.has_setup_stream() {
						let err = Error::UnexpectedStream;
						self.abort(&err);
						return Poll::Ready(Ok(()));
					}
					let mut cx = std::task::Context::from_waker(waiter.waker());
					let res = ready!(reader.poll_decode::<lite::Setup>(&mut cx));
					match res {
						Ok(setup) => {
							tracing::debug!(?setup, "received peer setup");
							self.subscriber.peer_setup.set(setup);
							return Poll::Ready(Ok(()));
						}
						Err(err) => {
							self.abort(&err);
							return Poll::Ready(Ok(()));
						}
					}
				}
				UniState::Group(recv) => {
					let res = ready!(recv.poll_serve(waiter));
					if let Err(err) = res {
						self.abort(&err);
					}
					return Poll::Ready(Ok(()));
				}
				UniState::Done => return Poll::Ready(Ok(())),
			}
		}
	}
}

/// Receives one GROUP stream into its subscription's track producer.
struct GroupRecv<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	reader: Reader<S::RecvStream, Version>,
	state: GroupRecvState,
}

// A state machine's enum is its storage: one transient instance per stream, so the
// big variant is the working state, not padding held in bulk.
#[allow(clippy::large_enum_variant)]
enum GroupRecvState {
	/// Reading the GROUP header.
	Header,
	/// Filling the group, bailing if the track or group dies first.
	Serve {
		/// Guarded: dropping this machine mid-group is a cancellation, not a clean end.
		group: crate::recv::Group,
		track: track::Producer,
		ingest: FrameIngest,
	},
	Done,
}

impl<S: crate::transport::poll::Session> GroupRecv<S> {
	fn new(subscriber: Subscriber<S>, reader: Reader<S::RecvStream, Version>) -> Self {
		Self {
			subscriber,
			reader,
			state: GroupRecvState::Header,
		}
	}

	fn poll_serve(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		loop {
			match &mut self.state {
				GroupRecvState::Header => {
					let mut cx = std::task::Context::from_waker(waiter.waker());
					let hdr = ready!(self.reader.poll_decode::<lite::Group>(&mut cx))?;

					let (group, track, timescale) = {
						let mut subs = self.subscriber.subscribes.lock();
						let entry = subs.get_mut(&hdr.subscribe).ok_or(Error::Cancel)?;

						let group_info = group::Info { sequence: hdr.sequence };
						// Stats (groups/frames/bytes) are counted in the model as the group
						// is written, through the tagged `track::Producer`.
						let mut group = entry.producer.create_group(group_info)?;
						// The stream may carry only the tail of the group; number the frames
						// from where the publisher said they start so a reader splicing
						// across routes lines them up.
						group.start_at(hdr.frame_start)?;
						(group, entry.producer.clone(), entry.timescale)
					};

					// The timescale came from TRACK_INFO (read before this subscription was
					// even registered), so frames decode immediately. No SUBSCRIBE_OK to
					// wait on.
					self.state = GroupRecvState::Serve {
						group: crate::recv::Group::new(group),
						track,
						ingest: FrameIngest::new(self.subscriber.runtime.clone(), timescale),
					};
				}
				GroupRecvState::Serve { group, track, ingest } => {
					// The track or group dying cancels the stream; the peer's own close
					// arrives through the ingest's reads.
					let res = 'serve: {
						if let Poll::Ready(err) = track.poll_closed(waiter) {
							break 'serve Err(err);
						}
						if let Poll::Ready(err) = group.poll_closed(waiter) {
							break 'serve Err(err);
						}
						match ingest.poll(&mut self.reader, group, waiter) {
							Poll::Ready(res) => break 'serve res,
							Poll::Pending => return Poll::Pending,
						}
					};

					let GroupRecvState::Serve { group, .. } = std::mem::replace(&mut self.state, GroupRecvState::Done)
					else {
						unreachable!()
					};
					match res {
						Ok(()) => {
							let _ = group.finish();
						}
						Err(err @ (Error::Cancel | Error::Stream(crate::StreamError::Cancel))) => {
							let _ = group.abort(err);
						}
						Err(err) => {
							tracing::debug!(%err, group = %group.sequence, "group error");
							let _ = group.abort(err.clone());
							return Poll::Ready(Err(err));
						}
					}
					return Poll::Ready(Ok(()));
				}
				GroupRecvState::Done => return Poll::Ready(Ok(())),
			}
		}
	}
}

/// Pumps bare FRAME messages from a reader into a group producer: the wire
/// format shared by GROUP streams and FETCH responses.
struct FrameIngest {
	runtime: crate::time::Clock,
	/// `Some` decodes the lite-05 zigzag-delta timestamp prefix; `None` stamps
	/// local receive time (pre-lite-05).
	timescale: Option<Timescale>,
	/// Previous frame's raw timestamp value (in `timescale` units), for the
	/// zigzag-delta decode. The first frame's delta is absolute (prev = 0).
	prev_ts: u64,
	phase: IngestPhase,
}

enum IngestPhase {
	/// Reading the timestamp delta (skipped without a timescale). Stream end here
	/// means the group has no more frames.
	Timing,
	/// Reading the frame size. Stream end here also ends the group (pre-lite-05,
	/// where there is no timing prefix to act as the sentinel).
	Size { timestamp: Option<Timestamp> },
	/// Streaming the frame payload.
	Payload { frame: frame::ProducerOwned },
}

impl FrameIngest {
	fn new(runtime: crate::time::Clock, timescale: Option<Timescale>) -> Self {
		Self {
			timescale,
			prev_ts: 0,
			phase: IngestPhase::Timing,
			runtime,
		}
	}

	/// `Ready(Ok(()))` once the stream FINs on a frame boundary. The caller
	/// finishes or aborts the group; a frame cut short mid-payload was already
	/// aborted here with the reason.
	fn poll<R: crate::transport::poll::RecvStream>(
		&mut self,
		reader: &mut Reader<R, Version>,
		group: &mut group::Producer,
		waiter: &kio::Waiter,
	) -> Poll<Result<(), Error>> {
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match &mut self.phase {
				IngestPhase::Timing => {
					let Some(scale) = self.timescale else {
						self.phase = IngestPhase::Size { timestamp: None };
						continue;
					};
					// The timestamp delta doubles as the per-frame sentinel.
					let Some(zz) = ready!(reader.poll_decode_maybe::<crate::coding::VarInt>(&mut cx))? else {
						return Poll::Ready(Ok(()));
					};
					let next: u64 = (self.prev_ts as i128 + zz.to_zigzag() as i128)
						.try_into()
						.map_err(|_| Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
					self.prev_ts = next;
					let timestamp = Timestamp::new(next, scale)
						.map_err(|_| Error::BoundsExceeded(crate::coding::BoundsExceeded))?;
					self.phase = IngestPhase::Size {
						timestamp: Some(timestamp),
					};
				}
				IngestPhase::Size { timestamp } => {
					let Some(size) = ready!(reader.poll_decode_maybe::<u64>(&mut cx))? else {
						return Poll::Ready(Ok(()));
					};
					// `create_frame_owned` is the allocation chokepoint and rejects an
					// oversized `size` before allocating, so no pre-check is needed. No
					// wire timestamp (pre-lite-05) means local receive time.
					let timestamp = timestamp.unwrap_or_else(|| Timestamp::from(self.runtime.now()));
					let frame = group.create_frame_owned(frame::Info { size, timestamp })?;
					self.phase = IngestPhase::Payload { frame };
				}
				IngestPhase::Payload { frame } => {
					let failed = ready!(reader.poll_read_frame(&mut cx, frame)).err();

					let IngestPhase::Payload { frame } = std::mem::replace(&mut self.phase, IngestPhase::Timing) else {
						unreachable!()
					};
					match failed {
						None => frame.finish()?,
						Some(err) => {
							// Fail the group with the reason, not the Drop fallback's
							// generic `Dropped`.
							let _ = frame.abort(err.clone());
							return Poll::Ready(Err(err));
						}
					}
				}
			}
		}
	}
}

/// Receives QUIC datagrams and routes each to its subscription's track producer
/// (lite-05 §6.4).
///
/// A decode error or an unknown subscribe id drops that datagram without tearing
/// down the session (best-effort); only a transport-level failure ends the loop.
struct DatagramRecv<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	// A dedicated receive handle: the poll interface takes `&mut self`.
	recv: S,
	enabled: bool,
}

impl<S: crate::transport::poll::Session> DatagramRecv<S> {
	fn new(subscriber: Subscriber<S>) -> Self {
		let recv = subscriber.session.clone();
		let enabled = subscriber.version.has_datagrams() && recv.max_datagram_size() > 0;
		Self {
			subscriber,
			recv,
			enabled,
		}
	}

	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		if !self.enabled {
			return Poll::Ready(Ok(()));
		}
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			let payload = ready!(self.recv.poll_recv_datagram(&mut cx)).map_err(Error::from_transport)?;
			if let Err(err) = self.subscriber.route_datagram(payload) {
				tracing::debug!(%err, "dropping datagram");
			}
		}
	}
}

/// Opens a PROBE stream on demand while a consumer is interested.
///
/// Loops forever: wait for a consumer, race the probe stream against the
/// consumer leaving, then loop back. Probe is best-effort, so stream errors are
/// logged but never tear down the session.
struct RecvBandwidth<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	state: BandwidthState<S>,
}

// A state machine's enum is its storage: one transient instance per stream, so the
// big variant is the working state, not padding held in bulk.
#[allow(clippy::large_enum_variant)]
enum BandwidthState<S: crate::transport::poll::Session> {
	/// lite-05+ negotiates probing: only open a PROBE stream if the peer
	/// advertised it (Report or higher) in its SETUP. Older versions have no
	/// SETUP, so probe is always available there.
	Gate,
	/// Wait until at least one consumer is interested in the estimate.
	WaitUsed,
	/// Race the last consumer leaving against the probe stream ending.
	Probing(ProbeStream<S>),
}

impl<S: crate::transport::poll::Session> RecvBandwidth<S> {
	fn new(subscriber: Subscriber<S>) -> Self {
		Self {
			subscriber,
			state: BandwidthState::Gate,
		}
	}

	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		loop {
			match &mut self.state {
				BandwidthState::Gate => {
					if self.subscriber.recv_bandwidth.is_none() {
						return Poll::Ready(Ok(()));
					}
					if self.subscriber.version.has_setup_stream()
						&& ready!(self.subscriber.peer_setup.poll_probe_level(waiter)) < lite::ProbeLevel::Report
					{
						tracing::debug!("peer does not support probing; skipping probe stream");
						return Poll::Ready(Ok(()));
					}
					self.state = BandwidthState::WaitUsed;
				}
				BandwidthState::WaitUsed => {
					let bandwidth = self.subscriber.recv_bandwidth.as_ref().expect("gated above");
					match ready!(bandwidth.poll_used(waiter)) {
						Ok(()) => self.state = BandwidthState::Probing(ProbeStream::new(&self.subscriber)),
						Err(_) => return Poll::Ready(Ok(())),
					}
				}
				BandwidthState::Probing(probe) => {
					let bandwidth = self.subscriber.recv_bandwidth.as_ref().expect("gated above");
					match bandwidth.poll_unused(waiter) {
						// Loop back: a new consumer may arrive later. Dropping the probe
						// machine resets its stream.
						Poll::Ready(Ok(())) => {
							self.state = BandwidthState::WaitUsed;
							continue;
						}
						// The channel closed: give up for the rest of the session.
						Poll::Ready(Err(_)) => return Poll::Ready(Ok(())),
						Poll::Pending => {}
					}
					match ready!(probe.poll(waiter)) {
						Ok(()) => tracing::debug!("probe stream closed"),
						Err(err) => tracing::warn!(%err, "probe stream error"),
					}
					// The stream ended (peer FIN'd or errored). Don't hammer an
					// uncooperative peer; give up for the rest of the session.
					return Poll::Ready(Ok(()));
				}
			}
		}
	}
}

/// One PROBE stream: send the type, then feed the peer's estimates into the
/// bandwidth producer until it FINs.
struct ProbeStream<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	session: S,
	state: ProbeState<S>,
}

enum ProbeState<S: crate::transport::poll::Session> {
	Open,
	Send { stream: Stream<S, Version> },
	Read { stream: Stream<S, Version> },
}

impl<S: crate::transport::poll::Session> ProbeStream<S> {
	fn new(subscriber: &Subscriber<S>) -> Self {
		Self {
			subscriber: subscriber.clone(),
			session: subscriber.session.clone(),
			state: ProbeState::Open,
		}
	}

	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match &mut self.state {
				ProbeState::Open => {
					// After a GOAWAY the peer must not see new streams. Probe is
					// best-effort; skip it rather than erroring.
					if self.subscriber.going_away.is_set() {
						return Poll::Ready(Ok(()));
					}
					let mut stream = ready!(Stream::poll_open(&mut self.session, self.subscriber.version, &mut cx))?;
					stream.writer.buffer(&lite::ControlType::Probe)?;
					self.state = ProbeState::Send { stream };
				}
				ProbeState::Send { stream } => {
					ready!(stream.writer.poll_flush(&mut cx))?;
					let ProbeState::Send { stream } = std::mem::replace(&mut self.state, ProbeState::Open) else {
						unreachable!()
					};
					self.state = ProbeState::Read { stream };
				}
				ProbeState::Read { stream } => {
					let bandwidth = self.subscriber.recv_bandwidth.as_ref().expect("gated by RecvBandwidth");
					loop {
						let Some(probe) = ready!(stream.reader.poll_decode_maybe::<lite::Probe>(&mut cx))? else {
							return Poll::Ready(Ok(()));
						};
						bandwidth.set(probe.bitrate.map(bandwidth::Rate::from_bps))?;
					}
				}
			}
		}
	}
}

/// One announce-interest stream: sends the ANNOUNCE_REQUEST for a prefix, then
/// feeds every received announce into the origin. Only its *error* ends the
/// session; a publisher FIN is a clean end for the prefix alone.
struct AnnouncePrefix<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	prefix: PathOwned,
	state: PrefixState<S>,
}

enum PrefixState<S: crate::transport::poll::Session> {
	/// Opening the control stream (after the GOAWAY gate).
	Open,
	/// Flushing the buffered request.
	Send { stream: Stream<S, Version> },
	/// Lite05+: reading the publisher's ANNOUNCE_OK.
	ReadOk { stream: Stream<S, Version> },
	/// Waiting for the link cost (may block on the peer's SETUP).
	Cost {
		stream: Stream<S, Version>,
		responder_origin: Option<crate::Hop>,
	},
	/// Lite01/02: reading the ANNOUNCE_INIT set.
	ReadInit { stream: Stream<S, Version>, run: PrefixRun },
	/// Streaming announce updates.
	Run { stream: Stream<S, Version>, run: PrefixRun },
}

/// The announce-decode loop's state, split out so the states above can share it.
struct PrefixRun {
	responder_origin: Option<crate::Hop>,
	/// What we charge every announcement arriving on this stream. Resolved once:
	/// it comes from the connect config or the peer's SETUP, neither of which
	/// changes for the life of the session.
	link_cost: u64,
	announced: Announced,
	// Lite06+: announce ids. Each received `active` implicitly assigns the next
	// per-stream ordinal; `ended`/`restart` reference it instead of repeating the
	// path. Tracked even for announces we drop locally (reflected loops), since
	// the sender doesn't know we dropped them. We never send a restart ourselves,
	// but a peer may.
	next_announce_id: u64,
	announced_by_id: HashMap<u64, PathOwned>,
}

impl<S: crate::transport::poll::Session> AnnouncePrefix<S> {
	fn new(subscriber: Subscriber<S>, prefix: PathOwned) -> Self {
		Self {
			subscriber,
			prefix,
			state: PrefixState::Open,
		}
	}

	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match &mut self.state {
				PrefixState::Open => {
					// A peer that sent GOAWAY told us to stop opening streams on this session.
					self.subscriber.check_going_away()?;
					let mut stream = ready!(Stream::poll_open(
						&mut self.subscriber.session,
						self.subscriber.version,
						&mut cx
					))?;

					stream.writer.buffer(&lite::ControlType::Announce)?;
					// Lite04/05: ask the peer to filter out announces that already passed
					// through us, so the reflected ones never hit the wire. Encoding drops
					// this on every other version, where start_announce below is the only
					// filter.
					// Hidden routes are requested too: the session mirrors the peer into
					// the origin, and each local reader opts in on its own
					// (`origin::Consumer::with_hidden`).
					stream.writer.buffer(&lite::AnnounceRequest {
						prefix: self.prefix.as_path(),
						exclude_hop: self.subscriber.self_origin.id(),
						hidden: true,
					})?;
					self.state = PrefixState::Send { stream };
				}
				PrefixState::Send { stream } => {
					ready!(stream.writer.poll_flush(&mut cx))?;
					let PrefixState::Send { stream } = std::mem::replace(&mut self.state, PrefixState::Open) else {
						unreachable!()
					};
					self.state = match self.subscriber.version.has_announce_ok() {
						true => PrefixState::ReadOk { stream },
						false => PrefixState::Cost {
							stream,
							responder_origin: None,
						},
					};
				}
				PrefixState::ReadOk { stream } => {
					// Lite05+: the publisher reports its own origin id, which we stamp onto
					// every received Announce's hop chain since it no longer does so itself.
					// Its `active` count marks where the initial set ends; nothing here needs
					// that boundary, so it is read and dropped. Callers that must not race an
					// announcement use `origin::Consumer::announced_broadcast`, which waits
					// for the path itself.
					let ok = ready!(stream.reader.poll_decode::<lite::AnnounceOk>(&mut cx))?;
					// A peer may legally report id 0 (no identity). Keep it: the assigned
					// identity stays on `via` and is never forwarded as a hop.
					let origin = ok.origin;
					let PrefixState::ReadOk { stream } = std::mem::replace(&mut self.state, PrefixState::Open) else {
						unreachable!()
					};
					self.state = PrefixState::Cost {
						stream,
						responder_origin: Some(origin),
					};
				}
				PrefixState::Cost { .. } => {
					let link_cost = ready!(self.subscriber.poll_link_cost(waiter));
					let PrefixState::Cost {
						stream,
						responder_origin,
					} = std::mem::replace(&mut self.state, PrefixState::Open)
					else {
						unreachable!()
					};

					let run = PrefixRun {
						responder_origin,
						link_cost,
						announced: Announced::default(),
						next_announce_id: 0,
						announced_by_id: HashMap::new(),
					};

					// Lite01/02 send the initial set as one ANNOUNCE_INIT message, so they
					// read that before the update stream. Every other version streams it as
					// ordinary announces.
					self.state = match self.subscriber.version {
						Version::Lite01 | Version::Lite02 => PrefixState::ReadInit { stream, run },
						_ => PrefixState::Run { stream, run },
					};
				}
				PrefixState::ReadInit { stream, run } => {
					let msg = ready!(stream.reader.poll_decode::<lite::AnnounceInit>(&mut cx))?;
					for suffix in msg.suffixes {
						let path = self.prefix.join(&suffix);
						// Lite01/02 don't carry hop information; the broadcast starts with
						// an empty chain and an unpriced link. Stats are attributed in the
						// model when this enters the origin via `create_broadcast`.
						self.subscriber.start_announce(
							path,
							crate::Hops::new(),
							crate::origin::Cost::UNKNOWN,
							0,
							run.responder_origin,
							&mut run.announced,
						)?;
					}
					let PrefixState::ReadInit { stream, run } = std::mem::replace(&mut self.state, PrefixState::Open)
					else {
						unreachable!()
					};
					self.state = PrefixState::Run { stream, run };
				}
				PrefixState::Run { stream, run } => {
					// A draining peer usually stops announcing, so react to the
					// GOAWAY itself; waiting for another message would leave the
					// route primary until the session finally closed. Idempotent,
					// since the signal stays set.
					if self.subscriber.going_away.poll(waiter).is_ready() {
						run.announced.drain();
					}
					// Drain every buffered announce BEFORE serving requests: a route
					// this pass attaches must have its request queue polled (and this
					// machine's waiter registered on it) below, in the same pass.
					// Serving first and then parking on the decode would strand a
					// request that arrives in between: its wake finds no waiter, and
					// nothing else re-polls this machine.
					loop {
						match stream.reader.poll_decode_maybe::<lite::AnnounceBroadcast>(&mut cx) {
							Poll::Ready(Ok(Some(announce))) => {
								self.subscriber.handle_announce(&self.prefix, announce, run)?;
							}
							Poll::Ready(Ok(None)) => {
								// The publisher FINed: it has nothing (more) to announce for this
								// prefix (e.g. a publish-only peer). That's a clean completion of
								// this announce stream, not a session error, so finish our side
								// and return Ok. Tearing down only the announce stream is correct
								// since no further progress can be made, but we must not
								// propagate an error that would kill the whole connection.
								stream.writer.finish().ok();
								return Poll::Ready(Ok(()));
							}
							Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
							Poll::Pending => break,
						}
					}
					// Materialize requested paths under the attached routes; leaves the
					// waiter registered on every route's request queue.
					run.announced.poll_serve(&self.subscriber, waiter);
					return Poll::Pending;
				}
			}
		}
	}
}

/// Serves the origin's track requests for one announced source until the peer
/// unannounces it (the source is finished) or the session dies. An unannounce
/// takes no new tracks but lets those in flight run to their own end (moq-lite:
/// retraction does not disturb subscriptions already in flight); the session
/// dying drops them.
struct SourceServe<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	path: PathOwned,
	dynamic: crate::broadcast::Dynamic,
	// A dedicated close-watch handle, since each pending operation needs its own.
	closed: S,
	tracks: kio::Tasks<TrackServeRun<S>>,
	// The source ended: no more track requests will arrive.
	ended: bool,
}

impl<S: crate::transport::poll::Session> SourceServe<S> {
	fn new(subscriber: Subscriber<S>, path: PathOwned, dynamic: crate::broadcast::Dynamic) -> Self {
		let closed = subscriber.session.clone();
		Self {
			subscriber,
			path,
			dynamic,
			closed,
			tracks: kio::Tasks::new(),
			ended: false,
		}
	}
}

impl<S: crate::transport::poll::Session> kio::Task for SourceServe<S> {
	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
		let _ = self.tracks.poll(waiter);

		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			if self.closed.poll_closed(&mut cx).is_ready() {
				// Session gone.
				return Poll::Ready(());
			}
			if self.ended {
				// Done once the tracks in flight are.
				return self.tracks.poll(waiter);
			}
			match self.dynamic.poll_requested_track(waiter) {
				Poll::Ready(Ok(request)) => {
					let serve = TrackServe {
						subscriber: self.subscriber.clone(),
						path: self.path.clone(),
						name: request.name().to_string(),
					};
					// One machine per track serves its lone subscription and any number
					// of fetches concurrently.
					self.tracks.push(TrackServeRun::new(serve, request));
				}
				// The source was finished (unannounced) or aborted.
				Poll::Ready(Err(err)) => {
					tracing::debug!(%err, "source closed");
					self.ended = true;
				}
				Poll::Pending => break,
			}
		}

		// Newly requested tracks start now rather than on the next wake.
		let _ = self.tracks.poll(waiter);
		Poll::Pending
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::coding::{Decode, Encode};
	use crate::lite::test_transport::SinkSession;
	use crate::model::ProduceTest;
	use futures::FutureExt;

	const VERSION: Version = Version::Lite05;

	/// Removing a subscription both stops delivery and releases the session's handle
	/// on the producer, so the track (its cached groups, its stats subscription) ends
	/// rather than outliving the subscription it belonged to.
	#[test]
	fn unsubscribe_drops_the_datagram_and_releases_the_producer() {
		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::default(),
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			peer_hop: None,
			cost: None,
			going_away: Default::default(),
		});

		let broadcast = crate::broadcast::Info::new().produce();
		// The broadcast keeps only a weak handle, so the map below owns the only strong
		// `track::Producer`: dropping it is what ends the track.
		let producer = broadcast.create_track("datagrams", None).unwrap();
		let mut received = producer.subscribe(None);
		subscriber.subscribes.lock().insert(
			7,
			TrackEntry {
				producer,
				timescale: Some(Timescale::default()),
			},
		);

		let payload = |sequence| {
			lite::Datagram {
				subscribe: 7,
				sequence,
				timestamp: sequence,
				payload: bytes::Bytes::from_static(b"x"),
			}
			.encode_bytes(VERSION)
			.unwrap()
		};
		subscriber.route_datagram(payload(1)).unwrap();
		assert_eq!(
			received
				.recv_datagram()
				.now_or_never()
				.unwrap()
				.unwrap()
				.unwrap()
				.sequence,
			1
		);

		subscriber.remove_subscribe(7);
		subscriber.route_datagram(payload(2)).unwrap();
		// Dropping the last producer is an abrupt teardown, so the track resolves with
		// `Dropped` rather than parking. A route that outlived the removal would keep the
		// producer alive and leave this pending forever.
		assert!(
			matches!(received.recv_datagram().now_or_never(), Some(Err(Error::Dropped))),
			"the track outlived its subscription"
		);
	}

	/// `establish` puts exactly one SUBSCRIBE on the wire, and the id is registered
	/// before any of it reaches the transport.
	///
	/// Both halves matter: a second stream re-requests the same id, which the peer is
	/// free to serve twice, and a late insert loses the race with a publisher that
	/// serves its first group the instant it reads the request (`recv_group` drops a
	/// group whose id isn't in the map yet).
	#[tokio::test]
	async fn establish_sends_one_registered_subscribe() {
		// Writes park until this opens, so the assertions below run at the exact moment
		// the request would hit the wire.
		let gate = kio::Producer::new(false);
		let session = SinkSession::gated_bi(gate.consume());

		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: session.clone(),
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			peer_hop: None,
			cost: None,
			going_away: Default::default(),
		});
		let subscribes = subscriber.subscribes.clone();
		let serve = TrackServe {
			subscriber,
			path: Path::new("room/host").to_owned(),
			name: "catalog.json".to_string(),
		};

		let broadcast = crate::broadcast::Info::new().produce();
		let mut producer = broadcast.create_track("catalog.json", None).unwrap();
		let mut sub = Sub::None;
		let mut establish = std::pin::pin!(serve.establish(
			&mut producer,
			&mut sub,
			Subscription::default(),
			Some(Timescale::default()),
		));

		// Parked on the first write: the stream is open and nothing has been sent yet.
		assert!(futures::poll!(establish.as_mut()).is_pending());
		assert_eq!(session.log.bi_opens(), 1);
		assert!(subscribes.lock().contains_key(&0), "registered before the wire");

		let Ok(mut open) = gate.write() else {
			panic!("gate closed")
		};
		*open = true;
		drop(open);

		establish.await.unwrap();

		// One request, on one stream, and nothing else behind it.
		assert_eq!(session.log.bi_opens(), 1);

		let writes = session.log.writes.lock().unwrap().clone();
		let mut wire = writes.as_slice();
		assert_eq!(
			lite::ControlType::decode(&mut wire, VERSION).unwrap(),
			lite::ControlType::Subscribe
		);
		let msg = lite::Subscribe::decode(&mut wire, VERSION).unwrap();
		assert_eq!(msg.id, 0);
		assert_eq!(msg.track, "catalog.json");
		assert!(wire.is_empty(), "a second SUBSCRIBE trailed the first");
	}

	/// Everything a `handle_subscription` test needs to stay alive for the call.
	struct Harness {
		serve: TrackServe<SinkSession>,
		session: SinkSession,
		producer: track::Producer,
		_broadcast: crate::broadcast::Producer,
		_gate: kio::Producer<bool>,
	}

	impl Harness {
		/// A `TrackServe` writing straight to a sink session at `version`.
		fn new(version: Version) -> Self {
			// Open the gate up front: these tests assert what reached the wire, not
			// what was true at the instant it would.
			let gate = kio::Producer::new(true);
			let session = SinkSession::gated_bi(gate.consume());
			let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
			let subscriber = Subscriber::new(SubscriberConfig {
				runtime: crate::time::Clock::tokio(),
				session: session.clone(),
				origin,
				recv_bandwidth: None,
				version,
				peer_setup: Default::default(),
				peer_hop: None,
				cost: None,
				going_away: Default::default(),
			});
			let broadcast = crate::broadcast::Info::new().produce();
			let producer = broadcast.create_track("catalog.json", None).unwrap();

			Self {
				serve: TrackServe {
					subscriber,
					path: Path::new("room/host").to_owned(),
					name: "catalog.json".to_string(),
				},
				session,
				producer,
				_broadcast: broadcast,
				_gate: gate,
			}
		}

		/// Everything written to the session so far.
		fn wire(&self) -> Vec<u8> {
			self.session.log.writes.lock().unwrap().clone()
		}
	}

	/// The `(group, frame)` bounds `resume::slice` produces after a mid-group takeover: a
	/// subscriber resuming at frame 3 of group 5, capped by a later boundary in the same
	/// group.
	fn mid_group_demand() -> Subscription {
		Subscription::default()
			.with_start(Position { group: 5, frame: 3 })
			.with_end(Position::after(5, 7))
	}

	/// A mid-group resume boundary handed to a peer that predates lite-06 is widened to
	/// the whole group rather than refused.
	///
	/// The codec rejects a frame bound such a peer cannot carry, so passing the demand
	/// through unchanged fails the SUBSCRIBE and hands the track back. The origin then
	/// re-splices the same route indefinitely, since the splice itself keeps succeeding
	/// and the retry budget never trips.
	#[tokio::test]
	async fn frame_bounds_widen_for_an_older_peer() {
		let mut h = Harness::new(Version::Lite05);
		let mut sub = Sub::None;

		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(mid_group_demand()),
				true,
				Some(Timescale::default()),
			)
			.await
			.expect("an older peer must not fail the subscribe");

		let wire = h.wire();
		let mut wire = wire.as_slice();
		assert_eq!(
			lite::ControlType::decode(&mut wire, Version::Lite05).unwrap(),
			lite::ControlType::Subscribe
		);
		let msg = lite::Subscribe::decode(&mut wire, Version::Lite05).unwrap();
		// The group bounds survive; only the frame offsets are widened away.
		assert_eq!((msg.start_group, msg.end_group), (Some(5), Some(5)));
		assert_eq!((msg.start_frame, msg.end_frame), (0, None));
	}

	/// The same demand on a lite-06 peer keeps its frame offsets, so the widening is
	/// version-gated rather than unconditional.
	#[tokio::test]
	async fn frame_bounds_survive_on_a_lite06_peer() {
		let mut h = Harness::new(Version::Lite06);
		let mut sub = Sub::None;

		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(mid_group_demand()),
				true,
				Some(Timescale::default()),
			)
			.await
			.unwrap();

		let wire = h.wire();
		let mut wire = wire.as_slice();
		assert_eq!(
			lite::ControlType::decode(&mut wire, Version::Lite06).unwrap(),
			lite::ControlType::Subscribe
		);
		let msg = lite::Subscribe::decode(&mut wire, Version::Lite06).unwrap();
		assert_eq!((msg.start_frame, msg.end_frame), (3, Some(7)));
	}

	/// The model's exclusive end maps back to the wire's inclusive pair.
	///
	/// The two disagree deliberately (see [`Subscription::end`]), so this pins the seam:
	/// an end at the head of a group means the group below it, served whole, while one
	/// mid-group caps the frame below it. Off by one here would silently drop or
	/// duplicate a frame at every relay hop.
	#[test]
	fn wire_bounds_convert_the_exclusive_end() {
		// The whole of group 5 is the head of group 6.
		let bounds = WireBounds::new(None, Some(Position::group(6)));
		assert_eq!((bounds.end_group, bounds.end_frame), (Some(5), None));

		// Group 5 through frame 2 is the head of frame 3.
		let bounds = WireBounds::new(None, Some(Position { group: 5, frame: 3 }));
		assert_eq!((bounds.end_group, bounds.end_frame), (Some(5), Some(2)));

		// Unbounded stays unbounded.
		let bounds = WireBounds::new(None, None);
		assert_eq!((bounds.end_group, bounds.end_frame), (None, None));

		// Starts are inclusive on both sides, so they pass straight through.
		let bounds = WireBounds::new(Some(Position { group: 5, frame: 3 }), None);
		assert_eq!((bounds.start_group, bounds.start_frame), (Some(5), 3));
	}

	/// The builders produce exactly what the wire conversion expects, so an inclusive
	/// bound survives the trip out to a peer unchanged.
	#[test]
	fn wire_bounds_match_the_builders() {
		let whole = Subscription::default().with_end(Position::after_group(5));
		let bounds = WireBounds::new(whole.start, whole.end);
		assert_eq!((bounds.end_group, bounds.end_frame), (Some(5), None));

		let capped = Subscription::default().with_end(Position::after(5, 2));
		let bounds = WireBounds::new(capped.start, capped.end);
		assert_eq!((bounds.end_group, bounds.end_frame), (Some(5), Some(2)));

		let started = Subscription::default().with_start(Position { group: 5, frame: 3 });
		let bounds = WireBounds::new(started.start, started.end);
		assert_eq!((bounds.start_group, bounds.start_frame), (Some(5), 3));
	}

	/// A subscription that asks for nothing opens nothing.
	///
	/// `Position::group(0)` is the empty range: nothing sorts below it. The wire cannot
	/// say that, and the nearest thing it can say is "through group 0", which would
	/// deliver the single group the caller excluded.
	#[tokio::test]
	async fn an_empty_range_opens_no_subscription() {
		let mut h = Harness::new(Version::Lite06);
		let mut sub = Sub::None;

		let empty = Subscription::default().with_end(Position::group(0));
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, Some(empty), true, Some(Timescale::default()))
			.await
			.unwrap();

		assert!(matches!(sub, Sub::None), "must not open a subscription");
		assert!(h.wire().is_empty(), "nothing reached the wire");
	}

	/// Demand collapsing to nothing cancels the upstream rather than sending a bound
	/// that means the opposite.
	#[tokio::test]
	async fn an_empty_range_cancels_a_live_subscription() {
		let mut h = Harness::new(Version::Lite06);
		let mut sub = Sub::None;

		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(Subscription::default()),
				true,
				Some(Timescale::default()),
			)
			.await
			.unwrap();
		assert!(matches!(sub, Sub::Active(_)), "the first subscriber opens one");
		let established = h.wire().len();

		let empty = Subscription::default().with_end(Position::group(0));
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, Some(empty), true, Some(Timescale::default()))
			.await
			.unwrap();

		assert!(matches!(sub, Sub::None), "the upstream must be canceled");
		assert_eq!(h.wire().len(), established, "no SUBSCRIBE_UPDATE claiming group 0");
	}

	/// Bounds that meet anywhere in the track are just as empty as ones that meet at the
	/// first position.
	///
	/// The wire has no encoding for either: an exclusive end at a group head floors to
	/// the group below it, so group 5 through group 5 would go out as `start_group = 5`,
	/// `end_group = 4`, an inverted range the publisher happily parks on.
	#[tokio::test]
	async fn a_nonzero_empty_range_opens_no_subscription() {
		let mut h = Harness::new(Version::Lite06);
		let mut sub = Sub::None;

		let empty = Subscription::default()
			.with_start(Position::group(5))
			.with_end(Position::group(5));
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, Some(empty), true, Some(Timescale::default()))
			.await
			.unwrap();

		assert!(matches!(sub, Sub::None), "must not open a subscription");
		assert!(h.wire().is_empty(), "nothing reached the wire");
	}

	/// Demand collapsing to an empty range mid-track cancels the upstream, the same way
	/// it does at the first position.
	#[tokio::test]
	async fn a_nonzero_empty_range_cancels_a_live_subscription() {
		let mut h = Harness::new(Version::Lite06);
		let mut sub = Sub::None;

		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(Subscription::default()),
				true,
				Some(Timescale::default()),
			)
			.await
			.unwrap();
		assert!(matches!(sub, Sub::Active(_)), "the first subscriber opens one");
		let established = h.wire().len();

		let empty = Subscription::default()
			.with_start(Position::group(5))
			.with_end(Position::group(5));
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, Some(empty), true, Some(Timescale::default()))
			.await
			.unwrap();

		assert!(matches!(sub, Sub::None), "the upstream must be canceled");
		assert_eq!(h.wire().len(), established, "no SUBSCRIBE_UPDATE inverting the range");
	}

	/// Widening rounds the end outward at the last group too, keeping the range at least
	/// as wide as the request.
	///
	/// Rounding inward there would empty a range the caller asked for, and the filter in
	/// `handle_subscription` runs before the widening, so nothing downstream would catch
	/// it.
	#[tokio::test]
	async fn frame_bounds_widen_outward_at_the_last_group() {
		let h = Harness::new(Version::Lite05);

		let mut subscription = Subscription::default()
			.with_start(Position {
				group: u64::MAX,
				frame: 1,
			})
			.with_end(Position::after(u64::MAX, 5));
		h.serve.widen_frame_bounds(&mut subscription);

		assert_eq!(subscription.start, Some(Position::group(u64::MAX)));
		// Past the last group there is no position to round up to, and unbounded is the
		// wider request.
		assert_eq!(subscription.end, None);
	}

	/// The widening covers SUBSCRIBE_UPDATE too: a downstream peer asking for a frame
	/// offset must not tear down an older upstream that is already serving.
	#[tokio::test]
	async fn frame_bounds_widen_on_update() {
		let mut h = Harness::new(Version::Lite05);
		let mut sub = Sub::None;

		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(Subscription::default()),
				true,
				Some(Timescale::default()),
			)
			.await
			.unwrap();
		let established = h.wire().len();

		// A lite-06 subscriber downstream now wants to resume mid-group.
		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(mid_group_demand()),
				true,
				Some(Timescale::default()),
			)
			.await
			.expect("a downstream frame offset must not tear down an older upstream");

		// SUBSCRIBE_UPDATE rides the subscribe stream with no control type ahead of it.
		let wire = h.wire();
		let mut wire = &wire[established..];
		let msg = lite::SubscribeUpdate::decode(&mut wire, Version::Lite05).unwrap();
		assert_eq!((msg.start_group, msg.start_frame), (Some(5), 0));
		assert_eq!((msg.end_group, msg.end_frame), (Some(5), None));
	}

	/// A buffered SUBSCRIBE_START describes the demand its SUBSCRIBE carried, so
	/// it applies exactly while the current start matches that demand: an update
	/// that moves the start makes it stale (applying it could reopen a range the
	/// publisher no longer serves, or clamp one it still does), and an update
	/// that moves back restores it (the publisher declared that range gone and
	/// sends no replacement START).
	#[tokio::test]
	async fn buffered_start_applies_iff_demand_matches() {
		let mut h = Harness::new(Version::Lite05);
		let mut sub = Sub::None;

		let demand = |group: u64| Some(Subscription::default().with_start(Position::group(group)));
		let applies = |sub: &Sub<SinkSession>| matches!(sub, Sub::Active(active) if active.start == active.requested);

		// Establish from group 3; the peer's START is considered in flight.
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, demand(3), true, Some(Timescale::default()))
			.await
			.unwrap();
		assert!(applies(&sub), "a fresh subscription accepts its START");

		// An end-only update leaves the start intact: the START stays valid.
		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(
					Subscription::default()
						.with_start(Position::group(3))
						.with_end(Position::group(9)),
				),
				true,
				Some(Timescale::default()),
			)
			.await
			.unwrap();
		assert!(applies(&sub), "an unmoved start keeps the START applicable");

		// The start moves: a buffered START is stale while it sits elsewhere.
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, demand(8), true, Some(Timescale::default()))
			.await
			.unwrap();
		assert!(!applies(&sub), "a moved start must invalidate a buffered START");

		// The start returns: the declaration matches the demand again, so the
		// publisher's skip (it sends no replacement START) must land.
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, demand(3), true, Some(Timescale::default()))
			.await
			.unwrap();
		assert!(applies(&sub), "demand returning restores the START");
	}

	/// The permanent-miss floor follows the demand in every direction: an update
	/// that moves the start forward retires the skipped range (the publisher
	/// stops serving it and no fresh START says so), one that moves it backward
	/// reopens it, and dropping to the live edge clears it entirely.
	#[tokio::test]
	async fn updates_move_the_declared_floor_both_ways() {
		let mut h = Harness::new(Version::Lite05);
		let mut sub = Sub::None;

		let demand = |group: u64| Some(Subscription::default().with_start(Position::group(group)));

		// Establish from group 5: the floor tracks the request until START lands.
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, demand(5), true, Some(Timescale::default()))
			.await
			.unwrap();
		assert_eq!(h.producer.start_sequence(), Some(5));

		// Forward: a reader waiting in [5, 8) must fail over, not stall.
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, demand(8), true, Some(Timescale::default()))
			.await
			.unwrap();
		assert_eq!(h.producer.start_sequence(), Some(8));

		// Backward: the reopened range must stop being a permanent miss.
		h.serve
			.handle_subscription(&mut h.producer, &mut sub, demand(3), true, Some(Timescale::default()))
			.await
			.unwrap();
		assert_eq!(h.producer.start_sequence(), Some(3));

		// Live edge: the floor is unknown until the next declaration, so a
		// group below the stale one must not be a permanent miss.
		h.serve
			.handle_subscription(
				&mut h.producer,
				&mut sub,
				Some(Subscription::default()),
				true,
				Some(Timescale::default()),
			)
			.await
			.unwrap();
		assert_eq!(h.producer.start_sequence(), None);
	}

	/// A second announce for a live path is a protocol error whatever its hops say. It
	/// must be caught before the reflection drops, because the caller has already bound
	/// an announce id to it: dropping it silently leaves that id pointing at a path
	/// owned by the earlier announce, and the `ANNOUNCE_END` that follows retires the
	/// wrong route.
	#[tokio::test]
	async fn a_double_announce_is_an_error_even_when_reflected() {
		let assigned = crate::Hop::new(777).unwrap();
		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: Some(assigned),
			going_away: Default::default(),
		});

		let path = Path::new("room/host").to_owned();
		let mut announced = Announced::default();
		assert!(
			subscriber
				.start_announce(
					path.clone(),
					crate::Hops::new(),
					crate::origin::Cost::default(),
					0,
					Some(assigned),
					&mut announced,
				)
				.unwrap()
		);

		// The same path again, this time with a chain that names the sender.
		let mut reflected = crate::Hops::new();
		reflected.push(assigned).unwrap();
		assert!(
			matches!(
				subscriber.start_announce(
					path.clone(),
					reflected,
					crate::origin::Cost::default(),
					0,
					Some(assigned),
					&mut announced,
				),
				Err(Error::ProtocolViolation)
			),
			"the double announce must be reported, not silently dropped",
		);
	}

	/// Every path out of `start_announce` that declines an announce records it first.
	///
	/// The decline paths are a list one edit can fall off the end of, and a miss is silent:
	/// the path reads as free, a later announce takes it, and the declined one's
	/// `ANNOUNCE_END` retires that route instead. This walks a reflection: the chain
	/// already names this session.
	#[tokio::test]
	async fn every_declined_announce_is_recorded() {
		let assigned = crate::Hop::new(777).unwrap();
		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin,
			recv_bandwidth: None,
			version: Version::Lite03,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: Some(assigned),
			going_away: Default::default(),
		});

		let path = Path::new("room/host").to_owned();
		let mut announced = Announced::default();

		// A chain that already names us is a reflection, declined but still recorded.
		let hops = crate::Hops::try_from(vec![crate::Hop::new(1).unwrap()]).unwrap();
		assert!(
			!subscriber
				.start_announce(
					path.clone(),
					hops,
					crate::origin::Cost::default(),
					0,
					None,
					&mut announced
				)
				.unwrap(),
			"a chain that already names this session must be declined",
		);

		// Declined, but still the peer's advertisement at that path.
		let mut fresh = crate::Hops::new();
		fresh.push(crate::Hop::new(7).unwrap()).unwrap();
		assert!(
			matches!(
				subscriber.start_announce(
					path.clone(),
					fresh,
					crate::origin::Cost::default(),
					0,
					None,
					&mut announced
				),
				Err(Error::ProtocolViolation)
			),
			"a declined announce still holds its path, so a second start for it is a violation",
		);
	}

	/// A dropped announce still holds its path until the peer retracts it.
	#[tokio::test]
	async fn a_dropped_announce_still_holds_its_path() {
		let assigned = crate::Hop::new(777).unwrap();
		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let consumer = origin.consume();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: Some(assigned),
			going_away: Default::default(),
		});

		let path = Path::new("room/host").to_owned();
		let mut announced = Announced::default();
		let mut reflected = crate::Hops::new();
		reflected.push(assigned).unwrap();
		assert!(
			!subscriber
				.start_announce(
					path.clone(),
					reflected,
					crate::origin::Cost::default(),
					0,
					Some(assigned),
					&mut announced,
				)
				.unwrap(),
			"a chain naming its own sender must be dropped",
		);
		assert!(consumer.get_broadcast("room/host").is_none());

		let mut hops = crate::Hops::new();
		hops.push(crate::Hop::new(7).unwrap()).unwrap();
		let err = subscriber
			.start_announce(
				path.clone(),
				hops,
				crate::origin::Cost::default(),
				0,
				Some(assigned),
				&mut announced,
			)
			.expect_err("a second start for the peer-owned path must be rejected");
		assert!(matches!(err, Error::ProtocolViolation));
	}

	/// An announce whose chain already names the sender came back through the sender.
	/// Appending it again would name one identity twice, which is tolerated in a lite
	/// chain but is a PROTOCOL_VIOLATION for an IETF peer the route is later forwarded
	/// to, so the route must never enter the model carrying it.
	#[tokio::test]
	async fn an_announce_reflected_by_its_sender_is_dropped() {
		let assigned = crate::Hop::new(777).unwrap();

		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let consumer = origin.consume();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: Some(assigned),
			going_away: Default::default(),
		});

		// The sender's identity is already in the chain: the route came back through it.
		let mut hops = crate::Hops::new();
		hops.push(assigned).unwrap();

		let mut announced = Announced::default();
		let accepted = subscriber
			.start_announce(
				Path::new("room/host").to_owned(),
				hops,
				crate::origin::Cost::default(),
				0,
				Some(assigned),
				&mut announced,
			)
			.unwrap();
		assert!(!accepted, "a chain naming its own sender must not become a route");

		tokio::time::sleep(std::time::Duration::from_millis(1)).await;
		assert!(consumer.get_broadcast("room/host").is_none());
	}

	/// A peer that was advertised a local path and announces it back with this
	/// origin's hop in the chain is a reflection, not a new path. The announce
	/// is dropped, the local front keeps serving, and the peer's own
	/// subscription (split-horizon excluded) still reads from it.
	#[tokio::test]
	async fn a_reflected_announce_does_not_displace_the_local_front() {
		let relay = crate::Hop::new(1).unwrap();
		let origin = origin::Config::new(relay).produce();
		let assigned = crate::Hop::new(777).unwrap();

		let local = origin.publish("room/host", origin::Route::default()).unwrap();
		let track = local.create_track("video", None).unwrap();
		let mut group = track.append_group().unwrap();
		group.write_frame(crate::Timestamp::ZERO, b"local".as_ref()).unwrap();
		group.finish().unwrap();

		// The peer's own subscription, excluding the hop the server minted for
		// it, is served from the local front before anything is announced back.
		let peer = origin.consume().excluding(assigned);
		let resolved = peer.request_broadcast("room/host").await.expect("resolves");
		let mut sub = resolved
			.track("video")
			.unwrap()
			.subscribe(None)
			.await
			.expect("subscribe");
		let mut group = sub.recv_group().await.expect("recv group").expect("track ended early");
		assert_eq!(
			&group.read_frame().await.expect("read frame").expect("frame").payload[..],
			b"local"
		);

		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin: origin.clone(),
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: Some(assigned),
			going_away: Default::default(),
		});

		// The path as advertised to the peer: our hop is already in the chain.
		let mut hops = crate::Hops::new();
		hops.push(relay).unwrap();
		let mut announced = Announced::default();
		let accepted = subscriber
			.start_announce(
				Path::new("room/host").to_owned(),
				hops,
				crate::origin::Cost::default(),
				0,
				Some(assigned),
				&mut announced,
			)
			.unwrap();
		assert!(!accepted, "an announce that already names this origin must be dropped");

		// The local front is still the one at the path, and still serving: the
		// peer's next request joins it rather than minting another.
		let still = peer
			.request_broadcast("room/host")
			.await
			.expect("the local front keeps serving");
		assert!(
			still.is_clone(&resolved),
			"the reflected announce must not replace the local front"
		);

		let mut group = track.append_group().unwrap();
		group.write_frame(crate::Timestamp::ZERO, b"still".as_ref()).unwrap();
		group.finish().unwrap();
		let mut group = sub.recv_group().await.expect("recv group").expect("track ended early");
		assert_eq!(
			&group.read_frame().await.expect("read frame").expect("frame").payload[..],
			b"still"
		);
	}

	/// A peer that declares no identity is marked anonymous (hop 0). The assigned
	/// identity stays on `via` for split-horizon and is never written into the chain.
	#[tokio::test]
	async fn assigned_peer_hop_attributes_announces() {
		let session = SinkSession::new(Default::default());
		let assigned = crate::Hop::new(777).unwrap();

		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let consumer = origin.consume();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session,
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			peer_hop: Some(assigned),
			cost: None,
			going_away: Default::default(),
		});

		// An announce with an empty chain and no responder id: the versions that
		// carry no hop information on the wire.
		let mut announced = Announced::default();
		let accepted = subscriber
			.start_announce(
				Path::new("room/host").to_owned(),
				crate::Hops::new(),
				crate::origin::Cost::UNKNOWN,
				0,
				None,
				&mut announced,
			)
			.unwrap();
		assert!(accepted);

		// The route is announced synchronously: hop 0 on the wire, assigned id local.
		let mut cursor = consumer.announced();
		let route = cursor.assert_next_active("room/host");
		let hops: Vec<_> = route.hops.iter().copied().collect();
		assert_eq!(hops, vec![crate::Hop::UNKNOWN]);
		assert!(route.is_anonymous());

		let mut hidden = consumer.excluding(assigned).announced();
		hidden.assert_next_wait();
	}

	/// Lite03 hop-count placeholders stay 0 and count as anonymous; they are not
	/// rewritten with the assigned identity.
	#[tokio::test]
	async fn lite03_placeholders_stay_anonymous() {
		let assigned = crate::Hop::new(777).unwrap();
		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let consumer = origin.consume();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin,
			recv_bandwidth: None,
			version: Version::Lite03,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: Some(assigned),
			going_away: Default::default(),
		});

		let hops = crate::Hops::try_from(vec![crate::Hop::UNKNOWN, crate::Hop::UNKNOWN]).unwrap();
		let mut announced = Announced::default();
		assert!(
			subscriber
				.start_announce(
					Path::new("room/host").to_owned(),
					hops,
					crate::origin::Cost::UNKNOWN,
					0,
					None,
					&mut announced,
				)
				.unwrap()
		);

		let mut cursor = consumer.announced();
		let route = cursor.assert_next_active("room/host");
		let hops: Vec<_> = route.hops.iter().copied().collect();
		assert_eq!(hops, vec![crate::Hop::UNKNOWN, crate::Hop::UNKNOWN]);
		assert!(route.is_anonymous());
	}

	/// A peer with no assigned identity is attributed the reserved origin 0
	/// (UNKNOWN). This layer never mints one of its own: whether an anonymous peer
	/// gets an identity, and whether two of its sessions share it, is the caller's
	/// policy, and a minted id here would be indistinguishable from a declared one.
	#[tokio::test]
	async fn absent_peer_hop_stamps_unknown() {
		let (mut subscriber, consumer) = restart_subscriber(SinkSession::new(Default::default()));

		let mut announced = Announced::default();
		subscriber
			.start_announce(
				Path::new("room/host").to_owned(),
				crate::Hops::new(),
				crate::origin::Cost::UNKNOWN,
				0,
				None,
				&mut announced,
			)
			.unwrap();

		let mut cursor = consumer.announced();
		let route = cursor.assert_next_active("room/host");
		let hops: Vec<_> = route.hops.iter().copied().collect();
		assert_eq!(hops, vec![crate::Hop::UNKNOWN]);
	}

	fn restart_subscriber(session: SinkSession) -> (Subscriber<SinkSession>, crate::origin::Consumer) {
		let origin = origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let consumer = origin.consume();
		let subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session,
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: None,
			going_away: Default::default(),
		});
		(subscriber, consumer)
	}

	/// A restart re-prices the announced route in place: consumers observe another
	/// active update with the new metadata rather than a retract-and-announce.
	#[tokio::test]
	async fn restart_updates_the_route_in_place() {
		let (mut subscriber, consumer) = restart_subscriber(SinkSession::new(Default::default()));

		let mut announced = Announced::default();
		let path = Path::new("room/host").to_owned();
		subscriber
			.start_announce(
				path.clone(),
				crate::Hops::new(),
				crate::origin::Cost::UNKNOWN,
				0,
				Some(crate::Hop::new(7).unwrap()),
				&mut announced,
			)
			.unwrap();

		let mut cursor = consumer.announced();
		cursor.assert_next_active("room/host");

		subscriber
			.restart_announce(
				path.clone(),
				crate::Hops::new(),
				crate::origin::Cost::new(5),
				0,
				Some(crate::Hop::new(7).unwrap()),
				&mut announced,
			)
			.unwrap();

		let route = cursor.assert_next_active("room/host");
		assert_eq!(route.cost, crate::origin::Cost::new(5).charged(0));
	}

	/// An announce stream that dies without an explicit `ended` retracts the route
	/// as promptly as an explicit retraction: a route into a dead session must not
	/// stay announced.
	///
	/// This falls out of `Announced` being a local whose announcements drop,
	/// which is exactly what makes it worth pinning: a refactor that hoisted the map
	/// to the session (outliving the stream) would leak the announcement instead.
	#[tokio::test(start_paused = true)]
	async fn a_lost_announce_stream_retracts_the_route() {
		let origin = crate::origin::Config::new(crate::Hop::new(1).unwrap()).produce();
		let consumer = origin.consume();
		let mut subscriber = Subscriber::new(SubscriberConfig {
			runtime: crate::time::Clock::tokio(),
			session: SinkSession::new(Default::default()),
			origin,
			recv_bandwidth: None,
			version: VERSION,
			peer_setup: Default::default(),
			cost: None,
			peer_hop: None,
			going_away: Default::default(),
		});

		let path = Path::new("room/host").to_owned();
		let hops = crate::Hops::try_from(vec![crate::Hop::new(7).unwrap()]).unwrap();
		let mut announced = Announced::default();
		subscriber
			.start_announce(
				path.clone(),
				hops,
				crate::origin::Cost::default(),
				1,
				None,
				&mut announced,
			)
			.unwrap();
		let mut cursor = consumer.announced();
		cursor.assert_next_active("room/host");

		// The stream ends without retracting anything: the map dies with it and the
		// route retracts.
		drop(announced);
		cursor.assert_next_ended("room/host");

		// An explicit retraction retracts it the same way.
		let hops = crate::Hops::try_from(vec![crate::Hop::new(7).unwrap()]).unwrap();
		let mut announced = Announced::default();
		subscriber
			.start_announce(
				path.clone(),
				hops,
				crate::origin::Cost::default(),
				1,
				None,
				&mut announced,
			)
			.unwrap();
		cursor.assert_next_active("room/host");
		assert!(announced.contains(&path.clone()), "the announce was not recorded");
		announced.retire(&path.clone());
		cursor.assert_next_ended("room/host");
	}
}

/// The four wire fields a subscription's half-open range encodes to.
///
/// The inverse of the publisher's `Bounds::positions`: the model carries whole
/// positions with an exclusive end, while the wire splits each bound into a group and a
/// frame and states both ends inclusive. The range must be non-empty, since an inclusive
/// end has nothing to say below the first position it excludes.
struct WireBounds {
	start_group: Option<u64>,
	start_frame: u64,
	end_group: Option<u64>,
	end_frame: Option<u64>,
}

impl WireBounds {
	fn new(start: Option<Position>, end: Option<Position>) -> Self {
		// An empty range has no wire encoding: flooring its end below asks for the
		// position it excludes, or inverts the range. `handle_subscription` drops such a
		// subscription instead. An absent start is the live edge, so it only makes the
		// range empty when the end sits at the very first position.
		debug_assert!(
			end.is_none_or(|end| end > start.unwrap_or_default()),
			"an empty range cannot be encoded; it should have been dropped as no demand"
		);

		let (end_group, end_frame) = match end {
			// An exclusive end at the head of a group means the group below it is the
			// last one, and it is served whole.
			Some(end) if end.frame == 0 => (Some(end.group.saturating_sub(1)), None),
			Some(end) => (Some(end.group), Some(end.frame - 1)),
			None => (None, None),
		};

		Self {
			start_group: start.map(|start| start.group),
			start_frame: start.map_or(0, |start| start.frame),
			end_group,
			end_frame,
		}
	}
}

/// The at-most-one live upstream subscription: its control stream plus the params
/// echoed in every SUBSCRIBE_UPDATE.
struct SubStream<S: crate::transport::poll::Session> {
	stream: Stream<S, Version>,
	id: u64,
	/// Original SUBSCRIBE params, echoed in every SUBSCRIBE_UPDATE; refreshed as the
	/// downstream aggregate changes.
	max_age: Duration,
	start: Option<Position>,
	priority: u8,
	/// The start the SUBSCRIBE itself carried, fixed for the stream's life. A
	/// SUBSCRIBE_START describes this demand and no fresh one follows an update,
	/// so a buffered START only applies while `start` still equals it: while the
	/// start sits elsewhere the request-tracked floor stands instead, and demand
	/// returning here makes the declaration valid again.
	requested: Option<Position>,
}

enum Sub<S: crate::transport::poll::Session> {
	None,
	Active(SubStream<S>),
}

/// Every advertisement the peer currently has live on one announce stream.
///
/// A declined advertisement remains present with no route because the peer still
/// owns its path and announce id until it retracts or restarts it.
#[derive(Default)]
struct Announced(HashMap<PathOwned, Option<AnnouncedRoute>>);

impl Announced {
	fn contains(&self, path: &PathOwned) -> bool {
		self.0.contains_key(path)
	}

	fn attach(&mut self, path: PathOwned, route: AnnouncedRoute) {
		self.0.insert(path, Some(route));
	}

	fn declined(&mut self, path: PathOwned) {
		if let Some(Some(route)) = self.0.insert(path, None) {
			route.finish();
		}
	}

	/// Record an advertisement before deciding what to do with it.
	///
	/// The peer owns the prefix from the moment it announces, whatever the receiver makes
	/// of it, so the record is taken up front and every way out of the decision leaves it
	/// standing. Accepting replaces it via [`Self::attach`]. Doing it this way rather than
	/// at each rejection is what stops the next early return from silently freeing a path
	/// the peer still holds.
	/// Only valid on a prefix the peer does not already hold, which the caller establishes
	/// with [`Self::contains`]. Overwriting an attached route here would drop its source
	/// without finishing it, which is [`Self::declined`]'s job.
	fn reserve(&mut self, path: PathOwned) {
		debug_assert!(!self.0.contains_key(&path), "reserved a prefix already advertised");
		self.0.insert(path, None);
	}

	fn attached(&mut self, path: &PathOwned) -> Option<&mut AnnouncedRoute> {
		self.0.get_mut(path)?.as_mut()
	}

	fn retire(&mut self, path: &PathOwned) {
		if let Some(Some(route)) = self.0.remove(path) {
			route.finish();
		}
	}

	/// Serve queued requests on every attached route: mint a source per requested
	/// path, hand its dynamic to the driver's serve machines, and answer the
	/// requester with its consumer.
	fn poll_serve<S: crate::transport::poll::Session>(&mut self, subscriber: &Subscriber<S>, waiter: &kio::Waiter) {
		let root = subscriber.origin.root().to_owned();
		for entry in self.0.values_mut().flatten() {
			while let Poll::Ready(Ok(request)) = entry.dynamic.poll_requested_broadcast(waiter) {
				// The request path is absolute; the wire (and our origin handle)
				// speak paths relative to the session's root.
				let Some(path) = request.path().strip_prefix(&root) else {
					// Outside our root: nothing we could name on the wire.
					continue;
				};
				let path = path.to_owned();
				let source = subscriber.origin.create_source(&path);
				let _ = subscriber.sources.try_push((path.clone(), source.dynamic()));
				request.accept(&source);
				entry
					.sources
					.insert(path, crate::model::broadcast::SourceGuard::new(source));
			}
		}
	}

	/// Re-price every attached route to a draining cost (the peer sent a GOAWAY).
	fn drain(&mut self) {
		for entry in self.0.values_mut().flatten() {
			entry.drain();
		}
	}
}

/// One received announce: the served route announced into the origin (the
/// advertisement plus its request queue), and the sources minted to serve
/// requested paths beneath it.
struct AnnouncedRoute {
	/// The route as last announced (post-charge), so a drain can re-price it
	/// without recomputing the chain.
	route: crate::origin::Route,
	/// Dropping it retracts the route and rejects its queued requests.
	dynamic: crate::origin::Dynamic,
	/// One minted source per requested path, finished on a clean retraction and
	/// aborted (via drop) when the session dies.
	sources: HashMap<PathOwned, crate::model::broadcast::SourceGuard>,
	/// Whether the GOAWAY drain already re-priced this route.
	drained: bool,
}

impl AnnouncedRoute {
	fn new(route: crate::origin::Route, dynamic: crate::origin::Dynamic) -> Self {
		Self {
			route,
			dynamic,
			sources: HashMap::new(),
			drained: false,
		}
	}

	/// The peer deliberately retracted the route: finish the minted sources so
	/// their consumers observe a clean end, and retract the announcement.
	fn finish(self) {
		for (_, source) in self.sources {
			source.finish();
		}
	}

	/// Update the announced route in place (a restart).
	fn update(&mut self, route: crate::origin::Route) {
		self.route = route.clone();
		self.drained = false;
		let _ = self.dynamic.update(route);
	}

	/// Re-price the route to [`crate::origin::Cost::DRAIN`] (the peer sent a
	/// GOAWAY): every other candidate outranks it while it stays selectable as
	/// the last path. Idempotent, since the signal stays set.
	fn drain(&mut self) {
		if self.drained {
			return;
		}
		self.drained = true;
		let mut route = self.route.clone();
		route.cost = crate::origin::Cost::DRAIN;
		let _ = self.dynamic.update(route);
	}
}

/// How a [`TrackServe`] run ends.
enum ServeEnd {
	/// The upstream FIN'd: the track is over for good.
	Finished,
	/// The route or session failed: abort the track so the origin re-splices it
	/// from another source.
	GiveBack(Error),
	/// No consumers or in-flight fetches remain; the owner must commit the idle abort.
	Idle,
}

/// Serves one requested track for a relay: owns this session's copy of the
/// track (spliced into the origin's logical track), driving the single upstream
/// subscription (opened lazily on the first downstream subscriber, canceled when
/// the last one leaves) concurrently with any number of one-shot fetches.
#[derive(Clone)]
struct TrackServe<S: crate::transport::poll::Session> {
	subscriber: Subscriber<S>,
	path: PathOwned,
	name: String,
}

impl<S: crate::transport::poll::Session> TrackServe<S> {
	fn widen_frame_bounds(&self, subscription: &mut Subscription) {
		if self.subscriber.version.has_frame_bounds() {
			return;
		}

		// Round both bounds outward to the enclosing group, so the peer sends at least
		// what was asked for and never less. Rounding the end down instead would be able
		// to empty a non-empty range, which has no wire encoding at all.
		let start = subscription.start.map(|start| Position::group(start.group));
		let end = subscription.end.and_then(|end| match end.frame {
			0 => Some(end),
			// Past the last group there is no position to round up to, and unbounded is
			// the wider request.
			_ => Position::after_group(end.group),
		});

		if (start, end) != (subscription.start, subscription.end) {
			tracing::debug!(
				track = %self.name,
				version = ?self.subscriber.version,
				"widening frame bounds to whole groups for an older peer"
			);
		}
		subscription.start = start;
		subscription.end = end;
	}

	/// Apply a subscription-demand change: hand back an [`Establish`] to open the
	/// upstream SUBSCRIBE on the first subscriber, buffer a SUBSCRIBE_UPDATE while
	/// live (the caller flushes), or cancel outright when the last one leaves.
	fn begin_subscription(
		&self,
		producer: &mut track::Producer,
		sub: &mut Sub<S>,
		pref: Option<Subscription>,
		supports_update: bool,
		timescale: Option<Timescale>,
	) -> Result<Begin<S>, Error> {
		// An empty half-open range asks for nothing, and the wire cannot say that: its
		// bounds are inclusive, so the nearest encoding either hands back the position
		// the caller excluded or inverts the range outright once the two bounds meet. No
		// demand at all is the faithful translation. `resume::slice` reaches this on its
		// own: a subscriber resuming exactly at a segment's cap owes that segment nothing.
		// An absent start is the live edge, wherever that lands, so the only end that is
		// certainly empty is the very first position, which is what `Position::default()`
		// stands in for.
		let pref = pref.filter(|sub| sub.end.is_none_or(|end| end > sub.start.unwrap_or_default()));

		match pref {
			Some(mut subscription) => {
				self.widen_frame_bounds(&mut subscription);
				match sub {
					Sub::None => {
						// Open an upstream SUBSCRIBE for the first subscriber.
						Ok(Begin::Establish(self.prepare_establish(
							producer,
							subscription,
							timescale,
						)))
					}
					Sub::Active(active) => {
						// Downstream preferences changed: forward them upstream as a
						// SUBSCRIBE_UPDATE (Lite03+ only; older peers can't carry one).
						let start_moved = active.start != subscription.start;
						active.priority = subscription.priority;
						active.max_age = subscription.max_age;
						active.start = subscription.start;
						if supports_update {
							// The floor follows the requested start, in both directions:
							// moving below a declared SUBSCRIBE_START reopens those groups
							// (the peer may serve them now), moving forward retires the
							// skipped range (the peer stops serving it, and no fresh START
							// will say so), and dropping to the live edge clears it until
							// the next declaration. A buffered START re-applies only if the
							// start returns to the demand that produced it (see
							// `SubStream::requested`).
							if start_moved {
								let _ = producer.start_at(active.start.map(|start| start.group));
							}
							buffer_update(active, subscription.end)?;
						}
						Ok(Begin::None)
					}
				}
			}
			None => {
				// Last subscriber left: cancel the upstream subscription outright. An
				// idle subscription still streams every group into a cache nobody
				// reads, and the upstream counts it as a live viewer of the broadcast.
				// A returning subscriber re-establishes from the current demand.
				if let Sub::Active(active) = sub {
					self.subscriber.remove_subscribe(active.id);
					let _ = active.stream.writer.finish();
					tracing::info!(track = %self.name, "subscribe canceled (idle)");
					*sub = Sub::None;
				}
				Ok(Begin::None)
			}
		}
	}

	/// Allocate the id, set the demand floor, and register the subscription, so the
	/// returned [`Establish`] can put the SUBSCRIBE on the wire.
	///
	/// Registration happens here, before any of it reaches the transport: `id` is
	/// live the moment the peer reads it, and a publisher may serve its first group
	/// immediately, so a late insert races the group stream (a group whose id isn't
	/// in the map yet is dropped, stalling the track forever). The caller
	/// deregisters `id` if the establish fails.
	///
	/// The subscription's bounds come straight from the demand aggregate. After a
	/// route change a takeover boundary caps the *previous* segment's `end_group`;
	/// the segment resuming the track keeps whatever start the subscribers asked for,
	/// so a live-edge subscriber gets the live edge upstream rather than a replay of
	/// the outage.
	fn prepare_establish(
		&self,
		producer: &mut track::Producer,
		subscription: Subscription,
		timescale: Option<Timescale>,
	) -> Establish<S> {
		let id = self.subscriber.next_id.fetch_add(1, atomic::Ordering::Relaxed);

		// Both halves of each bound come from the same position, so a frame can never
		// reach the wire without the group it counts from (which the peer would reject).
		// The floor tracks the requested start until this subscription's own
		// SUBSCRIBE_START refines it: the peer never serves below the request, a
		// previous subscription's declaration must not outlive its demand, and
		// live-edge demand (None) starts with no floor at all.
		let _ = producer.start_at(subscription.start.map(|start| start.group));

		tracing::info!(id, broadcast = %self.subscriber.log_path(&self.path), track = %self.name, "subscribe started");

		self.subscriber.subscribes.lock().insert(
			id,
			TrackEntry {
				producer: producer.clone(),
				timescale,
			},
		);

		let session = self.subscriber.session.clone();
		Establish {
			serve: self.clone(),
			closed: session.clone(),
			session,
			id,
			subscription,
			state: EstablishState::Open,
		}
	}

	/// Test shim: drive the upstream SUBSCRIBE open like the old `establish`.
	#[cfg(test)]
	async fn establish(
		&self,
		producer: &mut track::Producer,
		sub: &mut Sub<S>,
		subscription: Subscription,
		timescale: Option<Timescale>,
	) -> Result<(), Error> {
		let mut est = Box::new(self.prepare_establish(producer, subscription, timescale));
		let id = est.id;
		match kio::wait(move |waiter| est.poll(waiter)).await {
			Ok(active) => {
				*sub = Sub::Active(active);
				Ok(())
			}
			Err(err) => {
				self.subscriber.remove_subscribe(id);
				Err(err)
			}
		}
	}

	/// Test shim: apply one demand change like the old `handle_subscription`,
	/// driving the establish (or the update flush) to completion inline.
	#[cfg(test)]
	async fn handle_subscription(
		&self,
		producer: &mut track::Producer,
		sub: &mut Sub<S>,
		pref: Option<Subscription>,
		supports_update: bool,
		timescale: Option<Timescale>,
	) -> Result<(), Error> {
		match self.begin_subscription(producer, sub, pref, supports_update, timescale)? {
			Begin::Establish(est) => {
				let mut est = Box::new(est);
				let id = est.id;
				match kio::wait(move |waiter| est.poll(waiter)).await {
					Ok(active) => *sub = Sub::Active(active),
					Err(err) => {
						self.subscriber.remove_subscribe(id);
						return Err(err);
					}
				}
			}
			Begin::None => {
				if let Sub::Active(active) = sub {
					std::future::poll_fn(|cx| active.stream.writer.poll_flush(cx)).await?;
				}
			}
		}
		Ok(())
	}
}

/// What a demand change asks the serve loop to do next.
// A state machine's enum is its storage: one transient instance per stream, so the
// big variant is the working state, not padding held in bulk.
#[allow(clippy::large_enum_variant)]
enum Begin<S: crate::transport::poll::Session> {
	/// Nothing further: the update (if any) sits in the active stream's write
	/// buffer, flushed by the loop.
	None,
	/// Open an upstream SUBSCRIBE for the first subscriber.
	Establish(Establish<S>),
}

/// Buffer a SUBSCRIBE_UPDATE echoing the current params, varying only the end
/// bound. The caller flushes.
fn buffer_update<S: crate::transport::poll::Session>(
	active: &mut SubStream<S>,
	end: Option<Position>,
) -> Result<(), Error> {
	let bounds = WireBounds::new(active.start, end);
	active.stream.writer.buffer(&lite::SubscribeUpdate {
		priority: active.priority,
		max_age: active.max_age,
		start_group: bounds.start_group,
		end_group: bounds.end_group,
		start_frame: bounds.start_frame,
		end_frame: bounds.end_frame,
	})
}

/// Opens the upstream SUBSCRIBE control stream: send the request, then (pre
/// lite-05) wait for the SUBSCRIBE_OK. Resolves with the live [`SubStream`];
/// the caller deregisters the id on failure.
struct Establish<S: crate::transport::poll::Session> {
	serve: TrackServe<S>,
	session: S,
	// A dedicated close-watch handle for the SUBSCRIBE_OK wait.
	closed: S,
	id: u64,
	subscription: Subscription,
	state: EstablishState<S>,
}

enum EstablishState<S: crate::transport::poll::Session> {
	Open,
	Send {
		stream: Stream<S, Version>,
	},
	/// Older drafts: the first SUBSCRIBE_OK confirms it. Bail if the session
	/// dies meanwhile; a dying route hands the assignment back through the
	/// serve loop's teardown instead.
	WaitOk {
		stream: Stream<S, Version>,
	},
}

impl<S: crate::transport::poll::Session> Establish<S> {
	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<Result<SubStream<S>, Error>> {
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match &mut self.state {
				EstablishState::Open => {
					// A peer that sent GOAWAY told us to stop opening streams.
					self.serve.subscriber.check_going_away()?;
					let mut stream = ready!(Stream::poll_open(
						&mut self.session,
						self.serve.subscriber.version,
						&mut cx
					))?;

					let bounds = WireBounds::new(self.subscription.start, self.subscription.end);
					let msg = lite::Subscribe {
						id: self.id,
						broadcast: self.serve.path.as_path(),
						track: self.serve.name.as_str().into(),
						priority: self.subscription.priority,
						max_age: self.subscription.max_age,
						start_group: bounds.start_group,
						end_group: bounds.end_group,
						start_frame: bounds.start_frame,
						end_frame: bounds.end_frame,
					};
					stream.writer.buffer(&lite::ControlType::Subscribe)?;
					stream.writer.buffer(&msg)?;
					self.state = EstablishState::Send { stream };
				}
				EstablishState::Send { stream } => {
					ready!(stream.writer.poll_flush(&mut cx))?;
					let EstablishState::Send { stream } = std::mem::replace(&mut self.state, EstablishState::Open)
					else {
						unreachable!()
					};
					if !self.serve.subscriber.version.has_track_stream() {
						self.state = EstablishState::WaitOk { stream };
						continue;
					}
					return Poll::Ready(Ok(self.activate(stream)));
				}
				EstablishState::WaitOk { stream } => {
					if self.closed.poll_closed(&mut cx).is_ready() {
						return Poll::Ready(Err(Error::Dropped));
					}
					let resp = ready!(stream.reader.poll_decode::<lite::SubscribeResponse>(&mut cx))?;
					if !matches!(resp, lite::SubscribeResponse::Ok(_)) {
						return Poll::Ready(Err(Error::ProtocolViolation));
					}
					let EstablishState::WaitOk { stream } = std::mem::replace(&mut self.state, EstablishState::Open)
					else {
						unreachable!()
					};
					return Poll::Ready(Ok(self.activate(stream)));
				}
			}
		}
	}

	fn activate(&self, stream: Stream<S, Version>) -> SubStream<S> {
		SubStream {
			stream,
			id: self.id,
			max_age: self.subscription.max_age,
			start: self.subscription.start,
			priority: self.subscription.priority,
			requested: self.subscription.start,
		}
	}
}

/// Drives one [`TrackServe`]: the TRACK_INFO fetch, then the serve loop, then
/// the teardown that decides how the origin sees this copy end.
struct TrackServeRun<S: crate::transport::poll::Session> {
	serve: TrackServe<S>,
	state: TrackRunState<S>,
}

// A state machine's enum is its storage: one transient instance per stream, so the
// big variant is the working state, not padding held in bulk.
#[allow(clippy::large_enum_variant)]
enum TrackRunState<S: crate::transport::poll::Session> {
	/// Lite05+ learns the track's immutable properties once, up front, via a
	/// TRACK stream. The timescale then flows into every SUBSCRIBE and FETCH
	/// without a per-response header.
	Info {
		request: Option<track::Request>,
		info: TrackInfoFetch<S>,
	},
	Serve(ServeLoop<S>),
	Done,
}

impl<S: crate::transport::poll::Session> TrackServeRun<S> {
	fn new(serve: TrackServe<S>, request: track::Request) -> Self {
		let state = if serve.subscriber.version.has_track_stream() {
			TrackRunState::Info {
				request: Some(request),
				info: TrackInfoFetch::new(&serve),
			}
		} else {
			// No TRACK stream, so the publisher's retention window never reaches us:
			// the accepting side picks it (see `origin::Config::default_max_age`).
			let info = track::Info::default().with_max_age(serve.subscriber.origin.default_max_age());
			TrackRunState::Serve(ServeLoop::new(&serve, request, info, None))
		};
		Self { serve, state }
	}
}

impl<S: crate::transport::poll::Session> kio::Task for TrackServeRun<S> {
	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
		loop {
			match &mut self.state {
				TrackRunState::Info { request, info } => {
					let res = ready!(info.poll_fetch(&self.serve, waiter));
					let request = request.take().expect("request pending");
					match res {
						Ok(info) => {
							// Lite05 carries per-frame timestamps on the wire at this scale;
							// `Some` tells the ingest to decode them instead of stamping
							// local receive time.
							let timescale = Some(info.timescale);
							self.state = TrackRunState::Serve(ServeLoop::new(&self.serve, request, info, timescale));
						}
						Err(err) => {
							tracing::warn!(broadcast = %self.serve.subscriber.log_path(&self.serve.path), track = %self.serve.name, %err, "track info failed");
							// Rejecting the request lets the origin retry (bounded) on
							// another source; waiting subscribers stall rather than error
							// meanwhile.
							request.reject(err);
							self.state = TrackRunState::Done;
							return Poll::Ready(());
						}
					}
				}
				TrackRunState::Serve(serve_loop) => {
					let teardown = ready!(serve_loop.poll(&self.serve, waiter));
					let TrackRunState::Serve(mut serve_loop) = std::mem::replace(&mut self.state, TrackRunState::Done)
					else {
						unreachable!()
					};

					match teardown {
						ServeEnd::Idle => match serve_loop.serving.abort_unused(Error::Cancel) {
							Ok(()) => {
								tracing::debug!(broadcast = %self.serve.subscriber.log_path(&self.serve.path), track = %self.serve.name, "track released (idle)");
							}
							Err(used) => {
								serve_loop.serving = used;
								self.state = TrackRunState::Serve(serve_loop);
								continue;
							}
						},
						ServeEnd::Finished => {
							let _ = serve_loop.serving.finish();
						}
						ServeEnd::GiveBack(err) => {
							let _ = serve_loop.serving.abort(err);
						}
					}

					if let Sub::Active(active) = &mut serve_loop.sub {
						self.serve.subscriber.remove_subscribe(active.id);
						let _ = active.stream.writer.finish();
					}

					return Poll::Ready(());
				}
				TrackRunState::Done => return Poll::Ready(()),
			}
		}
	}
}

/// Opens a TRACK stream, reads the single TRACK_INFO, and maps it to the
/// model's [`track::Info`]. Lite05+ only. Bails if the session dies meanwhile.
struct TrackInfoFetch<S: crate::transport::poll::Session> {
	session: S,
	// A dedicated close-watch handle for the read.
	closed: S,
	state: TrackInfoState<S>,
}

enum TrackInfoState<S: crate::transport::poll::Session> {
	Open,
	Send { stream: Stream<S, Version> },
	Read { stream: Stream<S, Version> },
}

impl<S: crate::transport::poll::Session> TrackInfoFetch<S> {
	fn new(serve: &TrackServe<S>) -> Self {
		let session = serve.subscriber.session.clone();
		Self {
			closed: session.clone(),
			session,
			state: TrackInfoState::Open,
		}
	}

	fn poll_fetch(&mut self, serve: &TrackServe<S>, waiter: &kio::Waiter) -> Poll<Result<track::Info, Error>> {
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match &mut self.state {
				TrackInfoState::Open => {
					serve.subscriber.check_going_away()?;
					let mut stream = ready!(Stream::poll_open(&mut self.session, serve.subscriber.version, &mut cx))?;
					stream.writer.buffer(&lite::ControlType::Track)?;
					stream.writer.buffer(&lite::Track {
						broadcast: serve.path.as_path(),
						track: serve.name.as_str().into(),
					})?;
					self.state = TrackInfoState::Send { stream };
				}
				TrackInfoState::Send { stream } => {
					ready!(stream.writer.poll_flush(&mut cx))?;
					let TrackInfoState::Send { stream } = std::mem::replace(&mut self.state, TrackInfoState::Open)
					else {
						unreachable!()
					};
					self.state = TrackInfoState::Read { stream };
				}
				TrackInfoState::Read { stream } => {
					if self.closed.poll_closed(&mut cx).is_ready() {
						return Poll::Ready(Err(Error::Dropped));
					}
					let info = ready!(stream.reader.poll_decode::<lite::TrackInfo>(&mut cx))?;
					// The publisher FINs after TRACK_INFO; FIN our side too and let the
					// stream drop.
					let _ = stream.writer.finish();

					// Publisher Max Age rides on the wire, so the local retention
					// window matches what the upstream advertises (relays re-serve with
					// the same bound). `broadcast` is left at its default here;
					// `track::Request::accept` stamps the track's real broadcast.
					let model = track::Info::default()
						.with_timescale(info.timescale)
						.with_max_age(info.max_age)
						.with_priority(info.priority);
					return Poll::Ready(Ok(model));
				}
			}
		}
	}
}

/// The serve loop proper: owns this session's copy of the track (spliced into
/// the origin's logical track), driving the single upstream subscription
/// (opened lazily on the first downstream subscriber, canceled when the last
/// one leaves) concurrently with any number of one-shot fetches.
struct ServeLoop<S: crate::transport::poll::Session> {
	/// This session's copy, accepted with the resolved info. The origin splices
	/// it into the logical track; demand from the logical subscribers arrives
	/// through the producer's aggregate, sliced to this segment's bounds
	/// (including the resume floor after a source change).
	serving: track::Producer,
	/// Serve on-demand fetches of uncached groups from this session.
	dynamic: track::Dynamic,
	sub: Sub<S>,
	fetches: kio::Tasks<FetchServeRun<S>>,
	// A dedicated close-watch handle for the session-died arm.
	closed: S,
	// SUBSCRIBE_UPDATE only exists on Lite03+, so older peers can't carry a
	// preference change to an established subscription.
	supports_update: bool,
	supports_fetch: bool,
	timescale: Option<Timescale>,
	mode: ServeMode<S>,
}

// A state machine's enum is its storage: one transient instance per stream, so the
// big variant is the working state, not padding held in bulk.
#[allow(clippy::large_enum_variant)]
enum ServeMode<S: crate::transport::poll::Session> {
	/// Selecting the next event.
	Select,
	/// Driving an upstream SUBSCRIBE open. The demand arms wait meanwhile,
	/// exactly like the old inline await.
	Establish(Establish<S>),
}

impl<S: crate::transport::poll::Session> ServeLoop<S> {
	fn new(serve: &TrackServe<S>, request: track::Request, info: track::Info, timescale: Option<Timescale>) -> Self {
		// Register the fetch handler before accepting: `accept` releases the
		// request's own fetch gate, and a cache-miss fetch queued while TRACK_INFO
		// was in flight would be drained as NotFound in the gap.
		let dynamic = request.dynamic();
		let serving = request.accept(info);
		Self {
			serving,
			dynamic,
			sub: Sub::None,
			fetches: kio::Tasks::new(),
			closed: serve.subscriber.session.clone(),
			supports_update: !matches!(serve.subscriber.version, Version::Lite01 | Version::Lite02),
			supports_fetch: serve.subscriber.version.has_track_stream(),
			timescale,
			mode: ServeMode::Select,
		}
	}

	fn poll(&mut self, serve: &TrackServe<S>, waiter: &kio::Waiter) -> Poll<ServeEnd> {
		loop {
			match &mut self.mode {
				ServeMode::Establish(est) => {
					let res = ready!(est.poll(waiter));
					let id = est.id;
					self.mode = ServeMode::Select;
					match res {
						Ok(active) => self.sub = Sub::Active(active),
						Err(err) => {
							// Opening the upstream failed (usually the session dying): hand
							// the track back for another route to resume.
							serve.subscriber.remove_subscribe(id);
							return Poll::Ready(ServeEnd::GiveBack(err));
						}
					}
				}
				ServeMode::Select => {
					let mut cx = std::task::Context::from_waker(waiter.waker());

					// Deliver any buffered SUBSCRIBE_UPDATE before selecting, so the
					// demand that produced it is on the wire.
					if let Sub::Active(active) = &mut self.sub {
						match active.stream.writer.poll_flush(&mut cx) {
							Poll::Ready(Ok(())) => {}
							Poll::Ready(Err(err)) => {
								// The stream is broken; drop it (the writer resets) and
								// hand the track back.
								serve.subscriber.remove_subscribe(active.id);
								self.sub = Sub::None;
								return Poll::Ready(ServeEnd::GiveBack(err));
							}
							Poll::Pending => return Poll::Pending,
						}
					}

					// Biased: demand first, then completions, then closures.

					// (1) Track demand: a fetch, a subscription change, or the origin
					// handing the track to another route.

					// A fetch is cheap and one-shot, so serve it ahead of subscription churn.
					match self.dynamic.poll_requested_group(waiter) {
						Poll::Ready(Ok(req)) => {
							if self.supports_fetch {
								self.fetches
									.push(FetchServeRun::new(serve.clone(), req, self.timescale));
							} else {
								req.reject(Error::Version);
							}
							continue;
						}
						// Our own producer is alive (we hold it); treat as terminal anyway.
						Poll::Ready(Err(_)) => return Poll::Ready(ServeEnd::GiveBack(Error::Dropped)),
						Poll::Pending => {}
					}
					match self.serving.poll_subscription_changed(waiter) {
						Poll::Ready(Ok(pref)) => {
							match serve.begin_subscription(
								&mut self.serving,
								&mut self.sub,
								pref,
								self.supports_update,
								self.timescale,
							) {
								Ok(Begin::Establish(est)) => self.mode = ServeMode::Establish(est),
								Ok(Begin::None) => {}
								// Updating the upstream failed: hand the track back for
								// another route to resume.
								Err(err) => return Poll::Ready(ServeEnd::GiveBack(err)),
							}
							continue;
						}
						Poll::Ready(Err(_)) => return Poll::Ready(ServeEnd::GiveBack(Error::Dropped)),
						Poll::Pending => {}
					}

					// (2) In-flight fetches; completions just retire.
					let _ = self.fetches.poll(waiter);

					// (3) Nobody reads this copy anymore: the origin dropped its source
					// copy when demand ended, so drop it instead of holding the track
					// state (and its TRACK_INFO) for a reader that may never return.
					// In-flight fetches keep it alive: work already accepted still
					// gets finished.
					if self.fetches.is_empty() && self.serving.poll_unused(waiter).is_ready() {
						return Poll::Ready(ServeEnd::Idle);
					}

					// (4) The upstream subscribe stream closed, or carried a START/END/DROP.
					// Partial message bytes persist in the reader's buffer across turns.
					if let Sub::Active(active) = &mut self.sub
						&& let Poll::Ready(res) = active
							.stream
							.reader
							.poll_decode_maybe::<lite::SubscribeResponse>(&mut cx)
					{
						match res {
							Ok(Some(msg)) => {
								match &msg {
									// SUBSCRIBE_END declares the track's exclusive final
									// sequence, which may arrive while trailing groups are
									// still in flight. Record it on this segment's producer so
									// consumers learn the boundary early; the later stream FIN
									// then finds the track already finished.
									lite::SubscribeResponse::End(end) => {
										// finish_at rejects a boundary at or below the live
										// edge, which is what a peer sending an inclusive bound
										// looks like once the final group has already arrived.
										// Don't abort: the stream FIN still finishes the track,
										// so this only costs the early boundary. Warn anyway,
										// since it's our only signal that a peer disagrees
										// about the encoding.
										if let Err(err) = self.serving.finish_at(end.group) {
											tracing::warn!(track = %serve.name, group = end.group, %err, "invalid subscribe end");
										}
									}
									// SUBSCRIBE_START names the first group this feed serves:
									// the publisher skipped everything below it (e.g. it could
									// not serve the requested frame). Record it as a drop
									// signal, so a spliced reader waiting on a skipped group
									// fails over instead of stalling on a live route.
									lite::SubscribeResponse::Start(start) => {
										// A START describes the demand the SUBSCRIBE carried.
										// It applies only while the current start still matches
										// that demand (updates get no fresh START, so an update
										// that moved the start makes it stale, and one that
										// moved back restores it); elsewhere the
										// request-tracked floor stands rather than a guess.
										if active.start == active.requested {
											let _ = self.serving.start_at(start.group);
										}
									}
									// OK/DROP just resolve the range (the producer already
									// orders groups).
									_ => tracing::debug!(track = %serve.name, ?msg, "subscribe response"),
								}
								continue;
							}
							Ok(None) => {
								tracing::info!(broadcast = %serve.subscriber.log_path(&serve.path), track = %serve.name, "subscribe complete");
								// Upstream FIN'd the subscription: the publisher only FINs
								// once the track's final sequence is known and delivered, so
								// the logical track is over for good (bounded downstream
								// demand alone never FINs; the publisher parks, since a cap
								// can be raised).
								return Poll::Ready(ServeEnd::Finished);
							}
							Err(err) => {
								tracing::warn!(broadcast = %serve.subscriber.log_path(&serve.path), track = %serve.name, %err, "subscribe error");
								return Poll::Ready(ServeEnd::GiveBack(err));
							}
						}
					}

					// (5) The session died: hand the track back for another route.
					if self.closed.poll_closed(&mut cx).is_ready() {
						return Poll::Ready(ServeEnd::GiveBack(Error::Dropped));
					}

					return Poll::Pending;
				}
			}
		}
	}
}

/// Serves one downstream fetch end-to-end on its own bidi stream: send FETCH,
/// then fill the group from the bare FRAME messages that follow. The timescale
/// comes from this track's TRACK_INFO (already known), and the group sequence
/// is implicit from the request.
struct FetchServeRun<S: crate::transport::poll::Session> {
	serve: TrackServe<S>,
	session: S,
	timescale: Option<Timescale>,
	group: u64,
	state: FetchRunState<S>,
}

enum FetchRunState<S: crate::transport::poll::Session> {
	Open {
		request: Option<group::Request>,
	},
	Send {
		request: Option<group::Request>,
		stream: Stream<S, Version>,
		frame_start: u64,
	},
	Ingest {
		stream: Stream<S, Version>,
		producer: group::Producer,
		ingest: FrameIngest,
	},
	Done,
}

impl<S: crate::transport::poll::Session> FetchServeRun<S> {
	fn new(serve: TrackServe<S>, request: group::Request, timescale: Option<Timescale>) -> Self {
		let session = serve.subscriber.session.clone();
		let group = request.sequence();
		Self {
			serve,
			session,
			timescale,
			group,
			state: FetchRunState::Open { request: Some(request) },
		}
	}
}

impl<S: crate::transport::poll::Session> kio::Task for FetchServeRun<S> {
	fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
		let mut cx = std::task::Context::from_waker(waiter.waker());
		loop {
			match &mut self.state {
				FetchRunState::Open { request } => {
					tracing::info!(broadcast = %self.serve.subscriber.log_path(&self.serve.path), track = %self.serve.name, group = self.group, "fetch started");

					// A peer that sent GOAWAY told us to stop opening streams on this session.
					if self.serve.subscriber.going_away.is_set() {
						request.take().expect("request pending").reject(Error::GoingAway);
						self.state = FetchRunState::Done;
						return Poll::Ready(());
					}

					let mut stream = match ready!(Stream::poll_open(
						&mut self.session,
						self.serve.subscriber.version,
						&mut cx
					)) {
						Ok(stream) => stream,
						Err(err) => {
							tracing::warn!(track = %self.serve.name, %err, "fetch stream open failed");
							request.take().expect("request pending").reject(err);
							self.state = FetchRunState::Done;
							return Poll::Ready(());
						}
					};

					let request = request.take().expect("request pending");

					// A peer that predates lite-06 addresses whole groups only, so ask for
					// the whole group and number the response from 0. The wider group still
					// covers what the caller asked for (`fetch_group` positions their own
					// consumer), and is more reusable in the cache than the tail would have
					// been. Asking for the offset anyway would fail to encode and reject a
					// fetch we can serve.
					let frame_start = match self.serve.subscriber.version.has_frame_bounds() {
						true => request.frame_start(),
						false => 0,
					};

					let msg = lite::Fetch {
						broadcast: self.serve.path.as_path(),
						track: self.serve.name.as_str().into(),
						priority: request.priority(),
						group: self.group,
						start_frame: frame_start,
						// Always through the end of the group: a fetch that stopped short
						// would cache a group indistinguishable from a complete one. A
						// downstream cap is applied when serving, not when fetching.
						end_frame: None,
					};
					let buffered = stream
						.writer
						.buffer(&lite::ControlType::Fetch)
						.and_then(|()| stream.writer.buffer(&msg));
					if let Err(err) = buffered {
						stream.writer.abort(&err);
						request.reject(err);
						self.state = FetchRunState::Done;
						return Poll::Ready(());
					}
					self.state = FetchRunState::Send {
						request: Some(request),
						stream,
						frame_start,
					};
				}
				FetchRunState::Send { stream, .. } => {
					if let Err(err) = ready!(stream.writer.poll_flush(&mut cx)) {
						let FetchRunState::Send { request, stream, .. } =
							std::mem::replace(&mut self.state, FetchRunState::Done)
						else {
							unreachable!()
						};
						stream.writer.abort(&err);
						request.expect("request pending").reject(err);
						return Poll::Ready(());
					}
					let FetchRunState::Send {
						request,
						stream,
						frame_start,
					} = std::mem::replace(&mut self.state, FetchRunState::Done)
					else {
						unreachable!()
					};
					let request = request.expect("request pending");

					// Make the group available (resolving the downstream fetch) and fill
					// it. The track::Info only takes effect if the track isn't accepted yet
					// (a fetch with no live subscription); otherwise the group inherits the
					// accepted timescale. Relay-served FETCH is lite-05+, so `timescale` is
					// `Some`; fall back to the default scale defensively rather than
					// panicking.
					let group_info = track::Info::default()
						.with_timescale(self.timescale.unwrap_or_default())
						.with_max_age(self.serve.subscriber.origin.default_max_age());
					let mut producer = match request.accept(group_info) {
						Ok(producer) => producer,
						Err(err) => {
							// Already served (a concurrent fetch) or the track closed.
							tracing::debug!(track = %self.serve.name, group = self.group, %err, "fetch not served");
							stream.writer.abort(&err);
							return Poll::Ready(());
						}
					};

					// The response starts at the frame we asked for, so number it from
					// there rather than restarting the group at 0.
					if let Err(err) = producer.start_at(frame_start) {
						stream.writer.abort(&err);
						let _ = producer.abort(err);
						return Poll::Ready(());
					}

					self.state = FetchRunState::Ingest {
						stream,
						producer,
						ingest: FrameIngest::new(self.serve.subscriber.runtime.clone(), self.timescale),
					};
				}
				FetchRunState::Ingest {
					stream,
					producer,
					ingest,
				} => {
					let res = ready!(ingest.poll(&mut stream.reader, producer, waiter));
					let FetchRunState::Ingest { producer, .. } =
						std::mem::replace(&mut self.state, FetchRunState::Done)
					else {
						unreachable!()
					};
					match res {
						Ok(()) => {
							let producer = producer;
							let _ = producer.finish();
						}
						Err(err) => {
							let _ = producer.abort(err);
						}
					}
					return Poll::Ready(());
				}
				FetchRunState::Done => return Poll::Ready(()),
			}
		}
	}
}