sdx 1.13.0

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

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::future::Future;
use std::io::{IoSlice, Write};
use std::ops::Range;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use bytes::Bytes;
use shardline_xet_adapter::{ReconstructionFetchInfo, ReconstructionMultiRangeFetch};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
use tokio::sync::{Notify, OnceCell, OwnedSemaphorePermit, Semaphore, oneshot};
use tokio::task::{JoinHandle, JoinSet};
use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
use xet_core_structures::ExpWeightedMovingAvg;
// Keep the compatible upstream runtime constraint active for SDK consumers.
use xet_runtime as _;

use crate::{
    auth::TokenService,
    cache::ChunkCache,
    error::{SdxError, TransferError},
    hash::parse_xet_hash_hex,
    reconstruction::{ReconstructionResponse, fetch_reconstruction_response},
    retry::{RetryContext, RetryMarkers, RetryPolicy, RetryScope},
    transfer::{ByteRange, TransferClient},
    xorb::XorbReader,
};

/// Base download-buffer capacity shared across active downloads (2 GiB,
/// mirroring upstream `download_buffer_size`).
pub const DEFAULT_DOWNLOAD_BUFFER_SIZE: u64 = 2_147_483_648;
/// Additional download-buffer capacity allocated per active download
/// (512 MiB, mirroring upstream `download_buffer_perfile_size`).
pub const DEFAULT_DOWNLOAD_BUFFER_PERFILE_SIZE: u64 = 536_870_912;
/// Hard cap on the total download-buffer capacity (8 GiB, mirroring upstream
/// `download_buffer_limit`).
pub const DEFAULT_DOWNLOAD_BUFFER_LIMIT: u64 = 8_589_934_592;
/// Minimum size of a single term-metadata prefetch block (256 MiB).
pub const DEFAULT_MIN_RECONSTRUCTION_FETCH_SIZE: u64 = 268_435_456;
/// Maximum size of a single term-metadata prefetch block (8 GiB).
pub const DEFAULT_MAX_RECONSTRUCTION_FETCH_SIZE: u64 = 8_589_934_592;
/// Minimum term-metadata prefetch lead (1 GiB).
pub const DEFAULT_MIN_PREFETCH_BUFFER: u64 = 1_073_741_824;
/// Target block completion time for the prefetch estimator (15 minutes).
pub const DEFAULT_TARGET_BLOCK_COMPLETION_TIME_SECS: f64 = 900.0;
/// EWMA half-life (in samples) for the completion-rate estimator.
pub const DEFAULT_COMPLETION_RATE_ESTIMATOR_HALF_LIFE: f64 = 4.0;
/// Default fixed CAS connection-permit count (adaptive controller is M4).
pub const DEFAULT_DOWNLOAD_CONCURRENCY: usize = 4;

const MAX_BUFFERED_TERMS: usize = 128;
// Small fetch groups limit wire/decode transients and allocator retention;
// the independent term cap still collapses malicious one-byte descriptions.
const MAX_COALESCED_BLOCK_BYTES: u64 = 512 * 1024;

/// Tunable prefetch/buffer limits for the streaming download pipeline.
///
/// Defaults mirror the upstream `xet-runtime` `ReconstructionConfig`
/// (`xet-runtime-1.5.4/src/config/groups/reconstruction.rs`). The CLI `cat`
/// path should run with a modest buffer cap (64–256 MiB) per
/// `docs/SDX_PLAN.md` §4.4.4.
#[derive(Debug, Clone)]
pub struct StreamLimits {
    /// Minimum term-metadata prefetch block size, in bytes.
    pub min_reconstruction_fetch_size: u64,
    /// Maximum term-metadata prefetch block size, in bytes.
    pub max_reconstruction_fetch_size: u64,
    /// Minimum prefetch lead (`prefetched_pos - active_pos`), in bytes.
    pub min_prefetch_buffer: u64,
    /// Target completion time for a prefetch block, in seconds (drives the
    /// completion-rate-based block sizing).
    pub target_block_completion_time_secs: f64,
    /// Half-life (in samples) of the completion-rate EWMA.
    pub completion_rate_estimator_half_life: f64,
}

impl Default for StreamLimits {
    fn default() -> Self {
        Self {
            min_reconstruction_fetch_size: DEFAULT_MIN_RECONSTRUCTION_FETCH_SIZE,
            max_reconstruction_fetch_size: DEFAULT_MAX_RECONSTRUCTION_FETCH_SIZE,
            min_prefetch_buffer: DEFAULT_MIN_PREFETCH_BUFFER,
            target_block_completion_time_secs: DEFAULT_TARGET_BLOCK_COMPLETION_TIME_SECS,
            completion_rate_estimator_half_life: DEFAULT_COMPLETION_RATE_ESTIMATOR_HALF_LIFE,
        }
    }
}

/// Shared state for the streaming pipeline, derived from a
/// [`crate::XetClient`]'s `DownloadSessionInner`.
#[derive(Clone)]
pub(crate) struct StreamContext {
    pub transfer: TransferClient,
    pub api_base: String,
    pub buffer_semaphore: Arc<BufferSemaphore>,
    pub active_downloads: Arc<AtomicU64>,
    pub download_permits: Arc<Semaphore>,
    pub limits: StreamLimits,
    /// Optional on-disk chunk cache (M2b2); checked before every xorb fetch.
    pub chunk_cache: Option<Arc<ChunkCache>>,
    /// Count of ranged xorb transfer requests issued (network fetches), for
    /// observability/E2E request-counting.
    pub xorb_fetch_count: Arc<AtomicU64>,
    /// Token service (M4) for 401/403 refresh on retry.
    pub tokens: TokenService,
    /// Retry policy (M4) applied to reconstruction + xorb fetches.
    pub retry_policy: RetryPolicy,
    #[cfg(not(target_family = "wasm"))]
    pub blocking_runtime: Arc<tokio::runtime::Runtime>,
}

impl StreamContext {
    /// Builds a read-scoped [`RetryContext`] for a reconstruction / ranged-xorb
    /// request.
    pub(crate) fn retry_context(&self) -> RetryContext {
        RetryContext {
            policy: self.retry_policy.clone(),
            tokens: Some(self.tokens.clone()),
            scope: RetryScope::Read,
            markers: RetryMarkers::ranged_xorb(),
        }
    }
}

/// The process-global dedicated runtime used for blocking bridges
/// ([`DownloadStream::blocking_next`]).
///
/// A `tokio::runtime::Runtime` panics when dropped from within an async
/// runtime context, and it cannot be safely owned by a client that may be
/// dropped inside `#[tokio::main]`-style code. sdx therefore keeps a single
/// multi-threaded runtime in a process-global `OnceLock` (created lazily on the
/// first stream construction, errors propagated to the caller). It is never
/// dropped, so no thread can hit the panic; the cost is one idle blocking
/// runtime for the process lifetime once any stream has been used. This mirrors
/// hf-xet's shared `TaskRuntime` (the per-session variant arrives with the
/// stream-group layer, M2b2).
///
/// This is an I/O bridge shared by all clients, not a host-sized CPU pool.
/// Keep its workers bounded: spreading short wire/decode allocations across
/// every host core leaves separate allocator arenas resident long after the
/// byte reservations have been released. Network concurrency remains governed
/// by the existing per-client permits.
#[cfg(not(target_family = "wasm"))]
pub(crate) fn global_blocking_runtime() -> Result<Arc<tokio::runtime::Runtime>, SdxError> {
    static RUNTIME: OnceLock<Result<Arc<tokio::runtime::Runtime>, String>> = OnceLock::new();
    let slot = RUNTIME.get_or_init(|| {
        tokio::runtime::Builder::new_multi_thread()
            .worker_threads(
                std::thread::available_parallelism().map_or(1, |count| count.get().min(2)),
            )
            .enable_all()
            .build()
            .map(Arc::new)
            .map_err(|error| error.to_string())
    });
    match slot {
        Ok(runtime) => Ok(runtime.clone()),
        Err(message) => Err(SdxError::StreamInternal(format!(
            "blocking runtime failed to start: {message}"
        ))),
    }
}

/// Drive a borrowed download future on the SDK runtime without nesting Tokio
/// runtimes on the calling thread. The SDK's workers drive reconstruction even
/// while a current-thread caller's executor is blocked.
#[cfg(not(target_family = "wasm"))]
fn block_on_download<F, T>(runtime: &tokio::runtime::Runtime, future: F) -> Result<T, SdxError>
where
    F: Future<Output = Result<T, SdxError>> + Send,
    T: Send,
{
    if tokio::runtime::Handle::try_current().is_err() {
        return runtime.block_on(future);
    }
    std::thread::scope(|scope| {
        std::thread::Builder::new()
            .name("sdx-download-bridge".to_owned())
            .spawn_scoped(scope, || runtime.block_on(future))
            .map_err(SdxError::Io)?
            .join()
            .map_err(|_panic_payload| {
                SdxError::StreamInternal("download bridge thread panicked".to_owned())
            })?
    })
}

// ============================================================================
// Byte-denominated buffer semaphore
// ============================================================================

/// A byte-denominated semaphore for bounding in-flight download buffering.
///
/// Mirrors the upstream `xet-runtime` `AdjustableSemaphore`
/// (`adjustable_semaphore.rs`): the total permit count can be adjusted at any
/// time between a minimum and maximum bound (`increment_permits_to_target` on
/// download entry, `decrement_permits_to_target` via an exit guard). Permit
/// decreases are resolved lazily as issued permits drop.
///
/// Permit counts are **bytes**. Streaming reconstruction reserves complete
/// decoded blocks. The reservation remains held until all internally queued
/// slices of that block have been delivered or cancelled; a small term cannot
/// hide a much larger retained backing allocation.
///
/// Internally, permits are scaled by a power-of-two `basis` so the logical
/// count (up to the 8 GiB default limit) fits within tokio's `u32` per-acquire
/// limit; on 64-bit platforms the basis is 1 for any practical cap.
pub struct BufferSemaphore {
    semaphore: Arc<Semaphore>,
    total_permits: AtomicU64,
    enqueued_permit_decreases: AtomicU64,
    min_physical_permits: u64,
    max_physical_permits: u64,
    basis: u64,
    adjustment_lock: Mutex<()>,
}

/// A permit issued by a [`BufferSemaphore`], releasing its capacity on drop.
///
/// A permit can be split ([`split`](Self::split)) so a freshly incremented
/// (virtual) permit can be carved into per-term permits, giving a new download
/// immediate access without queueing behind existing acquires.
pub struct BufferPermit {
    permit: Option<OwnedSemaphorePermit>,
    num_physical_permits: u32,
    parent: Arc<BufferSemaphore>,
    // Internal term-count admission and backing-block ownership. Zero-byte
    // permits can carry these through the existing public writer interface.
    _term_slot: Option<OwnedSemaphorePermit>,
    _backing_block: Option<Arc<XorbBlock>>,
}

impl BufferSemaphore {
    /// Creates a byte-denominated semaphore with `initial_permits` capacity,
    /// adjustable within `[min_permits, max_permits]`.
    ///
    /// A fixed-capacity semaphore (`min == initial == max`) disables the
    /// dynamic per-download scaling.
    #[must_use]
    pub fn new(min_permits: u64, initial_permits: u64, max_permits: u64) -> Self {
        let basis = Self::compute_basis(max_permits);
        let min_physical = min_permits.div_ceil(basis);
        let max_physical = max_permits.div_ceil(basis);
        let initial_physical = initial_permits
            .div_ceil(basis)
            .clamp(min_physical, max_physical);
        Self {
            semaphore: Arc::new(Semaphore::new(
                usize::try_from(initial_physical).unwrap_or(usize::MAX),
            )),
            total_permits: AtomicU64::new(initial_physical),
            enqueued_permit_decreases: AtomicU64::new(0),
            min_physical_permits: min_physical,
            max_physical_permits: max_physical,
            basis,
            adjustment_lock: Mutex::new(()),
        }
    }

    /// The current total capacity in bytes.
    #[must_use]
    pub fn total_permits(&self) -> u64 {
        self.total_permits
            .load(Ordering::Relaxed)
            .saturating_mul(self.basis)
    }

    /// The current unissued capacity in bytes.
    #[must_use]
    pub fn available_permits(&self) -> u64 {
        u64::try_from(self.semaphore.available_permits())
            .unwrap_or(u64::MAX)
            .saturating_mul(self.basis)
    }

    /// Acquires `n` byte-permits.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError::StreamInternal`] when the semaphore is closed.
    pub async fn acquire_many(self: &Arc<Self>, n: u64) -> Result<BufferPermit, SdxError> {
        let physical = self.to_physical_acquire(n);
        let permit = self
            .semaphore
            .clone()
            .acquire_many_owned(physical)
            .await
            .map_err(|error| {
                SdxError::StreamInternal(format!("buffer permit acquire failed: {error}"))
            })?;
        Ok(BufferPermit {
            permit: Some(permit),
            num_physical_permits: physical,
            parent: self.clone(),
            _term_slot: None,
            _backing_block: None,
        })
    }

    /// Grows the total capacity to `target` bytes if it is currently below it,
    /// returning a virtual permit holding the newly added capacity.
    ///
    /// The returned permit can be [`split`](BufferPermit::split) for immediate
    /// term-level access that bypasses the FIFO acquire queue; when it drops,
    /// its capacity enters the semaphore.
    pub fn increment_permits_to_target(self: &Arc<Self>, target: u64) -> Option<BufferPermit> {
        let _lock = self
            .adjustment_lock
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let current = self.total_permits();
        if target <= current {
            return None;
        }
        self.increment_total_permits_impl(target.saturating_sub(current))
    }

    /// Shrinks the total capacity toward `target` bytes if it is currently
    /// above it. Issued permits remain valid; the decrease is resolved lazily.
    ///
    /// Returns the number of bytes by which the capacity was reduced.
    pub fn decrement_permits_to_target(&self, target: u64) -> Option<u64> {
        let _lock = self
            .adjustment_lock
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let current = self.total_permits();
        if target >= current {
            return None;
        }
        let n = current.saturating_sub(target);
        let physical_n = n.div_ceil(self.basis);
        if physical_n == 0 {
            return None;
        }
        let removed = attempt_sub(&self.total_permits, physical_n, self.min_physical_permits);
        if removed == 0 {
            return None;
        }
        let removed_u32 = u32::try_from(removed).unwrap_or(u32::MAX);
        if let Ok(permit) = self.semaphore.clone().try_acquire_many_owned(removed_u32) {
            permit.forget();
        } else {
            self.enqueued_permit_decreases
                .fetch_add(removed, Ordering::Relaxed);
        }
        Some(removed.saturating_mul(self.basis))
    }

    fn increment_total_permits_impl(self: &Arc<Self>, n: u64) -> Option<BufferPermit> {
        let physical_n = n.div_ceil(self.basis);
        if physical_n == 0 {
            return None;
        }
        let added = attempt_add(&self.total_permits, physical_n, self.max_physical_permits);
        if added == 0 {
            return None;
        }
        let cancelled = attempt_sub(&self.enqueued_permit_decreases, added, 0);
        let to_hold = added.saturating_sub(cancelled);
        Some(BufferPermit {
            permit: None,
            num_physical_permits: u32::try_from(to_hold).unwrap_or(u32::MAX),
            parent: self.clone(),
            _term_slot: None,
            _backing_block: None,
        })
    }

    fn to_physical_acquire(&self, n: u64) -> u32 {
        let total = self.total_permits.load(Ordering::Relaxed).max(1);
        u32::try_from(n.div_ceil(self.basis).clamp(1, total)).unwrap_or(u32::MAX)
    }

    /// Smallest power-of-two basis so that `max_permits / basis` fits within
    /// the platform per-acquire limit.
    const fn compute_basis(max_permits: u64) -> u64 {
        let mut basis: u64 = 1;
        while max_permits.div_ceil(basis) > u32::MAX as u64 {
            basis = basis.saturating_mul(2);
        }
        basis
    }
}

impl BufferPermit {
    const fn for_term(
        parent: Arc<BufferSemaphore>,
        slot: OwnedSemaphorePermit,
        block: Arc<XorbBlock>,
    ) -> Self {
        Self {
            permit: None,
            num_physical_permits: 0,
            parent,
            _term_slot: Some(slot),
            _backing_block: Some(block),
        }
    }
    /// The number of byte-permits held by this permit.
    #[must_use]
    pub fn num_permits(&self) -> u64 {
        u64::from(self.num_physical_permits).saturating_mul(self.parent.basis)
    }

    /// Splits `n` byte-permits off this permit into a new permit.
    ///
    /// Returns `None` when `n` is zero or exceeds the permits held.
    pub fn split(&mut self, n: u64) -> Option<BufferPermit> {
        let physical_n = n.div_ceil(self.parent.basis);
        if physical_n > u64::from(self.num_physical_permits) {
            return None;
        }
        let physical_n = u32::try_from(physical_n).unwrap_or(u32::MAX);
        self.num_physical_permits = self.num_physical_permits.saturating_sub(physical_n);
        if physical_n > 0 {
            let permit = self
                .permit
                .as_mut()
                .and_then(|permit| permit.split(usize::try_from(physical_n).unwrap_or(usize::MAX)));
            Some(BufferPermit {
                permit,
                num_physical_permits: physical_n,
                parent: self.parent.clone(),
                _term_slot: None,
                _backing_block: None,
            })
        } else {
            None
        }
    }
}

impl Drop for BufferPermit {
    fn drop(&mut self) {
        let parent = &self.parent;
        let num_permits = u64::from(self.num_physical_permits);
        let resolved = attempt_sub(&parent.enqueued_permit_decreases, num_permits, 0);
        if let Some(mut permit) = self.permit.take() {
            if resolved > 0 {
                // Consume the enqueued decrease; the remainder returns normally.
                if let Some(split) = permit.split(usize::try_from(resolved).unwrap_or(usize::MAX)) {
                    split.forget();
                }
            }
        } else {
            // Virtual permit: release the non-consumed portion into the semaphore.
            let to_return = num_permits.saturating_sub(resolved);
            if to_return > 0 {
                parent
                    .semaphore
                    .add_permits(usize::try_from(to_return).unwrap_or(usize::MAX));
            }
        }
    }
}

/// Adds up to `n`, clamped at `max_value`; returns the amount actually added.
fn attempt_add(counter: &AtomicU64, n: u64, max_value: u64) -> u64 {
    counter
        .try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
            if current >= max_value {
                None
            } else {
                Some(current.saturating_add(n).min(max_value))
            }
        })
        .map_or(0, |previous| {
            previous
                .saturating_add(n)
                .min(max_value)
                .saturating_sub(previous)
        })
}

/// Subtracts up to `n`, clamped at `min_value`; returns the amount actually
/// subtracted.
fn attempt_sub(counter: &AtomicU64, n: u64, min_value: u64) -> u64 {
    counter
        .try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
            if current <= min_value {
                None
            } else {
                Some(current.saturating_sub(n).max(min_value))
            }
        })
        .map_or(0, |previous| {
            let after = previous.saturating_sub(n).max(min_value);
            previous.saturating_sub(after)
        })
}

/// Runs `f` when the guard drops (used to shrink the download buffer on exit).
struct ExitGuard<F: FnOnce()>(Option<F>);

impl<F: FnOnce()> ExitGuard<F> {
    const fn new(f: F) -> Self {
        Self(Some(f))
    }

    fn disarm(&mut self) {
        drop(self.0.take());
    }
}

impl<F: FnOnce()> Drop for ExitGuard<F> {
    fn drop(&mut self) {
        if let Some(f) = self.0.take() {
            f();
        }
    }
}

// ============================================================================
// RunState: cancellation + error propagation
// ============================================================================

/// Internal error for the reconstruction run loop: separates genuine
/// cancellation (mapped to `Ok(0)`) from real errors (propagated as `Err`).
pub(crate) enum RunError {
    Cancelled,
    Error(SdxError),
}

impl From<SdxError> for RunError {
    fn from(error: SdxError) -> Self {
        RunError::Error(error)
    }
}

/// Shared cancellation/error state for one reconstruction pipeline.
///
/// Mirrors upstream `run_state.rs`: any background task that fails calls
/// [`set_error`](Self::set_error), which stores the first error **and** cancels
/// the token, immediately waking every `select!` branch listening on
/// [`cancelled`](Self::cancelled). Errors surface to the consumer via
/// [`check_error`](Self::check_error) at item boundaries.
pub(crate) struct RunState {
    cancellation_token: CancellationToken,
    has_error: AtomicBool,
    stored_error: Mutex<Option<SdxError>>,
    total_bytes_scheduled: AtomicU64,
    total_bytes_delivered: AtomicU64,
}

impl RunState {
    pub(crate) fn new(cancellation_token: CancellationToken) -> Arc<Self> {
        Arc::new(Self {
            cancellation_token,
            has_error: AtomicBool::new(false),
            stored_error: Mutex::new(None),
            total_bytes_scheduled: AtomicU64::new(0),
            total_bytes_delivered: AtomicU64::new(0),
        })
    }

    /// Stores the first error and cancels the token. Subsequent calls are
    /// ignored (first error wins).
    pub(crate) fn set_error(&self, error: SdxError) {
        let mut guard = self
            .stored_error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if guard.is_none() {
            *guard = Some(error);
            self.has_error.store(true, Ordering::Release);
        }
        drop(guard);
        self.cancellation_token.cancel();
    }

    /// Returns the stored error, if any, and clears it (the stream reports it
    /// once at an item boundary).
    pub(crate) fn check_error(&self) -> Result<(), SdxError> {
        let mut guard = self.stored_error.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(error) = guard.take() {
            self.has_error.store(false, Ordering::Release);
            return Err(error);
        }
        Ok(())
    }

    // Background tasks must leave the typed first error for the consumer.
    // Taking and re-publishing it creates a gap where cancellation looks clean.
    fn check_background_error(&self) -> Result<(), SdxError> {
        if let Some(message) = self.error_message() {
            return Err(SdxError::StreamInternal(message));
        }
        Ok(())
    }

    /// Checks errors first (so error-triggered cancellation returns the
    /// underlying error), then cancellation.
    pub(crate) fn check_run_state(&self) -> Result<(), RunError> {
        if let Err(error) = self.check_background_error() {
            return Err(RunError::Error(error));
        }
        if self.cancellation_token.is_cancelled() {
            return Err(RunError::Cancelled);
        }
        Ok(())
    }

    /// Cancels without an error (genuine external cancellation).
    pub(crate) fn cancel(&self) {
        self.cancellation_token.cancel();
    }

    /// Future that resolves when cancelled; for use in `select!`.
    pub(crate) async fn cancelled(&self) {
        self.cancellation_token.cancelled().await;
    }

    /// Records a term of `size` bytes as scheduled for delivery.
    pub(crate) fn record_new_term(&self, size: u64) {
        self.total_bytes_scheduled
            .fetch_add(size, Ordering::Relaxed);
    }

    /// Reports `size` bytes delivered to the consumer.
    pub(crate) fn report_bytes_written(&self, size: u64) {
        self.total_bytes_delivered
            .fetch_add(size, Ordering::Relaxed);
    }

    pub(crate) fn total_bytes_scheduled(&self) -> u64 {
        self.total_bytes_scheduled.load(Ordering::Relaxed)
    }

    pub(crate) fn total_bytes_delivered(&self) -> u64 {
        self.total_bytes_delivered.load(Ordering::Relaxed)
    }

    /// Returns a snapshot of the stored error message, if any (does not take
    /// the error out; [`check_error`](Self::check_error) still works).
    pub(crate) fn error_message(&self) -> Option<String> {
        if !self.has_error.load(Ordering::Acquire) {
            return None;
        }
        let guard = self
            .stored_error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        guard.as_ref().map(ToString::to_string)
    }

    /// Returns `true` when the cancellation token has been cancelled.
    pub(crate) fn is_cancelled(&self) -> bool {
        self.cancellation_token.is_cancelled()
    }
}

// ============================================================================
// DataWriter abstraction
// ============================================================================

/// A future that produces the data bytes for one file term.
pub type DataFuture = Pin<Box<dyn Future<Output = Result<Bytes, SdxError>> + Send + 'static>>;

/// Writer abstraction for the reconstruction pipeline (mirror `data_writer.rs`).
///
/// The reconstruction loop hands each term's `(relative_byte_range, permit,
/// data_future)` to the writer; `finish()` waits for all data to be written
/// and returns the number of bytes written.
#[async_trait::async_trait]
pub trait DataWriter: Send {
    /// Sets the data source for the next term.
    ///
    /// `byte_range` is relative to the requested download range. The optional
    /// buffer permit is released only after the data has been consumed/written.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the range is not sequential, the writer is
    /// finished, a prior background task failed, or the writer channel closed.
    async fn set_next_term_data_source(
        &mut self,
        byte_range: Range<u64>,
        permit: Option<BufferPermit>,
        data_future: DataFuture,
    ) -> Result<(), SdxError>;

    /// Consumes the writer, waiting for all data to be written, and returns
    /// the number of bytes written.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background task failed or the written byte
    /// count disagrees with the scheduled byte count.
    async fn finish(self: Box<Self>) -> Result<u64, SdxError>;
}

// ============================================================================
// SequentialWriter
// ============================================================================

/// Item sent through the sequential writer queue.
pub(crate) enum SequentialRetrievalItem {
    Data {
        receiver: oneshot::Receiver<Bytes>,
        permit: Option<BufferPermit>,
    },
    Finish,
}

/// A pending write with its buffer permit.
type PendingWrite = (Bytes, Option<BufferPermit>);

/// `write_vectored` iovec cap (mirror upstream `WRITEV_MAX_SLICE`).
const WRITEV_MAX_SLICE: usize = 24;

/// Background thread that drains the sequential writer queue into a `Write`
/// sink (the `reconstruct_to_writer` path).
struct SyncWriterThread {
    rx: UnboundedReceiver<SequentialRetrievalItem>,
    bytes_written: Arc<AtomicU64>,
    run_state: Arc<RunState>,
    pending: Option<SequentialRetrievalItem>,
    finished: bool,
}

impl SyncWriterThread {
    /// Returns the next write item, optionally blocking for it.
    ///
    /// When `should_block` is false and the data is not ready, the item is put
    /// back into `pending` and `None` is returned.
    fn next_write(&mut self, should_block: bool) -> Result<Option<PendingWrite>, SdxError> {
        if self.pending.is_none() {
            self.pending = if should_block {
                self.rx.blocking_recv()
            } else {
                self.rx.try_recv().ok()
            };
        }
        match self.pending.take() {
            Some(SequentialRetrievalItem::Data {
                mut receiver,
                permit,
            }) => {
                if should_block {
                    let data = match receiver.blocking_recv() {
                        Ok(data) => data,
                        Err(_) => {
                            self.run_state.check_background_error()?;
                            return Err(SdxError::StreamInternal(
                                "data sender was dropped before sending data".to_owned(),
                            ));
                        }
                    };
                    Ok(Some((data, permit)))
                } else {
                    match receiver.try_recv() {
                        Ok(data) => Ok(Some((data, permit))),
                        Err(oneshot::error::TryRecvError::Empty) => {
                            self.pending = Some(SequentialRetrievalItem::Data { receiver, permit });
                            Ok(None)
                        }
                        Err(oneshot::error::TryRecvError::Closed) => {
                            self.run_state.check_background_error()?;
                            Err(SdxError::StreamInternal(
                                "data sender was dropped before sending data".to_owned(),
                            ))
                        }
                    }
                }
            }
            Some(SequentialRetrievalItem::Finish) => {
                self.finished = true;
                Ok(None)
            }
            None => Ok(None),
        }
    }

    /// Writes each term completely while checking cancellation between writes.
    fn run(mut self, mut writer: impl Write) -> Result<(), SdxError> {
        while let Some((data, permit)) = self.next_write(true)? {
            let mut remaining = data.as_ref();
            while !remaining.is_empty() {
                self.run_state.check_background_error()?;
                if self.run_state.is_cancelled() {
                    return Ok(());
                }
                let written = match writer.write(remaining) {
                    Ok(0) => return Err(SdxError::Io(std::io::ErrorKind::WriteZero.into())),
                    Ok(written) => written,
                    Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
                    Err(error) => return Err(SdxError::Io(error)),
                };
                remaining = remaining.get(written..).ok_or_else(|| {
                    SdxError::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "writer returned an invalid byte count",
                    ))
                })?;
                self.bytes_written.fetch_add(
                    u64::try_from(written).unwrap_or(u64::MAX),
                    Ordering::Relaxed,
                );
            }
            // The buffer permit is released only after the data is written.
            drop(permit);
            if self.finished {
                break;
            }
        }
        self.run_state.check_background_error()?;
        if !self.run_state.is_cancelled() {
            writer.flush().map_err(SdxError::Io)?;
        }
        Ok(())
    }

    /// Runs the vectorized writer loop, batching pending writes into
    /// `write_vectored` calls of at most 24 iovecs (mirror upstream
    /// `WRITEV_MAX_SLICE`).
    fn run_vectorized(mut self, mut writer: impl Write) -> Result<(), SdxError> {
        let mut pending_writes: VecDeque<PendingWrite> = VecDeque::new();
        while !self.finished || !pending_writes.is_empty() {
            self.run_state.check_background_error()?;
            if self.run_state.is_cancelled() {
                return Ok(());
            }
            if pending_writes.is_empty() {
                let Some(write) = self.next_write(true)? else {
                    break;
                };
                pending_writes.push_back(write);
            }
            while let Some(write) = self.next_write(false)? {
                pending_writes.push_back(write);
            }
            let io_slices: Vec<IoSlice<'_>> = pending_writes
                .iter()
                .take(WRITEV_MAX_SLICE)
                .map(|(data, _)| IoSlice::new(data))
                .collect();
            self.run_state.check_background_error()?;
            if self.run_state.is_cancelled() {
                return Ok(());
            }
            let written = match writer.write_vectored(&io_slices) {
                Ok(0) if !io_slices.is_empty() => {
                    return Err(SdxError::StreamInternal(
                        "write_vectored returned 0 with non-empty buffers".to_owned(),
                    ));
                }
                Ok(n) => n,
                Err(ref error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(error) => return Err(SdxError::Io(error)),
            };
            self.bytes_written.fetch_add(
                u64::try_from(written).unwrap_or(u64::MAX),
                Ordering::Relaxed,
            );
            let mut remaining = written;
            while remaining > 0 && !pending_writes.is_empty() {
                let front_len = pending_writes
                    .front()
                    .map(|(data, _)| data.len())
                    .unwrap_or(0);
                if remaining >= front_len {
                    remaining = remaining.saturating_sub(front_len);
                    pending_writes.pop_front();
                } else {
                    if let Some(front) = pending_writes.front_mut() {
                        front.0 = front.0.slice(remaining..);
                    }
                    remaining = 0;
                }
            }
        }
        self.run_state.check_background_error()?;
        if !self.run_state.is_cancelled() {
            writer.flush().map_err(SdxError::Io)?;
        }
        Ok(())
    }
}

/// Writes data sequentially to an output sink from async data futures.
///
/// In streaming mode (`new_streaming`) no background thread is spawned: items
/// are pulled directly by a [`DownloadStream`]. In writer mode (`new`) a
/// background blocking thread performs the writes, enforcing strict byte-range
/// contiguity before any bytes hit the sink.
pub struct SequentialWriter {
    sender: UnboundedSender<SequentialRetrievalItem>,
    next_position: u64,
    background_handle: Option<JoinHandle<()>>,
    run_state: Arc<RunState>,
    bytes_written: Arc<AtomicU64>,
    active_tasks: JoinSet<Result<(), SdxError>>,
    finished: bool,
}

impl Drop for SequentialWriter {
    fn drop(&mut self) {
        if !self.finished {
            self.run_state.cancel();
        }
    }
}

#[async_trait::async_trait]
impl DataWriter for SequentialWriter {
    async fn set_next_term_data_source(
        &mut self,
        byte_range: Range<u64>,
        permit: Option<BufferPermit>,
        data_future: DataFuture,
    ) -> Result<(), SdxError> {
        self.run_state.check_background_error()?;
        while let Some(result) = self.active_tasks.try_join_next() {
            result.map_err(|error| SdxError::TaskJoin(error.to_string()))??;
        }
        if self.finished {
            return Err(SdxError::StreamInternal(
                "writer has already finished".to_owned(),
            ));
        }
        if byte_range.start != self.next_position {
            return Err(SdxError::StreamInternal(format!(
                "byte range not sequential: expected start at {}, got {}",
                self.next_position, byte_range.start
            )));
        }
        let expected_size = byte_range.end.saturating_sub(byte_range.start);
        self.next_position = byte_range.end;

        let (sender, receiver) = oneshot::channel();
        if self
            .sender
            .send(SequentialRetrievalItem::Data { receiver, permit })
            .is_err()
        {
            self.run_state.check_background_error()?;
            return Err(SdxError::StreamInternal(
                "background writer channel closed".to_owned(),
            ));
        }

        let run_state = self.run_state.clone();
        let task = async move {
            let result = async {
                run_state.check_background_error()?;
                let data = data_future.await?;
                if u64::try_from(data.len()).unwrap_or(u64::MAX) != expected_size {
                    return Err(SdxError::StreamInternal(format!(
                        "data size mismatch: expected {expected_size} bytes, got {} bytes",
                        data.len()
                    )));
                }
                Ok(data)
            }
            .await;
            // Keep the oneshot sender alive until the real failure is stored;
            // otherwise the consumer can observe a closed sender first.
            let result = match result {
                Ok(data) => sender.send(data).map_err(|_data| {
                    SdxError::StreamInternal("failed to send data: receiver dropped".to_owned())
                }),
                Err(error) => Err(error),
            };
            if let Err(error) = result {
                // `SdxError` is not `Clone`, so store the real error in the run
                // state (first error wins) and surface a generic marker through
                // the task result; `check_error` returns the real error first
                // at every boundary.
                run_state.set_error(error);
                Err(SdxError::StreamInternal(
                    "term data task failed; see run state".to_owned(),
                ))
            } else {
                result
            }
        };
        self.active_tasks.spawn(task);
        Ok(())
    }

    async fn finish(mut self: Box<Self>) -> Result<u64, SdxError> {
        self.run_state.check_background_error()?;
        if self.finished {
            return Err(SdxError::StreamInternal(
                "writer has already finished".to_owned(),
            ));
        }
        if self.sender.send(SequentialRetrievalItem::Finish).is_err() {
            self.run_state.check_background_error()?;
            return Err(SdxError::StreamInternal(
                "background writer channel closed".to_owned(),
            ));
        }
        let expected_bytes = self.next_position;
        while let Some(result) = self.active_tasks.join_next().await {
            result.map_err(|error| SdxError::TaskJoin(error.to_string()))??;
        }
        match self.background_handle.take() {
            Some(handle) => {
                handle.await.map_err(|error| {
                    SdxError::StreamInternal(format!("background writer task failed: {error}"))
                })?;
                self.run_state.check_background_error()?;
                let actual_bytes = self.bytes_written.load(Ordering::Relaxed);
                if actual_bytes != expected_bytes {
                    return Err(SdxError::StreamInternal(format!(
                        "bytes written mismatch: expected {expected_bytes} bytes, wrote {actual_bytes} bytes"
                    )));
                }
                self.finished = true;
                Ok(actual_bytes)
            }
            None => {
                // Streaming mode: no background writer thread; the consumer
                // (DownloadStream) reads items directly from the channel.
                self.finished = true;
                Ok(expected_bytes)
            }
        }
    }
}

impl SequentialWriter {
    /// Creates a streaming sequential writer that exposes its internal queue.
    ///
    /// No background writer thread is spawned; the returned receiver yields
    /// [`SequentialRetrievalItem`]s consumed by a [`DownloadStream`].
    pub(crate) fn new_streaming(
        run_state: Arc<RunState>,
    ) -> (
        Box<dyn DataWriter>,
        UnboundedReceiver<SequentialRetrievalItem>,
    ) {
        let (sender, receiver) = unbounded_channel();
        let writer = Box::new(Self {
            sender,
            next_position: 0,
            background_handle: None,
            run_state,
            bytes_written: Arc::new(AtomicU64::new(0)),
            active_tasks: JoinSet::new(),
            finished: false,
        });
        (writer, receiver)
    }

    /// Creates a sequential writer backed by the given `Write` impl.
    ///
    /// When `use_vectorized` is true, the background thread batches pending
    /// writes and uses `write_vectored` (≤ 24 iovecs). The writer is moved to a
    /// `spawn_blocking` thread for blocking I/O.
    #[allow(clippy::new_ret_no_self)]
    pub(crate) fn new<W: Write + Send + 'static>(
        writer: W,
        use_vectorized: bool,
        run_state: Arc<RunState>,
    ) -> Box<dyn DataWriter> {
        let (sender, receiver) = unbounded_channel();
        let bytes_written = Arc::new(AtomicU64::new(0));
        let run_state_thread = run_state.clone();
        let run_state_clone = run_state.clone();
        let bytes_written_clone = bytes_written.clone();

        let handle = tokio::task::spawn_blocking(move || {
            let writer_thread = SyncWriterThread {
                rx: receiver,
                bytes_written: bytes_written_clone,
                run_state: run_state_thread,
                pending: None,
                finished: false,
            };
            let result = if use_vectorized {
                writer_thread.run_vectorized(writer)
            } else {
                writer_thread.run(writer)
            };
            if let Err(error) = result {
                run_state_clone.set_error(error);
            }
        });

        Box::new(Self {
            sender,
            next_position: 0,
            background_handle: Some(handle),
            run_state,
            bytes_written,
            active_tasks: JoinSet::new(),
            finished: false,
        })
    }
}

// ============================================================================
// UnorderedWriter
// ============================================================================

/// A completed term ready for consumption.
pub(crate) struct CompletedTerm {
    pub byte_range: Range<u64>,
    pub data: Bytes,
    pub permit: Option<BufferPermit>,
}

/// Atomic progress counters shared between the writer, its spawned tasks, and
/// the consumer stream.
pub(crate) struct UnorderedWriterProgress {
    pub terms_in_progress: AtomicU64,
    pub bytes_in_progress: AtomicU64,
}

impl UnorderedWriterProgress {
    pub(crate) fn terms_in_progress(&self) -> u64 {
        self.terms_in_progress.load(Ordering::Acquire)
    }

    pub(crate) fn bytes_in_progress(&self) -> u64 {
        self.bytes_in_progress.load(Ordering::Relaxed)
    }
}

/// Writer that delivers completed data terms in arbitrary completion order.
///
/// Each `set_next_term_data_source` spawns a task that resolves the data
/// future and sends the result through an unbounded channel; the consumer
/// (an [`UnorderedDownloadStream`]) reads in completion order.
pub struct UnorderedWriter {
    result_tx: UnboundedSender<Result<CompletedTerm, SdxError>>,
    run_state: Arc<RunState>,
    progress: Arc<UnorderedWriterProgress>,
    task_set: JoinSet<Result<u64, SdxError>>,
    total_bytes_sent: u64,
    finished: bool,
}

impl Drop for UnorderedWriter {
    fn drop(&mut self) {
        if !self.finished {
            self.run_state.cancel();
        }
    }
}

#[async_trait::async_trait]
impl DataWriter for UnorderedWriter {
    async fn set_next_term_data_source(
        &mut self,
        byte_range: Range<u64>,
        permit: Option<BufferPermit>,
        data_future: DataFuture,
    ) -> Result<(), SdxError> {
        self.run_state.check_background_error()?;
        while let Some(result) = self.task_set.try_join_next() {
            self.total_bytes_sent = self
                .total_bytes_sent
                .saturating_add(result.map_err(|error| SdxError::TaskJoin(error.to_string()))??);
        }
        if self.finished {
            return Err(SdxError::StreamInternal(
                "writer has already finished".to_owned(),
            ));
        }
        let expected_size = byte_range.end.saturating_sub(byte_range.start);
        self.progress
            .terms_in_progress
            .fetch_add(1, Ordering::Relaxed);
        self.progress
            .bytes_in_progress
            .fetch_add(expected_size, Ordering::Relaxed);

        let result_tx = self.result_tx.clone();
        let run_state = self.run_state.clone();
        let progress = self.progress.clone();

        self.task_set.spawn(async move {
            let result = async {
                run_state.check_background_error()?;
                let data = data_future.await?;
                if u64::try_from(data.len()).unwrap_or(u64::MAX) != expected_size {
                    return Err(SdxError::StreamInternal(format!(
                        "data size mismatch: expected {expected_size} bytes, got {} bytes",
                        data.len()
                    )));
                }
                Ok(CompletedTerm {
                    byte_range,
                    data,
                    permit,
                })
            }
            .await;

            let completed_bytes = result
                .as_ref()
                .map(|term| u64::try_from(term.data.len()).unwrap_or(u64::MAX))
                .unwrap_or(0);
            match result {
                Ok(term) => {
                    drop(result_tx.send(Ok(term)));
                }
                Err(error) => {
                    // `SdxError` is not `Clone`: store the real error in the
                    // run state (which cancels the token, waking the consumer's
                    // `cancelled()` branch) instead of sending a marker. The
                    // consumer's `check_error` then surfaces the real error.
                    run_state.set_error(error);
                }
            }

            progress
                .bytes_in_progress
                .fetch_sub(expected_size, Ordering::Relaxed);
            progress.terms_in_progress.fetch_sub(1, Ordering::Release);

            if completed_bytes > 0 {
                Ok(completed_bytes)
            } else {
                run_state.check_background_error()?;
                Ok(0)
            }
        });

        Ok(())
    }

    async fn finish(mut self: Box<Self>) -> Result<u64, SdxError> {
        self.run_state.check_background_error()?;
        while let Some(result) = self.task_set.join_next().await {
            self.total_bytes_sent = self
                .total_bytes_sent
                .saturating_add(result.map_err(|error| SdxError::TaskJoin(error.to_string()))??);
        }
        self.finished = true;
        Ok(self.total_bytes_sent)
    }
}

/// The three-part result of building an unordered streaming writer.
type UnorderedStreamingWriter = (
    Box<dyn DataWriter>,
    UnboundedReceiver<Result<CompletedTerm, SdxError>>,
    Arc<UnorderedWriterProgress>,
);

impl UnorderedWriter {
    /// Creates an unordered writer for streaming use.
    ///
    /// Returns the writer (for the reconstruction task), the receiver end of
    /// the completion channel, and the shared progress counters.
    pub(crate) fn new_streaming(run_state: Arc<RunState>) -> UnorderedStreamingWriter {
        let (result_tx, result_rx) = unbounded_channel();
        let progress = Arc::new(UnorderedWriterProgress {
            terms_in_progress: AtomicU64::new(0),
            bytes_in_progress: AtomicU64::new(0),
        });
        let writer = Box::new(Self {
            result_tx,
            run_state,
            progress: progress.clone(),
            task_set: JoinSet::new(),
            total_bytes_sent: 0,
            finished: false,
        });
        (writer, result_rx, progress)
    }
}

// ============================================================================
// Term / xorb block model and reconstruction normalization
// ============================================================================

/// A single file term: a contiguous output byte range sourced from a slice of
/// one xorb block's decoded data.
#[derive(Clone)]
pub(crate) struct FileTerm {
    /// Absolute byte range in the output file.
    pub byte_range: Range<u64>,
    /// Flattened index into the xorb block's `chunk_offsets` for this term's
    /// starting chunk.
    pub xorb_block_start_index: usize,
    xorb_block_end_index: usize,
    unpacked_length: u64,
    /// Byte offset into the first chunk of the block, non-zero only for the
    /// first term when the query range starts mid-chunk.
    pub offset_into_first_range: u64,
    /// The xorb block sourcing this term.
    pub xorb_block: Arc<XorbBlock>,
}

/// Decoded xorb block data with per-chunk byte offsets for zero-copy slicing.
pub(crate) struct XorbBlockData {
    /// `(chunk_index, byte_offset)` pairs mapping each chunk to its start
    /// position within `data`.
    pub chunk_offsets: Vec<(usize, usize)>,
    /// The concatenated decompressed chunk data for this block.
    pub data: Bytes,
    _buffer_permit: BufferPermit,
}

/// A downloadable xorb byte range, with data cached for sharing across terms.
pub(crate) struct XorbBlock {
    /// 64-hex xorb hash (the content-addressed cache key).
    pub hash: String,
    /// Chunk range within the xorb, end-exclusive.
    pub chunk_range: (u64, u64),
    /// The transfer URL.
    pub url: String,
    /// The inclusive byte range to fetch from `url`.
    pub bytes: ByteRange,
    /// Cached decoded data; the first term to request it triggers the fetch.
    pub data: OnceCell<Arc<XorbBlockData>>,
    decoded_budget: u64,
    reservation: Mutex<Option<BufferPermit>>,
    reservation_started: AtomicBool,
    #[cfg(test)]
    publication_gate: Option<Arc<PublicationGate>>,
}

#[cfg(test)]
struct PublicationGate {
    ready: Mutex<Option<oneshot::Sender<()>>>,
    release: Mutex<std::sync::mpsc::Receiver<()>>,
}

impl XorbBlock {
    #[cfg(test)]
    fn wait_for_publication(&self) -> Result<(), SdxError> {
        if let Some(gate) = &self.publication_gate {
            let sender = gate
                .ready
                .lock()
                .map_err(|error| SdxError::StreamInternal(error.to_string()))?
                .take();
            if let Some(sender) = sender {
                let _ = sender.send(());
                gate.release
                    .lock()
                    .map_err(|error| SdxError::StreamInternal(error.to_string()))?
                    .recv_timeout(std::time::Duration::from_secs(5))
                    .map_err(|error| SdxError::StreamInternal(error.to_string()))?;
            }
        }
        Ok(())
    }

    async fn reserve(
        &self,
        ctx: &StreamContext,
        seed: &mut Option<BufferPermit>,
    ) -> Result<(), SdxError> {
        if self.data.get().is_some() || self.reservation_started.load(Ordering::Acquire) {
            return Ok(());
        }
        if self.decoded_budget > ctx.buffer_semaphore.total_permits() {
            return Err(SdxError::StreamInternal(
                "xorb decoded size exceeds download buffer capacity".to_owned(),
            ));
        }
        let permit = match seed
            .as_mut()
            .and_then(|reserved| reserved.split(self.decoded_budget))
        {
            Some(permit) => permit,
            None => {
                *seed = None;
                ctx.buffer_semaphore
                    .acquire_many(self.decoded_budget)
                    .await?
            }
        };
        *self.reservation.lock().unwrap_or_else(|p| p.into_inner()) = Some(permit);
        self.reservation_started.store(true, Ordering::Release);
        Ok(())
    }
    /// Retrieves (or reuses) the decoded block data, checking the on-disk
    /// chunk cache first and fetching from the CAS on a miss under a download
    /// permit.
    ///
    /// On a cache hit the download permit is never acquired and no network
    /// request is issued; successful ranged fetches are stored back to the
    /// cache best-effort within the admitted fetch (failures ignored).
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the download permit cannot be acquired, the
    /// xorb fetch fails, or the serialized bytes cannot be decoded.
    async fn retrieve_data(
        self: Arc<Self>,
        ctx: &StreamContext,
        token: &str,
    ) -> Result<Arc<XorbBlockData>, SdxError> {
        self.data
            .get_or_try_init(|| async {
                // The reconstruction producer reserves blocks in output order;
                // this also supports direct block retrieval in internal tests.
                self.reserve(ctx, &mut None).await?;
                // Reset failed or cancelled initialization, but keep successful
                // ownership asserted until OnceCell publishes the returned value.
                let mut reservation_reset = ExitGuard::new(|| {
                    self.reservation_started.store(false, Ordering::Release);
                });
                let buffer_permit = self
                    .reservation
                    .lock()
                    .unwrap_or_else(|p| p.into_inner())
                    .take()
                    .ok_or_else(|| {
                        SdxError::StreamInternal("xorb buffer reservation missing".to_owned())
                    })?;
                // M2b2: check the on-disk chunk cache before acquiring the
                // download permit / hitting the CAS (key: xorb hash + exact
                // chunk range, mirror `xet-data-1.5.4` `xorb_block.rs`).
                if let Some(cache) = &ctx.chunk_cache
                    && let Some(cached) = cache
                        .get_bounded(&self.hash, self.chunk_range, self.decoded_budget)
                        .await?
                {
                    if u64::try_from(cached.data.len()).unwrap_or(u64::MAX) > self.decoded_budget {
                        return Err(SdxError::StreamInternal(
                            "cached xorb exceeds buffer reservation".to_owned(),
                        ));
                    }
                    let base = usize::try_from(self.chunk_range.0).unwrap_or(usize::MAX);
                    let chunk_offsets = cached
                        .chunk_offsets
                        .iter()
                        .enumerate()
                        .map(|(index, offset)| {
                            (
                                base.saturating_add(index),
                                usize::try_from(*offset).unwrap_or(usize::MAX),
                            )
                        })
                        .collect();
                    let block_data = Arc::new(XorbBlockData {
                        chunk_offsets,
                        data: cached.data,
                        _buffer_permit: buffer_permit,
                    });
                    reservation_reset.disarm();
                    drop(reservation_reset);
                    #[cfg(test)]
                    self.wait_for_publication()?;
                    return Ok(block_data);
                }
                let _download_permit =
                    ctx.download_permits
                        .clone()
                        .acquire_owned()
                        .await
                        .map_err(|error| {
                            SdxError::StreamInternal(format!(
                                "download permit acquire failed: {error}"
                            ))
                        })?;
                let retry = ctx.retry_context();
                let url = self.url.clone();
                let bytes = self.bytes;
                let ranged = retry
                    .run(token.to_owned(), move |tok| {
                        let url = url.clone();
                        async move {
                            ctx.transfer
                                .fetch_xorb_range_bounded(&url, &tok, bytes)
                                .await
                        }
                    })
                    .await?;
                ctx.xorb_fetch_count.fetch_add(1, Ordering::Relaxed);
                // Chunk indices belong to this exact serialized byte range.
                // A server that ignores Range must not relabel its first chunk
                // as the requested starting chunk.
                if ranged.served_range != self.bytes {
                    return Err(SdxError::Transfer(TransferError::InvalidResponse(format!(
                        "xorb served range {:?} does not match requested range {:?}",
                        ranged.served_range, self.bytes
                    ))));
                }
                let chunk_data = XorbReader::new(ranged.data).decode_chunk_data_bounded(
                    usize::try_from(self.decoded_budget).unwrap_or(usize::MAX),
                )?;
                let expected_chunks = self
                    .chunk_range
                    .1
                    .checked_sub(self.chunk_range.0)
                    .ok_or_else(|| {
                        SdxError::StreamInternal("inverted xorb chunk range".to_owned())
                    })?;
                let actual_chunks = u64::try_from(chunk_data.chunk_offsets.len().saturating_sub(1))
                    .unwrap_or(u64::MAX);
                if actual_chunks != expected_chunks {
                    return Err(SdxError::FetchChunkCountMismatch {
                        url: self.url.clone(),
                        expected: expected_chunks,
                        actual: actual_chunks,
                    });
                }
                // Await the best-effort cache write inside this admitted fetch;
                // failures must not fail the download.
                if let Some(cache) = &ctx.chunk_cache {
                    let cache = cache.clone();
                    let hash = self.hash.clone();
                    let chunk_range = self.chunk_range;
                    let data = chunk_data.data.clone();
                    let chunk_offsets = chunk_data
                        .chunk_offsets
                        .iter()
                        .map(|offset| u32::try_from(*offset).unwrap_or(u32::MAX))
                        .collect::<Vec<u32>>();
                    // Keep cache work within this admitted fetch. A detached
                    // put otherwise retains decoded bytes after its reservation
                    // has returned and creates unbounded background tasks.
                    drop(cache.put(&hash, chunk_range, &chunk_offsets, &data).await);
                }
                let start_chunk = self.chunk_range.0;
                let base = usize::try_from(start_chunk).unwrap_or(usize::MAX);
                let chunk_offsets = chunk_data
                    .chunk_offsets
                    .iter()
                    .enumerate()
                    .map(|(index, offset)| (base.saturating_add(index), *offset))
                    .collect();
                let block_data = Arc::new(XorbBlockData {
                    chunk_offsets,
                    data: chunk_data.data,
                    _buffer_permit: buffer_permit,
                });
                reservation_reset.disarm();
                drop(reservation_reset);
                #[cfg(test)]
                self.wait_for_publication()?;
                Ok(block_data)
            })
            .await
            .cloned()
    }
}

impl FileTerm {
    /// Zero-copy slices this term's bytes out of the block's decoded data.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError::StreamInternal`] when the block data does not cover
    /// the term's byte range.
    fn extract_bytes(&self, block_data: &XorbBlockData) -> Result<Bytes, SdxError> {
        let (_, start_byte_offset) = block_data
            .chunk_offsets
            .get(self.xorb_block_start_index)
            .copied()
            .ok_or_else(|| {
                SdxError::StreamInternal(format!(
                    "chunk offset {} missing from xorb block",
                    self.xorb_block_start_index
                ))
            })?;
        let (_, end_byte_offset) = block_data
            .chunk_offsets
            .get(self.xorb_block_end_index)
            .copied()
            .ok_or_else(|| {
                SdxError::StreamInternal("term ending chunk offset missing".to_owned())
            })?;
        if u64::try_from(end_byte_offset.saturating_sub(start_byte_offset)).unwrap_or(u64::MAX)
            != self.unpacked_length
        {
            return Err(SdxError::StreamInternal(
                "term unpacked length disagrees with decoded chunks".to_owned(),
            ));
        }
        let start = start_byte_offset
            .checked_add(usize::try_from(self.offset_into_first_range).unwrap_or(usize::MAX))
            .ok_or_else(|| SdxError::StreamInternal("term start offset overflow".to_owned()))?;
        let expected_size =
            usize::try_from(self.byte_range.end.saturating_sub(self.byte_range.start))
                .unwrap_or(usize::MAX);
        let end = start
            .checked_add(expected_size)
            .ok_or_else(|| SdxError::StreamInternal("term end offset overflow".to_owned()))?;
        if end > block_data.data.len() {
            return Err(SdxError::StreamInternal(format!(
                "term byte range {start}..{end} exceeds xorb block data length {}",
                block_data.data.len()
            )));
        }
        Ok(block_data.data.slice(start..end))
    }

    /// Returns a future that retrieves and extracts this term's data bytes.
    ///
    /// If the xorb data is already cached, the future resolves immediately.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when the data-retrieval task cannot be spawned.
    async fn get_data_task(
        &self,
        ctx: &StreamContext,
        token: &str,
    ) -> Result<DataFuture, SdxError> {
        if let Some(block_data) = self.xorb_block.data.get() {
            let bytes = self.extract_bytes(block_data)?;
            return Ok(Box::pin(async move { Ok(bytes) }));
        }
        let file_term = self.clone();
        let xorb_block = self.xorb_block.clone();
        let token = token.to_owned();
        let ctx = ctx.clone();
        Ok(Box::pin(async move {
            let block_data = xorb_block.retrieve_data(&ctx, &token).await?;
            file_term.extract_bytes(&block_data)
        }))
    }
}

/// A block of file terms returned by one prefetched reconstruction request.
pub(crate) struct TermBlock {
    pub file_terms: Vec<FileTerm>,
    /// The end of the actual byte range covered (may be < requested end when
    /// the end of file was reached).
    pub actual_end: u64,
}

/// A normalized fetch descriptor for one xorb byte range.
#[derive(Debug, Clone, PartialEq, Eq)]
struct XorbDescriptor {
    url: String,
    bytes: ByteRange,
    chunks: (u64, u64),
}

/// Raw reconstruction fetch metadata in either wire version.
enum XorbDescriptorSource {
    V2(BTreeMap<String, Vec<ReconstructionMultiRangeFetch>>),
    V1(BTreeMap<String, Vec<ReconstructionFetchInfo>>),
}

impl XorbDescriptorSource {
    fn for_hash(&self, hash: &str) -> Vec<XorbDescriptor> {
        match self {
            XorbDescriptorSource::V2(xorbs) => xorbs
                .get(hash)
                .map(|entries| {
                    entries
                        .iter()
                        .flat_map(|entry| {
                            entry.ranges.iter().map(|range| XorbDescriptor {
                                url: entry.url.clone(),
                                bytes: ByteRange::new(range.bytes.start, range.bytes.end),
                                chunks: (range.chunks.start, range.chunks.end),
                            })
                        })
                        .collect()
                })
                .unwrap_or_default(),
            XorbDescriptorSource::V1(fetch_info) => fetch_info
                .get(hash)
                .map(|entries| {
                    entries
                        .iter()
                        .map(|entry| XorbDescriptor {
                            url: entry.url.clone(),
                            bytes: ByteRange::new(entry.url_range.start, entry.url_range.end),
                            chunks: (entry.range.start, entry.range.end),
                        })
                        .collect()
                })
                .unwrap_or_default(),
        }
    }
}

/// Fetches the term block covering `query_range`, returning `None` when the
/// range is at or past the end of the file (HTTP 416 is treated as EOF).
///
/// # Errors
///
/// Returns [`SdxError`] when the reconstruction request fails for a non-EOF
/// reason or the response cannot be normalized.
async fn fetch_term_block(
    ctx: &StreamContext,
    token: &str,
    file_id: &str,
    query_range: Range<u64>,
) -> Result<Option<TermBlock>, SdxError> {
    if query_range.start >= query_range.end {
        return Ok(None);
    }
    let wire_range = ByteRange::new(query_range.start, query_range.end.saturating_sub(1));
    let retry = ctx.retry_context();
    let response = match fetch_reconstruction_response(
        &ctx.transfer,
        Some(&retry),
        &ctx.api_base,
        token,
        file_id,
        Some(wire_range),
    )
    .await
    {
        Ok(response) => response,
        // Past-EOF reconstruction requests surface as 416; the prefetch loop
        // treats that as end-of-stream (`docs/SDX_PLAN.md` §4.4.4
        // `.with_expected_416()`).
        Err(SdxError::Transfer(TransferError::RangeNotSatisfiable(_))) => return Ok(None),
        Err(error) => return Err(error),
    };
    normalize_block(
        response,
        query_range.start,
        query_range.end,
        ctx.buffer_semaphore.total_permits(),
    )
}

/// Resolves descriptors once, then groups only consecutive output terms.
/// Far-apart reuse receives a fresh block: caching it across intervening blocks
/// would pin its byte reservation and could prevent the next block progressing.
fn normalize_block(
    response: ReconstructionResponse,
    query_start: u64,
    query_end: u64,
    buffer_capacity: u64,
) -> Result<Option<TermBlock>, SdxError> {
    let (offset_into_first_range, terms, descriptors) = match response {
        ReconstructionResponse::V2(resp) => (
            resp.offset_into_first_range,
            resp.terms,
            XorbDescriptorSource::V2(resp.xorbs),
        ),
        ReconstructionResponse::V1(resp) => (
            resp.offset_into_first_range,
            resp.terms,
            XorbDescriptorSource::V1(resp.fetch_info),
        ),
    };
    if terms.is_empty() {
        return Ok(None);
    }
    let mut descriptor_index: HashMap<String, Vec<XorbDescriptor>> = HashMap::new();
    let mut groups: Vec<FetchGroup> = Vec::new();
    let mut current_offset = query_start;
    let merge_limit = buffer_capacity.min(MAX_COALESCED_BLOCK_BYTES);
    for (term_index, term) in terms.iter().enumerate() {
        parse_xet_hash_hex(&term.hash)?;
        let sorted = descriptor_index
            .entry(term.hash.clone())
            .or_insert_with(|| {
                let mut list = descriptors.for_hash(&term.hash);
                list.sort_by_key(|descriptor| descriptor.chunks.0);
                list
            });
        let position = sorted.partition_point(|descriptor| descriptor.chunks.0 <= term.range.start);
        let descriptor = position
            .checked_sub(1)
            .and_then(|index| sorted.get(index))
            .filter(|descriptor| descriptor.chunks.1 >= term.range.end)
            .cloned()
            .ok_or_else(|| SdxError::MissingFetchInfo {
                term_index,
                hash: term.hash.clone(),
            })?;
        let exact = descriptor.chunks == (term.range.start, term.range.end);
        let budget = if exact {
            term.unpacked_length
        } else {
            buffer_capacity.min(64 * 1024 * 1024)
        };
        if budget > buffer_capacity
            || descriptor.bytes.start > descriptor.bytes.end
            || descriptor.chunks.1.saturating_sub(descriptor.chunks.0) > 8192
            || term.range.start >= term.range.end
        {
            return Err(SdxError::StreamInternal(
                "invalid or oversized reconstruction fetch block".to_owned(),
            ));
        }
        let offset = if term_index == 0 {
            offset_into_first_range
        } else {
            0
        };
        if offset > term.unpacked_length {
            return Err(SdxError::UnpackedLengthMismatch {
                term_index,
                expected: term.unpacked_length,
                actual: offset,
            });
        }
        let term_size = term.unpacked_length.saturating_sub(offset);
        let term_range = current_offset..current_offset.saturating_add(term_size);
        current_offset = term_range.end;
        let parsed = GroupTerm {
            byte_range: term_range,
            first_chunk: term.range.start,
            end_chunk: term.range.end,
            unpacked_length: term.unpacked_length,
            offset,
        };
        if let Some(group) = groups.last_mut() {
            if group.hash == term.hash && group.last_descriptor == descriptor {
                // A descriptor may cover several terms or repeated output.
                group.budget = group.budget.max(budget);
                group.exact &= exact;
                group.terms.push(parsed);
                continue;
            }
            if group.hash == term.hash
                && group.descriptor.url == descriptor.url
                && group.descriptor.chunks.1 == descriptor.chunks.0
                && group.descriptor.bytes.end.checked_add(1) == Some(descriptor.bytes.start)
                && group.exact
                && exact
                && group.terms.len() < MAX_BUFFERED_TERMS
                && group
                    .budget
                    .checked_add(budget)
                    .is_some_and(|size| size <= merge_limit)
            {
                group.descriptor.chunks.1 = descriptor.chunks.1;
                group.descriptor.bytes.end = descriptor.bytes.end;
                group.budget = group.budget.saturating_add(budget);
                group.last_descriptor = descriptor;
                group.terms.push(parsed);
                continue;
            }
        }
        groups.push(FetchGroup {
            hash: term.hash.clone(),
            descriptor: descriptor.clone(),
            last_descriptor: descriptor,
            budget,
            exact,
            terms: vec![parsed],
        });
    }
    let mut file_terms = Vec::with_capacity(terms.len());
    for group in groups {
        // Original descriptors often cover multiple terms. When those terms
        // cover the whole descriptor, reserve their actual declared total;
        // otherwise use the bounded xorb maximum for a partial descriptor.
        let budget = if group.exact {
            group.budget
        } else {
            let mut covered = BTreeMap::new();
            for term in &group.terms {
                covered.insert(term.first_chunk, (term.end_chunk, term.unpacked_length));
            }
            let mut cursor = group.descriptor.chunks.0;
            let mut length = 0u64;
            for (start, (end, bytes)) in covered {
                if start != cursor {
                    break;
                }
                cursor = end;
                length = length.checked_add(bytes).ok_or_else(|| {
                    SdxError::StreamInternal("decoded block length overflow".to_owned())
                })?;
            }
            if cursor == group.descriptor.chunks.1 {
                length
            } else {
                group.budget
            }
        };
        if budget > buffer_capacity {
            return Err(SdxError::StreamInternal(
                "decoded xorb exceeds download buffer capacity".to_owned(),
            ));
        }
        let block = Arc::new(XorbBlock {
            hash: group.hash,
            chunk_range: group.descriptor.chunks,
            url: group.descriptor.url,
            bytes: group.descriptor.bytes,
            data: OnceCell::new(),
            decoded_budget: budget.max(1),
            reservation: Mutex::new(None),
            reservation_started: AtomicBool::new(false),
            #[cfg(test)]
            publication_gate: None,
        });
        for term in group.terms {
            file_terms.push(FileTerm {
                byte_range: term.byte_range,
                xorb_block_start_index: usize::try_from(
                    term.first_chunk.saturating_sub(block.chunk_range.0),
                )
                .unwrap_or(usize::MAX),
                xorb_block_end_index: usize::try_from(
                    term.end_chunk.saturating_sub(block.chunk_range.0),
                )
                .unwrap_or(usize::MAX),
                unpacked_length: term.unpacked_length,
                offset_into_first_range: term.offset,
                xorb_block: block.clone(),
            });
        }
    }
    if current_offset > query_end {
        let shrink = current_offset.saturating_sub(query_end);
        if let Some(last) = file_terms.last_mut() {
            last.byte_range.end = last.byte_range.end.saturating_sub(shrink);
        }
        current_offset = query_end;
    }
    Ok(Some(TermBlock {
        file_terms,
        actual_end: current_offset,
    }))
}

struct GroupTerm {
    byte_range: Range<u64>,
    first_chunk: u64,
    end_chunk: u64,
    unpacked_length: u64,
    offset: u64,
}

struct FetchGroup {
    hash: String,
    descriptor: XorbDescriptor,
    last_descriptor: XorbDescriptor,
    budget: u64,
    exact: bool,
    terms: Vec<GroupTerm>,
}

// ============================================================================
// ReconstructionTermManager (term-metadata prefetch)
// ============================================================================

/// Manages iteration over file term blocks with adaptive prefetching.
///
/// Mirrors `xet-data-1.5.4` `reconstruction_terms/manager.rs`: prefetches
/// reconstruction blocks ahead of consumption so `prefetched_pos - active_pos`
/// stays above `min_prefetch_buffer`, sizing each block by the observed
/// completion rate clamped to
/// `[min_reconstruction_fetch_size, max_reconstruction_fetch_size]`.
struct ReconstructionTermManager {
    ctx: StreamContext,
    file_id: String,
    token: String,
    requested_byte_range: Range<u64>,
    last_block_info: Option<(std::time::Instant, Range<u64>)>,
    known_final_byte_position: Arc<AtomicU64>,
    prefetched_byte_position: u64,
    current_active_byte_position: u64,
    // A dropped queued or actively awaited handle cancels its HTTP work.
    prefetch_queue: VecDeque<AbortOnDropHandle<Result<Option<TermBlock>, SdxError>>>,
    completion_rate_estimator: ExpWeightedMovingAvg,
}

impl ReconstructionTermManager {
    async fn new(
        ctx: StreamContext,
        file_id: String,
        token: String,
        requested_byte_range: Range<u64>,
    ) -> Result<Self, SdxError> {
        let mut manager = Self {
            ctx,
            file_id,
            token,
            requested_byte_range: requested_byte_range.clone(),
            last_block_info: None,
            known_final_byte_position: Arc::new(AtomicU64::new(requested_byte_range.end)),
            prefetched_byte_position: requested_byte_range.start,
            current_active_byte_position: requested_byte_range.start,
            prefetch_queue: VecDeque::new(),
            completion_rate_estimator: ExpWeightedMovingAvg::new_count_decay(
                DEFAULT_COMPLETION_RATE_ESTIMATOR_HALF_LIFE,
            ),
        };
        // Seed the pipeline with two blocks so the first block's completion
        // time can be measured against the second.
        let initial = manager.ctx.limits.min_reconstruction_fetch_size;
        manager.prefetch_block(initial).await?;
        manager.prefetch_block(initial.saturating_mul(2)).await?;
        Ok(manager)
    }

    /// Returns the next block of file terms, or `None` when the file has been
    /// fully covered.
    async fn next_file_terms(&mut self) -> Result<Option<TermBlock>, SdxError> {
        // Update the completion-rate estimator from the previous block.
        if let Some((start_time, block_range)) = self.last_block_info.take() {
            let completion_time = start_time.elapsed().as_secs_f64();
            let block_size = block_range.end.saturating_sub(block_range.start) as f64;
            if block_size != 0.0 {
                // Scoped allow mirrors the upstream estimator's float math.
                #[allow(clippy::float_arithmetic)]
                {
                    self.completion_rate_estimator
                        .update(block_size / completion_time.max(1e-6));
                }
            }
        }
        self.check_prefetch_buffer().await?;
        let Some(join_handle) = self.prefetch_queue.pop_front() else {
            return Ok(None);
        };
        let maybe_block = join_handle
            .await
            .map_err(|error| SdxError::TaskJoin(error.to_string()))??;
        match maybe_block {
            Some(block) => {
                let block_start = block
                    .file_terms
                    .first()
                    .map(|t| t.byte_range.start)
                    .unwrap_or(0);
                let block_end = block.actual_end;
                self.last_block_info = Some((std::time::Instant::now(), block_start..block_end));
                self.current_active_byte_position = block_end;
                Ok(Some(block))
            }
            None => {
                // End of file: remember where iteration stopped.
                self.known_final_byte_position
                    .store(self.prefetched_byte_position, Ordering::Relaxed);
                Ok(None)
            }
        }
    }

    fn is_done_fetching(&self) -> bool {
        self.prefetched_byte_position >= self.known_final_byte_position.load(Ordering::Relaxed)
    }

    /// Ensures enough term metadata is prefetched to keep the pipeline fed.
    async fn check_prefetch_buffer(&mut self) -> Result<(), SdxError> {
        if self.is_done_fetching() {
            return Ok(());
        }
        // Scoped allow mirrors the upstream estimator's float math
        // (`manager.rs` `check_prefetch_buffer`).
        #[allow(clippy::float_arithmetic)]
        {
            let completion_rate = self.completion_rate_estimator.value();
            let target_time = self.ctx.limits.target_block_completion_time_secs;
            let prefetch_buffer_target = target_time * completion_rate;
            let min_buffer = self.ctx.limits.min_prefetch_buffer as f64;
            let target_buffer = prefetch_buffer_target.max(min_buffer);

            let current = self
                .prefetched_byte_position
                .saturating_sub(self.current_active_byte_position);
            if !self.prefetch_queue.is_empty() && target_buffer <= current as f64 {
                return Ok(());
            }
            // No `saturating_sub` for f64: clamp the deficit to >= 0.
            let deficit = (target_buffer - current as f64).max(0.0);
            let next_block_size = (deficit as u64).clamp(
                self.ctx.limits.min_reconstruction_fetch_size,
                self.ctx.limits.max_reconstruction_fetch_size,
            );
            self.prefetch_block(next_block_size).await
        }
    }

    /// Schedules a prefetch of `block_size` bytes starting at the current
    /// prefetch position.
    async fn prefetch_block(&mut self, block_size: u64) -> Result<(), SdxError> {
        let block_size = block_size.clamp(
            self.ctx.limits.min_reconstruction_fetch_size,
            self.ctx.limits.max_reconstruction_fetch_size,
        );
        let mut prefetch_range =
            self.prefetched_byte_position..self.prefetched_byte_position.saturating_add(block_size);

        let last_byte_position = self
            .known_final_byte_position
            .load(Ordering::Relaxed)
            .min(self.requested_byte_range.end);
        if prefetch_range.end > last_byte_position {
            prefetch_range.end = last_byte_position;
        }
        let min_fetch_size = self.ctx.limits.min_reconstruction_fetch_size;
        if prefetch_range.end.saturating_add(min_fetch_size) > self.requested_byte_range.end {
            prefetch_range.end = self.requested_byte_range.end;
        }
        // Empty range (empty file, or already at/past the end).
        if prefetch_range.start >= prefetch_range.end {
            return Ok(());
        }
        self.prefetched_byte_position = prefetch_range.end;

        let ctx = self.ctx.clone();
        let token = self.token.clone();
        let file_id = self.file_id.clone();
        let known_final_byte_position = self.known_final_byte_position.clone();
        let join_handle = tokio::task::spawn(async move {
            match fetch_term_block(&ctx, &token, &file_id, prefetch_range.clone()).await {
                Ok(Some(block)) => {
                    // The server clamped the range to the file end.
                    if block.actual_end < prefetch_range.end {
                        known_final_byte_position.store(block.actual_end, Ordering::Relaxed);
                    }
                    Ok(Some(block))
                }
                Ok(None) => {
                    // Past the end of the file.
                    known_final_byte_position.fetch_min(prefetch_range.start, Ordering::Relaxed);
                    Ok(None)
                }
                Err(error) => Err(error),
            }
        });
        self.prefetch_queue
            .push_back(AbortOnDropHandle::new(join_handle));
        Ok(())
    }
}

// ============================================================================
// FileReconstructor (pipeline)
// ============================================================================

/// Reconstructs a file from its content-addressed chunks by downloading xorb
/// blocks and streaming the reassembled data to a writer or pull-based stream.
///
/// Mirrors `xet-data-1.5.4` `file_reconstructor.rs`. The background task is
/// spawned at construction, paused, and auto-starts on the first
/// `next()`/`blocking_next()`; dropping the stream cancels promptly.
///
/// The on-disk chunk cache ([`ChunkCache`], M2b2) is checked before every xorb
/// fetch and populated on successful ranged fetches; it defaults to the
/// client-configured cache (see [`crate::XetClientBuilder::with_chunk_cache_dir`])
/// and is inherited by each reconstructor.
pub(crate) struct FileReconstructor {
    ctx: StreamContext,
    file_id: String,
    token: String,
    byte_range: Option<Range<u64>>,
    chunk_cache: Option<Arc<ChunkCache>>,
    cancellation_token: CancellationToken,
}

impl FileReconstructor {
    pub(crate) fn new(ctx: StreamContext, file_id: String, token: String) -> Self {
        let chunk_cache = ctx.chunk_cache.clone();
        Self {
            ctx,
            file_id,
            token,
            byte_range: None,
            chunk_cache,
            cancellation_token: CancellationToken::new(),
        }
    }

    pub(crate) const fn with_byte_range(mut self, byte_range: Range<u64>) -> Self {
        self.byte_range = Some(byte_range);
        self
    }

    /// Replaces the default cancellation token with the given one, for
    /// coordinated external cancellation (the stream-group layer, M2b2).
    pub(crate) fn with_cancellation_token(mut self, token: CancellationToken) -> Self {
        self.cancellation_token = token;
        self
    }

    /// Reconstructs the file to the given `Write` sink on a background
    /// `spawn_blocking` thread, returning the number of bytes written.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when reconstruction, a fetch, or a write fails.
    pub(crate) async fn reconstruct_to_writer<W: Write + Send + 'static>(
        self,
        writer: W,
    ) -> Result<u64, SdxError> {
        let run_state = RunState::new(self.cancellation_token.clone());
        let data_writer = SequentialWriter::new(writer, true, run_state.clone());
        self.run(data_writer, run_state).await
    }

    /// Reconstructs the file as a pull-based stream, spawning the (paused)
    /// reconstruction task on the client's dedicated blocking runtime.
    pub(crate) fn reconstruct_to_stream(self) -> DownloadStream {
        let run_state = RunState::new(self.cancellation_token.clone());
        let runtime = self.ctx.blocking_runtime.clone();
        DownloadStream::new(self, run_state, runtime)
    }

    /// Reconstructs the file as an unordered stream, yielding `(offset, Bytes)`
    /// in completion order.
    pub(crate) fn reconstruct_to_unordered_stream(self) -> UnorderedDownloadStream {
        let run_state = RunState::new(self.cancellation_token.clone());
        let runtime = self.ctx.blocking_runtime.clone();
        UnorderedDownloadStream::new(self, run_state, runtime)
    }

    async fn run(
        self,
        data_writer: Box<dyn DataWriter>,
        run_state: Arc<RunState>,
    ) -> Result<u64, SdxError> {
        match self.run_impl(data_writer, &run_state).await {
            Ok(value) => Ok(value),
            Err(RunError::Cancelled) => {
                // Genuine cancellation: surface any stored error without
                // consuming it (the stream path reports the typed error via
                // `check_error`).
                if let Some(message) = run_state.error_message() {
                    return Err(SdxError::StreamInternal(message));
                }
                Ok(0)
            }
            Err(RunError::Error(error)) => {
                // Store the error (first-wins) so the stream path can surface
                // the typed error via `check_error`; return an error to the
                // writer caller WITHOUT consuming the stored copy (consuming
                // it would make the stream path report "unknown error
                // occurred in background task").
                run_state.set_error(error);
                Err(run_state
                    .error_message()
                    .map(SdxError::StreamInternal)
                    .unwrap_or_else(|| SdxError::StreamInternal("download failed".to_owned())))
            }
        }
    }

    async fn run_impl(
        self,
        mut data_writer: Box<dyn DataWriter>,
        run_state: &RunState,
    ) -> Result<u64, RunError> {
        let Self {
            ctx,
            file_id,
            token,
            byte_range,
            chunk_cache,
            cancellation_token: _,
        } = self;
        // Per-reconstructor cache override wins; otherwise the client-configured
        // cache (already seeded into `ctx`) applies.
        let ctx = StreamContext {
            chunk_cache: chunk_cache.or_else(|| ctx.chunk_cache.clone()),
            ..ctx
        };

        run_state.check_run_state()?;
        let requested_range = byte_range.unwrap_or(0..u64::MAX);
        let mut term_manager = ReconstructionTermManager::new(
            ctx.clone(),
            file_id,
            token.clone(),
            requested_range.clone(),
        )
        .await?;

        // Dynamic buffer scaling: target = (base + n * perfile).min(limit).
        // `increment_permits_to_target` may return a virtual permit this
        // download can split from immediately; the exit guard recomputes the
        // target for the reduced download count and shrinks back if needed.
        let base = DEFAULT_DOWNLOAD_BUFFER_SIZE;
        let perfile = DEFAULT_DOWNLOAD_BUFFER_PERFILE_SIZE;
        let limit = DEFAULT_DOWNLOAD_BUFFER_LIMIT;
        let active = ctx
            .active_downloads
            .fetch_add(1, Ordering::Relaxed)
            .saturating_add(1);
        let target = base
            .saturating_add(active.saturating_mul(perfile))
            .min(limit);
        let mut seed_buffer_permit = ctx.buffer_semaphore.increment_permits_to_target(target);
        let semaphore = ctx.buffer_semaphore.clone();
        let active_downloads = ctx.active_downloads.clone();
        let _download_count_guard = ExitGuard::new(move || {
            let n = active_downloads
                .fetch_sub(1, Ordering::Relaxed)
                .saturating_sub(1);
            let shrunk_target = base.saturating_add(n.saturating_mul(perfile)).min(limit);
            semaphore.decrement_permits_to_target(shrunk_target);
        });

        // The range start offset: writer ranges are relative to this.
        let range_start_offset = requested_range.start;
        let term_slots = Arc::new(Semaphore::new(MAX_BUFFERED_TERMS));

        // Outer loop: retrieve blocks of file terms, aborting promptly on
        // cancellation via `select!`.
        loop {
            let maybe_block = tokio::select! {
                biased;
                () = run_state.cancelled() => {
                    run_state.check_run_state()?;
                    return Ok(0);
                }
                result = term_manager.next_file_terms() => result?,
            };
            let Some(block) = maybe_block else {
                break;
            };
            run_state.check_run_state()?;

            // Inner loop: process each file term in the block.
            for file_term in block.file_terms {
                run_state.check_run_state()?;
                let term_size = file_term
                    .byte_range
                    .end
                    .saturating_sub(file_term.byte_range.start);

                // Reserve the whole decoded allocation in output order. The
                // term guard keeps its backing block alive until delivery,
                // even when its own byte slice is much smaller than the block.
                let slot = tokio::select! {
                    biased;
                    () = run_state.cancelled() => { run_state.check_run_state()?; return Ok(0); }
                    result = term_slots.clone().acquire_owned() => result.map_err(|error| SdxError::StreamInternal(error.to_string()))?,
                };
                tokio::select! {
                    biased;
                    () = run_state.cancelled() => { run_state.check_run_state()?; return Ok(0); }
                    result = file_term.xorb_block.reserve(&ctx, &mut seed_buffer_permit) => result?,
                }
                let buffer_permit = BufferPermit::for_term(
                    ctx.buffer_semaphore.clone(),
                    slot,
                    file_term.xorb_block.clone(),
                );

                let data_future = file_term.get_data_task(&ctx, &token).await?;
                let relative_start = file_term
                    .byte_range
                    .start
                    .saturating_sub(range_start_offset);
                let relative_end = file_term.byte_range.end.saturating_sub(range_start_offset);
                data_writer
                    .set_next_term_data_source(
                        relative_start..relative_end,
                        Some(buffer_permit),
                        data_future,
                    )
                    .await?;
                run_state.record_new_term(term_size);
            }
        }

        // Finish the writer and wait for all data to be delivered.
        let bytes_written = tokio::select! {
            biased;
            () = run_state.cancelled() => {
                run_state.check_run_state()?;
                return Ok(0);
            }
            result = data_writer.finish() => result?,
        };
        Ok(bytes_written)
    }
}

// ============================================================================
// DownloadStream
// ============================================================================

struct PendingDownloadData {
    receiver: oneshot::Receiver<Bytes>,
    permit: Option<BufferPermit>,
}

/// A streaming download handle that yields data chunks as they are
/// reconstructed (mirror `data_writer/download_stream.rs`).
///
/// The reconstruction task is spawned at construction but pauses until
/// [`start`](Self::start) is called (or the first [`next`](Self::next) /
/// [`blocking_next`](Self::blocking_next)). Data is pulled from the sequential
/// writer's internal queue, bypassing the synchronous writer thread.
///
/// Each call to `next()`/`blocking_next()` returns the next sequential chunk,
/// or `Ok(None)` at end-of-stream **or** cancellation. Any reconstruction error
/// surfaces on the call that would have returned the next chunk (or on the
/// final `None`) via the shared run state.
pub struct DownloadStream {
    pending_data: Option<PendingDownloadData>,
    receiver: UnboundedReceiver<SequentialRetrievalItem>,
    finished: bool,
    run_state: Arc<RunState>,
    start_signal: Option<Arc<Notify>>,
    #[cfg(not(target_family = "wasm"))]
    runtime: Arc<tokio::runtime::Runtime>,
}

impl DownloadStream {
    /// Creates a new `DownloadStream`, spawning the (paused) reconstruction
    /// task on the client's dedicated runtime.
    pub(crate) fn new(
        reconstructor: FileReconstructor,
        run_state: Arc<RunState>,
        #[cfg(not(target_family = "wasm"))] runtime: Arc<tokio::runtime::Runtime>,
    ) -> Self {
        let (data_writer, receiver) = SequentialWriter::new_streaming(run_state.clone());
        let start_signal = Arc::new(Notify::new());
        let signal = start_signal.clone();
        let rs = run_state.clone();
        let task = async move {
            signal.notified().await;
            drop(reconstructor.run(data_writer, rs).await);
        };
        #[cfg(not(target_family = "wasm"))]
        {
            runtime.spawn(task);
        }
        #[cfg(target_family = "wasm")]
        {
            tokio::task::spawn(task);
        }
        Self {
            receiver,
            pending_data: None,
            finished: false,
            run_state,
            start_signal: Some(start_signal),
            #[cfg(not(target_family = "wasm"))]
            runtime,
        }
    }

    /// Unblocks the reconstruction task so it begins producing data.
    ///
    /// If already started, this is a no-op. Called automatically on the first
    /// [`next`](Self::next) / [`blocking_next`](Self::blocking_next). This
    /// method is non-async and does not require a tokio runtime context.
    pub fn start(&mut self) {
        if let Some(signal) = self.start_signal.take() {
            signal.notify_one();
        }
    }

    fn ensure_started(&mut self) {
        if self.start_signal.is_some() {
            self.start();
        }
    }

    fn cancel_reconstruction(&self) {
        self.run_state.cancel();
        if let Some(signal) = self.start_signal.as_ref() {
            signal.notify_one();
        }
    }

    /// Returns the next chunk of downloaded data asynchronously.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// Dropping this future before it completes preserves any pending chunk
    /// for the next call. Use [`cancel`](Self::cancel) to stop the download.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    pub async fn next(&mut self) -> Result<Option<Bytes>, SdxError> {
        if self.finished {
            return Ok(None);
        }
        if self.run_state.is_cancelled() {
            let terminal = self.run_state.check_error();
            self.cancel();
            terminal?;
            return Ok(None);
        }
        self.ensure_started();

        if self.pending_data.is_none() {
            let item = if let Ok(item) = self.receiver.try_recv() {
                Some(item)
            } else {
                tokio::select! {
                    biased;
                    recv = self.receiver.recv() => recv,
                    () = self.run_state.cancelled() => None,
                }
            };
            if self.run_state.is_cancelled() {
                let terminal = self.run_state.check_error();
                drop(item);
                self.cancel();
                terminal?;
                return Ok(None);
            }
            match item {
                Some(SequentialRetrievalItem::Data { receiver, permit }) => {
                    self.pending_data = Some(PendingDownloadData { receiver, permit });
                }
                Some(SequentialRetrievalItem::Finish) | None => {
                    self.finished = true;
                    self.run_state.check_error()?;
                    return Ok(None);
                }
            }
        }

        // Keep the in-flight receiver and its buffer permit in the stream.
        // Dropping a `next()` future (for example, on a timeout) must leave
        // this term available for the consumer's next attempt.
        let Some(pending) = self.pending_data.as_mut() else {
            return Err(SdxError::StreamInternal(
                "pending stream data is missing".to_owned(),
            ));
        };
        let result = tokio::select! {
            biased;
            data = &mut pending.receiver => Some(data),
            () = self.run_state.cancelled() => None,
        };
        if self.run_state.is_cancelled() {
            let terminal = self.run_state.check_error();
            self.cancel();
            terminal?;
            return Ok(None);
        }
        // A completed receiver cannot be polled again, and cancellation of
        // the whole reconstruction must release its permit promptly.
        if let Some(completed) = self.pending_data.take() {
            drop(completed.permit);
        }
        match result {
            Some(Ok(data)) => {
                self.run_state
                    .report_bytes_written(u64::try_from(data.len()).unwrap_or(u64::MAX));
                Ok(Some(data))
            }
            Some(Err(_)) => {
                self.run_state.check_error()?;
                if self.run_state.is_cancelled() {
                    self.finished = true;
                    return Ok(None);
                }
                Err(SdxError::StreamInternal(
                    "data sender was dropped before sending data".to_owned(),
                ))
            }
            None => {
                self.finished = true;
                self.run_state.check_error()?;
                Ok(None)
            }
        }
    }

    /// Returns the next chunk of downloaded data, blocking the current thread
    /// until data is available.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Runtime requirements
    ///
    /// This runs the async [`next`](Self::next) on a dedicated multi-threaded
    /// runtime owned by the client, so it works from plain CLI threads and
    /// from [`tokio::task::spawn_blocking`] **without** panicking (upstream
    /// `xet-data` panics inside an async runtime via `blocking_recv`). Calling
    /// it from within an async context is supported but blocks that executor
    /// thread until the next chunk arrives — prefer [`next`](Self::next)
    /// there.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    #[cfg(not(target_family = "wasm"))]
    pub fn blocking_next(&mut self) -> Result<Option<Bytes>, SdxError> {
        let runtime = self.runtime.clone();
        block_on_download(&runtime, self.next())
    }

    /// Cancels the in-progress (or not-yet-started) download.
    ///
    /// Subsequent calls to [`next`](Self::next) / [`blocking_next`](Self::blocking_next)
    /// return `Ok(None)`.
    pub fn cancel(&mut self) {
        self.cancel_reconstruction();
        drop(self.start_signal.take());
        self.receiver.close();
        while let Ok(item) = self.receiver.try_recv() {
            drop(item);
        }
        drop(self.pending_data.take());
        self.finished = true;
    }

    /// Returns the shared run state (for the stream-group status probe).
    pub(crate) fn run_state(&self) -> Arc<RunState> {
        self.run_state.clone()
    }

    /// Returns the not-yet-fired start signal, if the stream is still paused
    /// (the stream-group layer wakes paused tasks during abort).
    pub(crate) fn pending_start_signal(&self) -> Option<Arc<Notify>> {
        self.start_signal.clone()
    }
}

impl Drop for DownloadStream {
    fn drop(&mut self) {
        self.cancel_reconstruction();
        self.receiver.close();
    }
}

// ============================================================================
// UnorderedDownloadStream
// ============================================================================

/// A streaming download handle that yields data chunks in completion order,
/// each tagged with its byte offset in the output file (mirror
/// `data_writer/unordered_download_stream.rs`).
///
/// The reconstruction task is spawned at construction but pauses until
/// [`start`](Self::start) is called (or the first [`next`](Self::next) /
/// [`blocking_next`](Self::blocking_next)). Progress can be monitored via
/// [`total_bytes_expected`](Self::total_bytes_expected),
/// [`bytes_in_progress`](Self::bytes_in_progress), and
/// [`bytes_completed`](Self::bytes_completed).
pub struct UnorderedDownloadStream {
    /// Shared atomic progress counters (also held by the writer and its tasks).
    progress: Arc<UnorderedWriterProgress>,
    /// Channel receiver for completed terms from spawned tasks.
    receiver: UnboundedReceiver<Result<CompletedTerm, SdxError>>,
    /// Whether the stream has finished (no more data).
    finished: bool,
    /// Shared run state with the `FileReconstructor`.
    run_state: Arc<RunState>,
    /// Signal to unblock the spawned reconstruction task.
    start_signal: Option<Arc<Notify>>,
    #[cfg(not(target_family = "wasm"))]
    runtime: Arc<tokio::runtime::Runtime>,
}

impl UnorderedDownloadStream {
    /// Creates a new `UnorderedDownloadStream`, spawning the (paused)
    /// reconstruction task on the client's dedicated runtime.
    pub(crate) fn new(
        reconstructor: FileReconstructor,
        run_state: Arc<RunState>,
        #[cfg(not(target_family = "wasm"))] runtime: Arc<tokio::runtime::Runtime>,
    ) -> Self {
        let (writer, receiver, progress) = UnorderedWriter::new_streaming(run_state.clone());
        let start_signal = Arc::new(Notify::new());
        let signal = start_signal.clone();
        let rs = run_state.clone();
        let task = async move {
            signal.notified().await;
            drop(reconstructor.run(writer, rs).await);
        };
        #[cfg(not(target_family = "wasm"))]
        {
            runtime.spawn(task);
        }
        #[cfg(target_family = "wasm")]
        {
            tokio::task::spawn(task);
        }
        Self {
            progress,
            receiver,
            finished: false,
            run_state,
            start_signal: Some(start_signal),
            #[cfg(not(target_family = "wasm"))]
            runtime,
        }
    }

    /// Unblocks the reconstruction task so it begins producing data.
    ///
    /// If already started, this is a no-op. Called automatically on the first
    /// [`next`](Self::next) / [`blocking_next`](Self::blocking_next).
    pub fn start(&mut self) {
        if let Some(signal) = self.start_signal.take() {
            signal.notify_one();
        }
    }

    fn ensure_started(&mut self) {
        if self.start_signal.is_some() {
            self.start();
        }
    }

    fn cancel_reconstruction(&self) {
        self.run_state.cancel();
        if let Some(signal) = self.start_signal.as_ref() {
            signal.notify_one();
        }
    }

    /// Returns the next `(file_offset, chunk)` pair asynchronously.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    pub async fn next(&mut self) -> Result<Option<(u64, Bytes)>, SdxError> {
        if self.finished {
            return Ok(None);
        }
        if self.run_state.is_cancelled() {
            let terminal = self.run_state.check_error();
            self.cancel();
            terminal?;
            return Ok(None);
        }
        self.ensure_started();

        if let Ok(result) = self.receiver.try_recv() {
            return self.process_term(result);
        }
        let next_item = tokio::select! {
            biased;
            recv = self.receiver.recv() => recv,
            () = self.run_state.cancelled() => None,
        };
        match next_item {
            Some(result) => self.process_term(result),
            None => {
                if self.run_state.is_cancelled() {
                    let terminal = self.run_state.check_error();
                    self.cancel();
                    terminal?;
                    return Ok(None);
                }
                self.finished = true;
                self.run_state.check_error()?;
                Ok(None)
            }
        }
    }

    /// Returns the next `(file_offset, chunk)` pair, blocking the current
    /// thread until data is available.
    ///
    /// Returns `Ok(None)` when the download is complete or cancelled.
    ///
    /// # Runtime requirements
    ///
    /// See [`DownloadStream::blocking_next`] for the dedicated-runtime bridge
    /// and the upstream panic-in-async-runtime documentation.
    ///
    /// # Errors
    ///
    /// Returns [`SdxError`] when a background reconstruction task failed.
    #[cfg(not(target_family = "wasm"))]
    pub fn blocking_next(&mut self) -> Result<Option<(u64, Bytes)>, SdxError> {
        let runtime = self.runtime.clone();
        block_on_download(&runtime, self.next())
    }

    fn process_term(
        &mut self,
        result: Result<CompletedTerm, SdxError>,
    ) -> Result<Option<(u64, Bytes)>, SdxError> {
        if self.run_state.is_cancelled() {
            drop(result);
            let terminal = self.run_state.check_error();
            self.cancel();
            terminal?;
            return Ok(None);
        }
        let term = result?;
        let offset = term.byte_range.start;
        let data = term.data;
        // The buffer permit is released only after the consumer has received
        // these bytes.
        drop(term.permit);
        self.run_state
            .report_bytes_written(u64::try_from(data.len()).unwrap_or(u64::MAX));
        Ok(Some((offset, data)))
    }

    /// Cancels the in-progress (or not-yet-started) download.
    ///
    /// Subsequent calls to [`next`](Self::next) / [`blocking_next`](Self::blocking_next)
    /// return `Ok(None)`.
    pub fn cancel(&mut self) {
        self.cancel_reconstruction();
        drop(self.start_signal.take());
        self.receiver.close();
        while let Ok(item) = self.receiver.try_recv() {
            drop(item);
        }
        self.finished = true;
    }

    /// Total bytes scheduled for delivery so far (grows as term metadata is
    /// prefetched; equals the full file/range size at end-of-stream).
    #[must_use]
    pub fn total_bytes_expected(&self) -> u64 {
        self.run_state.total_bytes_scheduled()
    }

    /// Bytes currently being fetched by in-progress tasks.
    #[must_use]
    pub fn bytes_in_progress(&self) -> u64 {
        self.progress.bytes_in_progress()
    }

    /// Bytes delivered to the consumer through [`next`](Self::next) /
    /// [`blocking_next`](Self::blocking_next).
    #[must_use]
    pub fn bytes_completed(&self) -> u64 {
        self.run_state.total_bytes_delivered()
    }

    /// Number of tasks currently resolving data futures.
    #[must_use]
    pub fn terms_in_progress(&self) -> u64 {
        self.progress.terms_in_progress()
    }

    /// Returns the shared run state (for the stream-group status probe).
    pub(crate) fn run_state(&self) -> Arc<RunState> {
        self.run_state.clone()
    }

    /// Returns the not-yet-fired start signal, if the stream is still paused
    /// (the stream-group layer wakes paused tasks during abort).
    pub(crate) fn pending_start_signal(&self) -> Option<Arc<Notify>> {
        self.start_signal.clone()
    }
}

impl Drop for UnorderedDownloadStream {
    fn drop(&mut self) {
        self.cancel_reconstruction();
        self.receiver.close();
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::AtomicU64;
    use std::time::Duration;

    use serde_json::json;
    use tokio::runtime::Runtime;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{header, method, path},
    };

    use super::*;
    use crate::{auth::Auth, reconstruction, transfer::TransferClient};

    const FILE_ID: &str = "0000000000000000000000000000000000000000000000000000000000000000";
    const XORB_HASH: &str = "1111111111111111111111111111111111111111111111111111111111111111";
    const READ_TOKEN: &str = "read-token";

    /// Serializes chunk payloads with the pinned upstream serializer.
    fn serialize_payload(chunks: &[&[u8]]) -> Vec<u8> {
        use xet_core_structures::xorb_object::{CompressionScheme, serialize_chunk};
        let mut payload = Vec::new();
        for chunk in chunks {
            serialize_chunk(chunk, &mut payload, CompressionScheme::None).unwrap();
        }
        payload
    }

    fn v2_response_body(
        offset: u64,
        terms: serde_json::Value,
        xorbs: serde_json::Value,
    ) -> serde_json::Value {
        let mut body = serde_json::Map::new();
        body.insert(
            "offset_into_first_range".to_owned(),
            serde_json::Value::from(offset),
        );
        body.insert("terms".to_owned(), terms);
        body.insert("xorbs".to_owned(), xorbs);
        serde_json::Value::Object(body)
    }

    /// Small prefetch limits so unit tests exercise multiple term blocks
    /// without huge JSON responses.
    fn test_limits() -> StreamLimits {
        StreamLimits {
            min_reconstruction_fetch_size: 4096,
            max_reconstruction_fetch_size: 4096,
            min_prefetch_buffer: 8192,
            ..StreamLimits::default()
        }
    }

    /// Shared dedicated runtime for the streaming tests.
    ///
    /// Creating/dropping a `tokio::runtime::Runtime` inside an async test
    /// context panics ("cannot drop a runtime in a context where blocking is
    /// not allowed"), so a single runtime is created once and shared across
    /// all tests; it is dropped at process exit on a clean thread.
    fn test_runtime() -> Arc<Runtime> {
        static RUNTIME: std::sync::OnceLock<Arc<Runtime>> = std::sync::OnceLock::new();
        RUNTIME
            .get_or_init(|| Arc::new(Runtime::new().unwrap()))
            .clone()
    }

    fn test_stream_context(server: &MockServer, buffer_cap: u64) -> StreamContext {
        StreamContext {
            transfer: TransferClient::new(reqwest::Client::new()),
            api_base: server.uri(),
            buffer_semaphore: Arc::new(BufferSemaphore::new(buffer_cap, buffer_cap, buffer_cap)),
            active_downloads: Arc::new(AtomicU64::new(0)),
            download_permits: Arc::new(Semaphore::new(DEFAULT_DOWNLOAD_CONCURRENCY)),
            limits: test_limits(),
            chunk_cache: None,
            xorb_fetch_count: Arc::new(AtomicU64::new(0)),
            tokens: test_tokens(server),
            retry_policy: RetryPolicy::default(),
            blocking_runtime: test_runtime(),
        }
    }

    /// Builds a token service used only as a retry-context carrier in stream
    /// tests (its `read_token` is never exercised because tests never 401).
    fn test_tokens(server: &MockServer) -> TokenService {
        let auth = Auth::new(
            &server.uri(),
            crate::RepositoryId {
                provider: "github".to_owned(),
                owner: "team".to_owned(),
                repo: "assets".to_owned(),
                revision: "main".to_owned(),
            },
        )
        .unwrap()
        .with_token(READ_TOKEN.to_owned());
        auth.build().unwrap()
    }

    /// Mounts a 200 reconstruction response for `file_hash` scoped to exactly
    /// the `Range` header `bytes=start-end`; every other range gets 416
    /// (past-EOF), which the prefetch loop treats as end-of-stream.
    async fn reconstruction_mock(
        server: &MockServer,
        start: u64,
        end: u64,
        offset: u64,
        terms: serde_json::Value,
        xorbs: serde_json::Value,
    ) {
        Mock::given(method("GET"))
            .and(path(format!("/v2/reconstructions/{FILE_ID}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .and(header("range", format!("bytes={start}-{end}")))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(v2_response_body(offset, terms, xorbs)),
            )
            .mount(server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("/v2/reconstructions/{FILE_ID}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .respond_with(ResponseTemplate::new(416).set_body_json(json!({"error": "past eof"})))
            .mount(server)
            .await;
    }

    async fn xorb_range_mock(server: &MockServer, start: u64, end: u64, body: Vec<u8>) {
        Mock::given(method("GET"))
            .and(path(format!("/transfer/xorb/default/{XORB_HASH}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .and(header("range", format!("bytes={start}-{end}")))
            .respond_with(
                ResponseTemplate::new(206)
                    .insert_header(
                        "Content-Range",
                        format!("bytes {start}-{end}/{}", body.len()),
                    )
                    .set_body_raw(body, "application/octet-stream"),
            )
            .mount(server)
            .await;
    }

    /// Responds to actual arbitrary single-range HTTP requests. Coalescing
    /// tests must check network behavior, rather than a copied normalizer.
    async fn xorb_payload_mock(server: &MockServer, payload: Vec<u8>) {
        Mock::given(method("GET"))
            .and(path(format!("/transfer/xorb/default/{XORB_HASH}")))
            .respond_with(move |request: &wiremock::Request| {
                let range = request.headers.get("range").unwrap().to_str().unwrap();
                let (start, end) = range
                    .strip_prefix("bytes=")
                    .unwrap()
                    .split_once('-')
                    .unwrap();
                let start: usize = start.parse().unwrap();
                let end: usize = end.parse().unwrap();
                ResponseTemplate::new(206)
                    .insert_header(
                        "Content-Range",
                        format!("bytes {start}-{end}/{}", payload.len()),
                    )
                    .set_body_bytes(payload[start..=end].to_vec())
            })
            .mount(server)
            .await;
    }

    async fn adjacent_chunk_fixture(
        server: &MockServer,
        count: usize,
        size: usize,
        order: &[usize],
        requested: Option<Range<u64>>,
    ) -> Vec<u8> {
        let chunks: Vec<Vec<u8>> = (0..count)
            .map(|i| vec![u8::try_from(i % 251).unwrap(); size])
            .collect();
        let serialized_size = serialize_payload(&[&chunks[0]]).len();
        let payload = serialize_payload(&chunks.iter().map(Vec::as_slice).collect::<Vec<_>>());
        let expected: Vec<u8> = order
            .iter()
            .flat_map(|i| chunks[*i].iter().copied())
            .collect();
        let terms: serde_json::Value = order
            .iter()
            .map(
                |i| json!({"hash": XORB_HASH,"unpacked_length":size,"range":{"start":i,"end":i.saturating_add(1)}}),
            )
            .collect();
        let ranges: serde_json::Value = (0..count).map(|i| json!({"chunks":{"start":i,"end":i.saturating_add(1)},"bytes":{"start":i.saturating_mul(serialized_size),"end":i.saturating_add(1).saturating_mul(serialized_size).saturating_sub(1)}})).collect();
        let start = requested.as_ref().map_or(0, |range| range.start);
        let end = requested
            .as_ref()
            .map_or(4095, |range| range.end.saturating_sub(1));
        reconstruction_mock(server,start,end,start,terms,json!({XORB_HASH:[{"url":format!("{}/transfer/xorb/default/{XORB_HASH}",server.uri()),"ranges":ranges}]})).await;
        xorb_payload_mock(server, payload).await;
        requested.map_or_else(
            || expected.clone(),
            |range| expected[range.start as usize..range.end as usize].to_vec(),
        )
    }

    #[tokio::test]
    async fn streaming_coalesces_actual_http_requests_with_partial_slices() {
        let server = MockServer::start().await;
        let range = 3..507;
        let expected = adjacent_chunk_fixture(
            &server,
            64,
            8,
            &(0..64).collect::<Vec<_>>(),
            Some(range.clone()),
        )
        .await;
        let ctx = test_stream_context(&server, 256);
        let (output, _) = tokio::time::timeout(
            Duration::from_secs(3),
            drain(make_stream(ctx.clone(), Some(range))),
        )
        .await
        .unwrap();
        assert_eq!(output, expected);
        let requests = server.received_requests().await.unwrap();
        let fetches = requests
            .iter()
            .filter(|request| request.url.path().starts_with("/transfer/xorb/"))
            .count();
        assert_eq!(
            fetches, 2,
            "64 tiny descriptors should become two bounded block fetches"
        );
        assert_eq!(ctx.xorb_fetch_count.load(Ordering::Relaxed), 2);
        assert_eq!(ctx.buffer_semaphore.available_permits(), 256);
    }

    #[tokio::test]
    async fn streaming_gapped_and_repeated_ranges_do_not_pin_old_blocks() {
        let server = MockServer::start().await;
        let expected = adjacent_chunk_fixture(&server, 6, 8, &[0, 1, 4, 5, 0, 1], None).await;
        let ctx = test_stream_context(&server, 16);
        let (output, _) = tokio::time::timeout(
            Duration::from_secs(3),
            drain(make_stream(ctx.clone(), None)),
        )
        .await
        .unwrap();
        assert_eq!(output, expected);
        assert_eq!(ctx.xorb_fetch_count.load(Ordering::Relaxed), 3);
        assert_eq!(ctx.buffer_semaphore.available_permits(), 16);
    }

    #[tokio::test]
    async fn streaming_tiny_terms_bound_queued_work_until_consumer_advances() {
        let server = MockServer::start().await;
        let expected =
            adjacent_chunk_fixture(&server, 512, 1, &(0..512).collect::<Vec<_>>(), None).await;
        let ctx = test_stream_context(&server, 4096);
        let mut stream = make_stream(ctx.clone(), None);
        stream.start();
        tokio::time::timeout(Duration::from_secs(3), async {
            while stream
                .run_state
                .total_bytes_scheduled
                .load(Ordering::Relaxed)
                < MAX_BUFFERED_TERMS as u64
            {
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .unwrap();
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert_eq!(
            stream
                .run_state
                .total_bytes_scheduled
                .load(Ordering::Relaxed),
            MAX_BUFFERED_TERMS as u64
        );
        assert_eq!(
            ctx.buffer_semaphore.total_permits() - ctx.buffer_semaphore.available_permits(),
            128
        );
        let (output, _) = tokio::time::timeout(Duration::from_secs(3), drain(stream))
            .await
            .unwrap();
        assert_eq!(output, expected);
        assert_eq!(ctx.xorb_fetch_count.load(Ordering::Relaxed), 4);
        // MockServer::drop synchronously polls a Tokio RwLock. A fully drained
        // cooperative budget can defer its wake onto this same runtime, which
        // cannot advance while Drop is blocking. Force that condition, then
        // make only fixture teardown unconstrained.
        while tokio::task::coop::has_budget_remaining() {
            tokio::task::consume_budget().await;
        }
        assert!(!tokio::task::coop::has_budget_remaining());
        tokio::task::unconstrained(async { drop(server) }).await;
    }

    #[tokio::test]
    async fn cancelling_stream_releases_fetch_and_buffer_without_detached_tasks() {
        let server = MockServer::start().await;
        let payload = serialize_payload(&[b"payload"]);
        reconstruction_mock(&server,0,4095,0,json!([{"hash":XORB_HASH,"unpacked_length":7,"range":{"start":0,"end":1}}]),
            json!({XORB_HASH:[{"url":format!("{}/transfer/xorb/default/{XORB_HASH}",server.uri()),"ranges":[{"chunks":{"start":0,"end":1},"bytes":{"start":0,"end":payload.len()-1}}]}]})).await;
        Mock::given(method("GET"))
            .and(path(format!("/transfer/xorb/default/{XORB_HASH}")))
            .respond_with(
                ResponseTemplate::new(206)
                    .insert_header(
                        "Content-Range",
                        format!("bytes 0-{}/{}", payload.len() - 1, payload.len()),
                    )
                    .set_body_bytes(payload)
                    .set_delay(Duration::from_secs(2)),
            )
            .mount(&server)
            .await;
        let ctx = test_stream_context(&server, 128);
        let mut stream = make_stream(ctx.clone(), None);
        stream.start();
        tokio::time::timeout(Duration::from_secs(1), async {
            while ctx.download_permits.available_permits() == DEFAULT_DOWNLOAD_CONCURRENCY {
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .unwrap();
        drop(stream);
        tokio::time::timeout(Duration::from_millis(250), async {
            while ctx.download_permits.available_permits() != DEFAULT_DOWNLOAD_CONCURRENCY
                || ctx.buffer_semaphore.available_permits() != 128
            {
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .expect("cancelled stream left an untracked fetch holding permits");
        assert_eq!(ctx.xorb_fetch_count.load(Ordering::Relaxed), 0);
    }

    fn make_stream(ctx: StreamContext, range: Option<Range<u64>>) -> DownloadStream {
        let mut reconstructor =
            FileReconstructor::new(ctx, FILE_ID.to_owned(), READ_TOKEN.to_owned());
        if let Some(range) = range {
            reconstructor = reconstructor.with_byte_range(range);
        }
        reconstructor.reconstruct_to_stream()
    }

    fn make_unordered_stream(
        ctx: StreamContext,
        range: Option<Range<u64>>,
    ) -> UnorderedDownloadStream {
        let mut reconstructor =
            FileReconstructor::new(ctx, FILE_ID.to_owned(), READ_TOKEN.to_owned());
        if let Some(range) = range {
            reconstructor = reconstructor.with_byte_range(range);
        }
        reconstructor.reconstruct_to_unordered_stream()
    }

    async fn drain(mut stream: DownloadStream) -> (Vec<u8>, Vec<u64>) {
        let mut out = Vec::new();
        let mut sizes = Vec::new();
        while let Some(chunk) = stream.next().await.unwrap() {
            sizes.push(u64::try_from(chunk.len()).unwrap());
            out.extend_from_slice(&chunk);
        }
        (out, sizes)
    }

    // ── BufferSemaphore ─────────────────────────────────────────────────────

    #[test]
    fn buffer_semaphore_acquire_release_bounds_in_flight() {
        let sem = Arc::new(BufferSemaphore::new(100, 100, 100));
        assert_eq!(sem.total_permits(), 100);
        assert_eq!(sem.available_permits(), 100);

        let rt = Runtime::new().unwrap();
        rt.block_on(async {
            let p1 = sem.acquire_many(60).await.unwrap();
            assert_eq!(sem.available_permits(), 40);
            let p2 = sem.acquire_many(40).await.unwrap();
            assert_eq!(sem.available_permits(), 0);
            drop(p1);
            assert_eq!(sem.available_permits(), 60);
            drop(p2);
            assert_eq!(sem.available_permits(), 100);
        });
    }

    #[test]
    fn buffer_semaphore_scales_with_active_download_target() {
        let base = 100u64;
        let perfile = 50u64;
        let limit = 250u64;
        let sem = Arc::new(BufferSemaphore::new(base, base, limit));
        assert_eq!(sem.total_permits(), base);

        // One active download: target = base + perfile.
        let seed = sem.increment_permits_to_target(base + perfile);
        assert!(seed.is_some());
        assert_eq!(sem.total_permits(), 150);

        // Splitting the virtual permit gives immediate (queue-bypassing) access.
        let mut seed = seed.unwrap();
        let term = seed.split(40).unwrap();
        assert_eq!(term.num_permits(), 40);
        assert_eq!(sem.total_permits(), 150);
        drop(term);
        // Dropping the virtual remainder enters the semaphore.
        drop(seed);
        assert_eq!(sem.available_permits(), 150);

        // Two active downloads: target = base + 2*perfile = 200.
        let _seed2 = sem.increment_permits_to_target(base + perfile.saturating_mul(2));
        assert_eq!(sem.total_permits(), 200);

        // Shrink back to base on exit.
        assert!(sem.decrement_permits_to_target(base).is_some());
        assert_eq!(sem.total_permits(), 100);
    }

    #[test]
    fn buffer_semaphore_clamps_to_max_and_min() {
        let sem = Arc::new(BufferSemaphore::new(50, 50, 100));
        let _ = sem.increment_permits_to_target(10_000);
        assert_eq!(sem.total_permits(), 100);
        assert!(sem.increment_permits_to_target(100).is_none());
        let _ = sem.decrement_permits_to_target(0);
        assert_eq!(sem.total_permits(), 50);
    }

    #[test]
    fn buffer_semaphore_large_capacity_uses_scaling_basis() {
        // 8 GiB exceeds u32::MAX, so a basis > 1 is required; acquisitions of
        // arbitrarily large term sizes must still succeed.
        let sem = Arc::new(BufferSemaphore::new(
            DEFAULT_DOWNLOAD_BUFFER_SIZE,
            DEFAULT_DOWNLOAD_BUFFER_SIZE,
            DEFAULT_DOWNLOAD_BUFFER_LIMIT,
        ));
        // ceil(8 GiB / basis) must fit u32::MAX: basis = 4.
        assert_eq!(sem.basis, 4);
        let rt = Runtime::new().unwrap();
        rt.block_on(async {
            let p = sem
                .acquire_many(DEFAULT_DOWNLOAD_BUFFER_SIZE)
                .await
                .unwrap();
            assert!(p.num_permits() >= DEFAULT_DOWNLOAD_BUFFER_SIZE);
            drop(p);
            assert_eq!(sem.available_permits(), DEFAULT_DOWNLOAD_BUFFER_SIZE);
        });
    }

    // ── RunState ────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn run_state_error_surfaces_via_check_error() {
        let state = RunState::new(CancellationToken::new());
        assert!(state.check_error().is_ok());
        state.set_error(SdxError::StreamInternal("boom".to_owned()));
        let error = state.check_error().unwrap_err();
        assert!(matches!(error, SdxError::StreamInternal(_)));
        // Cancellation is triggered by the error.
        state.cancelled().await;
    }

    #[test]
    fn background_checks_preserve_first_typed_error_for_consumer() {
        let state = RunState::new(CancellationToken::new());
        state.set_error(SdxError::Transfer(TransferError::InvalidResponse(
            "original".to_owned(),
        )));
        assert!(state.check_background_error().is_err());
        assert!(state.check_run_state().is_err());
        assert!(
            matches!(state.check_error(), Err(SdxError::Transfer(TransferError::InvalidResponse(message))) if message == "original")
        );
        assert!(state.check_error().is_ok());
    }

    #[tokio::test]
    async fn run_state_cancel_returns_cancelled() {
        let state = RunState::new(CancellationToken::new());
        state.cancel();
        assert!(matches!(state.check_run_state(), Err(RunError::Cancelled)));
    }

    #[tokio::test]
    async fn run_state_tracks_scheduled_and_delivered_bytes() {
        let state = RunState::new(CancellationToken::new());
        state.record_new_term(100);
        state.record_new_term(50);
        assert_eq!(state.total_bytes_scheduled(), 150);
        state.report_bytes_written(75);
        assert_eq!(state.total_bytes_delivered(), 75);
    }

    // ── SequentialWriter (unit) ─────────────────────────────────────────────

    fn immediate_future(data: Bytes) -> DataFuture {
        Box::pin(async move { Ok(data) })
    }

    fn delayed_future(data: Bytes, delay: Duration) -> DataFuture {
        Box::pin(async move {
            tokio::time::sleep(delay).await;
            Ok(data)
        })
    }

    #[tokio::test]
    async fn sequential_writer_streaming_orders_chunks() {
        let state = RunState::new(CancellationToken::new());
        let (mut writer, mut receiver) = SequentialWriter::new_streaming(state);

        writer
            .set_next_term_data_source(
                0..5,
                None,
                delayed_future(Bytes::from("Hello"), Duration::from_millis(50)),
            )
            .await
            .unwrap();
        writer
            .set_next_term_data_source(
                5..6,
                None,
                delayed_future(Bytes::from(" "), Duration::from_millis(10)),
            )
            .await
            .unwrap();
        writer
            .set_next_term_data_source(6..11, None, immediate_future(Bytes::from("World")))
            .await
            .unwrap();
        let total = writer.finish().await.unwrap();
        assert_eq!(total, 11);

        let mut out = Vec::new();
        while let Some(item) = receiver.recv().await {
            match item {
                SequentialRetrievalItem::Data { receiver, permit } => {
                    let data = receiver.await.unwrap();
                    out.extend_from_slice(&data);
                    drop(permit);
                }
                SequentialRetrievalItem::Finish => break,
            }
        }
        assert_eq!(&out, b"Hello World");
    }

    struct CooperativeSink {
        always_interrupted: bool,
        interrupt_once: bool,
        permanent_error: bool,
        flush_error: bool,
        gate: Option<std::sync::mpsc::Receiver<()>>,
        started: Option<oneshot::Sender<()>>,
        dropped: Option<oneshot::Sender<()>>,
        written: Arc<AtomicU64>,
    }

    impl Write for CooperativeSink {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            if let Some(started) = self.started.take() {
                let _sent = started.send(());
            }
            if let Some(gate) = self.gate.take() {
                gate.recv().map_err(std::io::Error::other)?;
            }
            if self.always_interrupted || std::mem::take(&mut self.interrupt_once) {
                return Err(std::io::ErrorKind::Interrupted.into());
            }
            if self.permanent_error {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "owned sink failure",
                ));
            }
            let count = bytes.len().min(3);
            self.written
                .fetch_add(u64::try_from(count).unwrap_or(u64::MAX), Ordering::Relaxed);
            Ok(count)
        }

        fn flush(&mut self) -> std::io::Result<()> {
            if self.flush_error {
                Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "owned flush failure",
                ))
            } else {
                Ok(())
            }
        }
    }

    impl Drop for CooperativeSink {
        fn drop(&mut self) {
            if let Some(dropped) = self.dropped.take() {
                let _sent = dropped.send(());
            }
        }
    }

    #[tokio::test]
    async fn cooperative_writer_cancelled_finish_stops_retries_and_releases_permits() {
        for vectorized in [false, true] {
            for gated in [false, true] {
                let state = RunState::new(CancellationToken::new());
                let semaphore = Arc::new(BufferSemaphore::new(64, 64, 64));
                let written = Arc::new(AtomicU64::new(0));
                let (started_tx, started_rx) = oneshot::channel();
                let (dropped_tx, dropped_rx) = oneshot::channel();
                let (release_tx, gate_rx) = std::sync::mpsc::channel();
                let sink = CooperativeSink {
                    always_interrupted: !gated,
                    interrupt_once: false,
                    permanent_error: false,
                    flush_error: false,
                    gate: gated.then_some(gate_rx),
                    started: Some(started_tx),
                    dropped: Some(dropped_tx),
                    written: written.clone(),
                };
                let mut writer = SequentialWriter::new(sink, vectorized, state.clone());
                writer
                    .set_next_term_data_source(
                        0..64,
                        Some(semaphore.acquire_many(64).await.unwrap()),
                        immediate_future(Bytes::from(vec![7u8; 64])),
                    )
                    .await
                    .unwrap();
                let finishing = tokio::spawn(writer.finish());
                tokio::time::timeout(Duration::from_secs(5), started_rx)
                    .await
                    .unwrap()
                    .unwrap();
                assert_eq!(semaphore.available_permits(), 0);
                finishing.abort();
                assert!(finishing.await.unwrap_err().is_cancelled());
                assert!(state.is_cancelled());
                if gated {
                    release_tx.send(()).unwrap();
                }
                tokio::time::timeout(Duration::from_secs(5), dropped_rx)
                    .await
                    .unwrap()
                    .unwrap();
                assert_eq!(written.load(Ordering::Relaxed), if gated { 3 } else { 0 });
                assert_eq!(semaphore.available_permits(), 64);
            }
        }
    }

    #[tokio::test]
    async fn cooperative_writer_preserves_short_writes_interrupted_and_typed_errors() {
        for vectorized in [false, true] {
            for (permanent_error, flush_error) in [(false, false), (true, false), (false, true)] {
                let state = RunState::new(CancellationToken::new());
                let written = Arc::new(AtomicU64::new(0));
                let sink = CooperativeSink {
                    always_interrupted: false,
                    interrupt_once: true,
                    permanent_error,
                    flush_error,
                    gate: None,
                    started: None,
                    dropped: None,
                    written: written.clone(),
                };
                let mut writer = SequentialWriter::new(sink, vectorized, state.clone());
                writer
                    .set_next_term_data_source(
                        0..64,
                        None,
                        immediate_future(Bytes::from(vec![7u8; 64])),
                    )
                    .await
                    .unwrap();
                let result = writer.finish().await;
                if permanent_error || flush_error {
                    assert!(result.is_err());
                    assert!(
                        matches!(state.check_error(), Err(SdxError::Io(error)) if error.kind() == std::io::ErrorKind::BrokenPipe && error.to_string() == if permanent_error { "owned sink failure" } else { "owned flush failure" })
                    );
                } else {
                    assert_eq!(result.unwrap(), 64);
                    assert_eq!(written.load(Ordering::Relaxed), 64);
                    assert!(!state.is_cancelled());
                }
            }
        }
    }

    #[tokio::test]
    async fn sequential_writer_rejects_non_sequential_range() {
        let state = RunState::new(CancellationToken::new());
        let (mut writer, _receiver) = SequentialWriter::new_streaming(state);
        writer
            .set_next_term_data_source(0..5, None, immediate_future(Bytes::from("Hello")))
            .await
            .unwrap();
        let result = writer
            .set_next_term_data_source(10..15, None, immediate_future(Bytes::from("World")))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn sequential_writer_reports_size_mismatch() {
        let state = RunState::new(CancellationToken::new());
        let (mut writer, _receiver) = SequentialWriter::new_streaming(state);
        writer
            .set_next_term_data_source(0..10, None, immediate_future(Bytes::from("Hi")))
            .await
            .unwrap();
        let result = writer.finish().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn sequential_writer_releases_permit_after_write() {
        let sem = Arc::new(BufferSemaphore::new(10, 10, 10));
        let state = RunState::new(CancellationToken::new());
        let (mut writer, mut receiver) = SequentialWriter::new_streaming(state);

        let permit1 = sem.acquire_many(5).await.unwrap();
        let permit2 = sem.acquire_many(5).await.unwrap();
        assert_eq!(sem.available_permits(), 0);

        writer
            .set_next_term_data_source(0..5, Some(permit1), immediate_future(Bytes::from("Hello")))
            .await
            .unwrap();
        writer
            .set_next_term_data_source(5..6, Some(permit2), immediate_future(Bytes::from(" ")))
            .await
            .unwrap();
        writer.finish().await.unwrap();

        // Permits are only released after the consumer pulls the bytes.
        assert_eq!(sem.available_permits(), 0);
        while let Some(item) = receiver.recv().await {
            match item {
                SequentialRetrievalItem::Data { receiver, permit } => {
                    let _ = receiver.await.unwrap();
                    drop(permit);
                }
                SequentialRetrievalItem::Finish => break,
            }
        }
        assert_eq!(sem.available_permits(), 10);
    }

    #[tokio::test]
    async fn sequential_writer_background_thread_writes_and_flushes() {
        let state = RunState::new(CancellationToken::new());
        let mut writer = SequentialWriter::new(Vec::new(), false, state);
        writer
            .set_next_term_data_source(0..5, None, immediate_future(Bytes::from("Hello")))
            .await
            .unwrap();
        writer
            .set_next_term_data_source(5..11, None, immediate_future(Bytes::from(" World")))
            .await
            .unwrap();
        let total = writer.finish().await.unwrap();
        assert_eq!(total, 11);
    }

    // ── UnorderedWriter (unit) ──────────────────────────────────────────────

    #[tokio::test]
    async fn unordered_writer_yields_completion_order_with_offsets() {
        let state = RunState::new(CancellationToken::new());
        let (mut writer, mut receiver, _progress) = UnorderedWriter::new_streaming(state);

        writer
            .set_next_term_data_source(
                0..5,
                None,
                delayed_future(Bytes::from("Hello"), Duration::from_millis(80)),
            )
            .await
            .unwrap();
        writer
            .set_next_term_data_source(
                5..6,
                None,
                delayed_future(Bytes::from(" "), Duration::from_millis(40)),
            )
            .await
            .unwrap();
        writer
            .set_next_term_data_source(6..11, None, immediate_future(Bytes::from("World")))
            .await
            .unwrap();
        writer.finish().await.unwrap();

        let mut items = Vec::new();
        while let Some(result) = receiver.recv().await {
            let term = result.unwrap();
            items.push((term.byte_range.start, term.data.to_vec()));
            drop(term.permit);
        }
        items.sort_by_key(|(offset, _)| *offset);
        let out: Vec<u8> = items.into_iter().flat_map(|(_, data)| data).collect();
        assert_eq!(&out, b"Hello World");
    }

    // ── Full-stream wiremock tests ──────────────────────────────────────────

    #[tokio::test]
    async fn download_stream_yields_chunks_in_order() {
        let server = MockServer::start().await;
        let chunk_a = vec![7u8; 64];
        let chunk_b = vec![9u8; 64];
        let chunk_c = vec![3u8; 64];
        let payload = serialize_payload(&[&chunk_a, &chunk_b, &chunk_c]);

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 1, "end": 2}},
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 2, "end": 3}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 3}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let (out, _sizes) = drain(make_stream(ctx, None)).await;
        let mut expected = chunk_a.clone();
        expected.extend_from_slice(&chunk_b);
        expected.extend_from_slice(&chunk_c);
        assert_eq!(out, expected);
    }

    async fn assert_reservation_retry_after_failed_init(cancel: bool) {
        let server = MockServer::start().await;
        let decoded = vec![7; 128];
        let payload = serialize_payload(&[&decoded]);
        let response = ResponseTemplate::new(206)
            .insert_header(
                "Content-Range",
                format!(
                    "bytes 0-{}/{}",
                    payload.len().saturating_sub(1),
                    payload.len()
                ),
            )
            .set_body_bytes(vec![0; payload.len()]);
        Mock::given(method("GET"))
            .respond_with(if cancel {
                response.set_delay(Duration::from_secs(5))
            } else {
                response
            })
            .mount(&server)
            .await;
        let mut ctx = test_stream_context(&server, 4096);
        let block = Arc::new(XorbBlock {
            hash: XORB_HASH.to_owned(),
            chunk_range: (0, 1),
            url: server.uri(),
            bytes: ByteRange::new(0, (payload.len().saturating_sub(1)) as u64),
            data: OnceCell::new(),
            decoded_budget: 128,
            reservation: Mutex::new(None),
            reservation_started: AtomicBool::new(false),
            publication_gate: None,
        });
        let loader_block = Arc::clone(&block);
        let loader_context = ctx.clone();
        let loader = tokio::spawn(async move {
            loader_block
                .retrieve_data(&loader_context, READ_TOKEN)
                .await
        });
        if cancel {
            tokio::time::timeout(Duration::from_secs(2), async {
                loop {
                    if !server.received_requests().await.unwrap().is_empty() {
                        break;
                    }
                    tokio::task::yield_now().await;
                }
            })
            .await
            .unwrap();
            assert!(block.reservation_started.load(Ordering::Acquire));
            assert_eq!(
                ctx.buffer_semaphore.available_permits(),
                ctx.buffer_semaphore.total_permits().saturating_sub(128)
            );
            loader.abort();
            assert!(matches!(loader.await, Err(error) if error.is_cancelled()));
        } else {
            assert!(loader.await.unwrap().is_err());
        }
        assert!(block.data.get().is_none());
        assert!(!block.reservation_started.load(Ordering::Acquire));
        assert!(block.reservation.lock().unwrap().is_none());
        assert_eq!(
            ctx.buffer_semaphore.available_permits(),
            ctx.buffer_semaphore.total_permits()
        );
        let directory = tempfile::tempdir().unwrap();
        let cache = Arc::new(ChunkCache::new(directory.path(), 1024).unwrap());
        cache
            .put(XORB_HASH, (0, 1), &[0, 128], &decoded)
            .await
            .unwrap();
        ctx.chunk_cache = Some(cache);
        let data = block.clone().retrieve_data(&ctx, READ_TOKEN).await.unwrap();
        assert_eq!(data.data.as_ref(), decoded.as_slice());
        assert!(block.reservation_started.load(Ordering::Acquire));
        assert_eq!(
            ctx.buffer_semaphore.available_permits(),
            ctx.buffer_semaphore.total_permits().saturating_sub(128)
        );
        drop(data);
        drop(block);
        assert_eq!(
            ctx.buffer_semaphore.available_permits(),
            ctx.buffer_semaphore.total_permits()
        );
    }

    #[tokio::test]
    async fn error_initialization_releases_reservation_and_allows_retry() {
        assert_reservation_retry_after_failed_init(false).await;
    }

    #[tokio::test]
    async fn cancelled_initialization_releases_reservation_and_allows_retry() {
        assert_reservation_retry_after_failed_init(true).await;
    }

    async fn assert_reservation_publication(cache_hit: bool) {
        let server = MockServer::start().await;
        let decoded = vec![7; 128];
        let payload = serialize_payload(&[&decoded]);
        let mut ctx = test_stream_context(&server, 4096);
        let directory = tempfile::tempdir().unwrap();
        if cache_hit {
            let cache = Arc::new(ChunkCache::new(directory.path(), 1024).unwrap());
            cache
                .put(XORB_HASH, (0, 1), &[0, 128], &decoded)
                .await
                .unwrap();
            ctx.chunk_cache = Some(cache);
        } else {
            xorb_range_mock(
                &server,
                0,
                (payload.len().saturating_sub(1)) as u64,
                payload.clone(),
            )
            .await;
        }
        let (ready_tx, ready_rx) = oneshot::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let block = Arc::new(XorbBlock {
            hash: XORB_HASH.to_owned(),
            chunk_range: (0, 1),
            url: format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
            bytes: ByteRange::new(0, (payload.len().saturating_sub(1)) as u64),
            data: OnceCell::new(),
            decoded_budget: 128,
            reservation: Mutex::new(None),
            reservation_started: AtomicBool::new(false),
            publication_gate: Some(Arc::new(PublicationGate {
                ready: Mutex::new(Some(ready_tx)),
                release: Mutex::new(release_rx),
            })),
        });
        block.reserve(&ctx, &mut None).await.unwrap();
        let loader_block = Arc::clone(&block);
        let loader_context = ctx.clone();
        let loader = tokio::spawn(async move {
            loader_block
                .retrieve_data(&loader_context, READ_TOKEN)
                .await
        });
        ready_rx.await.unwrap();
        assert!(block.data.get().is_none());
        block.reserve(&ctx, &mut None).await.unwrap();
        let used = ctx
            .buffer_semaphore
            .total_permits()
            .saturating_sub(ctx.buffer_semaphore.available_permits());
        let unused_reservation = block.reservation.lock().unwrap().is_some();
        release_tx.send(()).unwrap();
        let data = loader.await.unwrap().unwrap();
        assert_eq!(data.data.as_ref(), decoded.as_slice());
        assert_eq!(
            used, 128,
            "one backing block must retain exactly one reservation before publication"
        );
        assert!(!unused_reservation);
        assert_eq!(
            ctx.xorb_fetch_count.load(Ordering::Relaxed),
            u64::from(!cache_hit)
        );
        drop(data);
        drop(block);
        assert_eq!(
            ctx.buffer_semaphore.available_permits(),
            ctx.buffer_semaphore.total_permits()
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn cache_hit_reservation_publication_keeps_single_permit() {
        assert_reservation_publication(true).await;
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn network_reservation_publication_keeps_single_permit() {
        assert_reservation_publication(false).await;
    }

    #[tokio::test]
    async fn download_stream_with_chunk_cache_serves_second_download_from_disk() {
        let server = MockServer::start().await;
        let chunk_a = vec![7u8; 64];
        let chunk_b = vec![9u8; 64];
        let payload = serialize_payload(&[&chunk_a, &chunk_b]);

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 1, "end": 2}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 2}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;

        let dir = tempfile::tempdir().unwrap();
        let cache =
            Arc::new(crate::cache::ChunkCache::new(dir.path().to_path_buf(), 1 << 20).unwrap());
        let mut ctx = test_stream_context(&server, 1_048_576);
        ctx.chunk_cache = Some(cache.clone());
        let mut expected = chunk_a.clone();
        expected.extend_from_slice(&chunk_b);

        // First download: cache miss, one network fetch.
        let (first, _) = drain(make_stream(ctx.clone(), None)).await;
        assert_eq!(first, expected);
        assert_eq!(ctx.xorb_fetch_count.load(Ordering::Relaxed), 1);
        // The cache put is best-effort; wait for it to land. Generous
        // budget (5 s) under slow instrumentation.
        for _ in 0..500 {
            if cache.entry_count().await.unwrap() == 1 {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(cache.entry_count().await.unwrap(), 1);

        // Second download: cache hit, no additional network fetch.
        let (second, _) = drain(make_stream(ctx.clone(), None)).await;
        assert_eq!(second, expected);
        assert_eq!(ctx.xorb_fetch_count.load(Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn streaming_xorb_rejects_full_body_for_nonzero_range() {
        let server = MockServer::start().await;
        let first = serialize_payload(&[b"AAAA"]);
        let second = serialize_payload(&[b"BBBB"]);
        let mut full = first.clone();
        full.extend_from_slice(&second);
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(full.clone()))
            .mount(&server)
            .await;
        let block = Arc::new(XorbBlock {
            hash: XORB_HASH.to_owned(),
            chunk_range: (1, 2),
            url: server.uri(),
            bytes: ByteRange::new(first.len() as u64, full.len() as u64 - 1),
            data: OnceCell::new(),
            decoded_budget: 1_048_576,
            reservation: Mutex::new(None),
            reservation_started: AtomicBool::new(false),
            #[cfg(test)]
            publication_gate: None,
        });
        let result = block
            .clone()
            .retrieve_data(&test_stream_context(&server, 1_048_576), READ_TOKEN)
            .await;
        assert!(matches!(
            result,
            Err(SdxError::Transfer(TransferError::InvalidResponse(_)))
        ));
        assert!(block.data.get().is_none());
    }

    fn queued_download_stream(
        receiver: UnboundedReceiver<SequentialRetrievalItem>,
        run_state: Arc<RunState>,
    ) -> DownloadStream {
        DownloadStream {
            receiver,
            pending_data: None,
            finished: false,
            run_state,
            start_signal: None,
            #[cfg(not(target_family = "wasm"))]
            runtime: test_runtime(),
        }
    }

    #[tokio::test]
    async fn timed_out_next_preserves_queued_and_active_data() {
        let state = RunState::new(CancellationToken::new());
        let semaphore = Arc::new(BufferSemaphore::new(1, 1, 1));
        let (tx, rx) = unbounded_channel();
        let mut stream = queued_download_stream(rx, state);
        let deadline = std::time::Duration::from_millis(1);
        // No item has been queued: cancelling the queue wait loses nothing.
        assert!(tokio::time::timeout(deadline, stream.next()).await.is_err());
        let (data_tx, data_rx) = oneshot::channel();
        tx.send(SequentialRetrievalItem::Data {
            receiver: data_rx,
            permit: Some(semaphore.acquire_many(1).await.unwrap()),
        })
        .unwrap();
        tx.send(SequentialRetrievalItem::Finish).unwrap();
        // The item is dequeued but its bytes have not arrived. Repeated
        // consumer timeouts must retain both the item and its buffer permit.
        for _ in 0..2 {
            assert!(tokio::time::timeout(deadline, stream.next()).await.is_err());
            assert_eq!(semaphore.available_permits(), 0);
            assert!(!data_tx.is_closed());
        }
        let expected = Bytes::from_static(b"preserved download chunk");
        data_tx.send(expected.clone()).unwrap();
        assert_eq!(stream.next().await.unwrap(), Some(expected));
        assert_eq!(semaphore.available_permits(), 1);
        assert!(stream.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn timed_out_next_preserves_background_error() {
        let state = RunState::new(CancellationToken::new());
        let (tx, rx) = unbounded_channel();
        let (data_tx, data_rx) = oneshot::channel();
        tx.send(SequentialRetrievalItem::Data {
            receiver: data_rx,
            permit: None,
        })
        .unwrap();
        tx.send(SequentialRetrievalItem::Finish).unwrap();
        let mut stream = queued_download_stream(rx, state.clone());
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(1), stream.next())
                .await
                .is_err()
        );
        // A queued Finish cannot bypass the still-pending term while the
        // producer has not yet published its failure.
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(1), stream.next())
                .await
                .is_err()
        );
        state.set_error(SdxError::StreamInternal(
            "delayed producer error".to_owned(),
        ));
        drop(data_tx);
        assert!(
            matches!(stream.next().await, Err(SdxError::StreamInternal(message))
            if message == "delayed producer error")
        );
        assert!(stream.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn cancelling_stream_releases_timed_out_pending_data() {
        let state = RunState::new(CancellationToken::new());
        let semaphore = Arc::new(BufferSemaphore::new(1, 1, 1));
        let (tx, rx) = unbounded_channel();
        let (data_tx, data_rx) = oneshot::channel();
        tx.send(SequentialRetrievalItem::Data {
            receiver: data_rx,
            permit: Some(semaphore.acquire_many(1).await.unwrap()),
        })
        .unwrap();
        let mut stream = queued_download_stream(rx, state);
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(1), stream.next())
                .await
                .is_err()
        );
        stream.cancel();
        assert_eq!(semaphore.available_permits(), 1);
        assert!(data_tx.is_closed());
        assert!(stream.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn dropping_stream_releases_timed_out_pending_data() {
        let state = RunState::new(CancellationToken::new());
        let semaphore = Arc::new(BufferSemaphore::new(1, 1, 1));
        let (tx, rx) = unbounded_channel();
        let (data_tx, data_rx) = oneshot::channel();
        tx.send(SequentialRetrievalItem::Data {
            receiver: data_rx,
            permit: Some(semaphore.acquire_many(1).await.unwrap()),
        })
        .unwrap();
        let mut stream = queued_download_stream(rx, state);
        assert!(
            tokio::time::timeout(std::time::Duration::from_millis(1), stream.next())
                .await
                .is_err()
        );
        drop(stream);
        assert_eq!(semaphore.available_permits(), 1);
        assert!(data_tx.is_closed());
    }

    #[tokio::test]
    async fn cancelled_stream_with_closed_data_sender_finishes_cleanly() {
        let state = RunState::new(CancellationToken::new());
        let semaphore = Arc::new(BufferSemaphore::new(1, 1, 1));
        let permit = semaphore.acquire_many(1).await.unwrap();
        let (data_tx, data_rx) = oneshot::channel();
        let (tx, rx) = unbounded_channel();
        tx.send(SequentialRetrievalItem::Data {
            receiver: data_rx,
            permit: Some(permit),
        })
        .unwrap();
        // Both select branches are ready: producer shutdown dropped the
        // sender, and external cancellation was already requested.
        state.cancel();
        drop(data_tx);
        let mut stream = DownloadStream {
            receiver: rx,
            pending_data: None,
            finished: false,
            run_state: state,
            start_signal: None,
            #[cfg(not(target_family = "wasm"))]
            runtime: test_runtime(),
        };
        assert!(stream.next().await.unwrap().is_none());
        assert_eq!(semaphore.available_permits(), 1);
    }

    #[tokio::test]
    async fn download_stream_reports_incompatible_full_body_response() {
        let server = MockServer::start().await;
        let first = serialize_payload(&[b"AAAA"]);
        let mut full = first.clone();
        full.extend_from_slice(&serialize_payload(&[b"BBBB"]));
        reconstruction_mock(&server, 0, 3, 0,
            json!([{ "hash": XORB_HASH, "unpacked_length": 4, "range": {"start": 1, "end": 2}}]),
            json!({XORB_HASH: [{ "url": format!("{}/xorb", server.uri()),
                "ranges": [{"chunks": {"start": 1, "end": 2}, "bytes": {"start": first.len(), "end": full.len() - 1}}]
            }]})).await;
        Mock::given(method("GET"))
            .and(path("/xorb"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(full))
            .mount(&server)
            .await;
        let mut stream = make_stream(test_stream_context(&server, 1_048_576), Some(0..4));
        let result = stream.next().await;
        assert!(
            matches!(
                result,
                Err(SdxError::Transfer(TransferError::InvalidResponse(_)))
            ),
            "unexpected stream result: {result:?}"
        );
    }

    #[tokio::test]
    async fn streaming_xorb_rejects_unexpected_chunk_count_before_caching() {
        let server = MockServer::start().await;
        let full = serialize_payload(&[b"AAAA", b"BBBB"]);
        let range = ByteRange::new(0, full.len() as u64 - 1);
        Mock::given(method("GET"))
            .respond_with(
                ResponseTemplate::new(206)
                    .insert_header(
                        "Content-Range",
                        format!("bytes 0-{}/{}", range.end, full.len()),
                    )
                    .set_body_bytes(full),
            )
            .mount(&server)
            .await;
        let block = Arc::new(XorbBlock {
            hash: XORB_HASH.to_owned(),
            chunk_range: (1, 2),
            url: server.uri(),
            bytes: range,
            data: OnceCell::new(),
            decoded_budget: 1_048_576,
            reservation: Mutex::new(None),
            reservation_started: AtomicBool::new(false),
            #[cfg(test)]
            publication_gate: None,
        });
        let dir = tempfile::tempdir().unwrap();
        let cache =
            Arc::new(crate::cache::ChunkCache::new(dir.path().to_path_buf(), 1 << 20).unwrap());
        let mut ctx = test_stream_context(&server, 1_048_576);
        ctx.chunk_cache = Some(cache.clone());
        let result = block.retrieve_data(&ctx, READ_TOKEN).await;
        assert!(matches!(
            result,
            Err(SdxError::FetchChunkCountMismatch {
                expected: 1,
                actual: 2,
                ..
            })
        ));
        assert_eq!(cache.entry_count().await.unwrap(), 0);
    }

    #[tokio::test]
    async fn download_stream_accepts_exact_full_body_response() {
        let server = MockServer::start().await;
        let payload = serialize_payload(&[b"AAAA", b"BBBB"]);
        reconstruction_mock(&server, 0, 4095, 0,
            json!([{ "hash": XORB_HASH, "unpacked_length": 8, "range": {"start": 0, "end": 2}}]),
            json!({XORB_HASH: [{ "url": format!("{}/xorb", server.uri()),
                "ranges": [{"chunks": {"start": 0, "end": 2}, "bytes": {"start": 0, "end": payload.len() - 1}}]
            }]})).await;
        Mock::given(method("GET"))
            .and(path("/xorb"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(payload))
            .mount(&server)
            .await;
        let (out, _) = drain(make_stream(test_stream_context(&server, 1_048_576), None)).await;
        assert_eq!(out, b"AAAABBBB");
    }

    #[tokio::test]
    async fn download_stream_eof_after_last_chunk() {
        let server = MockServer::start().await;
        let chunk = vec![5u8; 64];
        let payload = serialize_payload(&[&chunk]);

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let mut stream = make_stream(ctx, None);
        let first = stream.next().await.unwrap().unwrap();
        assert_eq!(first, chunk);
        // EOF at the end.
        assert!(stream.next().await.unwrap().is_none());
        assert!(stream.next().await.unwrap().is_none());
    }

    async fn pending_prefetch_task() -> (
        AbortOnDropHandle<Result<Option<TermBlock>, SdxError>>,
        oneshot::Receiver<()>,
    ) {
        let (started_tx, started_rx) = oneshot::channel();
        let (dropped_tx, dropped_rx) = oneshot::channel();
        let handle = tokio::spawn(async move {
            let _guard = ExitGuard::new(move || {
                let _sent = dropped_tx.send(());
            });
            started_tx.send(()).unwrap();
            std::future::pending::<Result<Option<TermBlock>, SdxError>>().await
        });
        started_rx.await.unwrap();
        (AbortOnDropHandle::new(handle), dropped_rx)
    }

    #[tokio::test]
    async fn dropping_term_manager_aborts_queued_prefetch() {
        let server = MockServer::start().await;
        let mut manager = ReconstructionTermManager::new(
            test_stream_context(&server, 1_048_576),
            FILE_ID.to_owned(),
            READ_TOKEN.to_owned(),
            0..0,
        )
        .await
        .unwrap();
        let (handle, dropped) = pending_prefetch_task().await;
        manager.prefetch_queue.push_back(handle);
        drop(manager);
        tokio::time::timeout(std::time::Duration::from_secs(1), dropped)
            .await
            .unwrap()
            .unwrap();
    }

    #[tokio::test]
    async fn cancelling_next_file_terms_aborts_actively_popped_prefetch() {
        let server = MockServer::start().await;
        let mut manager = ReconstructionTermManager::new(
            test_stream_context(&server, 1_048_576),
            FILE_ID.to_owned(),
            READ_TOKEN.to_owned(),
            0..0,
        )
        .await
        .unwrap();
        let (handle, dropped) = pending_prefetch_task().await;
        manager.prefetch_queue.push_back(handle);
        let mut next = Box::pin(manager.next_file_terms());
        std::future::poll_fn(|cx| {
            assert!(next.as_mut().poll(cx).is_pending());
            std::task::Poll::Ready(())
        })
        .await;
        // Cancel the awaiting operation while keeping the manager alive:
        // aborting only the remaining queue would miss this popped handle.
        drop(next);
        assert!(manager.prefetch_queue.is_empty());
        tokio::time::timeout(std::time::Duration::from_secs(1), dropped)
            .await
            .unwrap()
            .unwrap();
        drop(manager);
    }

    #[tokio::test]
    async fn download_stream_empty_file_yields_immediate_eof() {
        let server = MockServer::start().await;
        reconstruction_mock(&server, 0, 4095, 0, json!([]), json!({})).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let (out, _sizes) = drain(make_stream(ctx, None)).await;
        assert!(out.is_empty());
    }

    #[tokio::test]
    async fn download_stream_byte_range_honors_start_offset() {
        let server = MockServer::start().await;
        let chunk = vec![7u8; 64];
        let payload = serialize_payload(&[&chunk]);

        // The requested range 16..64 is clamped into a single prefetch block,
        // so the only wire request is `bytes=16-63`.
        reconstruction_mock(
            &server,
            16,
            63,
            16,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let (out, _sizes) = drain(make_stream(ctx, Some(16..64))).await;
        assert_eq!(out, chunk[16..64]);
    }

    #[tokio::test]
    async fn cancelled_retained_stream_discards_queue_and_releases_shared_budget() {
        for unordered in [false, true] {
            for mode in 0..4 {
                let server = MockServer::start().await;
                let chunk = vec![7u8; 64];
                let payload = serialize_payload(&[&chunk]);
                reconstruction_mock(
                    &server,
                    0,
                    4095,
                    0,
                    json!([
                        {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
                        {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}
                    ]),
                    json!({XORB_HASH: [{
                        "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                        "ranges": [{"chunks": {"start": 0, "end": 1},
                            "bytes": {"start": 0, "end": payload.len().saturating_sub(1)}}]
                    }]}),
                )
                .await;
                xorb_payload_mock(&server, payload).await;
                let ctx = test_stream_context(&server, 64);
                let state;
                if unordered {
                    let mut stream = make_unordered_stream(ctx.clone(), None);
                    assert_eq!(stream.next().await.unwrap().unwrap().1, chunk);
                    tokio::time::timeout(Duration::from_secs(5), async {
                        while stream.receiver.is_empty() {
                            tokio::task::yield_now().await;
                        }
                    })
                    .await
                    .unwrap();
                    assert_eq!(ctx.buffer_semaphore.available_permits(), 0);
                    state = stream.run_state.clone();
                    match mode {
                        1 => stream.cancel(),
                        2 => state.cancel(),
                        3 => state.set_error(SdxError::Transfer(TransferError::NotFound(
                            "owned queued failure".to_owned(),
                        ))),
                        _ => {}
                    }
                    let result = stream.next().await;
                    if mode == 0 {
                        assert_eq!(result.unwrap().unwrap().1, chunk);
                    } else if mode == 3 {
                        assert!(
                            matches!(result, Err(SdxError::Transfer(TransferError::NotFound(message)))
                            if message == "owned queued failure")
                        );
                    } else {
                        assert!(result.unwrap().is_none());
                    }
                    assert!(stream.next().await.unwrap().is_none());
                    assert!(stream.receiver.is_empty());
                    tokio::time::timeout(Duration::from_secs(5), async {
                        while ctx.buffer_semaphore.available_permits() != 64 {
                            tokio::task::yield_now().await;
                        }
                    })
                    .await
                    .unwrap();
                    let mut sibling = make_unordered_stream(ctx.clone(), None);
                    assert_eq!(
                        tokio::time::timeout(Duration::from_secs(5), sibling.next())
                            .await
                            .unwrap()
                            .unwrap()
                            .unwrap()
                            .1,
                        chunk
                    );
                    assert_eq!(sibling.next().await.unwrap().unwrap().1, chunk);
                    assert!(sibling.next().await.unwrap().is_none());
                    // Keep the original handle alive throughout sibling recovery.
                    assert!(stream.next().await.unwrap().is_none());
                } else {
                    let mut stream = make_stream(ctx.clone(), None);
                    assert_eq!(stream.next().await.unwrap().unwrap(), chunk);
                    tokio::time::timeout(Duration::from_secs(5), async {
                        while stream.receiver.is_empty() {
                            tokio::task::yield_now().await;
                        }
                    })
                    .await
                    .unwrap();
                    assert_eq!(ctx.buffer_semaphore.available_permits(), 0);
                    state = stream.run_state.clone();
                    match mode {
                        1 => stream.cancel(),
                        2 => state.cancel(),
                        3 => state.set_error(SdxError::Transfer(TransferError::NotFound(
                            "owned queued failure".to_owned(),
                        ))),
                        _ => {}
                    }
                    let result = stream.next().await;
                    if mode == 0 {
                        assert_eq!(result.unwrap().unwrap(), chunk);
                    } else if mode == 3 {
                        assert!(
                            matches!(result, Err(SdxError::Transfer(TransferError::NotFound(message)))
                            if message == "owned queued failure")
                        );
                    } else {
                        assert!(result.unwrap().is_none());
                    }
                    assert!(stream.next().await.unwrap().is_none());
                    assert!(stream.receiver.is_empty());
                    tokio::time::timeout(Duration::from_secs(5), async {
                        while ctx.buffer_semaphore.available_permits() != 64 {
                            tokio::task::yield_now().await;
                        }
                    })
                    .await
                    .unwrap();
                    let mut sibling = make_stream(ctx.clone(), None);
                    assert_eq!(
                        tokio::time::timeout(Duration::from_secs(5), sibling.next())
                            .await
                            .unwrap()
                            .unwrap()
                            .unwrap(),
                        chunk
                    );
                    assert_eq!(sibling.next().await.unwrap().unwrap(), chunk);
                    assert!(sibling.next().await.unwrap().is_none());
                    assert!(stream.next().await.unwrap().is_none());
                }
                assert_eq!(
                    state.total_bytes_delivered(),
                    if mode == 0 { 128 } else { 64 }
                );
            }
        }
    }

    #[tokio::test]
    async fn download_stream_buffer_semaphore_bounds_in_flight_bytes() {
        let server = MockServer::start().await;
        // 32 chunks × 64 bytes = 2 KiB, with a 256-byte buffer cap: only a few
        // terms may be buffered at once, yet the stream must complete.
        let chunks: Vec<Vec<u8>> = (0..32u8).map(|i| vec![i; 64]).collect();
        let payload = serialize_payload(
            chunks
                .iter()
                .map(Vec::as_slice)
                .collect::<Vec<_>>()
                .as_slice(),
        );

        let terms: serde_json::Value = chunks
            .iter()
            .enumerate()
            .map(|(i, chunk)| {
                json!({
                    "hash": XORB_HASH,
                    "unpacked_length": chunk.len(),
                    "range": {"start": i as u64, "end": i as u64 + 1}
                })
            })
            .collect();
        let serialized_chunk_length = serialize_payload(&[chunks[0].as_slice()]).len() as u64;
        let ranges: serde_json::Value = (0..32u64)
            .map(|i| {
                json!({
                    "chunks": {"start": i, "end": i + 1},
                    "bytes": {"start": i * serialized_chunk_length, "end": (i + 1) * serialized_chunk_length - 1}
                })
            })
            .collect();

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            terms,
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": ranges
                }]
            }),
        )
        .await;
        xorb_payload_mock(&server, payload).await;

        let cap = 256u64;
        let ctx = test_stream_context(&server, cap);
        let mut stream = make_unordered_stream(ctx.clone(), None);
        let mut expected = Vec::new();
        for chunk in &chunks {
            expected.extend_from_slice(chunk);
        }
        // Start without consuming: completed terms retain their backing block
        // permits, so the producer must fill and then wait on this finite cap.
        stream.start();
        tokio::time::timeout(Duration::from_secs(5), async {
            while ctx.buffer_semaphore.available_permits() != 0 || stream.receiver.is_empty() {
                stream.run_state.check_background_error().unwrap();
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("producer did not fill the buffer before consumption");
        let peak_held = cap.saturating_sub(ctx.buffer_semaphore.available_permits());
        assert_eq!(peak_held, cap);
        assert!(peak_held > 0);

        let initial = stream.receiver.try_recv().unwrap().unwrap();
        {
            let backing = initial
                .permit
                .as_ref()
                .unwrap()
                ._backing_block
                .as_ref()
                .unwrap();
            let decoded = backing.data.get().unwrap();
            let decoded_bytes = u64::try_from(decoded.data.len()).unwrap();
            assert!(decoded_bytes > 0);
            assert!(decoded_bytes <= decoded._buffer_permit.num_permits());
            assert!(decoded._buffer_permit.num_permits() <= cap);
        }
        // The completed item is still retained. A further reservation cannot
        // succeed until consumption releases its backing block's capacity.
        let mut waiting = Box::pin(ctx.buffer_semaphore.acquire_many(1));
        assert!(futures_util::poll!(&mut waiting).is_pending());
        drop(waiting);

        let mut received = std::collections::BTreeMap::new();
        let (offset, chunk) = stream.process_term(Ok(initial)).unwrap().unwrap();
        assert!(received.insert(offset, chunk).is_none());
        while let Some((offset, chunk)) = stream.next().await.unwrap() {
            assert!(received.insert(offset, chunk).is_none());
            let available = ctx.buffer_semaphore.available_permits();
            let held = cap
                .checked_sub(available)
                .expect("buffer capacity exceeded its cap");
            assert!(held <= cap);
        }
        assert_eq!(received.len(), chunks.len());
        let actual: Vec<u8> = received
            .into_values()
            .flat_map(|chunk| chunk.to_vec())
            .collect();
        assert_eq!(actual, expected);
        // After full consumption the semaphore is back to capacity.
        assert_eq!(ctx.buffer_semaphore.available_permits(), cap);
    }

    #[tokio::test]
    async fn download_unordered_stream_yields_completion_order() {
        let server = MockServer::start().await;
        let chunk_a = vec![7u8; 64];
        let chunk_b = vec![9u8; 64];
        let payload_a = serialize_payload(&[&chunk_a]);
        let payload_b = serialize_payload(&[&chunk_b]);
        let split = payload_a.len() as u64;
        let final_byte = split + payload_b.len() as u64 - 1;

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 1, "end": 2}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": split - 1}},
                        {"chunks": {"start": 1, "end": 2}, "bytes": {"start": split, "end": final_byte}}
                    ]
                }]
            }),
        )
        .await;
        let mut payload = payload_a;
        payload.extend_from_slice(&payload_b);
        xorb_payload_mock(&server, payload).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let mut stream = make_unordered_stream(ctx, None);
        let mut expected = chunk_a.clone();
        expected.extend_from_slice(&chunk_b);
        let mut pieces: Vec<(u64, Vec<u8>)> = Vec::new();
        while let Some((offset, chunk)) = stream.next().await.unwrap() {
            pieces.push((offset, chunk.to_vec()));
        }
        // The stream yields completion order (not file order): reassemble by
        // offset to verify byte-identity.
        pieces.sort_by_key(|(offset, _)| *offset);
        let mut out = Vec::new();
        let offsets: Vec<u64> = pieces.iter().map(|(offset, _)| *offset).collect();
        for (_, data) in pieces {
            out.extend_from_slice(&data);
        }
        assert_eq!(offsets, vec![0, 64]);
        assert_eq!(out, expected);
    }

    #[tokio::test]
    async fn download_stream_cancel_stops_promptly() {
        let server = MockServer::start().await;
        let chunk_a = vec![7u8; 64];
        let chunk_b = vec![9u8; 64];
        let payload = serialize_payload(&[&chunk_a, &chunk_b]);

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 1, "end": 2}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 2}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let mut stream = make_stream(ctx, None);
        let first = stream.next().await.unwrap().unwrap();
        assert_eq!(first, chunk_a);
        stream.cancel();
        // After cancel, subsequent calls return Ok(None) and stay finished.
        assert!(stream.next().await.unwrap().is_none());
        assert!(stream.next().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn download_stream_drop_cancels_background_task() {
        let server = MockServer::start().await;
        let chunk = vec![5u8; 64];
        let payload = serialize_payload(&[&chunk]);

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;

        let ctx = test_stream_context(&server, 1_048_576);
        let mut stream = make_stream(ctx, None);
        // Pull one chunk, then drop mid-stream: the background task must be
        // cancelled rather than leaking.
        let first = stream.next().await.unwrap().unwrap();
        assert_eq!(first, chunk);
        drop(stream);
        // Allow any in-flight task to observe the cancellation.
        tokio::task::yield_now().await;
    }

    async fn blocking_stream_fixture() -> (MockServer, StreamContext) {
        let server = MockServer::start().await;
        let payload = serialize_payload(&[&[5u8; 64]]);
        let last_byte = u64::try_from(payload.len())
            .unwrap()
            .checked_sub(1)
            .unwrap();
        reconstruction_mock(
            &server, 0, 4095, 0,
            json!([{"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}]),
            json!({XORB_HASH: [{
                "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                "ranges": [{"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": last_byte}}]
            }]}),
        ).await;
        xorb_range_mock(&server, 0, last_byte, payload).await;
        let context = test_stream_context(&server, 1_048_576);
        (server, context)
    }

    async fn check_blocking_streams_inside_runtime() {
        let (_server, context) = blocking_stream_fixture().await;
        let mut ordered = make_stream(context.clone(), None);
        let mut output = Vec::new();
        while let Some(bytes) = ordered.blocking_next().unwrap() {
            output.extend_from_slice(&bytes);
        }
        assert_eq!(output, vec![5u8; 64]);
        assert!(ordered.blocking_next().unwrap().is_none());

        let mut unordered = make_unordered_stream(context.clone(), None);
        let (offset, bytes) = unordered.blocking_next().unwrap().unwrap();
        assert_eq!(offset, 0);
        assert_eq!(&bytes[..], &[5u8; 64]);
        assert!(unordered.blocking_next().unwrap().is_none());

        let mut ordered_cancelled = make_stream(context.clone(), None);
        ordered_cancelled.cancel();
        assert!(ordered_cancelled.blocking_next().unwrap().is_none());
        let mut unordered_cancelled = make_unordered_stream(context, None);
        unordered_cancelled.cancel();
        assert!(unordered_cancelled.blocking_next().unwrap().is_none());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn blocking_next_works_inside_current_thread_runtime() {
        check_blocking_streams_inside_runtime().await;
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn blocking_next_works_inside_multi_thread_runtime() {
        check_blocking_streams_inside_runtime().await;
    }

    #[test]
    fn unordered_blocking_next_works_from_plain_thread() {
        let runtime = Runtime::new().unwrap();
        let (server, mut stream) = runtime.block_on(async {
            let (server, context) = blocking_stream_fixture().await;
            (server, make_unordered_stream(context, None))
        });
        drop(runtime);
        let (offset, bytes) = stream.blocking_next().unwrap().unwrap();
        assert_eq!(offset, 0);
        assert_eq!(&bytes[..], &[5u8; 64]);
        assert!(stream.blocking_next().unwrap().is_none());
        drop(server);
    }

    #[test]
    fn blocking_next_works_from_plain_thread() {
        let rt = Runtime::new().unwrap();
        let (server, mut stream) = rt.block_on(async {
            let server = MockServer::start().await;
            let chunk = vec![5u8; 64];
            let payload = serialize_payload(&[&chunk]);
            reconstruction_mock(
                &server,
                0,
                4095,
                0,
                json!([
                    {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}
                ]),
                json!({
                    XORB_HASH: [{
                        "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                        "ranges": [
                            {"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": payload.len() - 1}}
                        ]
                    }]
                }),
            )
            .await;
            xorb_range_mock(&server, 0, (payload.len() - 1) as u64, payload).await;
            let ctx = test_stream_context(&server, 1_048_576);
            (server, make_stream(ctx, None))
        });
        drop(rt);

        // Consume on a plain (non-async) thread via the dedicated runtime.
        let handle = std::thread::spawn(move || {
            let mut out = Vec::new();
            while let Some(chunk) = stream.blocking_next().unwrap() {
                out.extend_from_slice(&chunk);
            }
            (out, stream)
        });
        let (out, _stream) = handle.join().unwrap();
        assert_eq!(out, vec![5u8; 64]);
        drop(server);
    }

    #[tokio::test]
    async fn download_stream_matches_reconstruct_output() {
        // Use two separate mock servers: the M2a `reconstruct` path sends no
        // Range header, while the streaming path sends `bytes=0-4095` (with a
        // 416 fallback), so the mock sets must not overlap.
        let full_server = MockServer::start().await;
        let stream_server = MockServer::start().await;
        let chunk_a = vec![7u8; 64];
        let chunk_b = vec![9u8; 64];
        let payload = serialize_payload(&[&chunk_a, &chunk_b]);

        let terms = json!([
            {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}},
            {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 1, "end": 2}}
        ]);
        let full_xorbs = json!({
            XORB_HASH: [{
                "url": format!("{}/transfer/xorb/default/{XORB_HASH}", full_server.uri()),
                "ranges": [
                    {"chunks": {"start": 0, "end": 2}, "bytes": {"start": 0, "end": payload.len() - 1}}
                ]
            }]
        });
        let stream_xorbs = json!({
            XORB_HASH: [{
                "url": format!("{}/transfer/xorb/default/{XORB_HASH}", stream_server.uri()),
                "ranges": [
                    {"chunks": {"start": 0, "end": 2}, "bytes": {"start": 0, "end": payload.len() - 1}}
                ]
            }]
        });

        // Full-file reconstruction (no Range header) via the M2a path.
        Mock::given(method("GET"))
            .and(path(format!("/v2/reconstructions/{FILE_ID}")))
            .and(header("authorization", format!("Bearer {READ_TOKEN}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(v2_response_body(
                0,
                terms.clone(),
                full_xorbs,
            )))
            .mount(&full_server)
            .await;
        xorb_range_mock(&full_server, 0, (payload.len() - 1) as u64, payload.clone()).await;

        // Streaming path uses the ranged request; map the prefetch range.
        reconstruction_mock(&stream_server, 0, 4095, 0, terms, stream_xorbs).await;
        xorb_range_mock(
            &stream_server,
            0,
            (payload.len() - 1) as u64,
            payload.clone(),
        )
        .await;

        let mut expected = chunk_a.clone();
        expected.extend_from_slice(&chunk_b);

        // M2a sequential reconstruction.
        let transfer = TransferClient::new(reqwest::Client::new());
        let file = reconstruction::reconstruct(
            &transfer,
            None,
            &full_server.uri(),
            READ_TOKEN,
            FILE_ID,
            None,
        )
        .await
        .unwrap();
        assert_eq!(file.data, expected);

        // Streaming path.
        let ctx = test_stream_context(&stream_server, 1_048_576);
        let (out, _sizes) = drain(make_stream(ctx, None)).await;
        assert_eq!(out, expected);
    }

    #[tokio::test]
    async fn download_stream_surfaces_background_errors() {
        let server = MockServer::start().await;
        let chunk = vec![5u8; 64];
        let payload = serialize_payload(&[&chunk]);

        reconstruction_mock(
            &server,
            0,
            4095,
            0,
            json!([
                {"hash": XORB_HASH, "unpacked_length": 64, "range": {"start": 0, "end": 1}}
            ]),
            json!({
                XORB_HASH: [{
                    "url": format!("{}/transfer/xorb/default/{XORB_HASH}", server.uri()),
                    "ranges": [
                        {"chunks": {"start": 0, "end": 1}, "bytes": {"start": 0, "end": payload.len() - 1}}
                    ]
                }]
            }),
        )
        .await;
        // No xorb mock: the fetch 404s, and the error must surface via the
        // stream's check_error at an item boundary.
        let _ = payload;

        let ctx = test_stream_context(&server, 1_048_576);
        let mut stream = make_stream(ctx, None);
        // Drain the stream, capturing whether `next()` surfaced the background
        // error directly. The xorb is deliberately un-mocked so the ranged fetch
        // 404s; that failure must surface through the stream at an item boundary
        // and never be silently swallowed. The background task starts paused and
        // auto-starts on the first `next()`; under slow/instrumented execution
        // the first `next()` can race the 404 (returning a derived
        // data-pipeline error, or `Ok(None)` before the root error is observed),
        // so the deterministic check is on the shared `RunState`: the
        // reconstruction task re-sets the root error on exit, so drain to EOF,
        // wait for it to be recorded, then surface it via `check_error`.
        let mut surfaced: Option<SdxError> = None;
        loop {
            match stream.next().await {
                Ok(Some(_)) => {}
                Ok(None) => break,
                Err(error) => {
                    surfaced = Some(error);
                    break;
                }
            }
        }
        // If `next()` did not surface the root NotFound directly, allow the
        // background task to re-set it in the run state, then surface it via
        // `check_error` at the terminal boundary.
        if !matches!(
            surfaced,
            Some(SdxError::Transfer(TransferError::NotFound(_)))
        ) {
            for _ in 0..500 {
                if stream.run_state.error_message().is_some() {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
            surfaced = stream.run_state.check_error().err();
        }
        assert!(
            matches!(
                surfaced,
                Some(SdxError::Transfer(TransferError::NotFound(_)))
            ),
            "background xorb fetch failure was swallowed or surfaced a wrong error; got {surfaced:?}"
        );
    }
}