nzb-dispatch 0.2.9

Article-level dispatcher: per-server worker pool, priority gating, retry + hopeless tracking. Part of the nzb-* layered usenet engine.
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
//! Download engine — shared NNTP worker pool that services all active jobs.
//!
//! Architecture:
//! - A single long-lived [`WorkerPool`] is owned by [`crate::queue_manager::QueueManager`].
//! - For each enabled server, exactly `server.connections` workers are
//!   spawned and live as long as the server stays enabled. When the server
//!   list or per-server connection limit changes, the pool reconciles.
//! - Jobs register a [`JobContext`] and push their work items into a
//!   [`SharedWorkQueue`]. Workers pop items tagged with `job_id` and look up
//!   per-job state (assembler, progress sink, pause/cancel flags) via the
//!   shared [`JobContextMap`].
//! - Pause / cancel / completion are per-job flags; workers themselves are
//!   never torn down on job transitions. Pausing a job causes workers holding
//!   one of its items to return that item to the queue and pull something
//!   else. Cancelling a job drains its items and drops in-flight results.
//! - Transient provider outages leave work queued until circuit-breaker
//!   cooldown expires; only definitive provider outcomes resolve an article.
//!
//! Retry logic (per article):
//! 1. Try the article on the current server up to [`MAX_TRIES_PER_SERVER`]
//!    times, reconnecting on transient errors.
//! 2. On `ArticleNotFound` (430) — requeue with the current server added to
//!    `tried_servers`; another worker on a different server picks it up.
//! 3. On connection loss — requeue and reconnect.
//! 4. On decode error — treated like "not available on this server", try
//!    another.
//! 5. An article is missing only when every enabled provider explicitly
//!    returned `430`. Circuit-broken and transiently failing providers do
//!    not contribute evidence of absence.
//! 6. A job only fails if failed articles exceed the threshold and no par2
//!    recovery is possible.

use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use parking_lot::Mutex;
use tokio::sync::{Notify, mpsc};
use tokio::task::JoinHandle;
use tracing::{debug, error, info, trace, warn};

use nzb_core::config::ServerConfig;
use nzb_core::models::NzbJob;
use nzb_decode::FileAssembler;
use nzb_decode::yenc::decode_yenc;
use nzb_nntp::Pipeline;
use nzb_nntp::connection::{ConnectionState, NntpConnection};
use nzb_nntp::error::NntpError;

use crate::bandwidth::BandwidthLimiter;

fn increment_counter(name: &'static str) {
    opentelemetry::global::meter_provider()
        .meter("nzb-dispatch")
        .u64_counter(name)
        .build()
        .add(1, &[]);
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Max times to retry an article on the SAME server before trying the next.
const MAX_TRIES_PER_SERVER: u32 = 3;
/// How many timeouts, dropped connections or unclassified errors one article
/// absorbs on a server that is otherwise up, before the error counts as that
/// server's definitive outcome. A server-wide outage (502, 480, 403) is not
/// counted: the circuit breaker handles those.
const MAX_OUTAGE_TRIES_PER_SERVER: u32 = 10;
/// Delay between reconnection attempts.
const RECONNECT_DELAY: Duration = Duration::from_secs(5);
/// Max reconnect attempts before giving up on a server for this session.
const MAX_RECONNECT_ATTEMPTS: u32 = 5;
/// Stagger delay between worker initial connections to avoid thundering herd.
/// Each worker waits conn_idx * WORKER_RAMP_DELAY before its first connect.
const WORKER_RAMP_DELAY: Duration = Duration::from_millis(15);
/// Consecutive connect failures before circuit-breaking a server.
const CIRCUIT_BREAK_THRESHOLD: u32 = 3;
/// Cooldown after auth/permission failure (bad credentials, 502, account blocked).
const AUTH_FAILURE_COOLDOWN: Duration = Duration::from_secs(120);
/// Cooldown after transient connection failures exceed threshold.
const TRANSIENT_FAILURE_COOLDOWN: Duration = Duration::from_secs(30);
/// Supervisor tick interval for detecting stuck jobs.
const SUPERVISOR_INTERVAL: Duration = Duration::from_secs(1);

/// Default maximum idle time before a worker is evicted by the supervisor.
/// Tunable per pool via [`WorkerPool::set_max_worker_idle`]. Production code
/// uses the default; the test harness shrinks this to make Phase 5 tests
/// converge in seconds rather than minutes.
const DEFAULT_MAX_WORKER_IDLE: Duration = Duration::from_secs(60);
/// Worker idle poll interval when the shared queue is empty.
const WORKER_IDLE_POLL: Duration = Duration::from_millis(500);

/// Phase 7: capacity of the per-job progress channel. The handler reads
/// this at ~articles per second; under DB-lock contention or
/// post-processing pauses it can fall behind. With this cap, the worst
/// case is bounded buffering plus a `WARN` from
/// [`try_send_progress`] when the channel is full.
pub const PROGRESS_CHANNEL_CAPACITY: usize = 10_000;

/// Send a progress update to the per-job channel. On `Full` (handler
/// backpressure), log a warning and drop the update — the alternative is
/// awaiting and stalling the worker, which would cascade into the entire
/// download pipeline. On `Closed` (handler shut down), drop silently.
///
/// Workers should call this through their `JobContext` rather than
/// touching `progress_tx` directly.
fn try_send_progress(tx: &mpsc::Sender<ProgressUpdate>, job_id: &str, update: ProgressUpdate) {
    if let Err(e) = tx.try_send(update) {
        match e {
            mpsc::error::TrySendError::Full(_) => {
                warn!(
                    job_id,
                    capacity = PROGRESS_CHANNEL_CAPACITY,
                    "Progress channel full — dropping update (handler backpressure)"
                );
            }
            mpsc::error::TrySendError::Closed(_) => {
                // Handler has shut down. Workers can't recover this state;
                // dropping is correct.
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Global connection tracking — semaphore-backed permit pools
// ---------------------------------------------------------------------------

/// Tracks the per-server NNTP connection budget. Each server has a
/// `tokio::sync::Semaphore` whose initial permit count is the configured
/// `connections` limit. Workers acquire a permit *before* connecting and
/// hold it for their entire lifetime; the permit's `Drop` releases the slot
/// synchronously back to the pool. This makes over-allocation a type-level
/// impossibility — once `limit` permits are out, the next acquire awaits.
///
/// **Limit changes at runtime** are handled differently for grow vs shrink:
///
/// - **Grow** (e.g. 5 → 10): the existing semaphore is given the additional
///   permits via `add_permits`; existing slot holders are unaffected.
/// - **Shrink** (e.g. 10 → 5): the entire `ServerSlot` is replaced with a
///   fresh one. Old permit holders continue to reference the orphaned
///   semaphore via their `Arc`; their drops release back to it (a no-op
///   since nothing else points at it). Workers detect the replacement via
///   [`ConnectionTracker::slot_is_current`] and exit on the next iteration.
pub struct ConnectionTracker {
    pools: Mutex<HashMap<String, ServerSlot>>,
}

#[derive(Clone)]
struct ServerSlot {
    name: String,
    limit: usize,
    semaphore: Arc<tokio::sync::Semaphore>,
    connected: Arc<AtomicUsize>,
}

impl ConnectionTracker {
    pub fn new() -> Self {
        Self {
            pools: Mutex::new(HashMap::new()),
        }
    }

    /// Set or update the per-server connection limit.
    ///
    /// - First call for a `server_id`: creates a fresh semaphore with `limit` permits.
    /// - Subsequent call with the same `limit` and `server_name`: no-op.
    /// - Grow (`limit > current`): adds permits in place.
    /// - Shrink or rename: replaces the slot. Old permit holders detach
    ///   naturally via [`slot_is_current`].
    pub fn set_limit(&self, server_id: &str, server_name: &str, limit: usize) {
        let mut pools = self.pools.lock();
        match pools.get_mut(server_id) {
            Some(slot) if slot.limit == limit && slot.name == server_name => {
                // No change.
            }
            Some(slot) if limit > slot.limit && slot.name == server_name => {
                let added = limit - slot.limit;
                let old = slot.limit;
                slot.semaphore.add_permits(added);
                slot.limit = limit;
                info!(
                    server_id,
                    server = %server_name,
                    old_limit = old,
                    new_limit = limit,
                    added,
                    "Connection pool grew in place"
                );
            }
            existing => {
                // Capture diagnostics before re-borrowing `pools` for insert.
                let (prev_limit, prev_name) = match existing {
                    Some(s) => (Some(s.limit), Some(s.name.clone())),
                    None => (None, None),
                };
                pools.insert(
                    server_id.to_string(),
                    ServerSlot {
                        name: server_name.to_string(),
                        limit,
                        semaphore: Arc::new(tokio::sync::Semaphore::new(limit)),
                        connected: Arc::new(AtomicUsize::new(0)),
                    },
                );
                if let Some(prev) = prev_limit {
                    let renamed = prev_name.as_deref() != Some(server_name);
                    info!(
                        server_id,
                        server = %server_name,
                        old_limit = prev,
                        new_limit = limit,
                        renamed,
                        "Connection pool replaced (shrink or rename); old permits orphaned"
                    );
                } else {
                    info!(
                        server_id,
                        server = %server_name,
                        limit,
                        "Connection pool created"
                    );
                }
            }
        }
    }

    /// Forget a server entirely (e.g. on `update_servers` removing it).
    /// Existing permit holders are unaffected; they will detect that their
    /// slot is no longer current and exit.
    pub fn remove_server(&self, server_id: &str) {
        self.pools.lock().remove(server_id);
    }

    /// Acquire a connection slot for `server_id`. Awaits if the pool is at
    /// the limit. Returns `None` if the server isn't registered or its
    /// limit is zero.
    pub async fn acquire(&self, server_id: &str) -> Option<ConnectionSlot> {
        // Snapshot the ServerSlot under lock, release the lock before await.
        let server_slot = {
            let pools = self.pools.lock();
            pools.get(server_id).cloned()?
        };
        if server_slot.limit == 0 {
            return None;
        }
        let permit = Arc::clone(&server_slot.semaphore)
            .acquire_owned()
            .await
            .ok()?;
        Some(ConnectionSlot {
            server_id: server_id.to_string(),
            server_name: server_slot.name,
            semaphore_origin: server_slot.semaphore,
            connected: server_slot.connected,
            is_connected: false,
            _permit: permit,
        })
    }

    /// Returns true if `slot` was acquired from the *current* semaphore for
    /// its server. False if the limit was changed (semaphore replaced) or
    /// the server was removed — the worker should exit at its next safe
    /// checkpoint.
    pub fn slot_is_current(&self, slot: &ConnectionSlot) -> bool {
        matches!(self.slot_status(slot), SlotStatus::Current)
    }

    /// Like [`slot_is_current`] but distinguishes the reason a slot is no
    /// longer current — useful for diagnostics on the worker exit path.
    pub fn slot_status(&self, slot: &ConnectionSlot) -> SlotStatus {
        let pools = self.pools.lock();
        match pools.get(&slot.server_id) {
            Some(server_slot) => {
                if Arc::ptr_eq(&server_slot.semaphore, &slot.semaphore_origin) {
                    SlotStatus::Current
                } else {
                    SlotStatus::PoolReplaced
                }
            }
            None => SlotStatus::ServerRemoved,
        }
    }

    /// `(server_id, active, limit)` triples for the live pool. `active` is
    /// derived from the semaphore's available permits and is always
    /// `<= limit` by construction.
    pub fn snapshot(&self) -> Vec<(String, usize, usize)> {
        let pools = self.pools.lock();
        pools
            .iter()
            .map(|(id, slot)| {
                let active = slot
                    .limit
                    .saturating_sub(slot.semaphore.available_permits());
                (id.clone(), active, slot.limit)
            })
            .collect()
    }

    /// `(server_id, active, limit)` triples for sockets currently transferring
    /// an article. Authenticated sockets waiting for work are idle/free.
    pub fn connected_snapshot(&self) -> Vec<(String, usize, usize)> {
        let pools = self.pools.lock();
        pools
            .iter()
            .map(|(id, slot)| {
                (
                    id.clone(),
                    slot.connected.load(Ordering::Relaxed).min(slot.limit),
                    slot.limit,
                )
            })
            .collect()
    }

    /// Total currently-held permits across all servers in the live pool.
    /// Permits held against orphaned (replaced) semaphores are NOT counted —
    /// they'll go away as the holding workers exit.
    pub fn total(&self) -> usize {
        let pools = self.pools.lock();
        pools
            .values()
            .map(|s| s.limit.saturating_sub(s.semaphore.available_permits()))
            .sum()
    }
}

impl Default for ConnectionTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// Why a `ConnectionSlot` may no longer match its server's live pool.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotStatus {
    /// Slot is still attached to the current semaphore for its server.
    Current,
    /// The semaphore was replaced (set_limit shrunk or rebuilt the pool).
    /// Old permit holders should exit at their next safe checkpoint.
    PoolReplaced,
    /// The server has been removed entirely from the tracker.
    ServerRemoved,
}

/// RAII handle for one acquired NNTP connection slot. The underlying
/// semaphore permit is released synchronously on drop. Workers should hold
/// a `ConnectionSlot` for their entire lifetime — across reconnects, even
/// across temporary connect failures — and only drop it when exiting.
pub struct ConnectionSlot {
    server_id: String,
    server_name: String,
    /// The Arc identity of the semaphore the permit was issued by.
    /// Used by `ConnectionTracker::slot_is_current` to detect a stale slot
    /// after a `set_limit` shrink (which replaces the semaphore).
    semaphore_origin: Arc<tokio::sync::Semaphore>,
    connected: Arc<AtomicUsize>,
    is_connected: bool,
    _permit: tokio::sync::OwnedSemaphorePermit,
}

impl ConnectionSlot {
    pub fn server_id(&self) -> &str {
        &self.server_id
    }
    pub fn server_name(&self) -> &str {
        &self.server_name
    }

    fn mark_active(&mut self) {
        if !self.is_connected {
            self.connected.fetch_add(1, Ordering::Relaxed);
            self.is_connected = true;
        }
    }

    fn mark_inactive(&mut self) {
        if self.is_connected {
            self.connected.fetch_sub(1, Ordering::Relaxed);
            self.is_connected = false;
        }
    }

    fn activity(&mut self) -> ConnectionActivity<'_> {
        self.mark_active();
        ConnectionActivity { slot: self }
    }
}

impl Drop for ConnectionSlot {
    fn drop(&mut self) {
        self.mark_inactive();
    }
}

/// Marks a connection as actively transferring an article for the lifetime
/// of the guard. An authenticated but idle socket does not consume a "used"
/// connection in API/UI accounting.
struct ConnectionActivity<'a> {
    slot: &'a mut ConnectionSlot,
}

impl Drop for ConnectionActivity<'_> {
    fn drop(&mut self) {
        self.slot.mark_inactive();
    }
}

// ---------------------------------------------------------------------------
// Server health tracking (circuit breaker)
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub struct ServerHealth {
    pub consecutive_failures: u32,
    pub disabled_until: Option<Instant>,
    pub reason: Option<String>,
    pub is_auth_failure: bool,
}

impl Default for ServerHealth {
    fn default() -> Self {
        Self::new()
    }
}

impl ServerHealth {
    pub fn new() -> Self {
        Self {
            consecutive_failures: 0,
            disabled_until: None,
            reason: None,
            is_auth_failure: false,
        }
    }

    pub fn is_available(&self) -> bool {
        match self.disabled_until {
            None => true,
            Some(until) => Instant::now() >= until,
        }
    }

    pub fn record_failure(&mut self, is_auth: bool, reason: &str) {
        self.consecutive_failures += 1;
        self.is_auth_failure = is_auth;
        self.reason = Some(reason.to_string());

        if is_auth || self.consecutive_failures >= CIRCUIT_BREAK_THRESHOLD {
            let cooldown = if is_auth {
                AUTH_FAILURE_COOLDOWN
            } else {
                TRANSIENT_FAILURE_COOLDOWN
            };
            self.disabled_until = Some(Instant::now() + cooldown);
        }
    }

    pub fn record_success(&mut self) {
        *self = Self::new();
    }
}

pub type ServerHealthMap = Arc<Mutex<HashMap<String, ServerHealth>>>;

// ---------------------------------------------------------------------------
// Progress update messages
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub enum ProgressUpdate {
    /// Every enabled NNTP provider is temporarily unavailable. The job stays
    /// active and will retry automatically when a provider recovers.
    WaitingForProviders { job_id: String, message: String },
    /// At least one NNTP provider recovered after a
    /// [`ProgressUpdate::WaitingForProviders`] notification.
    ProvidersAvailable { job_id: String },
    ArticleComplete {
        job_id: String,
        file_id: String,
        segment_number: u32,
        decoded_bytes: u64,
        file_complete: bool,
        server_id: Option<String>,
        /// Filename declared by the yEnc header. This lets the queue layer
        /// recognize obfuscated PAR2 files before terminal completion.
        yenc_filename: Option<String>,
    },
    /// An article could not be retrieved. `failure` carries the typed
    /// classification of *why* (NotFound, ServerDown, AuthFailed, …).
    /// See `crate::article_failure` for the taxonomy.
    ArticleFailed {
        job_id: String,
        file_id: String,
        segment_number: u32,
        failure: crate::article_failure::ArticleFailure,
    },
    JobFinished {
        job_id: String,
        success: bool,
        articles_failed: usize,
        download_time_secs: f64,
    },
    JobAborted {
        job_id: String,
        reason: String,
        articles_failed: usize,
        download_time_secs: f64,
    },
}

// ---------------------------------------------------------------------------
// Work item
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct WorkItem {
    pub(crate) job_id: String,
    pub(crate) file_id: String,
    pub(crate) filename: String,
    pub(crate) message_id: String,
    pub(crate) segment_number: u32,
    /// Servers already tried for this article (by server ID).
    pub(crate) tried_servers: Vec<String>,
    /// Definitive per-provider outcomes. Transient failures are not recorded
    /// because they provide no evidence about article availability.
    pub(crate) provider_outcomes: HashMap<String, crate::article_failure::ArticleFailureKind>,
    /// Number of attempts on the current server.
    pub(crate) tries_on_current: u32,
    /// Timeouts and dropped connections seen for this article while the
    /// server was otherwise healthy. Reset when the article moves server.
    pub(crate) outage_tries: u32,
}

// ---------------------------------------------------------------------------
// Per-job context
// ---------------------------------------------------------------------------

/// Per-job state that workers reference via `item.job_id`.
///
/// Everything a worker needs to process an article for a specific job lives
/// here. The queue manager owns one `Arc<JobContext>` per active job; the
/// pool holds a clone in its [`JobContextMap`] so workers can look it up.
pub(crate) struct JobContext {
    pub job_id: String,
    pub work_dir: PathBuf,
    pub assembler: Arc<FileAssembler>,
    pub progress_tx: mpsc::Sender<ProgressUpdate>,
    pub yenc_names: Arc<Mutex<HashMap<String, String>>>,
    pub nzb_filenames: HashMap<String, String>,
    /// Articles that still need a definitive result (success or all-server
    /// failure). When this reaches zero, `JobFinished` is emitted.
    pub articles_remaining: AtomicUsize,
    pub articles_failed: AtomicUsize,
    pub paused: AtomicBool,
    pub cancelled: AtomicBool,
    /// Optional abort reason — if set when articles_remaining hits zero
    /// (or when cancellation fires), `JobAborted` is emitted instead of
    /// `JobFinished`.
    pub abort_reason: Mutex<Option<String>>,
    pub total_decode_us: Arc<AtomicU64>,
    pub total_assemble_us: Arc<AtomicU64>,
    pub total_articles_decoded: Arc<AtomicU64>,
    pub engine_start: Instant,
    active_started: Mutex<Option<Instant>>,
    active_elapsed: Mutex<Duration>,
    /// Total bytes across all files (for perf summary throughput).
    pub total_bytes: u64,
    /// The first `size=` seen per file. Only a present size is pinned, and it
    /// is a cross-check rather than an authority: the NZB-declared size is
    /// the bound, so one article with a wrong or missing `size=` must not
    /// make every later article of the file fail.
    pinned_file_sizes: Mutex<HashMap<String, u64>>,
    /// Ensures JobFinished/JobAborted is only emitted once.
    finished: AtomicBool,
    /// Avoid repeatedly reporting the same all-provider outage while the
    /// workers wait for circuit-breaker cooldown.
    waiting_for_providers_reported: AtomicBool,
}

pub(crate) type JobContextMap = Arc<Mutex<HashMap<String, Arc<JobContext>>>>;

impl JobContext {
    fn new(
        job: &NzbJob,
        assembler: Arc<FileAssembler>,
        progress_tx: mpsc::Sender<ProgressUpdate>,
        total_articles: usize,
    ) -> Self {
        let nzb_filenames = job
            .files
            .iter()
            .map(|f| (f.id.clone(), f.filename.clone()))
            .collect();
        Self {
            job_id: job.id.clone(),
            work_dir: job.work_dir.clone(),
            assembler,
            progress_tx,
            yenc_names: Arc::new(Mutex::new(HashMap::new())),
            nzb_filenames,
            articles_remaining: AtomicUsize::new(total_articles),
            articles_failed: AtomicUsize::new(0),
            paused: AtomicBool::new(false),
            cancelled: AtomicBool::new(false),
            abort_reason: Mutex::new(None),
            total_decode_us: Arc::new(AtomicU64::new(0)),
            total_assemble_us: Arc::new(AtomicU64::new(0)),
            total_articles_decoded: Arc::new(AtomicU64::new(0)),
            engine_start: Instant::now(),
            active_started: Mutex::new(Some(Instant::now())),
            active_elapsed: Mutex::new(Duration::ZERO),
            total_bytes: job.total_bytes,
            pinned_file_sizes: Mutex::new(HashMap::new()),
            finished: AtomicBool::new(false),
            waiting_for_providers_reported: AtomicBool::new(false),
        }
    }

    fn report_waiting_for_providers(&self, message: &str) {
        if self
            .waiting_for_providers_reported
            .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            try_send_progress(
                &self.progress_tx,
                &self.job_id,
                ProgressUpdate::WaitingForProviders {
                    job_id: self.job_id.clone(),
                    message: message.to_string(),
                },
            );
        }
    }

    fn report_providers_available(&self) {
        if self
            .waiting_for_providers_reported
            .swap(false, Ordering::Relaxed)
        {
            try_send_progress(
                &self.progress_tx,
                &self.job_id,
                ProgressUpdate::ProvidersAvailable {
                    job_id: self.job_id.clone(),
                },
            );
        }
    }

    fn pause_clock(&self) {
        let mut started = self.active_started.lock();
        if let Some(at) = started.take() {
            *self.active_elapsed.lock() += at.elapsed();
        }
    }

    fn resume_clock(&self) {
        let mut started = self.active_started.lock();
        if started.is_none() {
            *started = Some(Instant::now());
        }
    }

    fn active_elapsed(&self) -> Duration {
        let elapsed = *self.active_elapsed.lock();
        elapsed
            + self
                .active_started
                .lock()
                .map_or(Duration::ZERO, |at| at.elapsed())
    }

    /// Decrement articles_remaining. If it reaches zero, run deobfuscation
    /// and emit the job-finished/aborted terminal update. Idempotent.
    fn resolve_one(&self) {
        let prev = self.articles_remaining.fetch_sub(1, Ordering::Relaxed);
        if prev != 1 {
            return;
        }
        self.emit_terminal();
    }

    /// Emit the terminal (JobFinished / JobAborted) message. Safe to call
    /// multiple times; only the first call does anything.
    fn emit_terminal(&self) {
        if self.finished.swap(true, Ordering::Relaxed) {
            return;
        }

        // Run deobfuscation before signalling completion so post-processing
        // sees the final filenames.
        self.deobfuscate_files();

        let download_elapsed = self.engine_start.elapsed();
        let active_elapsed = self.active_elapsed();
        let decode_total_us = self.total_decode_us.load(Ordering::Relaxed);
        let assemble_total_us = self.total_assemble_us.load(Ordering::Relaxed);
        let articles_decoded = self.total_articles_decoded.load(Ordering::Relaxed);
        let elapsed_us = download_elapsed.as_micros().max(1);
        let throughput_mbps = (self.total_bytes as f64 / download_elapsed.as_secs_f64().max(0.001))
            / (1024.0 * 1024.0);
        info!(
            job_id = %self.job_id,
            elapsed_secs = download_elapsed.as_secs_f64(),
            total_bytes = self.total_bytes,
            throughput_mbps = format!("{throughput_mbps:.2}"),
            "Download phase complete"
        );
        info!(
            job_id = %self.job_id,
            articles_decoded,
            decode_secs = format!("{:.3}", decode_total_us as f64 / 1_000_000.0),
            assemble_secs = format!("{:.3}", assemble_total_us as f64 / 1_000_000.0),
            decode_pct = format!("{:.1}", decode_total_us as f64 / elapsed_us as f64 * 100.0),
            assemble_pct = format!("{:.1}", assemble_total_us as f64 / elapsed_us as f64 * 100.0),
            "Decode timing summary (cumulative across all workers)"
        );

        let abort_reason = self.abort_reason.lock().clone();
        if let Some(reason) = abort_reason {
            let failed = self.articles_failed.load(Ordering::Relaxed);
            try_send_progress(
                &self.progress_tx,
                &self.job_id,
                ProgressUpdate::JobAborted {
                    job_id: self.job_id.clone(),
                    reason,
                    articles_failed: failed,
                    download_time_secs: active_elapsed.as_secs_f64(),
                },
            );
            return;
        }

        let failed = self.articles_failed.load(Ordering::Relaxed);
        try_send_progress(
            &self.progress_tx,
            &self.job_id,
            ProgressUpdate::JobFinished {
                job_id: self.job_id.clone(),
                success: failed == 0,
                articles_failed: failed,
                download_time_secs: active_elapsed.as_secs_f64(),
            },
        );
    }

    /// Choose the best filename between NZB subject and yEnc header per file
    /// and rename on disk if needed. Called exactly once at job completion.
    fn deobfuscate_files(&self) {
        let renames = self.yenc_names.lock();
        for (file_id, yenc_name) in renames.iter() {
            let Some(nzb_name) = self.nzb_filenames.get(file_id) else {
                continue;
            };
            if nzb_name == yenc_name {
                continue;
            }
            let clean_yenc = std::path::Path::new(yenc_name.as_str())
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(yenc_name);
            if clean_yenc.is_empty() || nzb_name == clean_yenc {
                continue;
            }

            let nzb_has_ext = has_known_extension(nzb_name);
            let yenc_has_ext = has_known_extension(clean_yenc);

            let (old_name, new_name) = if yenc_has_ext && !nzb_has_ext {
                (nzb_name.as_str(), clean_yenc)
            } else if nzb_has_ext && !yenc_has_ext {
                continue;
            } else if yenc_has_ext && nzb_has_ext {
                (nzb_name.as_str(), clean_yenc)
            } else {
                continue;
            };

            let old_path = self.work_dir.join(old_name);
            let new_path = self.work_dir.join(new_name);
            if old_path.exists() && !new_path.exists() {
                if let Err(e) = std::fs::rename(&old_path, &new_path) {
                    warn!(
                        job_id = %self.job_id,
                        from = %old_name,
                        to = %new_name,
                        "Failed to deobfuscate file: {e}"
                    );
                } else {
                    info!(
                        job_id = %self.job_id,
                        from = %old_name,
                        to = %new_name,
                        "Deobfuscated file"
                    );
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Shared work queue
// ---------------------------------------------------------------------------

/// Multi-job queue with per-server round-robin fairness and PAR2-first
/// priority within each submission.
///
/// Items submitted via [`SharedWorkQueue::submit_items`] are inserted so that
/// PAR2 index and volume files land ahead of data files (matching the prior
/// per-job ordering), while data files land at the tail. Cross-job ordering
/// is FIFO by submission time until a server has served a job; it then prefers
/// another eligible job before returning to that job's backlog.
pub(crate) struct SharedWorkQueue {
    inner: Mutex<QueueState>,
    notify: Notify,
}

struct QueueState {
    items: VecDeque<WorkItem>,
    /// Last job selected by each server. This is intentionally per server:
    /// separate NNTP providers can make independent fair scheduling choices.
    last_served: HashMap<String, String>,
}

impl SharedWorkQueue {
    pub fn new() -> Self {
        Self {
            inner: Mutex::new(QueueState {
                items: VecDeque::new(),
                last_served: HashMap::new(),
            }),
            notify: Notify::new(),
        }
    }

    /// Insert a batch of work items with PAR2 items ahead of data items.
    /// Cross-batch order is preserved: PAR2 items from this batch go after
    /// any existing items, then data items.
    pub fn submit_items(&self, mut items: Vec<WorkItem>) {
        items.sort_by_key(|item| par2_sort_key(&item.filename));
        let had_items = !items.is_empty();
        {
            let mut q = self.inner.lock();
            q.items.reserve(items.len());
            for item in items {
                q.items.push_back(item);
            }
        }
        if had_items {
            self.notify.notify_waiters();
        }
    }

    /// Push a single item back onto the front (used when a worker is
    /// returning an item because its job is paused or its server was just
    /// tried for this item).
    fn push_front(&self, item: WorkItem) {
        self.inner.lock().items.push_front(item);
        self.notify.notify_waiters();
    }

    /// Push a single item to the back (used after handle_article_not_available
    /// when another server can still try it).
    fn push_back(&self, item: WorkItem) {
        self.inner.lock().items.push_back(item);
        self.notify.notify_waiters();
    }

    /// `(workable, total)` for `server_id`. `workable` is the number of
    /// items in the queue that are eligible for a worker on `server_id`;
    /// `total` is the queue length. Used by the supervisor's starvation
    /// diagnostic — if `workable == 0` while `total > 0`, the server has
    /// items it can't service yet (either already tried, or waiting on a
    /// higher-priority server).
    ///
    /// An item is "workable" for this server when:
    /// - `server_id` is NOT in `item.tried_servers`, AND
    /// - no healthy higher-priority server still needs to try it (i.e. every
    ///   server in `higher_priority_servers` is already in `item.tried_servers`).
    ///
    /// Pass an empty slice when the caller has no strictly-higher-priority
    /// peers (priority 0, single-server setups, or all peers circuit-broken).
    pub(crate) fn workable_count_for(
        &self,
        server_id: &str,
        higher_priority_servers: &[String],
    ) -> (usize, usize) {
        let q = self.inner.lock();
        let total = q.items.len();
        let workable = q
            .items
            .iter()
            .filter(|i| !i.tried_servers.iter().any(|s| s == server_id))
            .filter(|i| {
                higher_priority_servers
                    .iter()
                    .all(|hp| i.tried_servers.contains(hp))
            })
            .count();
        (workable, total)
    }

    /// Pop the next item that can be processed by a worker on `server_id`.
    ///
    /// Prefers an eligible item from a job other than the one this server last
    /// served, then falls back to any eligible item. It also enforces server
    /// priority: items where any healthy higher-priority server has not yet
    /// tried the article are skipped for the backup server.
    ///
    /// `higher_priority_servers` is a caller-prepared list of server IDs with
    /// strictly higher priority (lower priority number) than the caller, filtered
    /// to only enabled + healthy servers. See `run_worker_pipelined` and
    /// `run_worker_serial` for the canonical computation. Empty slice disables
    /// the priority gate (priority-0 servers, single-server setups, or all
    /// higher-priority peers circuit-broken → backup can take over).
    ///
    /// Returns `None` if the queue is empty or if every item is either already
    /// tried here or pending a higher-priority server.
    fn pop_workable(
        &self,
        server_id: &str,
        higher_priority_servers: &[String],
    ) -> Option<WorkItem> {
        let mut state = self.inner.lock();
        let last_served = state.last_served.get(server_id).cloned();
        let is_eligible = |item: &WorkItem| {
            !item.tried_servers.iter().any(|s| s == server_id)
                && higher_priority_servers
                    .iter()
                    .all(|server| item.tried_servers.contains(server))
        };

        let selected = last_served
            .as_deref()
            .and_then(|last_job| {
                state
                    .items
                    .iter()
                    .position(|item| is_eligible(item) && item.job_id != last_job)
            })
            .or_else(|| state.items.iter().position(is_eligible));

        if let Some(index) = selected {
            let item = state.items.remove(index)?;
            state
                .last_served
                .insert(server_id.to_string(), item.job_id.clone());
            Some(item)
        } else {
            None
        }
    }

    /// Remove all items belonging to `job_id`. Used on cancel_job / remove_job.
    fn drain_job(&self, job_id: &str) -> Vec<WorkItem> {
        let mut q = self.inner.lock();
        let mut kept = VecDeque::with_capacity(q.items.len());
        let mut drained = Vec::new();
        while let Some(item) = q.items.pop_front() {
            if item.job_id == job_id {
                drained.push(item);
            } else {
                kept.push_back(item);
            }
        }
        q.items = kept;
        drained
    }

    /// Remove and return every queued item matching `predicate`.
    /// Remove and return the items matching `predicate`, leaving the rest in
    /// place and in order.
    fn take_where(&self, mut predicate: impl FnMut(&WorkItem) -> bool) -> Vec<WorkItem> {
        let mut q = self.inner.lock();
        let mut taken = Vec::new();
        let mut index = 0;
        while index < q.items.len() {
            if predicate(&q.items[index]) {
                taken.push(q.items.remove(index).expect("index < len"));
            } else {
                index += 1;
            }
        }
        taken
    }

    pub fn len(&self) -> usize {
        self.inner.lock().items.len()
    }
}

impl Default for SharedWorkQueue {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Worker pool
// ---------------------------------------------------------------------------

struct ActiveWorker {
    shutdown: Arc<AtomicBool>,
    /// Worker heartbeat: monotonic millis since pool creation
    /// (`WorkerPool::created_at`). Updated by the worker on every
    /// "definitive progress" event (successful decode or definitive
    /// failure). The supervisor reads this to detect zombie workers.
    last_progress: Arc<AtomicU64>,
    handle: JoinHandle<()>,
}

/// Long-lived worker pool that services all active download jobs.
pub struct WorkerPool {
    work_queue: Arc<SharedWorkQueue>,
    job_contexts: JobContextMap,
    pub(crate) servers: Arc<Mutex<Vec<ServerConfig>>>,
    server_health: ServerHealthMap,
    bandwidth: Arc<BandwidthLimiter>,
    conn_tracker: Arc<ConnectionTracker>,
    stall_timeout: Option<Duration>,
    /// Reference epoch for worker heartbeats. All `last_progress` values
    /// store millis elapsed since this instant.
    created_at: Instant,
    /// Idle threshold above which the supervisor evicts a worker.
    /// Mutable so the harness (and runtime config reload) can adjust it
    /// without recreating the pool.
    max_worker_idle: Mutex<Duration>,
    /// Per-server "last starvation log" timestamp; rate-limits the
    /// "no workable items" diagnostic to once per minute per server.
    starvation_log: Mutex<HashMap<String, Instant>>,
    /// Lifetime count of worker evictions performed by the heartbeat
    /// watchdog. Useful for tests and observability — a non-zero value
    /// means at least one worker stalled long enough to be reclaimed.
    evictions: AtomicU64,
    workers: Mutex<HashMap<String, Vec<ActiveWorker>>>,
    shutdown: Arc<AtomicBool>,
    supervisor_handle: Mutex<Option<JoinHandle<()>>>,
}

impl WorkerPool {
    pub fn new(
        servers: Arc<Mutex<Vec<ServerConfig>>>,
        bandwidth: Arc<BandwidthLimiter>,
        conn_tracker: Arc<ConnectionTracker>,
        stall_timeout_secs: u64,
    ) -> Arc<Self> {
        let stall_timeout = if stall_timeout_secs > 0 {
            Some(Duration::from_secs(stall_timeout_secs))
        } else {
            None
        };
        Arc::new(Self {
            work_queue: Arc::new(SharedWorkQueue::new()),
            job_contexts: Arc::new(Mutex::new(HashMap::new())),
            servers,
            server_health: Arc::new(Mutex::new(HashMap::new())),
            bandwidth,
            conn_tracker,
            stall_timeout,
            created_at: Instant::now(),
            max_worker_idle: Mutex::new(DEFAULT_MAX_WORKER_IDLE),
            starvation_log: Mutex::new(HashMap::new()),
            evictions: AtomicU64::new(0),
            workers: Mutex::new(HashMap::new()),
            shutdown: Arc::new(AtomicBool::new(false)),
            supervisor_handle: Mutex::new(None),
        })
    }

    /// Override the worker idle eviction threshold. Tests use this to make
    /// the supervisor's heartbeat check converge in seconds.
    pub fn set_max_worker_idle(&self, d: Duration) {
        *self.max_worker_idle.lock() = d;
    }

    /// Read current worker idle eviction threshold.
    pub fn max_worker_idle(&self) -> Duration {
        *self.max_worker_idle.lock()
    }

    /// Millis elapsed since the pool was constructed. Used as the
    /// monotonic clock for `ActiveWorker::last_progress`.
    fn elapsed_ms(&self) -> u64 {
        self.created_at.elapsed().as_millis() as u64
    }

    /// Reference `Instant` used as the epoch for `last_progress` / heartbeat
    /// timestamps. Exposed so the NNTP layer can share the same clock when
    /// ticking its socket-liveness heartbeat — values then compare directly
    /// against `self.elapsed_ms()` in the supervisor's idle-worker check.
    fn created_at(&self) -> Instant {
        self.created_at
    }

    /// Collect server IDs with strictly higher priority (lower priority number)
    /// than `my_priority`, restricted to enabled + healthy (non-circuit-broken)
    /// servers. `my_server_id` is excluded (a server never blocks itself).
    ///
    /// Used by worker loops and the supervisor to drive the priority gate in
    /// [`SharedWorkQueue::pop_workable`] and [`SharedWorkQueue::workable_count_for`].
    /// See `sabnzbd/nzb/article.py::get_article` for the reference behaviour.
    fn higher_priority_servers(&self, my_priority: u8, my_server_id: &str) -> Vec<String> {
        let servers = self.servers.lock();
        let health = self.server_health.lock();
        servers
            .iter()
            .filter(|s| s.enabled && s.priority < my_priority && s.id != my_server_id)
            .filter(|s| health.get(&s.id).is_none_or(|h| h.is_available()))
            .map(|s| s.id.clone())
            .collect()
    }

    /// Return a queue-facing message when no enabled provider can currently
    /// accept work. A circuit-broken provider is deliberately retried later,
    /// so this is a waiting condition rather than an article failure.
    fn provider_unavailable_message(&self) -> Option<&'static str> {
        let servers = self.servers.lock();
        let enabled: Vec<_> = servers.iter().filter(|server| server.enabled).collect();
        if enabled.is_empty() {
            return Some("Waiting for providers: no enabled NNTP servers are configured.");
        }

        let health = self.server_health.lock();
        enabled
            .iter()
            .all(|server| health.get(&server.id).is_some_and(|entry| !entry.is_available()))
            .then_some(
                "Waiting for providers: every enabled server is temporarily unavailable. rustnzb will retry automatically.",
            )
    }

    fn report_provider_outage(&self) {
        let Some(message) = self.provider_unavailable_message() else {
            return;
        };
        let contexts: Vec<_> = self.job_contexts.lock().values().cloned().collect();
        for ctx in contexts {
            ctx.report_waiting_for_providers(message);
        }
    }

    fn report_providers_available(&self) {
        let contexts: Vec<_> = self.job_contexts.lock().values().cloned().collect();
        for ctx in contexts {
            ctx.report_providers_available();
        }
    }

    /// Lifetime count of worker evictions performed by the heartbeat
    /// watchdog. Increases by 1 each time the supervisor reclaims a stalled
    /// worker. Test harnesses use this as a positive signal that the Phase
    /// 5 idle watchdog actually fired.
    pub fn eviction_count(&self) -> u64 {
        self.evictions.load(Ordering::Relaxed)
    }

    /// Spawn workers for all currently enabled servers and start the
    /// supervisor task. Call once at queue-manager startup.
    pub fn start(self: &Arc<Self>) {
        self.reconcile_servers();

        let this = Arc::clone(self);
        let handle = tokio::spawn(async move {
            this.supervisor_loop().await;
        });
        *self.supervisor_handle.lock() = Some(handle);
    }

    /// Create or tear down workers to match the current server list.
    ///
    /// For each enabled server, ensures exactly `server.connections` workers
    /// exist. Extra workers (from a shrunk limit or disabled server) have
    /// their per-worker shutdown flag flipped so they exit gracefully after
    /// the current article.
    pub fn reconcile_servers(self: &Arc<Self>) {
        if self.shutdown.load(Ordering::Relaxed) {
            return;
        }

        let servers_snapshot: Vec<ServerConfig> = self.servers.lock().clone();
        let mut workers = self.workers.lock();

        // First pass: retire workers for servers that are gone or disabled.
        let mut retire: Vec<String> = Vec::new();
        for key in workers.keys() {
            let still_active = servers_snapshot.iter().any(|s| s.enabled && &s.id == key);
            if !still_active {
                retire.push(key.clone());
            }
        }
        for key in retire {
            if let Some(list) = workers.remove(&key) {
                for w in list {
                    w.shutdown.store(true, Ordering::Relaxed);
                    // Don't await — workers check shutdown on next loop
                    // iteration and exit within ~WORKER_IDLE_POLL.
                    drop(w.handle);
                }
            }
        }

        // Second pass: spawn or shrink to match target count per enabled server.
        for server in &servers_snapshot {
            if !server.enabled {
                continue;
            }
            let target = (server.connections as usize).min(500);
            let entry = workers.entry(server.id.clone()).or_default();

            // Shrink: signal extras to exit.
            while entry.len() > target {
                if let Some(w) = entry.pop() {
                    w.shutdown.store(true, Ordering::Relaxed);
                    drop(w.handle);
                }
            }

            // Grow: spawn new workers with stagger.
            let current = entry.len();
            for conn_idx in current..target {
                let worker_shutdown = Arc::new(AtomicBool::new(false));
                // Initialize heartbeat to *now* so the worker has a full
                // grace period before its first eviction check.
                let last_progress = Arc::new(AtomicU64::new(self.elapsed_ms()));
                let pool = Arc::clone(self);
                let server_clone = server.clone();
                let ws_clone = Arc::clone(&worker_shutdown);
                let lp_clone = Arc::clone(&last_progress);
                let handle = tokio::spawn(async move {
                    pool_worker(pool, server_clone, conn_idx, ws_clone, lp_clone).await;
                });
                entry.push(ActiveWorker {
                    shutdown: worker_shutdown,
                    last_progress,
                    handle,
                });
            }
        }
    }

    /// Register a new job context and submit its unfinished articles to the
    /// shared queue. Called by QueueManager::launch_download.
    pub(crate) fn submit_job(self: &Arc<Self>, ctx: Arc<JobContext>, items: Vec<WorkItem>) {
        let job_id = ctx.job_id.clone();
        if items.is_empty() {
            // Nothing to do — emit completion immediately.
            ctx.emit_terminal();
            return;
        }
        self.job_contexts.lock().insert(job_id.clone(), ctx);
        self.work_queue.submit_items(items);
        self.report_provider_outage();
        debug!(job_id = %job_id, queue_len = self.work_queue.len(), "Job submitted to worker pool");
    }

    /// Unregister a normally completed job and close its assembler files.
    ///
    /// This must only be called after `JobFinished` is received, which means
    /// every article has reached a definitive result and no worker can write
    /// another segment for this job. Abort and cancellation paths unregister
    /// their contexts separately because they may still have in-flight work.
    pub(crate) fn release_completed_job(&self, job_id: &str) {
        let ctx = self.job_contexts.lock().remove(job_id);
        if let Some(ctx) = ctx {
            // Workers can briefly retain an Arc<JobContext> after resolving
            // the final article. Clear the assembler explicitly so those
            // transient references do not keep every output file open during
            // post-processing.
            ctx.assembler.clear_job(job_id);
        }
    }

    /// Pause a job: workers stop pulling its items, and any item currently
    /// being held while paused is returned to the queue.
    pub fn pause_job(&self, job_id: &str) {
        if let Some(ctx) = self.job_contexts.lock().get(job_id) {
            ctx.pause_clock();
            ctx.paused.store(true, Ordering::Relaxed);
        }
    }

    /// Resume a paused job.
    pub fn resume_job(&self, job_id: &str) {
        if let Some(ctx) = self.job_contexts.lock().get(job_id) {
            ctx.resume_clock();
            ctx.paused.store(false, Ordering::Relaxed);
            // Wake any workers that were idle waiting for work.
            self.work_queue.notify.notify_waiters();
        }
    }

    /// Abort a job with a reason. Drains queued items, sets the abort flag,
    /// and emits JobAborted via the job's progress channel.
    pub fn abort_job(&self, job_id: &str, reason: String) -> bool {
        let ctx = self.job_contexts.lock().get(job_id).cloned();
        let Some(ctx) = ctx else {
            return false;
        };
        {
            let mut abort_reason = ctx.abort_reason.lock();
            if abort_reason.is_some() {
                return false;
            }
            *abort_reason = Some(reason);
        }
        ctx.cancelled.store(true, Ordering::Relaxed);
        let drained = self.work_queue.drain_job(job_id);
        // Decrement the remaining counter for drained items so the terminal
        // callback fires if nothing is in-flight for this job.
        for _ in drained {
            ctx.resolve_one();
        }
        // In-flight items still own the remaining count. They will resolve
        // (without writing) as their responses arrive or after a connection
        // failure requeues them. Only the final resolution emits JobAborted.
        if ctx.articles_remaining.load(Ordering::Relaxed) == 0 {
            ctx.emit_terminal();
        }
        true
    }

    /// Cancel a job silently (no JobFinished / JobAborted emission).
    /// Used by `remove_job` when the user deletes a job from the queue —
    /// the progress receiver is about to be dropped anyway.
    pub fn cancel_job(&self, job_id: &str) {
        let ctx = self.job_contexts.lock().remove(job_id);
        let Some(ctx) = ctx else {
            return;
        };
        ctx.cancelled.store(true, Ordering::Relaxed);
        let _ = self.work_queue.drain_job(job_id);
    }

    /// Per-tick checks that maintain pool health: idle-worker eviction,
    /// dead-worker reaping, worker reconciliation, and starvation diagnostics.
    ///
    /// Circuit-broken providers retain their queued articles. Workers retry
    /// after the provider cooldown instead of converting a transient outage
    /// into a persistent per-job pause.
    async fn supervisor_loop(self: Arc<Self>) {
        let mut ticker = tokio::time::interval(SUPERVISOR_INTERVAL);
        loop {
            ticker.tick().await;
            if self.shutdown.load(Ordering::Relaxed) {
                break;
            }

            // ---------- 1. Heartbeat eviction ----------
            // Compute idle threshold + current epoch outside the workers lock.
            let now_ms = self.elapsed_ms();
            let max_idle_ms = self.max_worker_idle().as_millis() as u64;

            // Pre-compute per-server "has workable items now" so idle backup
            // workers aren't evicted when there's legitimately nothing for
            // them to do (waiting on higher-priority servers to fail first).
            // Computed once per tick, outside the workers lock, to avoid
            // lock-ordering hazards. Matches SABnzbd's idle-thread model
            // (sabnzbd/downloader.py — idle threads stay connected).
            let server_priorities: Vec<(String, u8)> = {
                let srv = self.servers.lock();
                srv.iter()
                    .filter(|s| s.enabled)
                    .map(|s| (s.id.clone(), s.priority))
                    .collect()
            };
            let has_workable: HashMap<String, bool> = server_priorities
                .iter()
                .map(|(sid, prio)| {
                    let hp = self.higher_priority_servers(*prio, sid);
                    let (workable, _) = self.work_queue.workable_count_for(sid, &hp);
                    (sid.clone(), workable > 0)
                })
                .collect();

            {
                let workers = self.workers.lock();
                for (server_id, list) in workers.iter() {
                    for (idx, w) in list.iter().enumerate() {
                        if w.shutdown.load(Ordering::Relaxed) {
                            continue;
                        }
                        let last = w.last_progress.load(Ordering::Relaxed);
                        let idle = now_ms.saturating_sub(last);
                        if idle > max_idle_ms {
                            // Bug 2 fix: don't evict a worker whose server
                            // has no workable items. It's idle because it's
                            // waiting for its primary/higher-priority peers
                            // to fail articles — not because it's zombied.
                            // If the server isn't in the map at all (e.g.
                            // disabled mid-tick), default to true (evict).
                            if !has_workable.get(server_id).copied().unwrap_or(true) {
                                continue;
                            }
                            warn!(
                                server = %server_id,
                                worker_idx = idx,
                                idle_ms = idle,
                                max_idle_ms,
                                "Idle-worker watchdog: evicting stalled worker"
                            );
                            w.shutdown.store(true, Ordering::Relaxed);
                            self.evictions.fetch_add(1, Ordering::Relaxed);
                        }
                    }
                }
            }

            // ---------- 2. Reap finished workers and respawn ----------
            {
                let mut workers = self.workers.lock();
                for list in workers.values_mut() {
                    list.retain(|w| !w.handle.is_finished());
                }
            }
            // Reconcile fills any gaps left by reaped workers.
            self.reconcile_servers();

            // ---------- 3. Resolve articles no longer waiting on a required server ----------
            self.resolve_items_not_waiting_on_required_providers();

            // ---------- 4. Starvation diagnostic ----------
            // For each enabled server: if the queue has items but none are
            // workable for this server, log once per minute. "Not workable"
            // can mean either (a) every item has already been tried here, or
            // (b) every item is still waiting on a higher-priority server
            // (backup server legitimately idle — not a bug).
            let now_instant = Instant::now();
            for (sid, prio) in &server_priorities {
                let hp = self.higher_priority_servers(*prio, sid);
                let (workable, total) = self.work_queue.workable_count_for(sid, &hp);
                if workable == 0 && total > 0 {
                    let mut log = self.starvation_log.lock();
                    let should_log = log
                        .get(sid)
                        .map(|t| now_instant.duration_since(*t) >= Duration::from_secs(60))
                        .unwrap_or(true);
                    if should_log {
                        log.insert(sid.clone(), now_instant);
                        let reason = if hp.is_empty() {
                            "every item has been tried here already"
                        } else {
                            "every item has been tried here, or is waiting for a higher-priority server"
                        };
                        info!(
                            server = %sid,
                            total_items = total,
                            higher_priority_servers = hp.len(),
                            "Queue has items but none are workable for this server ({reason})"
                        );
                    }
                }
            }
        }
    }

    /// Fail queued articles that every required provider has already
    /// answered definitively.
    ///
    /// An item is normally resolved by the worker that records the last
    /// outcome. When an optional server becomes unavailable after the other
    /// servers have answered, the item is left in the queue waiting for that
    /// server, whose workers no longer pull work. Since the optional server is
    /// no longer required, resolve such items here.
    fn resolve_items_not_waiting_on_required_providers(&self) {
        // Nothing can become resolvable unless an optional server is down:
        // with every enabled server required, an item resolves only when a
        // worker records the last server's outcome. Skip the queue walk.
        {
            let servers = self.servers.lock();
            let health = self.server_health.lock();
            let optional_down = servers.iter().any(|server| {
                server.enabled
                    && server.optional
                    && health.get(&server.id).is_some_and(|h| !h.is_available())
            });
            if !optional_down {
                return;
            }
        }
        let taken = {
            let servers = self.servers.lock();
            let health = self.server_health.lock();
            self.work_queue.take_where(|item| {
                !item.provider_outcomes.is_empty()
                    && all_enabled_providers_definitive(&servers, &health, &item.provider_outcomes)
            })
        };
        for item in taken {
            let ctx = self.job_contexts.lock().get(&item.job_id).cloned();
            let Some(ctx) = ctx else {
                continue;
            };
            if ctx.cancelled.load(Ordering::Relaxed) {
                ctx.resolve_one();
                continue;
            }
            let last_server = item.tried_servers.last().cloned().unwrap_or_default();
            let last_kind = item
                .provider_outcomes
                .get(&last_server)
                .copied()
                .unwrap_or(crate::article_failure::ArticleFailureKind::NotFound);
            fail_article_everywhere(
                &item,
                &last_server,
                &ctx,
                "supervisor",
                last_kind,
                "Article unavailable on every required server (optional servers unavailable)",
            );
        }
    }

    /// Shut down all workers gracefully. In-flight articles finish first.
    pub async fn shutdown(self: &Arc<Self>) {
        self.shutdown.store(true, Ordering::Relaxed);
        let handles: Vec<JoinHandle<()>> = {
            let mut workers = self.workers.lock();
            let mut out = Vec::new();
            for (_id, list) in workers.drain() {
                for w in list {
                    w.shutdown.store(true, Ordering::Relaxed);
                    out.push(w.handle);
                }
            }
            out
        };
        // Notify workers so any parked on notify.notified() wake up.
        self.work_queue.notify.notify_waiters();

        await_worker_shutdown(handles, Duration::from_secs(10)).await;

        if let Some(h) = self.supervisor_handle.lock().take() {
            h.abort();
        }
    }

    pub fn conn_tracker(&self) -> &Arc<ConnectionTracker> {
        &self.conn_tracker
    }

    /// Whether this job still has an active context in the pool.
    pub fn has_job(&self, job_id: &str) -> bool {
        self.job_contexts.lock().contains_key(job_id)
    }

    /// Active (unpaused) download time of a registered job, in seconds.
    pub fn job_active_secs(&self, job_id: &str) -> Option<f64> {
        self.job_contexts
            .lock()
            .get(job_id)
            .map(|ctx| ctx.active_elapsed().as_secs_f64())
    }
}

async fn await_worker_shutdown(mut handles: Vec<JoinHandle<()>>, timeout: Duration) {
    let deadline = tokio::time::Instant::now() + timeout;
    for handle in &mut handles {
        if tokio::time::timeout_at(deadline, &mut *handle)
            .await
            .is_err()
        {
            break;
        }
    }
    for handle in handles {
        if !handle.is_finished() {
            handle.abort();
        }
    }
}

// ---------------------------------------------------------------------------
// Worker body
// ---------------------------------------------------------------------------

/// Single pool worker. Owns an NNTP connection to `primary_server` and pulls
/// items from the shared queue until `worker_shutdown` is flipped (server
/// reconciled away, limit shrunk) or the pool shuts down.
///
/// The worker acquires its connection slot (a semaphore permit from the
/// per-server pool) **before** the first connect attempt and holds it for
/// the entire lifetime of the worker, across every reconnect. This bounds
/// concurrent connections to `server.connections` by construction.
async fn pool_worker(
    pool: Arc<WorkerPool>,
    primary_server: ServerConfig,
    conn_idx: usize,
    worker_shutdown: Arc<AtomicBool>,
    last_progress: Arc<AtomicU64>,
) {
    let worker_id = format!("{}#{}", primary_server.id, conn_idx);

    // Stagger worker startup to avoid thundering herd of connections.
    if conn_idx > 0 {
        let stagger = WORKER_RAMP_DELAY * conn_idx as u32;
        tokio::time::sleep(stagger).await;
    }

    let should_exit = |worker_shutdown: &Arc<AtomicBool>, pool: &Arc<WorkerPool>| {
        worker_shutdown.load(Ordering::Relaxed) || pool.shutdown.load(Ordering::Relaxed)
    };

    // Acquire the slot up-front. If the server isn't registered or its limit
    // is zero, the worker has nothing to do — exit.
    let mut conn_slot = match pool.conn_tracker.acquire(&primary_server.id).await {
        Some(slot) => slot,
        None => {
            info!(
                worker = %worker_id,
                server = %primary_server.name,
                "No connection slot available (server removed or limit=0); worker exiting"
            );
            return;
        }
    };

    'reconnect: loop {
        if should_exit(&worker_shutdown, &pool) {
            return;
        }

        // If the limit was shrunk under us, the semaphore will have been
        // replaced. Drop our (now-orphaned) slot and exit cleanly.
        match pool.conn_tracker.slot_status(&conn_slot) {
            SlotStatus::Current => {}
            SlotStatus::PoolReplaced => {
                info!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    reason = "pool_replaced",
                    "Connection slot is stale (connection limit changed); worker exiting"
                );
                return;
            }
            SlotStatus::ServerRemoved => {
                info!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    reason = "server_removed",
                    "Connection slot is stale (server removed from tracker); worker exiting"
                );
                return;
            }
        }

        // Check circuit breaker before connecting. Compute an owned bool
        // so we don't hold the MutexGuard across an await point.
        let circuit_broken = {
            let health = pool.server_health.lock();
            health
                .get(&primary_server.id)
                .is_some_and(|h| !h.is_available())
        };
        if circuit_broken {
            pool.report_provider_outage();
            tokio::time::sleep(WORKER_IDLE_POLL).await;
            continue 'reconnect;
        }

        info!(
            worker = %worker_id,
            server = %primary_server.name,
            host = %primary_server.host,
            port = primary_server.port,
            ssl = primary_server.ssl,
            conn_idx,
            "Worker starting — connecting to primary server"
        );

        let mut conn = NntpConnection::new(worker_id.clone());
        // Attach socket-liveness heartbeat BEFORE connect so every byte
        // received — from the welcome banner onward — counts as progress.
        // This is the fix for false-eviction of slow-but-working workers:
        // previously `last_progress` only advanced on full article decode,
        // so a worker receiving a 50-second article looked idle for the
        // entire fetch. Now any line read from the socket keeps it alive.
        // Matches SABnzbd's `nw.timeout` model (newswrapper.py:315).
        conn.set_io_heartbeat(last_progress.clone(), pool.created_at());
        if let Err(e) = connect_with_retry(
            &mut conn,
            &primary_server,
            &worker_id,
            &pool.server_health,
            &pool.servers,
        )
        .await
        {
            warn!(
                worker = %worker_id,
                server = %primary_server.name,
                host = %primary_server.host,
                "Worker FAILED to connect after all retries: {e}"
            );
            if should_exit(&worker_shutdown, &pool) {
                return;
            }
            pool.report_provider_outage();
            tokio::time::sleep(RECONNECT_DELAY).await;
            continue 'reconnect;
        }
        pool.report_providers_available();
        let pipe_depth = primary_server.pipelining.max(1);
        let active_conns = pool.conn_tracker.total();
        info!(
            worker = %worker_id,
            server = %primary_server.name,
            host = %primary_server.host,
            pipelining = pipe_depth,
            total_nntp_connections = active_conns,
            "Worker connected and ready"
        );

        // NOTE: do not tick heartbeat here. Reconnects are *not* progress
        // — counting them masks the zombie cycle (worker reconnects forever
        // without ever decoding an article). The heartbeat is initialised
        // to spawn time in `reconcile_servers`, which gives every worker a
        // full grace period to first-connect and process its first article.
        let reconnect_needed = if pipe_depth <= 1 {
            run_worker_serial(
                &pool,
                &primary_server,
                &worker_id,
                &worker_shutdown,
                &mut conn,
                &mut conn_slot,
                &last_progress,
            )
            .await
        } else {
            run_worker_pipelined(
                &pool,
                &primary_server,
                &worker_id,
                pipe_depth,
                &worker_shutdown,
                &mut conn,
                &mut conn_slot,
                &last_progress,
            )
            .await
        };

        let _ = conn.quit().await;
        match reconnect_needed {
            WorkerExit::Reconnect => {
                // Loop back to the top and reconnect — slot is preserved.
                continue 'reconnect;
            }
            WorkerExit::Exit => {
                // Slot drops here when conn_slot goes out of scope.
                return;
            }
        }
    }
}

enum WorkerExit {
    /// Exit the worker function entirely (server retired or pool shutdown).
    Exit,
    /// Reconnect and keep pulling work (transient connection loss).
    Reconnect,
}

/// Wait for work, with early exit on shutdown / server retirement.
/// Returns `Some(item, ctx)` when a processable item is available, or `None`
/// if the worker should exit.
///
/// `higher_priority_servers` gates which items this server is allowed to take
/// — see `pop_workable` for the priority model.
async fn next_work_item(
    pool: &Arc<WorkerPool>,
    server_id: &str,
    higher_priority_servers: &[String],
    worker_shutdown: &Arc<AtomicBool>,
) -> Option<(WorkItem, Arc<JobContext>)> {
    loop {
        if worker_shutdown.load(Ordering::Relaxed) || pool.shutdown.load(Ordering::Relaxed) {
            return None;
        }

        if let Some(item) = pool
            .work_queue
            .pop_workable(server_id, higher_priority_servers)
        {
            // Look up the job context. If the job is gone or cancelled, drop
            // the item and keep going.
            let ctx = pool.job_contexts.lock().get(&item.job_id).cloned();
            let Some(ctx) = ctx else {
                continue;
            };
            if ctx.cancelled.load(Ordering::Relaxed) {
                ctx.resolve_one();
                continue;
            }
            // Respect per-job pause: return the item and wait.
            if ctx.paused.load(Ordering::Relaxed) {
                pool.work_queue.push_back(item);
                tokio::time::sleep(WORKER_IDLE_POLL).await;
                continue;
            }
            return Some((item, ctx));
        }

        // Queue empty (or nothing workable for this server) — wait with a
        // timeout so we still notice shutdown and new work alike.
        let notified = pool.work_queue.notify.notified();
        tokio::select! {
            _ = notified => {}
            _ = tokio::time::sleep(WORKER_IDLE_POLL) => {}
        }
    }
}

async fn run_worker_serial(
    pool: &Arc<WorkerPool>,
    primary_server: &ServerConfig,
    worker_id: &str,
    worker_shutdown: &Arc<AtomicBool>,
    conn: &mut NntpConnection,
    conn_slot: &mut ConnectionSlot,
    last_progress: &Arc<AtomicU64>,
) -> WorkerExit {
    let mut consecutive_errors: u32 = 0;

    loop {
        // Server runtime checks.
        let server_disabled = pool
            .servers
            .lock()
            .iter()
            .find(|s| s.id == primary_server.id)
            .is_none_or(|s| !s.enabled);
        if server_disabled {
            info!(
                worker = %worker_id,
                server = %primary_server.name,
                "Server disabled, worker exiting"
            );
            return WorkerExit::Exit;
        }
        {
            let health = pool.server_health.lock();
            if let Some(h) = health.get(&primary_server.id)
                && !h.is_available()
            {
                info!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    reason = h.reason.as_deref().unwrap_or("unknown"),
                    "Server circuit-broken, worker reconnecting after cooldown"
                );
                return WorkerExit::Reconnect;
            }
        }

        // Snapshot of healthy servers with strictly higher priority (lower
        // priority number). Used as the priority gate in pop_workable:
        // items waiting for a higher-priority server won't be dispatched
        // to this worker. Recomputed each loop iteration so runtime
        // priority / health changes are picked up. See SABnzbd
        // `Article.get_article` for the reference behaviour.
        let higher_priority_servers =
            pool.higher_priority_servers(primary_server.priority, &primary_server.id);

        let Some((mut item, ctx)) = next_work_item(
            pool,
            &primary_server.id,
            &higher_priority_servers,
            worker_shutdown,
        )
        .await
        else {
            return WorkerExit::Exit;
        };

        let result = {
            let _activity = conn_slot.activity();
            let fetch_fut = fetch_article_with_retry(
                conn,
                &item,
                &ctx.assembler,
                &ctx.cancelled,
                primary_server,
                worker_id,
            );
            if let Some(timeout) = pool.stall_timeout {
                match tokio::time::timeout(timeout, fetch_fut).await {
                    Ok(r) => r,
                    Err(_) => {
                        warn!(
                            worker = %worker_id,
                            server = %primary_server.name,
                            article = %item.message_id,
                            "Connection stalled — no response within {}s, reconnecting",
                            timeout.as_secs()
                        );
                        if retry_or_fail_over(
                            item,
                            primary_server,
                            pool,
                            &ctx,
                            worker_id,
                            crate::article_failure::ArticleFailureKind::Timeout,
                            "connection stalled",
                        ) {
                            last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                        }
                        return WorkerExit::Reconnect;
                    }
                }
            } else {
                fetch_fut.await
            }
        };

        match result {
            Ok(process_result) => {
                consecutive_errors = 0;
                ctx.total_decode_us
                    .fetch_add(process_result.decode_us, Ordering::Relaxed);
                ctx.total_assemble_us
                    .fetch_add(process_result.assemble_us, Ordering::Relaxed);
                ctx.total_articles_decoded.fetch_add(1, Ordering::Relaxed);
                if let Some(ref yname) = process_result.yenc_filename {
                    ctx.yenc_names
                        .lock()
                        .entry(item.file_id.clone())
                        .or_insert_with(|| crate::util::normalize_nfc(yname));
                }
                if let Some(n) = std::num::NonZeroU32::new(process_result.decoded_bytes as u32) {
                    let _ = pool.bandwidth.acquire_download(n).await;
                }
                try_send_progress(
                    &ctx.progress_tx,
                    &item.job_id,
                    ProgressUpdate::ArticleComplete {
                        job_id: item.job_id.clone(),
                        file_id: item.file_id.clone(),
                        segment_number: item.segment_number,
                        decoded_bytes: process_result.decoded_bytes,
                        file_complete: process_result.file_complete,
                        server_id: Some(primary_server.id.clone()),
                        yenc_filename: process_result.yenc_filename.clone(),
                    },
                );
                ctx.resolve_one();
                // Heartbeat: definitive forward progress.
                last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
            }
            Err(ArticleError::ArticleNotFound) => {
                if handle_article_not_available(
                    &mut item,
                    primary_server,
                    &pool.servers,
                    &pool.server_health,
                    &ctx,
                    &pool.work_queue,
                    worker_id,
                    crate::article_failure::ArticleFailureKind::NotFound,
                    "Article not found on any server",
                ) {
                    last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                }
            }
            Err(ArticleError::ConnectionLost(msg)) => {
                increment_counter("nntp.transient_reconnects");
                consecutive_errors += 1;
                warn!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    host = %primary_server.host,
                    consecutive_errors,
                    max_reconnects = MAX_RECONNECT_ATTEMPTS,
                    article = %item.message_id,
                    "Connection lost: {msg}"
                );
                pool.work_queue.push_front(item);
                if consecutive_errors > MAX_RECONNECT_ATTEMPTS {
                    warn!(
                        worker = %worker_id,
                        server = %primary_server.name,
                        host = %primary_server.host,
                        consecutive_errors,
                        "Too many consecutive errors — worker reconnecting"
                    );
                    return WorkerExit::Reconnect;
                }
                return WorkerExit::Reconnect;
            }
            Err(ArticleError::ProviderUnavailable { kind, message }) => {
                increment_counter("nntp.transient_reconnects");
                let is_auth = matches!(
                    kind,
                    crate::article_failure::ArticleFailureKind::AuthFailed
                        | crate::article_failure::ArticleFailureKind::PermissionDenied
                );
                warn!(
                    job_id = %item.job_id,
                    file_id = %item.file_id,
                    segment_number = item.segment_number,
                    message_id = %item.message_id,
                    server_id = %primary_server.id,
                    worker_id = %worker_id,
                    original_failure_kind = kind.as_str(),
                    "Provider unavailable during article fetch: {message}"
                );
                pool.server_health
                    .lock()
                    .entry(primary_server.id.clone())
                    .or_default()
                    .record_failure(is_auth, &message);
                pool.report_provider_outage();
                pool.work_queue.push_front(item);
                return WorkerExit::Reconnect;
            }
            Err(ArticleError::ServerError { kind, message }) => {
                if retry_or_fail_over(item, primary_server, pool, &ctx, worker_id, kind, &message) {
                    last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                }
                if conn.state != ConnectionState::Ready {
                    return WorkerExit::Reconnect;
                }
            }
            Err(ArticleError::DecodeError(msg)) => {
                if handle_article_not_available(
                    &mut item,
                    primary_server,
                    &pool.servers,
                    &pool.server_health,
                    &ctx,
                    &pool.work_queue,
                    worker_id,
                    crate::article_failure::ArticleFailureKind::DecodeError,
                    &format!("Decode error: {msg}"),
                ) {
                    last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                }
            }
            Err(ArticleError::Cancelled) => {
                // Mirror the pipelined path: an aborted job's in-flight
                // article resolves without being written or reported.
                ctx.resolve_one();
            }
            Err(ArticleError::AssemblyError(msg)) => {
                error!(job_id = %item.job_id, file_id = %item.file_id, segment_number = item.segment_number, message_id = %item.message_id, server_id = %primary_server.id, worker_id = %worker_id, original_failure_kind = "decode_error", terminal_failure_kind = "decode_error", "Assembly error: {msg}");
                try_send_progress(
                    &ctx.progress_tx,
                    &item.job_id,
                    ProgressUpdate::ArticleFailed {
                        job_id: item.job_id.clone(),
                        file_id: item.file_id.clone(),
                        segment_number: item.segment_number,
                        failure: crate::article_failure::ArticleFailure::decode_error(
                            &primary_server.id,
                            format!("Assembly error: {msg}"),
                        ),
                    },
                );
                ctx.articles_failed.fetch_add(1, Ordering::Relaxed);
                ctx.resolve_one();
                last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
async fn run_worker_pipelined(
    pool: &Arc<WorkerPool>,
    primary_server: &ServerConfig,
    worker_id: &str,
    pipe_depth: u8,
    worker_shutdown: &Arc<AtomicBool>,
    conn: &mut NntpConnection,
    conn_slot: &mut ConnectionSlot,
    last_progress: &Arc<AtomicU64>,
) -> WorkerExit {
    let mut pipeline = Pipeline::new(pipe_depth);
    let mut in_flight_items: HashMap<u64, WorkItem> = HashMap::new();
    let mut next_tag: u64 = 0;
    let mut consecutive_errors: u32 = 0;

    // Perf metrics
    let mut perf_articles: u64 = 0;
    let mut perf_bytes: u64 = 0;
    let mut perf_queue_lock_us: u64 = 0;
    let mut perf_receive_us: u64 = 0;
    let mut perf_decode_us: u64 = 0;
    let mut perf_assemble_us: u64 = 0;
    let mut perf_bandwidth_us: u64 = 0;
    let mut perf_yield_us: u64 = 0;
    let mut perf_flush_us: u64 = 0;
    let mut perf_last_log = Instant::now();
    const PERF_LOG_INTERVAL: Duration = Duration::from_secs(10);

    loop {
        if worker_shutdown.load(Ordering::Relaxed) || pool.shutdown.load(Ordering::Relaxed) {
            requeue_all(&mut in_flight_items, &pool.work_queue);
            return WorkerExit::Exit;
        }

        // Server runtime checks.
        let server_disabled = pool
            .servers
            .lock()
            .iter()
            .find(|s| s.id == primary_server.id)
            .is_none_or(|s| !s.enabled);
        if server_disabled {
            info!(
                worker = %worker_id,
                server = %primary_server.name,
                "Server disabled, worker exiting"
            );
            requeue_all(&mut in_flight_items, &pool.work_queue);
            return WorkerExit::Exit;
        }
        {
            let health = pool.server_health.lock();
            if let Some(h) = health.get(&primary_server.id)
                && !h.is_available()
            {
                info!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    reason = h.reason.as_deref().unwrap_or("unknown"),
                    "Server circuit-broken, worker reconnecting after cooldown"
                );
                requeue_all(&mut in_flight_items, &pool.work_queue);
                return WorkerExit::Reconnect;
            }
        }

        // Snapshot of healthy servers with strictly higher priority. Gates
        // which items the pipeline-fill and wait-for-work paths are allowed
        // to take (see `pop_workable`). Recomputed each loop iteration so
        // runtime priority / health changes are picked up.
        let higher_priority_servers =
            pool.higher_priority_servers(primary_server.priority, &primary_server.id);

        // Fill the pipeline.
        while pipeline.pending_count() + pipeline.in_flight_count() < pipe_depth as usize {
            let lock_t = Instant::now();
            let item = pool
                .work_queue
                .pop_workable(&primary_server.id, &higher_priority_servers);
            perf_queue_lock_us += lock_t.elapsed().as_micros() as u64;
            let Some(item) = item else {
                break;
            };
            // Look up ctx to respect pause/cancel.
            let ctx = pool.job_contexts.lock().get(&item.job_id).cloned();
            let Some(ctx) = ctx else {
                continue;
            };
            if ctx.cancelled.load(Ordering::Relaxed) {
                ctx.resolve_one();
                continue;
            }
            if ctx.paused.load(Ordering::Relaxed) {
                pool.work_queue.push_back(item);
                break;
            }
            let tag = next_tag;
            next_tag += 1;
            pipeline.submit(item.message_id.clone(), tag);
            in_flight_items.insert(tag, item);
        }

        // If nothing is queued and nothing in flight, wait for work.
        if pipeline.is_empty() && in_flight_items.is_empty() {
            let Some((first_item, ctx)) = next_work_item(
                pool,
                &primary_server.id,
                &higher_priority_servers,
                worker_shutdown,
            )
            .await
            else {
                return WorkerExit::Exit;
            };
            let _ = ctx; // ctx is validated in next_work_item
            let tag = next_tag;
            next_tag += 1;
            pipeline.submit(first_item.message_id.clone(), tag);
            in_flight_items.insert(tag, first_item);
        }

        let _activity = conn_slot.activity();
        let flush_t = Instant::now();
        if let Err(e) = pipeline.flush_sends(conn).await {
            warn!(
                worker = %worker_id,
                server = %primary_server.name,
                host = %primary_server.host,
                error = %e,
                in_flight = in_flight_items.len(),
                "Pipeline send error — re-queuing all in-flight items"
            );
            requeue_all(&mut in_flight_items, &pool.work_queue);
            consecutive_errors += 1;
            if consecutive_errors > MAX_RECONNECT_ATTEMPTS {
                warn!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    consecutive_errors,
                    "Too many pipeline errors — worker reconnecting"
                );
                return WorkerExit::Reconnect;
            }
            tokio::time::sleep(RECONNECT_DELAY).await;
            return WorkerExit::Reconnect;
        }
        perf_flush_us += flush_t.elapsed().as_micros() as u64;

        // Read one response.
        let recv_t = Instant::now();
        trace!(
            worker = %worker_id,
            in_flight = in_flight_items.len(),
            stall_timeout_secs = pool.stall_timeout.map(|d| d.as_secs()).unwrap_or(0),
            "Pipeline: awaiting response"
        );
        let result = if let Some(timeout) = pool.stall_timeout {
            match tokio::time::timeout(timeout, pipeline.receive_one(conn)).await {
                Ok(r) => r,
                Err(_) => {
                    let elapsed_ms = recv_t.elapsed().as_millis();
                    warn!(
                        worker = %worker_id,
                        server = %primary_server.name,
                        elapsed_ms,
                        in_flight = in_flight_items.len(),
                        "Connection stalled — no response within {}s, reconnecting",
                        timeout.as_secs()
                    );
                    requeue_all(&mut in_flight_items, &pool.work_queue);
                    return WorkerExit::Reconnect;
                }
            }
        } else {
            pipeline.receive_one(conn).await
        };
        perf_receive_us += recv_t.elapsed().as_micros() as u64;

        match result {
            Ok(Some(pipe_result)) => {
                let Some(mut item) = in_flight_items.remove(&pipe_result.request.tag) else {
                    continue;
                };
                // Look up the ctx for this item's job (may have been cancelled).
                let ctx = pool.job_contexts.lock().get(&item.job_id).cloned();
                let Some(ctx) = ctx else {
                    continue;
                };
                if ctx.cancelled.load(Ordering::Relaxed) {
                    ctx.resolve_one();
                    continue;
                }

                match pipe_result.result {
                    Ok(response) => {
                        consecutive_errors = 0;
                        let raw_data = response.data.unwrap_or_default();
                        let yield_t = Instant::now();
                        tokio::task::yield_now().await;
                        perf_yield_us += yield_t.elapsed().as_micros() as u64;
                        let decode_result = decode_and_assemble(
                            &item,
                            &raw_data,
                            &ctx.assembler,
                            Some(&ctx.pinned_file_sizes),
                        );
                        // Return the buffer to the connection's pool so the
                        // next article's fetch reuses it instead of
                        // allocating fresh.
                        conn.release_body_buffer(raw_data);
                        match decode_result {
                            Ok(process_result) => {
                                perf_decode_us += process_result.decode_us;
                                perf_assemble_us += process_result.assemble_us;
                                perf_bytes += process_result.decoded_bytes;
                                perf_articles += 1;
                                ctx.total_decode_us
                                    .fetch_add(process_result.decode_us, Ordering::Relaxed);
                                ctx.total_assemble_us
                                    .fetch_add(process_result.assemble_us, Ordering::Relaxed);
                                ctx.total_articles_decoded.fetch_add(1, Ordering::Relaxed);
                                if let Some(ref yname) = process_result.yenc_filename {
                                    ctx.yenc_names
                                        .lock()
                                        .entry(item.file_id.clone())
                                        .or_insert_with(|| crate::util::normalize_nfc(yname));
                                }
                                let bw_t = Instant::now();
                                if let Some(n) =
                                    std::num::NonZeroU32::new(process_result.decoded_bytes as u32)
                                {
                                    let _ = pool.bandwidth.acquire_download(n).await;
                                }
                                perf_bandwidth_us += bw_t.elapsed().as_micros() as u64;
                                try_send_progress(
                                    &ctx.progress_tx,
                                    &item.job_id,
                                    ProgressUpdate::ArticleComplete {
                                        job_id: item.job_id.clone(),
                                        file_id: item.file_id.clone(),
                                        segment_number: item.segment_number,
                                        decoded_bytes: process_result.decoded_bytes,
                                        file_complete: process_result.file_complete,
                                        server_id: Some(primary_server.id.clone()),
                                        yenc_filename: process_result.yenc_filename.clone(),
                                    },
                                );
                                ctx.resolve_one();
                                // Heartbeat: definitive forward progress.
                                last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);

                                if perf_last_log.elapsed() >= PERF_LOG_INTERVAL {
                                    let elapsed = perf_last_log.elapsed().as_secs_f64();
                                    let mbps = perf_bytes as f64 / elapsed / (1024.0 * 1024.0);
                                    info!(
                                        worker = %worker_id,
                                        articles = perf_articles,
                                        throughput_mbps = format!("{mbps:.1}"),
                                        recv_ms = perf_receive_us / 1000,
                                        decode_ms = perf_decode_us / 1000,
                                        assemble_ms = perf_assemble_us / 1000,
                                        queue_lock_ms = perf_queue_lock_us / 1000,
                                        flush_ms = perf_flush_us / 1000,
                                        yield_ms = perf_yield_us / 1000,
                                        bw_wait_ms = perf_bandwidth_us / 1000,
                                        "Worker perf summary"
                                    );
                                    perf_articles = 0;
                                    perf_bytes = 0;
                                    perf_queue_lock_us = 0;
                                    perf_receive_us = 0;
                                    perf_decode_us = 0;
                                    perf_assemble_us = 0;
                                    perf_bandwidth_us = 0;
                                    perf_yield_us = 0;
                                    perf_flush_us = 0;
                                    perf_last_log = Instant::now();
                                }
                            }
                            Err(ArticleError::DecodeError(msg)) => {
                                if handle_article_not_available(
                                    &mut item,
                                    primary_server,
                                    &pool.servers,
                                    &pool.server_health,
                                    &ctx,
                                    &pool.work_queue,
                                    worker_id,
                                    crate::article_failure::ArticleFailureKind::DecodeError,
                                    &format!("Decode error: {msg}"),
                                ) {
                                    last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                                }
                            }
                            Err(ArticleError::AssemblyError(msg)) => {
                                error!(job_id = %item.job_id, file_id = %item.file_id, segment_number = item.segment_number, message_id = %item.message_id, server_id = %primary_server.id, worker_id = %worker_id, original_failure_kind = "decode_error", terminal_failure_kind = "decode_error", "Assembly error: {msg}");
                                try_send_progress(
                                    &ctx.progress_tx,
                                    &item.job_id,
                                    ProgressUpdate::ArticleFailed {
                                        job_id: item.job_id.clone(),
                                        file_id: item.file_id.clone(),
                                        segment_number: item.segment_number,
                                        failure:
                                            crate::article_failure::ArticleFailure::decode_error(
                                                &primary_server.id,
                                                format!("Assembly error: {msg}"),
                                            ),
                                    },
                                );
                                ctx.articles_failed.fetch_add(1, Ordering::Relaxed);
                                ctx.resolve_one();
                                last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                            }
                            Err(_) => {}
                        }
                    }
                    Err(
                        NntpError::ArticleNotFound(_)
                        | NntpError::NoSuchGroup(_)
                        | NntpError::NoArticleSelected(_),
                    ) => {
                        // 430 and 411/412/420/423 are article-level "not
                        // here" answers; the pipelined connection stays usable.
                        if handle_article_not_available(
                            &mut item,
                            primary_server,
                            &pool.servers,
                            &pool.server_health,
                            &ctx,
                            &pool.work_queue,
                            worker_id,
                            crate::article_failure::ArticleFailureKind::NotFound,
                            "Article not found on any server",
                        ) {
                            last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                        }
                    }
                    Err(NntpError::Connection(_) | NntpError::Io(_)) => {
                        increment_counter("nntp.transient_reconnects");
                        warn!(
                            job_id = %item.job_id,
                            file_id = %item.file_id,
                            segment_number = item.segment_number,
                            worker = %worker_id,
                            server = %primary_server.name,
                            host = %primary_server.host,
                            article = %item.message_id,
                            in_flight = in_flight_items.len(),
                            consecutive_errors,
                            "Pipeline: connection lost during receive — re-queuing all"
                        );
                        pool.work_queue.push_front(item);
                        requeue_all(&mut in_flight_items, &pool.work_queue);
                        consecutive_errors += 1;
                        if consecutive_errors > MAX_RECONNECT_ATTEMPTS {
                            return WorkerExit::Reconnect;
                        }
                        tokio::time::sleep(RECONNECT_DELAY).await;
                        return WorkerExit::Reconnect;
                    }
                    Err(e) => {
                        increment_counter("nntp.transient_reconnects");
                        let failure = crate::article_failure::ArticleFailure::from_nntp(
                            &e,
                            &primary_server.id,
                        );
                        warn!(
                            job_id = %item.job_id,
                            file_id = %item.file_id,
                            segment_number = item.segment_number,
                            message_id = %item.message_id,
                            server_id = %primary_server.id,
                            worker_id = %worker_id,
                            original_failure_kind = failure.kind.as_str(),
                            attempt = item.tries_on_current + 1,
                            "Transient pipeline error — re-queuing in-flight work and reconnecting: {e}"
                        );
                        // Only provider-level failures count against the
                        // circuit breaker, as in the serial path. Article-level
                        // answers (protocol errors such as 451, timeouts) are
                        // capped per server by the outage-try limit below;
                        // counting them let a few bad articles pause the whole
                        // server.
                        if counts_against_circuit_breaker(&e) {
                            let is_auth = matches!(
                                failure.kind,
                                crate::article_failure::ArticleFailureKind::AuthFailed
                                    | crate::article_failure::ArticleFailureKind::PermissionDenied
                            );
                            pool.server_health
                                .lock()
                                .entry(primary_server.id.clone())
                                .or_default()
                                .record_failure(is_auth, &e.to_string());
                            pool.report_provider_outage();
                        }
                        // A server-wide outage (502, 480, 403) says nothing
                        // about the article, so it is re-queued without
                        // spending a try: the circuit breaker decides when the
                        // server is unusable. A timeout or a dropped
                        // connection on a server that is otherwise serving
                        // articles may be this one article, so those are
                        // capped — otherwise one poison article is retried at
                        // the head of the queue forever.
                        let server_wide = matches!(
                            failure.kind,
                            crate::article_failure::ArticleFailureKind::ServerDown
                                | crate::article_failure::ArticleFailureKind::AuthFailed
                                | crate::article_failure::ArticleFailureKind::PermissionDenied
                        );
                        let article_outage = matches!(
                            failure.kind,
                            crate::article_failure::ArticleFailureKind::Timeout
                                | crate::article_failure::ArticleFailureKind::ConnectionClosed
                                | crate::article_failure::ArticleFailureKind::Other
                        );
                        if server_wide {
                            pool.work_queue.push_front(item);
                        } else if article_outage {
                            item.outage_tries += 1;
                            if item.outage_tries < MAX_OUTAGE_TRIES_PER_SERVER {
                                pool.work_queue.push_front(item);
                            } else if retry_or_fail_over(
                                item,
                                primary_server,
                                pool,
                                &ctx,
                                worker_id,
                                failure.kind,
                                &e.to_string(),
                            ) {
                                last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                            }
                        } else if retry_or_fail_over(
                            item,
                            primary_server,
                            pool,
                            &ctx,
                            worker_id,
                            failure.kind,
                            &e.to_string(),
                        ) {
                            last_progress.store(pool.elapsed_ms(), Ordering::Relaxed);
                        }
                        requeue_all(&mut in_flight_items, &pool.work_queue);
                        return WorkerExit::Reconnect;
                    }
                }
            }
            Ok(None) => {
                // No in-flight requests — loop will fill more.
            }
            Err(e) => {
                warn!(
                    worker = %worker_id,
                    server = %primary_server.name,
                    host = %primary_server.host,
                    error = %e,
                    in_flight = in_flight_items.len(),
                    consecutive_errors,
                    "Pipeline receive error"
                );
                requeue_all(&mut in_flight_items, &pool.work_queue);
                consecutive_errors += 1;
                if consecutive_errors > MAX_RECONNECT_ATTEMPTS {
                    return WorkerExit::Reconnect;
                }
                tokio::time::sleep(RECONNECT_DELAY).await;
                return WorkerExit::Reconnect;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Connection with retry
// ---------------------------------------------------------------------------

async fn connect_with_retry(
    conn: &mut NntpConnection,
    server: &ServerConfig,
    worker_id: &str,
    server_health: &ServerHealthMap,
    all_servers: &Arc<Mutex<Vec<ServerConfig>>>,
) -> Result<(), String> {
    for attempt in 1..=MAX_RECONNECT_ATTEMPTS {
        {
            let health = server_health.lock();
            if let Some(h) = health.get(&server.id)
                && !h.is_available()
            {
                return Err(format!(
                    "Server circuit-broken: {}",
                    h.reason.as_deref().unwrap_or("unknown")
                ));
            }
        }

        let current_config = all_servers
            .lock()
            .iter()
            .find(|s| s.id == server.id)
            .cloned()
            .unwrap_or_else(|| server.clone());

        info!(
            worker = %worker_id,
            server = %current_config.name,
            host = %current_config.host,
            port = current_config.port,
            attempt,
            max_attempts = MAX_RECONNECT_ATTEMPTS,
            "Connect attempt starting"
        );
        match conn.connect(&current_config).await {
            Ok(()) => {
                info!(
                    worker = %worker_id,
                    server = %current_config.name,
                    host = %current_config.host,
                    attempt,
                    "Connect attempt succeeded"
                );
                server_health
                    .lock()
                    .entry(server.id.clone())
                    .or_default()
                    .record_success();
                return Ok(());
            }
            Err(e) => {
                let is_auth = matches!(e, NntpError::Auth(_) | NntpError::ServiceUnavailable(_));
                {
                    let mut health = server_health.lock();
                    let entry = health.entry(server.id.clone()).or_default();
                    entry.record_failure(is_auth, &e.to_string());
                    if !entry.is_available() {
                        warn!(
                            worker = %worker_id,
                            server = %current_config.name,
                            host = %current_config.host,
                            error = %e,
                            cooldown_secs = if is_auth { AUTH_FAILURE_COOLDOWN.as_secs() } else { TRANSIENT_FAILURE_COOLDOWN.as_secs() },
                            "Server circuit-broken — stopping all connection attempts"
                        );
                        return Err(format!("Server circuit-broken: {e}"));
                    }
                }

                warn!(
                    worker = %worker_id,
                    server = %current_config.name,
                    host = %current_config.host,
                    attempt,
                    max_attempts = MAX_RECONNECT_ATTEMPTS,
                    error = %e,
                    is_auth,
                    "Connect attempt FAILED: {e}"
                );

                if is_auth {
                    return Err(format!("Auth/permission failure: {e}"));
                }

                if attempt < MAX_RECONNECT_ATTEMPTS {
                    info!(
                        worker = %worker_id,
                        server = %current_config.name,
                        delay_secs = RECONNECT_DELAY.as_secs(),
                        "Waiting before retry"
                    );
                    tokio::time::sleep(RECONNECT_DELAY).await;
                    *conn = NntpConnection::new(worker_id.to_string());
                } else {
                    return Err(format!(
                        "All {MAX_RECONNECT_ATTEMPTS} connect attempts failed: {e}"
                    ));
                }
            }
        }
    }
    Err("Connect retry loop exited unexpectedly".into())
}

// ---------------------------------------------------------------------------
// Helpers: re-queue, not-available routing, par2 sort key
// ---------------------------------------------------------------------------

/// Handle an article that's not available on this server (not found, decode
/// error, etc.): mark the server as tried and either requeue or mark failed.
///
/// `kind` lets the failure be classified — if every server has been tried
/// and the failure was per-server (NotFound, ServerDown, …), we promote it
/// to a definitive `NotFound` for the hopeless tracker. DecodeError stays
/// classified as DecodeError because it's typically not server-specific.
#[allow(clippy::too_many_arguments)]
fn handle_article_not_available(
    item: &mut WorkItem,
    primary_server: &ServerConfig,
    all_servers: &Arc<Mutex<Vec<ServerConfig>>>,
    server_health: &ServerHealthMap,
    ctx: &Arc<JobContext>,
    work_queue: &Arc<SharedWorkQueue>,
    worker_id: &str,
    kind: crate::article_failure::ArticleFailureKind,
    error_msg: &str,
) -> bool {
    item.provider_outcomes
        .insert(primary_server.id.clone(), kind);
    if !item.tried_servers.contains(&primary_server.id) {
        item.tried_servers.push(primary_server.id.clone());
    }
    item.tries_on_current = 0;
    item.outage_tries = 0;

    let all_definitive = all_enabled_providers_definitive(
        &all_servers.lock(),
        &server_health.lock(),
        &item.provider_outcomes,
    );

    debug!(
        article = %item.message_id,
        server = %primary_server.id,
        kind = kind.as_str(),
        tried_count = item.tried_servers.len(),
        all_definitive,
        "Article returned error on this server"
    );

    // (debug log immediately below was added for observability)
    if all_definitive {
        fail_article_everywhere(item, &primary_server.id, ctx, worker_id, kind, error_msg);
        true
    } else {
        // push_FRONT (not push_back): put the failed item at the front of the
        // queue so the next eligible server picks it up IMMEDIATELY instead
        // of queueing behind thousands of fresh items. Same-server workers
        // rotate the item back via pop_workable's existing skip-and-push_back
        // logic. This transforms a retention-dead NZB from "11+ minutes per
        // article's full-server cascade" into "fractions of a second per
        // cascade" — the dominant failure mode for hung downloads.
        work_queue.push_front(item.clone());
        false
    }
}

/// Handle a non-connection error for `item` on `primary_server`: retry it on
/// the same server up to [`MAX_TRIES_PER_SERVER`] times, then record the
/// error as this server's definitive outcome so the article fails over to
/// the next server (or fails once every server has an outcome). Without the
/// cap such errors were re-queued for the same server forever.
///
/// Returns `true` when the article was resolved as failed.
fn retry_or_fail_over(
    mut item: WorkItem,
    primary_server: &ServerConfig,
    pool: &Arc<WorkerPool>,
    ctx: &Arc<JobContext>,
    worker_id: &str,
    kind: crate::article_failure::ArticleFailureKind,
    message: &str,
) -> bool {
    item.tries_on_current += 1;
    if item.tries_on_current < MAX_TRIES_PER_SERVER {
        pool.work_queue.push_front(item);
        return false;
    }
    handle_article_not_available(
        &mut item,
        primary_server,
        &pool.servers,
        &pool.server_health,
        ctx,
        &pool.work_queue,
        worker_id,
        kind,
        &format!(
            "Article failed on every server; last error after {MAX_TRIES_PER_SERVER} attempts: {message}"
        ),
    )
}

/// Resolve an article as failed: every required provider has given a
/// definitive outcome. `server_id` is the provider that answered last.
fn fail_article_everywhere(
    item: &WorkItem,
    server_id: &str,
    ctx: &Arc<JobContext>,
    worker_id: &str,
    kind: crate::article_failure::ArticleFailureKind,
    error_msg: &str,
) {
    let mut provider_outcomes = item
        .provider_outcomes
        .iter()
        .map(|(server, outcome)| format!("{server}={}", outcome.as_str()))
        .collect::<Vec<_>>();
    provider_outcomes.sort_unstable();
    let outcomes = provider_outcomes.join(",");
    let all_not_found = item
        .provider_outcomes
        .values()
        .all(|outcome| *outcome == crate::article_failure::ArticleFailureKind::NotFound);
    let final_kind = if all_not_found {
        crate::article_failure::ArticleFailureKind::NotFound
    } else {
        crate::article_failure::ArticleFailureKind::DecodeError
    };
    warn!(
        job_id = %item.job_id,
        file_id = %item.file_id,
        segment_number = item.segment_number,
        message_id = %item.message_id,
        server_id = %server_id,
        worker_id = %worker_id,
        original_failure_kind = kind.as_str(),
        terminal_failure_kind = final_kind.as_str(),
        attempt = item.tried_servers.len(),
        provider_outcomes = %outcomes,
        "{error_msg}"
    );
    let final_failure = if final_kind == crate::article_failure::ArticleFailureKind::DecodeError {
        crate::article_failure::ArticleFailure::decode_error(
            server_id,
            format!("{error_msg}; provider outcomes: {outcomes}"),
        )
    } else {
        increment_counter("articles.explicit_global_absence");
        crate::article_failure::ArticleFailure::not_found_anywhere(server_id, outcomes)
    };
    try_send_progress(
        &ctx.progress_tx,
        &item.job_id,
        ProgressUpdate::ArticleFailed {
            job_id: item.job_id.clone(),
            file_id: item.file_id.clone(),
            segment_number: item.segment_number,
            failure: final_failure,
        },
    );
    ctx.articles_failed.fetch_add(1, Ordering::Relaxed);
    ctx.resolve_one();
}

/// Whether every provider whose answer is required has given a definitive
/// outcome for an article.
///
/// Every enabled server is required, except an `optional` server that is
/// currently unavailable (circuit open, e.g. it cannot be reached). A
/// required server that is down still blocks the decision: an outage is not
/// evidence that the article is missing. An optional server is a best-effort
/// extra, so it must not hold articles hostage while it is down.
fn all_enabled_providers_definitive(
    servers: &[ServerConfig],
    health: &HashMap<String, ServerHealth>,
    outcomes: &HashMap<String, crate::article_failure::ArticleFailureKind>,
) -> bool {
    servers
        .iter()
        .filter(|server| server.enabled)
        .filter(|server| {
            !(server.optional && health.get(&server.id).is_some_and(|h| !h.is_available()))
        })
        .all(|server| outcomes.contains_key(&server.id))
}

/// Whether a fetch error says the provider itself is unhealthy, and so should
/// count against its circuit breaker: connection/TLS, auth, permission, 502
/// and timeouts. A server that accepts the connection and then black-holes
/// the read is as unhealthy as one that refuses it. Article-level answers
/// never count.
fn counts_against_circuit_breaker(e: &NntpError) -> bool {
    matches!(
        e,
        NntpError::Connection(_)
            | NntpError::Io(_)
            | NntpError::Tls(_)
            | NntpError::Auth(_)
            | NntpError::AuthRequired(_)
            | NntpError::PermissionDenied(_)
            | NntpError::ServiceUnavailable(_)
            | NntpError::Timeout(_)
    )
}

/// Re-queue all in-flight items back to the work queue (on connection loss).
fn requeue_all(in_flight: &mut HashMap<u64, WorkItem>, work_queue: &Arc<SharedWorkQueue>) {
    let items: Vec<WorkItem> = in_flight.drain().map(|(_, item)| item).collect();
    for item in items {
        work_queue.push_front(item);
    }
}

/// Sort key for work-queue prioritisation of PAR2 files. Index files (0)
/// first, then volume files (1), then data files (2).
fn par2_sort_key(filename: &str) -> u8 {
    let lower = filename.to_lowercase();
    if lower.ends_with(".par2") {
        if lower.contains(".vol") { 1 } else { 0 }
    } else {
        2
    }
}

pub fn has_known_extension(name: &str) -> bool {
    let lower = name.to_lowercase();
    if let Some(dot_pos) = lower.rfind('.') {
        let ext = &lower[dot_pos + 1..];
        matches!(
            ext,
            "rar"
                | "r00"
                | "r01"
                | "r02"
                | "r03"
                | "r04"
                | "r05"
                | "zip"
                | "7z"
                | "gz"
                | "bz2"
                | "xz"
                | "tar"
                | "mkv"
                | "mp4"
                | "avi"
                | "wmv"
                | "ts"
                | "m4v"
                | "mov"
                | "mpg"
                | "mpeg"
                | "mp3"
                | "flac"
                | "ogg"
                | "m4a"
                | "aac"
                | "wav"
                | "srt"
                | "sub"
                | "idx"
                | "ass"
                | "ssa"
                | "sup"
                | "nfo"
                | "jpg"
                | "jpeg"
                | "png"
                | "gif"
                | "bmp"
                | "par2"
                | "001"
                | "002"
                | "003"
                | "004"
                | "005"
        )
    } else {
        false
    }
}

// ---------------------------------------------------------------------------
// Public helper used by queue_manager: build work items + context for a job
// ---------------------------------------------------------------------------

/// Build the WorkItems for a job's unfinished articles and an initialised
/// JobContext. Called by QueueManager before [`WorkerPool::submit_job`].
pub(crate) fn build_job_submission(
    job: &NzbJob,
    progress_tx: mpsc::Sender<ProgressUpdate>,
    enabled_server_ids: &[String],
) -> (Arc<JobContext>, Vec<WorkItem>) {
    let assembler = Arc::new(FileAssembler::new());
    for file in &job.files {
        let output_path = job.work_dir.join(&file.filename);
        let completed_segments: Vec<u32> = file
            .articles
            .iter()
            .filter(|article| article.downloaded)
            .map(|article| article.segment_number)
            .collect();
        // Register the declared segment numbers rather than assuming 1..=N:
        // an NZB may skip or repeat numbers.
        let segment_numbers: Vec<u32> = file
            .articles
            .iter()
            .map(|article| article.segment_number)
            .collect();
        // Only trust the NZB size when every segment reported one. The parser
        // turns a missing or unparsable `bytes` attribute into 0, so a file
        // whose segments omit it sums to 0 (or to an understatement) and
        // every article would then be rejected as past the declared size.
        // With no bound, the write check falls back to the article's size=.
        let declared_bytes = file
            .articles
            .iter()
            .all(|article| article.bytes > 0)
            .then_some(file.bytes);
        if let Err(e) = assembler.register_file_with_segment_numbers(
            &job.id,
            &file.id,
            output_path,
            &segment_numbers,
            &completed_segments,
            declared_bytes,
        ) {
            error!(file = %file.filename, "Failed to register file for assembly: {e}");
        }
    }

    // `tried_servers` on a persisted article is only ever written when the
    // article reached a terminal `ArticleFailed`. That is only still terminal
    // if every server enabled now was one of them: a server added or
    // re-enabled since the failure has never been asked, so the article must
    // be fetched again rather than skipped.
    let is_previously_failed = |article: &nzb_nntp::Article| {
        !article.downloaded
            && !enabled_server_ids.is_empty()
            && enabled_server_ids
                .iter()
                .all(|server| article.tried_servers.iter().any(|tried| tried == server))
    };
    let previously_failed = job
        .files
        .iter()
        .flat_map(|file| file.articles.iter())
        .filter(|article| is_previously_failed(article))
        .count();

    let work_items: Vec<WorkItem> = job
        .files
        .iter()
        .flat_map(|file| {
            file.articles
                .iter()
                .filter(|article| !article.downloaded && !is_previously_failed(article))
                .map(move |article| WorkItem {
                    job_id: job.id.clone(),
                    file_id: file.id.clone(),
                    filename: file.filename.clone(),
                    message_id: article.message_id.clone(),
                    segment_number: article.segment_number,
                    tried_servers: article.tried_servers.clone(),
                    provider_outcomes: HashMap::new(),
                    tries_on_current: 0,
                    outage_tries: 0,
                })
        })
        .collect();

    let total_remaining = work_items.len();
    let ctx = Arc::new(JobContext::new(
        job,
        assembler,
        progress_tx,
        total_remaining,
    ));
    ctx.articles_failed
        .store(previously_failed, Ordering::Relaxed);
    (ctx, work_items)
}

// ---------------------------------------------------------------------------
// Article fetch with per-server retry
// ---------------------------------------------------------------------------

async fn fetch_article_with_retry(
    conn: &mut NntpConnection,
    item: &WorkItem,
    assembler: &FileAssembler,
    cancelled: &AtomicBool,
    _server: &ServerConfig,
    worker_id: &str,
) -> Result<ProcessResult, ArticleError> {
    // Retries of article-level errors are counted per item by the caller
    // (`WorkItem::tries_on_current`), so each call makes a single attempt.
    let attempt = item.tries_on_current + 1;
    let fetch_start = Instant::now();
    match conn.fetch_article(&item.message_id).await {
        Ok(response) => {
            let fetch_us = fetch_start.elapsed().as_micros();
            let raw_data = response.data.unwrap_or_default();
            debug!(
                worker = %worker_id,
                article = %item.message_id,
                raw_bytes = raw_data.len(),
                fetch_us,
                "NNTP fetch complete"
            );
            // The job may have been aborted while this fetch was in
            // flight. Like the pipelined path, drop the response rather
            // than writing it into an aborted job's files.
            if cancelled.load(Ordering::Relaxed) {
                conn.release_body_buffer(raw_data);
                return Err(ArticleError::Cancelled);
            }
            let result = decode_and_assemble(item, &raw_data, assembler, None);
            // Return the buffer to the connection's pool so the next
            // article's fetch reuses it instead of allocating fresh.
            conn.release_body_buffer(raw_data);
            result
        }
        Err(NntpError::ArticleNotFound(_)) => {
            debug!(
                worker = %worker_id,
                article = %item.message_id,
                "Article not found (430) — will try next server"
            );
            Err(ArticleError::ArticleNotFound)
        }
        Err(e @ (NntpError::NoSuchGroup(_) | NntpError::NoArticleSelected(_))) => {
            // 411/412/420/423: an article-level "not here" answer. Retrying on
            // this server cannot change it.
            debug!(
                worker = %worker_id,
                article = %item.message_id,
                error = %e,
                "Article unavailable on this server — will try next server"
            );
            Err(ArticleError::ArticleNotFound)
        }
        Err(e @ (NntpError::Connection(_) | NntpError::Io(_))) => {
            warn!(
                worker = %worker_id,
                article = %item.message_id,
                attempt,
                error = %e,
                conn_state = ?conn.state,
                "Connection/IO error during fetch — connection lost"
            );
            Err(ArticleError::ConnectionLost(format!(
                "Connection error on attempt {attempt}: {e}"
            )))
        }
        Err(e @ NntpError::Tls(_)) => {
            warn!(
                worker = %worker_id,
                article = %item.message_id,
                attempt,
                error = %e,
                "TLS error during fetch — connection lost"
            );
            Err(ArticleError::ConnectionLost(format!("TLS error: {e}")))
        }
        Err(e @ NntpError::ServiceUnavailable(_)) => {
            warn!(
                worker = %worker_id,
                article = %item.message_id,
                attempt,
                error = %e,
                "Service unavailable (502) during article fetch — likely rate limited or blocked"
            );
            Err(ArticleError::ProviderUnavailable {
                kind: crate::article_failure::ArticleFailureKind::ServerDown,
                message: e.to_string(),
            })
        }
        Err(e @ (NntpError::AuthRequired(_) | NntpError::Auth(_))) => {
            warn!(
                worker = %worker_id,
                article = %item.message_id,
                attempt,
                error = %e,
                "Auth required (480) during article fetch — session expired or rate limited"
            );
            Err(ArticleError::ProviderUnavailable {
                kind: crate::article_failure::ArticleFailureKind::AuthFailed,
                message: e.to_string(),
            })
        }
        Err(e @ NntpError::PermissionDenied(_)) => Err(ArticleError::ProviderUnavailable {
            kind: crate::article_failure::ArticleFailureKind::PermissionDenied,
            message: e.to_string(),
        }),
        Err(e) => {
            // Protocol / unexpected response / timeout and the like. The caller
            // retries up to MAX_TRIES_PER_SERVER times on this server, then
            // records a definitive outcome so the article fails over.
            warn!(
                worker = %worker_id,
                article = %item.message_id,
                attempt,
                max_tries = MAX_TRIES_PER_SERVER,
                error = %e,
                "Article fetch error on this server"
            );
            Err(ArticleError::ServerError {
                kind: crate::article_failure::ArticleFailure::from_nntp(&e, "").kind,
                message: e.to_string(),
            })
        }
    }
}

// ---------------------------------------------------------------------------
// Article processing
// ---------------------------------------------------------------------------

#[derive(Debug)]
struct ProcessResult {
    decoded_bytes: u64,
    file_complete: bool,
    yenc_filename: Option<String>,
    decode_us: u64,
    assemble_us: u64,
}

#[derive(Debug, thiserror::Error)]
enum ArticleError {
    #[error("Article not found on server")]
    ArticleNotFound,
    #[error("Connection lost: {0}")]
    ConnectionLost(String),
    /// A non-connection error for this article on this server (protocol
    /// error, unexpected response, timeout). Retried a bounded number of
    /// times per server, then treated as a definitive outcome.
    #[error("Server error ({kind:?}): {message}")]
    ServerError {
        kind: crate::article_failure::ArticleFailureKind,
        message: String,
    },
    #[error("Provider unavailable ({kind:?}): {message}")]
    ProviderUnavailable {
        kind: crate::article_failure::ArticleFailureKind,
        message: String,
    },
    #[error("Decode error: {0}")]
    DecodeError(String),
    #[error("Assembly error: {0}")]
    AssemblyError(String),
    /// The job was cancelled while the fetch was in flight; the article was
    /// not written.
    #[error("Job cancelled")]
    Cancelled,
}

/// Choose the file offset a decoded article is written at, rejecting headers
/// that would place it outside the file.
///
/// The offset comes from `=ypart begin=` and is used directly as the `pwrite`
/// position. The bound is the size the NZB declared for the file
/// (`declared_bytes`), not the `size=` the article itself claims: a forged
/// `size=2e12 begin=1e12` would otherwise create a terabyte sparse file. The
/// first `size=` seen for a file is pinned (`pinned_size`) and later articles
/// must agree with it. A multi-segment file with no bound at all — no NZB
/// size and no `size=` — is rejected, as is a `part_end` that does not
/// describe exactly the decoded bytes. A missing `=ypart` on a later segment
/// would overwrite the start of the file and is rejected too.
fn validated_write_offset(
    segment_number: u32,
    decoded: &nzb_decode::YencDecodeResult,
    data_len: u64,
    declared_bytes: Option<u64>,
    pinned_size: Option<u64>,
) -> Result<u64, String> {
    let file_size = decoded.file_size;
    let part_begin = decoded.part_begin;
    let part_end = decoded.part_end;
    if file_size != pinned_size {
        return Err(format!(
            "article size {file_size:?} does not match the size {pinned_size:?} established for this file"
        ));
    }
    let bound = match declared_bytes.or(pinned_size) {
        Some(size) => Some(size),
        None if segment_number <= 1 => None,
        None => {
            return Err(format!(
                "no declared file size for multi-segment file (segment {segment_number})"
            ));
        }
    };
    let begin = match part_begin {
        Some(begin) => begin,
        // A single-part article (no =ypart) can only be the first segment.
        None if segment_number <= 1 => 0,
        None => {
            return Err(format!(
                "no =ypart header on segment {segment_number} of a multi-part file"
            ));
        }
    };
    if let Some(size) = bound {
        if size == 0 {
            return Err("declared file size is 0".to_string());
        }
        if begin >= size {
            return Err(format!(
                "=ypart begin {begin} is past the declared file size {size}"
            ));
        }
        match begin.checked_add(data_len) {
            Some(end) if end <= size => {
                if let Some(part_end) = part_end
                    && part_end != end
                {
                    return Err(format!(
                        "=ypart end {part_end} does not match the decoded bytes ending at {end}"
                    ));
                }
            }
            _ => {
                return Err(format!(
                    "part range begin={begin} len={data_len} exceeds declared file size {size}"
                ));
            }
        }
    }
    Ok(begin)
}

fn decode_and_assemble(
    item: &WorkItem,
    raw_data: &[u8],
    assembler: &FileAssembler,
    pinned_file_sizes: Option<&Mutex<HashMap<String, u64>>>,
) -> Result<ProcessResult, ArticleError> {
    let decode_start = Instant::now();
    let decoded = decode_yenc(raw_data).map_err(|e| {
        ArticleError::DecodeError(format!(
            "yEnc decode failed for {} seg {}: {e}",
            item.filename, item.segment_number
        ))
    })?;
    let decode_us = decode_start.elapsed().as_micros();

    // Remember the first size= seen for this file, but only a real one: an
    // article that omits size= must not become the pin. The pin is a
    // cross-check. The NZB-declared size is what bounds the write, so when it
    // is known a disagreement is logged and the article is still written.
    let declared = assembler.declared_bytes(&item.job_id, &item.file_id);
    let pinned_size = match (pinned_file_sizes, decoded.file_size) {
        (Some(sizes), Some(size)) => {
            let mut sizes = sizes.lock();
            match sizes.entry(item.file_id.clone()) {
                std::collections::hash_map::Entry::Occupied(existing) => Some(*existing.get()),
                std::collections::hash_map::Entry::Vacant(slot) => {
                    slot.insert(size);
                    Some(size)
                }
            }
        }
        (Some(sizes), None) => sizes.lock().get(&item.file_id).copied(),
        (None, size) => size,
    };
    if declared.is_some() && decoded.file_size != pinned_size {
        warn!(
            file_id = %item.file_id,
            segment_number = item.segment_number,
            article_size = ?decoded.file_size,
            pinned_size = ?pinned_size,
            "yEnc size= disagrees with the size pinned for this file; the NZB-declared size is the bound"
        );
    }

    let decoded_len = decoded.data.len() as u64;
    let data_begin = validated_write_offset(
        item.segment_number,
        &decoded,
        decoded_len,
        declared,
        if declared.is_some() {
            decoded.file_size
        } else {
            pinned_size
        },
    )
    .map_err(|reason| {
        ArticleError::DecodeError(format!(
            "Corrupt yEnc article for {} seg {}: {reason}",
            item.filename, item.segment_number
        ))
    })?;
    let yenc_filename = decoded.filename;

    let assemble_start = Instant::now();
    let file_complete = assembler
        .assemble_article(
            &item.job_id,
            &item.file_id,
            item.segment_number,
            data_begin,
            &decoded.data,
        )
        .map_err(|e| {
            ArticleError::AssemblyError(format!(
                "Assembly failed for {} seg {}: {e}",
                item.filename, item.segment_number
            ))
        })?;
    let assemble_us = assemble_start.elapsed().as_micros();

    debug!(
        file = %item.filename,
        segment = item.segment_number,
        raw_bytes = raw_data.len(),
        decoded_bytes = decoded_len,
        decode_us,
        assemble_us,
        "Article decode+assemble timing"
    );

    Ok(ProcessResult {
        decoded_bytes: decoded_len,
        file_complete,
        yenc_filename,
        decode_us: decode_us as u64,
        assemble_us: assemble_us as u64,
    })
}

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

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

    fn worker_pool_without_servers() -> Arc<WorkerPool> {
        WorkerPool::new(
            Arc::new(Mutex::new(Vec::new())),
            Arc::new(BandwidthLimiter::new(Default::default())),
            Arc::new(ConnectionTracker::new()),
            0,
        )
    }

    #[tokio::test(start_paused = true)]
    async fn worker_shutdown_uses_one_shared_deadline() {
        let handles = (0..3)
            .map(|_| tokio::spawn(std::future::pending()))
            .collect();
        let shutdown = tokio::spawn(await_worker_shutdown(handles, Duration::from_secs(10)));
        tokio::task::yield_now().await;
        tokio::time::advance(Duration::from_secs(9)).await;
        tokio::task::yield_now().await;
        assert!(!shutdown.is_finished());
        tokio::time::advance(Duration::from_secs(2)).await;
        shutdown.await.unwrap();
    }

    fn test_job(job_id: &str, root: &std::path::Path) -> NzbJob {
        NzbJob {
            id: job_id.to_string(),
            name: job_id.to_string(),
            category: "Default".to_string(),
            status: nzb_core::models::JobStatus::Downloading,
            priority: nzb_core::models::Priority::Normal,
            total_bytes: 1,
            downloaded_bytes: 0,
            file_count: 1,
            files_completed: 0,
            article_count: 1,
            articles_downloaded: 0,
            articles_failed: 0,
            added_at: chrono::Utc::now(),
            completed_at: None,
            work_dir: root.to_path_buf(),
            output_dir: root.join("complete"),
            password: None,
            error_message: None,
            speed_bps: 0,
            pp_override: None,
            delete_archives: None,
            server_stats: Vec::new(),
            files: Vec::new(),
        }
    }

    fn insert_test_context(pool: &WorkerPool, job: &NzbJob, assembler: Arc<FileAssembler>) {
        let (progress_tx, _progress_rx) = mpsc::channel(1);
        let ctx = Arc::new(JobContext::new(job, assembler, progress_tx, 1));
        pool.job_contexts.lock().insert(job.id.clone(), ctx);
    }

    #[test]
    fn submission_preserves_declared_segment_numbers() {
        let temp = tempfile::tempdir().unwrap();
        let mut job = test_job("segment-identity", temp.path());
        let article = |message_id: &str, segment_number: u32, bytes: u64| nzb_nntp::Article {
            message_id: message_id.to_string(),
            segment_number,
            bytes,
            downloaded: false,
            data_begin: None,
            data_size: None,
            crc32: None,
            tried_servers: Vec::new(),
            tries: 0,
        };
        job.files.push(nzb_core::models::NzbFile {
            id: "file-1".into(),
            filename: "out-of-order.bin".into(),
            bytes: 1_000,
            bytes_downloaded: 0,
            is_par2: false,
            par2_setname: None,
            par2_vol: None,
            par2_blocks: None,
            assembled: false,
            groups: Vec::new(),
            articles: vec![article("third", 3, 300), article("first", 1, 100)],
        });
        let (tx, _rx) = mpsc::channel(4);

        let (_ctx, items) = build_job_submission(&job, tx, &["srv1".into()]);

        assert_eq!(
            items
                .iter()
                .map(|item| (item.message_id.as_str(), item.segment_number))
                .collect::<Vec<_>>(),
            vec![("third", 3), ("first", 1)]
        );
    }

    #[test]
    fn file_without_segment_bytes_still_assembles() {
        let temp = tempfile::tempdir().unwrap();
        let mut job = test_job("no-bytes", temp.path());
        let article = |message_id: &str, segment_number: u32| nzb_nntp::Article {
            message_id: message_id.to_string(),
            segment_number,
            bytes: 0,
            downloaded: false,
            data_begin: None,
            data_size: None,
            crc32: None,
            tried_servers: Vec::new(),
            tries: 0,
        };
        job.files.push(nzb_core::models::NzbFile {
            id: "file-1".into(),
            filename: "out.bin".into(),
            bytes: 0,
            bytes_downloaded: 0,
            is_par2: false,
            par2_setname: None,
            par2_vol: None,
            par2_blocks: None,
            assembled: false,
            groups: Vec::new(),
            articles: vec![article("seg1", 1), article("seg2", 2)],
        });
        let (tx, _rx) = mpsc::channel(4);
        let (ctx, _items) = build_job_submission(&job, tx, &["srv1".into()]);
        // A missing bytes= attribute parses as 0, so there is no NZB bound.
        assert_eq!(ctx.assembler.declared_bytes(&job.id, "file-1"), None);

        let (seg1, _) = yenc_simd::encode_article(b"AAAA", "out.bin", 1, 2, 0, 8);
        let (seg2, _) = yenc_simd::encode_article(b"BBBB", "out.bin", 2, 2, 4, 8);
        let item = |segment_number| {
            let mut item = make_item(&job.id, "msg@test", "out.bin");
            item.file_id = "file-1".into();
            item.segment_number = segment_number;
            item
        };
        decode_and_assemble(&item(1), &seg1, &ctx.assembler, None).unwrap();
        let second = decode_and_assemble(&item(2), &seg2, &ctx.assembler, None).unwrap();

        assert!(second.file_complete);
        assert_eq!(
            std::fs::read(temp.path().join("out.bin")).unwrap(),
            b"AAAABBBB"
        );
    }

    #[test]
    fn submission_with_segment_gap_completes_when_all_declared_segments_written() {
        let temp = tempfile::tempdir().unwrap();
        let mut job = test_job("segment-gap", temp.path());
        let article = |message_id: &str, segment_number: u32| nzb_nntp::Article {
            message_id: message_id.to_string(),
            segment_number,
            bytes: 4,
            downloaded: false,
            data_begin: None,
            data_size: None,
            crc32: None,
            tried_servers: Vec::new(),
            tries: 0,
        };
        job.files.push(nzb_core::models::NzbFile {
            id: "file-1".into(),
            filename: "gap.bin".into(),
            bytes: 16,
            bytes_downloaded: 0,
            is_par2: false,
            par2_setname: None,
            par2_vol: None,
            par2_blocks: None,
            assembled: false,
            groups: Vec::new(),
            // Segment 3 is absent from the NZB.
            articles: vec![article("s1", 1), article("s2", 2), article("s4", 4)],
        });
        let (tx, _rx) = mpsc::channel(4);
        let (ctx, _items) = build_job_submission(&job, tx, &["srv1".into()]);

        let asm = &ctx.assembler;
        assert!(
            !asm.assemble_article(&job.id, "file-1", 1, 0, b"AAAA")
                .unwrap()
        );
        assert!(
            !asm.assemble_article(&job.id, "file-1", 2, 4, b"BBBB")
                .unwrap()
        );
        // Segment 4 must be accepted and must complete the file.
        assert!(
            asm.assemble_article(&job.id, "file-1", 4, 12, b"DDDD")
                .unwrap()
        );
        assert!(asm.is_file_complete(&job.id, "file-1"));
        assert_eq!(asm.get_file_progress(&job.id, "file-1"), (3, 3));
    }

    #[test]
    fn submission_does_not_requeue_previously_failed_articles() {
        let temp = tempfile::tempdir().unwrap();
        let mut job = test_job("previously-failed", temp.path());
        let article = |message_id: &str, segment_number: u32, tried: &[&str]| nzb_nntp::Article {
            message_id: message_id.to_string(),
            segment_number,
            bytes: 100,
            downloaded: false,
            data_begin: None,
            data_size: None,
            crc32: None,
            tried_servers: tried.iter().map(|s| s.to_string()).collect(),
            tries: tried.len() as u32,
        };
        job.files.push(nzb_core::models::NzbFile {
            id: "file-1".into(),
            filename: "partial.bin".into(),
            bytes: 200,
            bytes_downloaded: 0,
            is_par2: false,
            par2_setname: None,
            par2_vol: None,
            par2_blocks: None,
            assembled: false,
            groups: Vec::new(),
            articles: vec![article("pending", 1, &[]), article("failed", 2, &["srv1"])],
        });
        let (tx, _rx) = mpsc::channel(4);

        let (ctx, items) = build_job_submission(&job, tx, &["srv1".into()]);

        assert_eq!(
            items
                .iter()
                .map(|item| item.message_id.as_str())
                .collect::<Vec<_>>(),
            vec!["pending"]
        );
        assert_eq!(ctx.articles_remaining.load(Ordering::Relaxed), 1);
        assert_eq!(ctx.articles_failed.load(Ordering::Relaxed), 1);

        // A server enabled since the failure has never been asked, so the
        // article is fetched again instead of being skipped.
        let (tx, _rx) = mpsc::channel(4);
        let (ctx, items) = build_job_submission(&job, tx, &["srv1".into(), "srv2".into()]);
        assert_eq!(items.len(), 2);
        assert_eq!(ctx.articles_failed.load(Ordering::Relaxed), 0);
    }

    fn decode_test_item(job_id: &str, segment_number: u32) -> WorkItem {
        let mut item = make_item(job_id, "msg@test", "out.bin");
        item.segment_number = segment_number;
        item
    }

    #[test]
    fn decode_rejects_ypart_offset_beyond_declared_file_size() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("out.bin");
        let assembler = FileAssembler::new();
        assembler
            .register_file("j1", "f1", path.clone(), 2)
            .unwrap();

        // Part 2 of an 8-byte file claims to start at ~1 TB.
        let (raw, _) = yenc_simd::encode_article(b"BBBB", "out.bin", 2, 2, 1_000_000_000_000, 8);
        let result = decode_and_assemble(&decode_test_item("j1", 2), &raw, &assembler, None);

        assert!(
            matches!(result, Err(ArticleError::DecodeError(_))),
            "expected corrupt-article error, got {result:?}"
        );
        assert!(std::fs::metadata(&path).unwrap().len() <= 8);
        assert_eq!(assembler.get_file_progress("j1", "f1"), (0, 2));
    }

    #[test]
    fn decode_rejects_forged_size_past_nzb_declared_bytes() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("out.bin");
        let assembler = FileAssembler::new();
        // The NZB says the file is 8 bytes. The article claims 2 TB and asks
        // to be written at 1 TB, which the article's own size= would allow.
        assembler
            .register_file_with_segment_numbers("j1", "f1", path.clone(), &[1, 2], &[], Some(8))
            .unwrap();

        let (raw, _) = yenc_simd::encode_article(
            b"BBBB",
            "out.bin",
            2,
            2,
            1_000_000_000_000,
            2_000_000_000_000,
        );
        let result = decode_and_assemble(&decode_test_item("j1", 2), &raw, &assembler, None);

        assert!(
            matches!(result, Err(ArticleError::DecodeError(_))),
            "forged size= must not win over the NZB size, got {result:?}"
        );
        assert!(std::fs::metadata(&path).unwrap().len() <= 8);
        assert_eq!(assembler.get_file_progress("j1", "f1"), (0, 2));
    }

    #[test]
    fn decode_rejects_missing_size_on_multi_segment_file() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("out.bin");
        let assembler = FileAssembler::new();
        // No NZB size, and the article carries no size= either.
        assembler
            .register_file("j1", "f1", path.clone(), 2)
            .unwrap();

        let (mut raw, _) = yenc_simd::encode_article(b"BBBB", "out.bin", 2, 2, 4, 8);
        let header_end = raw.windows(2).position(|w| w == b"\r\n").unwrap();
        raw.splice(
            0..header_end,
            b"=ybegin part=2 line=128 name=out.bin".iter().copied(),
        );
        let result = decode_and_assemble(&decode_test_item("j1", 2), &raw, &assembler, None);

        assert!(
            matches!(result, Err(ArticleError::DecodeError(_))),
            "a multi-segment file with no bound at all must be rejected, got {result:?}"
        );
        assert_eq!(std::fs::metadata(&path).unwrap().len(), 0);
        assert_eq!(assembler.get_file_progress("j1", "f1"), (0, 2));
    }

    #[test]
    fn decode_rejects_ypart_range_overrunning_declared_file_size() {
        let temp = tempfile::tempdir().unwrap();
        let assembler = FileAssembler::new();
        assembler
            .register_file("j1", "f1", temp.path().join("out.bin"), 2)
            .unwrap();

        // Begins inside the file but runs 2 bytes past its declared end.
        let (raw, _) = yenc_simd::encode_article(b"BBBB", "out.bin", 2, 2, 6, 8);
        let result = decode_and_assemble(&decode_test_item("j1", 2), &raw, &assembler, None);

        assert!(matches!(result, Err(ArticleError::DecodeError(_))));
        assert_eq!(assembler.get_file_progress("j1", "f1"), (0, 2));
    }

    #[test]
    fn decode_rejects_missing_ypart_on_non_first_segment() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("out.bin");
        let assembler = FileAssembler::new();
        assembler
            .register_file("j1", "f1", path.clone(), 2)
            .unwrap();

        let (seg1, _) = yenc_simd::encode_article(b"AAAA", "out.bin", 1, 2, 0, 8);
        decode_and_assemble(&decode_test_item("j1", 1), &seg1, &assembler, None).unwrap();

        // Segment 2 arrives as a single-part article (no =ypart). Writing it
        // at offset 0 would overwrite segment 1.
        let (seg2, _) = yenc_simd::encode_article(b"ZZZZ", "out.bin", 1, 1, 0, 4);
        let result = decode_and_assemble(&decode_test_item("j1", 2), &seg2, &assembler, None);

        assert!(matches!(result, Err(ArticleError::DecodeError(_))));
        assert_eq!(std::fs::read(&path).unwrap(), b"AAAA");
        assert_eq!(assembler.get_file_progress("j1", "f1"), (1, 2));
    }

    #[test]
    fn decode_accepts_valid_parts_and_single_part_articles() {
        let temp = tempfile::tempdir().unwrap();
        let multi = temp.path().join("multi.bin");
        let single = temp.path().join("single.bin");
        let assembler = FileAssembler::new();
        assembler
            .register_file("j1", "f1", multi.clone(), 2)
            .unwrap();
        assembler
            .register_file("j1", "f2", single.clone(), 1)
            .unwrap();

        let (seg2, _) = yenc_simd::encode_article(b"BBBB", "multi.bin", 2, 2, 4, 8);
        let (seg1, _) = yenc_simd::encode_article(b"AAAA", "multi.bin", 1, 2, 0, 8);
        assert!(
            !decode_and_assemble(&decode_test_item("j1", 2), &seg2, &assembler, None)
                .unwrap()
                .file_complete
        );
        assert!(
            decode_and_assemble(&decode_test_item("j1", 1), &seg1, &assembler, None)
                .unwrap()
                .file_complete
        );
        assert_eq!(std::fs::read(&multi).unwrap(), b"AAAABBBB");

        let (whole, _) = yenc_simd::encode_article(b"ONE", "single.bin", 1, 1, 0, 3);
        let mut item = decode_test_item("j1", 1);
        item.file_id = "f2".into();
        assert!(
            decode_and_assemble(&item, &whole, &assembler, None)
                .unwrap()
                .file_complete
        );
        assert_eq!(std::fs::read(&single).unwrap(), b"ONE");
    }

    #[tokio::test]
    async fn serial_fetch_does_not_write_article_after_job_cancelled() {
        use nzb_nntp::testutil::{MockConfig, MockNntpServer, test_config};

        let (encoded, _) = yenc_simd::encode_article(b"payload", "out.bin", 1, 1, 0, 7);
        let mut articles = HashMap::new();
        articles.insert("msg@test".to_string(), encoded);
        let server = MockNntpServer::start(MockConfig {
            articles,
            ..MockConfig::default()
        })
        .await;
        let config = test_config(server.port());
        let mut conn = NntpConnection::new(config.id.clone());
        conn.connect(&config).await.unwrap();

        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("out.bin");
        let assembler = FileAssembler::new();
        assembler
            .register_file("j1", "f1", path.clone(), 1)
            .unwrap();
        let item = make_item("j1", "msg@test", "out.bin");

        // abort_job() flips the flag while the fetch is in flight.
        let cancelled = AtomicBool::new(true);
        let result =
            fetch_article_with_retry(&mut conn, &item, &assembler, &cancelled, &config, "w0").await;

        assert!(
            matches!(result, Err(ArticleError::Cancelled)),
            "expected Cancelled, got {result:?}"
        );
        assert_eq!(assembler.get_file_progress("j1", "f1"), (0, 1));
        assert_eq!(std::fs::metadata(&path).unwrap().len(), 0);

        // Sanity: the same fetch succeeds and writes when not cancelled.
        let not_cancelled = AtomicBool::new(false);
        let result =
            fetch_article_with_retry(&mut conn, &item, &assembler, &not_cancelled, &config, "w0")
                .await
                .unwrap();
        assert!(result.file_complete);
        assert_eq!(std::fs::read(&path).unwrap(), b"payload");
    }

    #[cfg(target_os = "linux")]
    fn open_fd_count_under(root: &std::path::Path) -> usize {
        std::fs::read_dir("/proc/self/fd")
            .expect("read /proc/self/fd")
            .filter_map(Result::ok)
            .filter_map(|entry| std::fs::read_link(entry.path()).ok())
            .filter(|target| target.starts_with(root))
            .count()
    }

    #[test]
    fn has_known_extension_recognizes_archives() {
        assert!(has_known_extension("movie.rar"));
        assert!(has_known_extension("movie.part01.rar"));
        assert!(has_known_extension("file.zip"));
        assert!(has_known_extension("file.7z"));
        assert!(has_known_extension("archive.001"));
    }

    #[test]
    fn has_known_extension_recognizes_video() {
        assert!(has_known_extension("episode.mkv"));
        assert!(has_known_extension("movie.mp4"));
        assert!(has_known_extension("video.avi"));
        assert!(has_known_extension("clip.ts"));
    }

    #[test]
    fn has_known_extension_recognizes_par2() {
        assert!(has_known_extension("file.par2"));
        assert!(has_known_extension("file.vol00+01.par2"));
        assert!(has_known_extension("file.vol015-031.par2"));
    }

    #[test]
    fn has_known_extension_recognizes_misc() {
        assert!(has_known_extension("info.nfo"));
        assert!(has_known_extension("sub.srt"));
        assert!(has_known_extension("cover.jpg"));
        assert!(has_known_extension("song.flac"));
    }

    #[test]
    fn has_known_extension_rejects_obfuscated_hashes() {
        assert!(!has_known_extension("9b6a324d7560b87091685020371ba869"));
        assert!(!has_known_extension("1fG1GP7L2263LHXH213HTNIxZsX7l0cv44BZ"));
        assert!(!has_known_extension("DfKUx3bl7L6PSo6276WSaXSZ7"));
        assert!(!has_known_extension("Q77O1ZxL237vc241z77hFoLBxl"));
    }

    #[test]
    fn has_known_extension_rejects_unknown_extensions() {
        assert!(!has_known_extension("file.xyz123"));
        assert!(!has_known_extension("noext"));
        assert!(!has_known_extension(""));
    }

    #[test]
    fn has_known_extension_case_insensitive() {
        assert!(has_known_extension("file.RAR"));
        assert!(has_known_extension("file.MKV"));
        assert!(has_known_extension("file.Par2"));
        assert!(has_known_extension("file.MP4"));
    }

    fn make_item(job_id: &str, msg_id: &str, filename: &str) -> WorkItem {
        WorkItem {
            job_id: job_id.to_string(),
            file_id: "f1".to_string(),
            filename: filename.to_string(),
            message_id: msg_id.to_string(),
            segment_number: 1,
            tried_servers: Vec::new(),
            provider_outcomes: HashMap::new(),
            tries_on_current: 0,
            outage_tries: 0,
        }
    }

    #[test]
    fn shared_queue_par2_first() {
        let q = SharedWorkQueue::new();
        q.submit_items(vec![
            make_item("j1", "a", "movie.rar"),
            make_item("j1", "b", "movie.par2"),
            make_item("j1", "c", "movie.vol00+01.par2"),
            make_item("j1", "d", "movie.r00"),
        ]);
        let first = q.pop_workable("srv1", &[]).unwrap();
        assert_eq!(first.filename, "movie.par2", "index file first");
        let second = q.pop_workable("srv1", &[]).unwrap();
        assert_eq!(second.filename, "movie.vol00+01.par2", "vol file second");
    }

    #[test]
    fn shared_queue_skips_tried_servers() {
        let q = SharedWorkQueue::new();
        let mut item = make_item("j1", "a", "file.rar");
        item.tried_servers.push("srv1".to_string());
        q.submit_items(vec![item, make_item("j1", "b", "other.rar")]);

        // srv1 should skip the first item and return the second.
        let picked = q.pop_workable("srv1", &[]).unwrap();
        assert_eq!(picked.message_id, "b");
    }

    #[test]
    fn shared_queue_round_robins_eligible_jobs_per_server() {
        let q = SharedWorkQueue::new();
        q.submit_items(vec![
            make_item("job-a", "a-1", "first.rar"),
            make_item("job-a", "a-2", "second.rar"),
            make_item("job-b", "b-1", "third.rar"),
        ]);

        assert_eq!(q.pop_workable("srv1", &[]).unwrap().job_id, "job-a");
        assert_eq!(q.pop_workable("srv1", &[]).unwrap().job_id, "job-b");
        assert_eq!(q.pop_workable("srv1", &[]).unwrap().job_id, "job-a");
    }

    #[tokio::test]
    async fn provider_outage_is_reported_once_then_cleared_on_recovery() {
        let temp = tempfile::tempdir().unwrap();
        let server = ServerConfig::new("srv1", "one.invalid");
        let pool = WorkerPool::new(
            Arc::new(Mutex::new(vec![server.clone()])),
            Arc::new(BandwidthLimiter::new(Default::default())),
            Arc::new(ConnectionTracker::new()),
            0,
        );
        let job = test_job("provider-outage", temp.path());
        let (progress_tx, mut progress_rx) = mpsc::channel(4);
        let ctx = Arc::new(JobContext::new(
            &job,
            Arc::new(FileAssembler::new()),
            progress_tx,
            1,
        ));
        pool.job_contexts.lock().insert(job.id.clone(), ctx);
        pool.server_health
            .lock()
            .entry(server.id.clone())
            .or_default()
            .record_failure(false, "connection refused");
        pool.server_health
            .lock()
            .entry(server.id.clone())
            .or_default()
            .record_failure(false, "connection refused");
        pool.server_health
            .lock()
            .entry(server.id.clone())
            .or_default()
            .record_failure(false, "connection refused");

        pool.report_provider_outage();
        pool.report_provider_outage();
        match progress_rx.recv().await.unwrap() {
            ProgressUpdate::WaitingForProviders { message, .. } => {
                assert!(message.contains("retry automatically"));
            }
            other => panic!("unexpected progress event: {other:?}"),
        }
        assert!(
            progress_rx.try_recv().is_err(),
            "outage event is deduplicated"
        );

        pool.server_health
            .lock()
            .get_mut(&server.id)
            .unwrap()
            .record_success();
        pool.report_providers_available();
        assert!(matches!(
            progress_rx.recv().await,
            Some(ProgressUpdate::ProvidersAvailable { .. })
        ));
    }

    #[test]
    fn unavailable_provider_does_not_prove_global_absence() {
        let servers = vec![
            ServerConfig::new("srv1", "one.invalid"),
            ServerConfig::new("srv2", "two.invalid"),
        ];
        let mut outcomes = HashMap::new();
        outcomes.insert(
            "srv1".to_string(),
            crate::article_failure::ArticleFailureKind::NotFound,
        );

        let health = HashMap::new();
        assert!(!all_enabled_providers_definitive(
            &servers, &health, &outcomes
        ));
        outcomes.insert(
            "srv2".to_string(),
            crate::article_failure::ArticleFailureKind::NotFound,
        );
        assert!(all_enabled_providers_definitive(
            &servers, &health, &outcomes
        ));
    }

    #[test]
    fn unavailable_optional_provider_is_not_required() {
        let mut optional = ServerConfig::new("fill", "fill.invalid");
        optional.optional = true;
        let servers = vec![ServerConfig::new("main", "main.invalid"), optional];
        let mut outcomes = HashMap::new();
        outcomes.insert(
            "main".to_string(),
            crate::article_failure::ArticleFailureKind::NotFound,
        );
        let mut health = HashMap::new();

        // A healthy optional server is still asked.
        assert!(!all_enabled_providers_definitive(
            &servers, &health, &outcomes
        ));

        let mut down = ServerHealth::new();
        down.record_failure(true, "502 on connect");
        health.insert("fill".to_string(), down);
        assert!(all_enabled_providers_definitive(
            &servers, &health, &outcomes
        ));

        // A required server that is down still blocks the decision.
        let mut main_down = ServerHealth::new();
        main_down.record_failure(true, "502 on connect");
        health.insert("main".to_string(), main_down);
        outcomes.clear();
        assert!(!all_enabled_providers_definitive(
            &servers, &health, &outcomes
        ));
    }

    #[tokio::test]
    async fn supervisor_sweep_fails_items_left_waiting_on_down_optional_server() {
        let temp = tempfile::tempdir().unwrap();
        let pool = worker_pool_without_servers();
        let mut optional = ServerConfig::new("fill", "fill.invalid");
        optional.optional = true;
        *pool.servers.lock() = vec![ServerConfig::new("main", "main.invalid"), optional];

        let job = test_job("sweep", temp.path());
        let (progress_tx, mut progress_rx) = mpsc::channel(8);
        let ctx = Arc::new(JobContext::new(
            &job,
            Arc::new(FileAssembler::new()),
            progress_tx,
            1,
        ));
        pool.job_contexts.lock().insert(job.id.clone(), ctx.clone());
        let mut item = make_item("sweep", "missing@test", "payload.bin");
        item.tried_servers.push("main".into());
        item.provider_outcomes.insert(
            "main".into(),
            crate::article_failure::ArticleFailureKind::NotFound,
        );
        pool.work_queue.push_front(item);

        // Optional server still healthy: the item keeps waiting for it.
        pool.resolve_items_not_waiting_on_required_providers();
        assert_eq!(pool.work_queue.len(), 1);

        // It goes down after the main server answered.
        let mut down = ServerHealth::new();
        down.record_failure(true, "502 on connect");
        pool.server_health.lock().insert("fill".into(), down);
        pool.resolve_items_not_waiting_on_required_providers();

        assert_eq!(pool.work_queue.len(), 0);
        assert_eq!(ctx.articles_failed.load(Ordering::Relaxed), 1);
        assert_eq!(ctx.articles_remaining.load(Ordering::Relaxed), 0);
        let mut saw_failure = false;
        while let Ok(update) = progress_rx.try_recv() {
            saw_failure |= matches!(update, ProgressUpdate::ArticleFailed { .. });
        }
        assert!(saw_failure);
    }

    #[tokio::test]
    async fn abort_has_one_owner_and_waits_for_in_flight_resolution() {
        let temp = tempfile::tempdir().unwrap();
        let pool = worker_pool_without_servers();
        let job = test_job("abort-drain", temp.path());
        let assembler = Arc::new(FileAssembler::new());
        let (progress_tx, mut progress_rx) = mpsc::channel(8);
        let ctx = Arc::new(JobContext::new(&job, assembler, progress_tx, 3));
        ctx.articles_failed.store(2, Ordering::Relaxed);
        pool.job_contexts
            .lock()
            .insert(job.id.clone(), Arc::clone(&ctx));
        pool.work_queue.submit_items(vec![
            make_item(&job.id, "queued-1", "file.rar"),
            make_item(&job.id, "queued-2", "file.rar"),
        ]);

        assert!(pool.abort_job(&job.id, "original reason".into()));
        assert!(!pool.abort_job(&job.id, "overwritten reason".into()));
        assert_eq!(ctx.articles_remaining.load(Ordering::Relaxed), 1);
        assert!(!ctx.finished.load(Ordering::Relaxed));
        assert!(progress_rx.try_recv().is_err());

        // Simulate the sole in-flight worker settling after its write handle
        // is no longer usable. Only now may the terminal event be published.
        ctx.resolve_one();
        match progress_rx.recv().await.unwrap() {
            ProgressUpdate::JobAborted {
                reason,
                articles_failed,
                download_time_secs,
                ..
            } => {
                assert_eq!(reason, "original reason");
                assert_eq!(articles_failed, 2);
                assert!(download_time_secs >= 0.0);
            }
            other => panic!("unexpected terminal event: {other:?}"),
        }
    }

    #[test]
    fn pop_workable_respects_priority() {
        // Fresh item (tried_servers empty). A backup-priority caller whose
        // higher_priority_servers list is non-empty must NOT get the item —
        // the primary server still needs a chance first.
        let q = SharedWorkQueue::new();
        q.submit_items(vec![make_item("j1", "a", "file.rar")]);

        let higher = vec!["srv_primary".to_string()];
        assert!(q.pop_workable("srv_backup", &higher).is_none());

        // Primary server (empty higher list) should still get it.
        let item = q.pop_workable("srv_primary", &[]).unwrap();
        assert_eq!(item.message_id, "a");
    }

    #[test]
    fn pop_workable_allows_backup_after_primary_tried() {
        // Once the primary has been added to tried_servers (because it
        // failed), the backup is allowed to take the item.
        let q = SharedWorkQueue::new();
        let mut item = make_item("j1", "a", "file.rar");
        item.tried_servers.push("srv_primary".to_string());
        q.submit_items(vec![item]);

        let higher = vec!["srv_primary".to_string()];
        let picked = q.pop_workable("srv_backup", &higher).unwrap();
        assert_eq!(picked.message_id, "a");
    }

    #[test]
    fn pop_workable_ignores_circuit_broken_higher_server() {
        // When the caller's `higher_priority_servers` list is empty because
        // the primary was filtered out as circuit-broken/disabled, the backup
        // gets items immediately — no waiting for the dead primary.
        let q = SharedWorkQueue::new();
        q.submit_items(vec![make_item("j1", "a", "file.rar")]);

        let higher: Vec<String> = vec![]; // primary filtered out by caller
        let item = q.pop_workable("srv_backup", &higher).unwrap();
        assert_eq!(item.message_id, "a");
    }

    #[test]
    fn workable_count_for_respects_priority() {
        let q = SharedWorkQueue::new();
        q.submit_items(vec![
            make_item("j1", "a", "a.rar"),
            make_item("j1", "b", "b.rar"),
        ]);

        // Backup: both items need primary first → workable=0.
        let higher = vec!["srv_primary".to_string()];
        let (workable, total) = q.workable_count_for("srv_backup", &higher);
        assert_eq!(workable, 0);
        assert_eq!(total, 2);

        // Primary: both items are workable.
        let (workable, total) = q.workable_count_for("srv_primary", &[]);
        assert_eq!(workable, 2);
        assert_eq!(total, 2);
    }

    #[test]
    fn shared_queue_drain_job_removes_only_target() {
        let q = SharedWorkQueue::new();
        q.submit_items(vec![
            make_item("j1", "a", "a.rar"),
            make_item("j2", "b", "b.rar"),
            make_item("j1", "c", "c.rar"),
        ]);
        let drained = q.drain_job("j1");
        assert_eq!(drained.len(), 2);
        assert_eq!(q.len(), 1);
        let remaining = q.pop_workable("srv1", &[]).unwrap();
        assert_eq!(remaining.job_id, "j2");
    }

    #[test]
    fn release_completed_job_drops_context_and_closes_assembler_files() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let assembler = Arc::new(FileAssembler::new());
        let job_id = "completed-job";
        assembler
            .register_file(job_id, "file-1", tempdir.path().join("file.rar"), 1)
            .expect("register file");
        assert_eq!(assembler.get_file_progress(job_id, "file-1"), (0, 1));

        let job = test_job(job_id, tempdir.path());
        let pool = worker_pool_without_servers();
        insert_test_context(&pool, &job, Arc::clone(&assembler));
        assert!(pool.has_job(job_id));

        pool.release_completed_job(job_id);

        assert!(!pool.has_job(job_id));
        assert_eq!(assembler.get_file_progress(job_id, "file-1"), (0, 0));
    }

    #[test]
    fn job_active_secs_reports_registered_jobs_only() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let job = test_job("active-secs", tempdir.path());
        let pool = worker_pool_without_servers();
        assert_eq!(pool.job_active_secs(&job.id), None);

        insert_test_context(&pool, &job, Arc::new(FileAssembler::new()));
        pool.pause_job(&job.id);
        let paused = pool.job_active_secs(&job.id).expect("registered job");
        assert!(paused >= 0.0);
        // A paused job's clock is stopped.
        assert_eq!(pool.job_active_secs(&job.id), Some(paused));

        pool.release_completed_job(&job.id);
        assert_eq!(pool.job_active_secs(&job.id), None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn repeated_completed_jobs_do_not_accumulate_file_descriptors() {
        const JOBS: usize = 64;
        const FILES_PER_JOB: usize = 8;

        let tempdir = tempfile::tempdir().expect("tempdir");
        let pool = worker_pool_without_servers();
        assert_eq!(open_fd_count_under(tempdir.path()), 0);

        for job_index in 0..JOBS {
            let job_id = format!("job-{job_index}");
            let job_dir = tempdir.path().join(&job_id);
            let assembler = Arc::new(FileAssembler::new());
            for file_index in 0..FILES_PER_JOB {
                assembler
                    .register_file(
                        &job_id,
                        &format!("file-{file_index}"),
                        job_dir.join(format!("file-{file_index}.rar")),
                        1,
                    )
                    .expect("register file");
            }
            assert_eq!(open_fd_count_under(tempdir.path()), FILES_PER_JOB);

            let job = test_job(&job_id, &job_dir);
            insert_test_context(&pool, &job, assembler);
            pool.release_completed_job(&job_id);

            assert!(!pool.has_job(&job_id));
            assert_eq!(
                open_fd_count_under(tempdir.path()),
                0,
                "completed job {job_index} retained output file descriptors"
            );
        }

        assert!(pool.job_contexts.lock().is_empty());
    }

    // -----------------------------------------------------------------------
    // ConnectionTracker (Phase 4 — semaphore-backed slots)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn connection_tracker_acquire_releases_slot_on_drop() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 2);
        let s1 = t.acquire("srv1").await.unwrap();
        let s2 = t.acquire("srv1").await.unwrap();
        assert_eq!(t.total(), 2);
        // Synchronous release on drop.
        drop(s1);
        assert_eq!(t.total(), 1);
        drop(s2);
        assert_eq!(t.total(), 0);
    }

    #[tokio::test]
    async fn connection_tracker_blocks_at_limit() {
        let t = Arc::new(ConnectionTracker::new());
        t.set_limit("srv1", "Server 1", 1);
        let _held = t.acquire("srv1").await.unwrap();

        // Third acquire on a 1-slot pool must block. Wrap with a short
        // timeout — if it does NOT time out, the cap was breached.
        let t2 = Arc::clone(&t);
        let res = tokio::time::timeout(Duration::from_millis(150), async move {
            t2.acquire("srv1").await
        })
        .await;
        assert!(
            res.is_err(),
            "second acquire should block while limit is reached"
        );
    }

    #[tokio::test]
    async fn connection_tracker_grow_in_place_lets_more_acquire() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 2);
        let _a = t.acquire("srv1").await.unwrap();
        let _b = t.acquire("srv1").await.unwrap();
        // No more capacity — but grow to 4 and we should be able to take 2
        // more without releasing the existing slots.
        t.set_limit("srv1", "Server 1", 4);
        let _c = t.acquire("srv1").await.unwrap();
        let _d = t.acquire("srv1").await.unwrap();
        assert_eq!(t.total(), 4);
    }

    #[tokio::test]
    async fn connection_tracker_shrink_marks_old_slots_stale() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 4);
        let s = t.acquire("srv1").await.unwrap();
        assert!(t.slot_is_current(&s));

        // Shrink to 1 — old semaphore is replaced.
        t.set_limit("srv1", "Server 1", 1);
        assert!(
            !t.slot_is_current(&s),
            "after shrink, the previously-acquired slot must be marked stale"
        );

        // The new pool starts empty (1 permit available, 0 in use). Old
        // permit holder is no longer counted in `total()` because its
        // semaphore is orphaned.
        assert_eq!(t.total(), 0);

        // We can still acquire from the new pool.
        let new_slot = t.acquire("srv1").await.unwrap();
        assert!(t.slot_is_current(&new_slot));
        assert_eq!(t.total(), 1);
    }

    #[tokio::test]
    async fn connection_tracker_remove_server_marks_slot_stale() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 2);
        let s = t.acquire("srv1").await.unwrap();
        assert!(t.slot_is_current(&s));

        t.remove_server("srv1");
        assert!(
            !t.slot_is_current(&s),
            "after remove_server, the slot must be marked stale"
        );
        assert_eq!(t.total(), 0);
    }

    #[tokio::test]
    async fn connection_tracker_snapshot_reflects_active_count() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 3);
        t.set_limit("srv2", "Server 2", 5);

        let _a1 = t.acquire("srv1").await.unwrap();
        let _a2 = t.acquire("srv1").await.unwrap();
        let _b1 = t.acquire("srv2").await.unwrap();

        let mut snap = t.snapshot();
        snap.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(snap.len(), 2);
        assert_eq!(snap[0], ("srv1".into(), 2, 3));
        assert_eq!(snap[1], ("srv2".into(), 1, 5));
    }

    #[tokio::test]
    async fn active_snapshot_counts_only_article_activity() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 3);

        let mut connected = t.acquire("srv1").await.unwrap();
        let _disconnected = t.acquire("srv1").await.unwrap();
        assert_eq!(t.connected_snapshot(), vec![("srv1".into(), 0, 3)]);

        connected.mark_active();
        assert_eq!(t.connected_snapshot(), vec![("srv1".into(), 1, 3)]);

        connected.mark_inactive();
        assert_eq!(t.connected_snapshot(), vec![("srv1".into(), 0, 3)]);
    }

    #[tokio::test]
    async fn activity_guard_clears_count_when_fetch_scope_ends() {
        let t = ConnectionTracker::new();
        t.set_limit("srv1", "Server 1", 1);
        let mut slot = t.acquire("srv1").await.unwrap();

        {
            let _activity = slot.activity();
            assert_eq!(t.connected_snapshot(), vec![("srv1".into(), 1, 1)]);
        }

        assert_eq!(t.connected_snapshot(), vec![("srv1".into(), 0, 1)]);
        assert_eq!(t.snapshot(), vec![("srv1".into(), 1, 1)]);
    }

    #[test]
    fn only_provider_level_errors_count_against_circuit_breaker() {
        let s = || "x".to_string();
        for e in [
            NntpError::Connection(s()),
            NntpError::Tls(s()),
            NntpError::Auth(s()),
            NntpError::AuthRequired(s()),
            NntpError::PermissionDenied(s()),
            NntpError::ServiceUnavailable(s()),
            NntpError::Timeout(s()),
        ] {
            assert!(counts_against_circuit_breaker(&e), "{e}");
        }
        for e in [
            NntpError::ArticleNotFound(s()),
            NntpError::NoSuchGroup(s()),
            NntpError::NoArticleSelected(s()),
            NntpError::Protocol(s()),
        ] {
            assert!(!counts_against_circuit_breaker(&e), "{e}");
        }
    }
}