aria2-core 0.3.5

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
//! Engine main loop: promotion/demotion, EngineCommand dispatch, and
//! deadline-driven maintenance.
//!
//! Mirrors the C++ `DownloadEngine::run()` loop structure. Each pass:
//! 1. Process incoming `EngineCommand`s (add/remove/pause/unpause/halt etc.)
//! 2. Collect completed task notifications and decrement `num_commands`
//! 3. Demote stopped groups from active to stopped results
//! 4. Promote reserved groups and spawn download tasks via `task_spawner`
//! 5. Run deadline-driven maintenance (timeouts and session auto-save)
//! 6. Check exit condition

use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};

use super::download_event_hooks::{DownloadEvent, DownloadEventHooks};
use super::engine_command::{
    EngineCommand, EngineCommandReceiver, EngineCommandTryRecvError, TaskResult,
};
use super::task_spawner::{CommandDependencies, spawn_download_task};
use crate::dns::dns_cache::DnsCache;
use crate::error::{Aria2Error, RecoverableError};
use crate::filesystem::file_allocation_man::FileAllocationMan;
use crate::ftp::FtpConnectionPool;
use crate::network::ConnectionContext;
use crate::rate_limiter::RateLimiter;
use crate::request::request_group::{DownloadResultCode, DownloadStatus, GroupId, HaltReason};
use crate::request::request_group_man::RequestGroupMan;
use crate::selector::server_stat_man::ServerStatMan;
use crate::session::auto_save_coordinator::AutoSaveCoordinator;
use crate::util::rwlock_ext::RwLockRecover;

/// Maximum number of stopped results to keep before pruning.
/// Mirrors C++ `MAX_DOWNLOAD_RESULT` (default 1000).
const MAX_STOPPED_RESULTS: usize = 1000;
const SHUTDOWN_WAIT: Duration = Duration::from_secs(5);
// forceShutdown is an emergency path. Give protocol cleanup a short bounded
// window, then abort the task so process shutdown cannot be held open by a
// broken or unresponsive protocol implementation.
const FORCE_SHUTDOWN_WAIT: Duration = Duration::from_secs(1);

fn should_mark_failed_connection(error: &Aria2Error) -> bool {
    matches!(
        error,
        Aria2Error::Network(_)
            | Aria2Error::Recoverable(
                RecoverableError::TemporaryNetworkFailure { .. } | RecoverableError::Timeout
            )
    )
}

async fn mark_failed_connection(
    dns_cache: &tokio::sync::Mutex<DnsCache>,
    error: &Aria2Error,
    context: &ConnectionContext,
    use_async_dns: bool,
) {
    if !use_async_dns || !should_mark_failed_connection(error) {
        return;
    }

    let mut dns = dns_cache.lock().await;
    dns.mark_bad_context(context);
    if !dns.has_good_address(&context.endpoint) {
        dns.remove_cached(context.endpoint.hostname(), context.endpoint.port());
    }
}

enum ProcessedTaskResult {
    Success,
    Failed(Aria2Error),
    Cancelled,
}

/// Context passed into the engine loop, holding shared state that the
/// loop needs to coordinate between EngineCommand processing, promotion,
/// demotion, and deadline-driven maintenance.
pub struct EngineLoopContext {
    /// The request group manager (active/reserved/stopped queues).
    pub group_man: Arc<RequestGroupMan>,

    /// FTP connection pool for dependency injection into download commands.
    pub ftp_pool: Arc<FtpConnectionPool>,

    /// DNS cache for dependency injection.
    pub dns_cache: Arc<tokio::sync::Mutex<DnsCache>>,

    /// Unified deadline-driven coordinator for session and control-file saves.
    pub auto_save: Option<Arc<tokio::sync::Mutex<AutoSaveCoordinator>>>,

    /// Lock-free session dirty signal used when `auto_save` is busy writing.
    pub auto_save_dirty_signal: Option<Arc<std::sync::atomic::AtomicBool>>,

    /// Download event hooks for firing on-download-start/complete/error/pause/stop.
    /// Mirrors C++ `util::executeHookByOptName()`.
    pub event_hooks: Arc<DownloadEventHooks>,

    /// File allocation manager for sequential disk pre-allocation.
    /// Mirrors C++ `DownloadEngine::fileAllocationMan_` (a `SequentialPicker`).
    /// When a download needs file allocation, the entry is queued here and
    /// processed one at a time to avoid disk thrashing.
    pub file_alloc_man: Arc<tokio::sync::RwLock<FileAllocationMan>>,

    /// Whether the engine should stay alive even with no active downloads
    /// (used for RPC listen mode). Mirrors C++ `keepRunning_`.
    pub keep_alive: bool,

    /// Shared server statistics used by URI selectors and housekeeping.
    pub server_stat_man: Arc<ServerStatMan>,

    /// Maximum age for server-stat cleanup. `None` means unlimited.
    pub server_stat_max_age: Option<Duration>,

    /// Optional server-stat output and its deadline-driven save state.
    pub server_stat_save_path: Option<PathBuf>,
    pub server_stat_save_interval: Option<Duration>,
    pub server_stat_next_save: Option<Instant>,

    /// Process-wide rate limiter shared across all downloads.
    /// When `Some`, passed to each spawned `DownloadCommand` so that
    /// `ThrottledWriter` and segment download loops enforce a global
    /// bandwidth ceiling in addition to per-download limits.
    pub global_limiter: Option<RateLimiter>,

    /// Process-wide public tracker catalog shared by BT commands.
    #[cfg(feature = "bittorrent")]
    pub public_tracker_catalog:
        Arc<aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList>,

    /// Engine-owned registry shared by all BitTorrent commands.
    #[cfg(feature = "bittorrent")]
    pub bt_registry: Arc<std::sync::RwLock<crate::engine::bt_registry::BtRegistry>>,

    /// Process-level BitTorrent TCP listener and info-hash router.
    #[cfg(feature = "bittorrent")]
    pub bt_listener: Arc<crate::engine::bt_peer_listener::BtPeerListenerManager>,

    /// Process-level Local Peer Discovery manager and receive loop.
    #[cfg(feature = "bittorrent")]
    pub lpd_manager: Arc<crate::engine::lpd_manager::LpdManager>,
}

/// Tracks a spawned download task for timeout enforcement and cleanup.
type CommandGeneration = u64;

struct RunningDownload {
    /// JoinHandle for the spawned tokio task.
    _handle: JoinHandle<()>,
    shutdown: Option<CancellationToken>,
    /// Stable identity of this command instance, independent of its GID.
    generation: CommandGeneration,
    /// Instant at which the last network payload was received.
    last_activity: Instant,
    /// Inactivity timeout. `None` means the task never times out.
    timeout: Option<Duration>,
}

/// Mark the auto-save session as dirty so the next configured save deadline
/// (subject to `save-session-interval`) actually persists state.
///
/// C++ aria2's `AutoSaveCommand` unconditionally saves every interval; our
/// `AutoSaveSession` adds a dirty gate to avoid redundant disk writes. Every
/// caller that mutates download state (queue membership, status, options,
/// progress) must flip this flag or `save_if_dirty()` never writes.
fn mark_session_dirty(ctx: &EngineLoopContext) {
    if let Some(signal) = &ctx.auto_save_dirty_signal {
        signal.store(true, std::sync::atomic::Ordering::Release);
    }
}

/// Run the main engine loop.
///
/// This function runs until:
/// - No active/reserved downloads remain AND `keep_alive` is false, OR
/// - A shutdown signal is received via `shutdown_rx`.
///
/// The loop processes `EngineCommand`s from `cmd_rx`, task completion
/// notifications from `completion_rx`, and runs deadline-driven maintenance.
pub async fn run_engine_loop(
    ctx: EngineLoopContext,
    cmd_rx: mpsc::UnboundedReceiver<EngineCommand>,
    shutdown_rx: tokio::sync::oneshot::Receiver<()>,
) {
    run_engine_loop_with_receiver(
        ctx,
        EngineCommandReceiver::from_unbounded(cmd_rx),
        shutdown_rx,
    )
    .await;
}

pub(crate) async fn run_engine_loop_with_receiver(
    mut ctx: EngineLoopContext,
    mut cmd_rx: EngineCommandReceiver,
    mut shutdown_rx: tokio::sync::oneshot::Receiver<()>,
) {
    info!("Engine loop started (event-driven dispatch)");

    let mut running_downloads: Vec<(GroupId, RunningDownload)> = Vec::new();
    let mut completed_generations: HashSet<CommandGeneration> = HashSet::new();
    let mut next_generation: CommandGeneration = 1;
    let mut halt_requested = false;
    let mut force_halt_requested = false;
    let mut shutdown_received = false;
    let mut command_closed = false;
    let mut completion_closed = false;
    let mut first_pass = true;
    let mut schedule_on_next_pass = false;

    // Completion channel: spawned tasks send (GID, TaskResult) here when done.
    let (completion_tx, mut completion_rx) =
        mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();

    loop {
        // ── 1. Process all incoming EngineCommands ───────────────────────
        // Drain the command channel before doing anything else, so that
        // batch RPC requests (e.g. addUri followed by unpause) are applied
        // atomically within the same event-processing pass.
        let commands_processed = process_engine_commands(
            &mut ctx,
            &mut cmd_rx,
            &mut running_downloads,
            &mut halt_requested,
            &mut force_halt_requested,
            &completion_tx,
        )
        .await;

        // Promote groups that were already queued before the engine started.
        // Later passes promote after completion/demotion so a requeued group
        // is scheduled without relying on a fixed-rate wake-up.
        if first_pass {
            promote_reserved_groups(
                &ctx,
                &mut running_downloads,
                halt_requested,
                force_halt_requested,
                &mut next_generation,
                &completion_tx,
            );
        }

        // ── 2. Collect completed task notifications ──────────────────────
        // Process all pending task completion messages.
        let completions_processed = process_task_completions(
            &ctx,
            &mut completion_rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        // ── 3. Demote stopped groups (active → stopped results) ──────────
        // Mirrors C++ `removeStoppedGroup()`.
        let demoted_gids = { ctx.group_man.remove_stopped_groups(Some(&ctx.event_hooks)) };

        if !demoted_gids.is_empty() {
            debug!("Demoted {} groups to stopped", demoted_gids.len());
            // Demotion moved groups to stopped results: persist the change.
            mark_session_dirty(&ctx);
            run_event_cleanup(&ctx).await;
        }

        // ── 4. Promote groups made runnable by this pass or the preceding
        // event wake-up. ──────────────────────────────────────────────────
        // A group requeued from a completion must be promoted before the
        // engine parks. The first-pass orphan requeue is deliberately left
        // for the next external event so an already-pending shutdown cannot
        // turn it into new work.
        let needs_follow_up_promotion = (!first_pass && commands_processed)
            || completions_processed
            || !demoted_gids.is_empty()
            || schedule_on_next_pass;
        if needs_follow_up_promotion {
            promote_reserved_groups(
                &ctx,
                &mut running_downloads,
                halt_requested,
                force_halt_requested,
                &mut next_generation,
                &completion_tx,
            );
        }

        first_pass = false;
        schedule_on_next_pass = false;

        // ── 5. Check exit condition ──────────────────────────────────────
        let all_done = ctx.group_man.download_finished() && running_downloads.is_empty();

        // A graceful halt must wind the engine down even in keep-alive (RPC)
        // mode. C++ achieves this because every routine command (RPC
        // listener, fill-request-group, …) returns `true` — removing itself
        // from `commands_` — once `isHaltRequested()`, so `run()`'s
        // `while (!commands_.empty())` terminates. Without this branch
        // `aria2.shutdown` would hang forever whenever `--enable-rpc` is set,
        // since `all_done && !keep_alive` can never be true there.
        let graceful_done = halt_requested && running_downloads.is_empty();

        let force_done =
            force_halt_requested && running_downloads.is_empty() && completion_rx.is_empty();
        if force_done || graceful_done || (all_done && !ctx.keep_alive) {
            if force_halt_requested {
                info!("Force halt completed, shutting down engine");
            } else if graceful_done {
                info!("Graceful halt completed, engine shutting down");
            } else {
                info!("All downloads completed, engine shutting down");
            }
            break;
        }

        // ── 6. Wait for a command, task completion, a real maintenance
        // deadline,
        // or shutdown signal. The engine stays parked while idle.
        let maintenance_wait =
            wait_for_deadline(next_maintenance_deadline(&ctx, &running_downloads).await);
        tokio::pin!(maintenance_wait);
        tokio::select! {
            command = cmd_rx.recv(), if !command_closed => {
                match command {
                    Ok(command) => {
                        let mut prefetched = PrefetchedEngineCommand {
                            first: Some(command),
                            receiver: &mut cmd_rx,
                        };
                        schedule_on_next_pass |= process_engine_commands(
                            &mut ctx,
                            &mut prefetched,
                            &mut running_downloads,
                            &mut halt_requested,
                            &mut force_halt_requested,
                            &completion_tx,
                        )
                        .await;
                    }
                    Err(EngineCommandTryRecvError::Closed) => command_closed = true,
                    Err(EngineCommandTryRecvError::Empty) => unreachable!(
                        "async engine command receive cannot return empty"
                    ),
                }
            }
            completion = completion_rx.recv(), if !completion_closed => {
                match completion {
                    Some(completion) => {
                        let mut prefetched = PrefetchedCompletion {
                            first: Some(completion),
                            receiver: &mut completion_rx,
                        };
                        schedule_on_next_pass |= process_task_completions(
                            &ctx,
                            &mut prefetched,
                            &mut running_downloads,
                            &mut completed_generations,
                        )
                        .await;
                    }
                    None => completion_closed = true,
                }
            }
            _ = &mut maintenance_wait => {
                run_deadline_maintenance(&mut ctx, &mut running_downloads).await;
            }
            Ok(_) = &mut shutdown_rx, if !shutdown_received => {
                shutdown_received = true;
                info!("Shutdown signal received");
                // Process graceful halt
                ctx.group_man
                    .halt_all(crate::request::request_group::HaltReason::ShutdownSignal);
                halt_requested = true;

                // Give running tasks a chance to finish gracefully.
                // In C++ this is handled by the next iteration detecting
                // numCommand_ == 0 on halted groups.
            }
        }
    }

    // ── Cleanup on exit ──────────────────────────────────────────────────
    // Mirrors C++ `onEndOfRun()`.
    on_end_of_run(&ctx, &mut running_downloads).await;

    info!("Engine loop exited");
}

/// Promote reserved groups and create their protocol tasks.
///
/// Promotion is kept in one helper because the engine may need to run it both
/// for groups present before startup and immediately after a completion frees
/// a slot. The latter is the event-driven replacement for the old idle scan.
fn promote_reserved_groups(
    ctx: &EngineLoopContext,
    running_downloads: &mut Vec<(GroupId, RunningDownload)>,
    halt_requested: bool,
    force_halt_requested: bool,
    next_generation: &mut CommandGeneration,
    completion_tx: &mpsc::UnboundedSender<(GroupId, CommandGeneration, TaskResult)>,
) {
    // Once a halt has been requested the engine must stop admitting new work.
    let promoted = if halt_requested || force_halt_requested {
        Vec::new()
    } else {
        ctx.group_man.fill_from_reserver()
    };

    for group in &promoted {
        let gid = group.recover().gid();
        group.recover().clear_connection_contexts();
        let generation = *next_generation;
        *next_generation = next_generation.wrapping_add(1);
        match spawn_download_task(
            Arc::clone(group),
            CommandDependencies {
                dns_cache: Arc::clone(&ctx.dns_cache),
                global_limiter: ctx.global_limiter.clone(),
                #[cfg(feature = "bittorrent")]
                public_tracker_catalog: Arc::clone(&ctx.public_tracker_catalog),
                #[cfg(feature = "bittorrent")]
                bt_registry: Arc::clone(&ctx.bt_registry),
                #[cfg(feature = "bittorrent")]
                bt_listener: Arc::clone(&ctx.bt_listener),
                #[cfg(feature = "bittorrent")]
                lpd_manager: Arc::clone(&ctx.lpd_manager),
            },
            generation,
            completion_tx.clone(),
        ) {
            Some((handle, shutdown_tx)) => {
                let timeout = group.recover().timeout();
                running_downloads.push((
                    gid,
                    RunningDownload {
                        _handle: handle,
                        shutdown: Some(shutdown_tx),
                        generation,
                        last_activity: Instant::now(),
                        timeout,
                    },
                ));
                debug!(
                    gid = gid.value(),
                    "Spawned download task for promoted group"
                );

                // Fire on-download-start hook.
                // C++: `util::executeHookByOptName(groupToAdd, e->getOption(),
                //            PREF_ON_DOWNLOAD_START)`
                ctx.event_hooks
                    .fire_event(DownloadEvent::Start, &group.recover());
            }
            None => {
                warn!(
                    gid = gid.value(),
                    "Failed to spawn download task for promoted group"
                );
                ctx.group_man
                    .fail_spawned_group(gid, "Failed to spawn download task");
            }
        }
    }

    if !promoted.is_empty() {
        debug!("Promoted {} groups from reserved to active", promoted.len());
        mark_session_dirty(ctx);
    }
}

trait EngineCommandQueue {
    fn try_command(&mut self) -> Result<EngineCommand, EngineCommandTryRecvError>;
}

impl EngineCommandQueue for EngineCommandReceiver {
    fn try_command(&mut self) -> Result<EngineCommand, EngineCommandTryRecvError> {
        self.try_recv()
    }
}

struct PrefetchedEngineCommand<'a, R> {
    first: Option<EngineCommand>,
    receiver: &'a mut R,
}

impl<R: EngineCommandQueue> EngineCommandQueue for PrefetchedEngineCommand<'_, R> {
    fn try_command(&mut self) -> Result<EngineCommand, EngineCommandTryRecvError> {
        self.first
            .take()
            .map_or_else(|| self.receiver.try_command(), Ok)
    }
}

/// Process all pending `EngineCommand` messages from the channel.
async fn process_engine_commands<R: EngineCommandQueue>(
    ctx: &mut EngineLoopContext,
    cmd_rx: &mut R,
    running_downloads: &mut Vec<(GroupId, RunningDownload)>,
    halt_requested: &mut bool,
    force_halt_requested: &mut bool,
    completion_tx: &mpsc::UnboundedSender<(GroupId, CommandGeneration, TaskResult)>,
) -> bool {
    let mut processed = false;
    while let Ok(cmd) = cmd_rx.try_command() {
        processed = true;
        // Every EngineCommand mutates session state (queue membership,
        // per-group status, or options), so mark the session dirty to make
        // the periodic auto-save persist these changes.
        mark_session_dirty(ctx);
        match cmd {
            EngineCommand::AddDownload { group } => {
                let man = &ctx.group_man;
                let gid = group.recover().gid();
                // Add to the reserved queue; the current event pass promotes
                // it immediately after command processing.
                man.add_group_arc(group);
                info!(gid = gid.value(), "Added download to reserved queue");
            }
            #[cfg(all(feature = "metalink", feature = "bittorrent"))]
            EngineCommand::AddMetalinkGraph { graph } => {
                let man = &ctx.group_man;
                match man.add_metalink_graph(graph) {
                    Ok((metadata_gid, payload_gid)) => info!(
                        metadata_gid = metadata_gid.value(),
                        payload_gid = payload_gid.value(),
                        "Added Metalink graph to reserved queue"
                    ),
                    Err(error) => warn!(%error, "Failed to add Metalink graph"),
                }
            }

            EngineCommand::RemoveDownload { gid } => {
                let man = &ctx.group_man;
                if let Err(e) = man.remove_group(gid) {
                    warn!(gid = gid.value(), error = %e, "Failed to remove download");
                    continue;
                }
                // Let the command observe the RequestGroup halt signal. This
                // preserves the protocol-owned cleanup seam: HTTP downloaders
                // cancel requests, flush queued writes, and save progress
                // before reporting the user removal.
            }

            EngineCommand::ForceRemoveDownload { gid } => {
                let man = &ctx.group_man;
                if let Err(e) = man.force_remove_group(gid) {
                    warn!(gid = gid.value(), error = %e, "Failed to force-remove download");
                    continue;
                }
                // Force removal still travels through the command's halt
                // check so protocol-specific writers can persist a coherent
                // checkpoint before the task is accounted as removed.
            }

            EngineCommand::Pause { gid } => {
                let man = &ctx.group_man;
                let should_apply = man.find_group(gid).is_some_and(|group| {
                    matches!(
                        group.recover().status(),
                        DownloadStatus::Active | DownloadStatus::Waiting
                    )
                });
                if should_apply && let Err(e) = man.pause_group(gid) {
                    warn!(gid = gid.value(), error = %e, "Failed to pause download");
                }
            }

            EngineCommand::ForcePause { gid } => {
                let man = &ctx.group_man;
                let should_apply = man.find_group(gid).is_some_and(|group| {
                    matches!(
                        group.recover().status(),
                        DownloadStatus::Active | DownloadStatus::Waiting
                    )
                });
                if should_apply && let Err(e) = man.force_pause_group(gid) {
                    warn!(gid = gid.value(), error = %e, "Failed to force-pause download");
                }
                // NOTE: the running task is intentionally NOT aborted here.
                // force_pause_group() marks the group Paused; the download
                // loop observes this via check_cancelled() and terminates by
                // itself. Aborting the handle would skip the completion
                // notification, leaving num_commands stuck above 0 so the
                // paused group could never be re-queued to the reserved list.
            }

            EngineCommand::Unpause { gid } => {
                let man = &ctx.group_man;
                let should_apply = man
                    .find_group(gid)
                    .is_some_and(|group| group.recover().status().is_paused());
                if should_apply && let Err(e) = man.unpause_group(gid) {
                    warn!(gid = gid.value(), error = %e, "Failed to unpause download");
                }
            }

            EngineCommand::TaskCompleted { gid, result: _ } => {
                // NOTE: TaskCompleted via the engine command channel is NOT the
                // primary completion path. Spawned tasks report completion via
                // the `completion_tx` channel, which is handled by
                // `process_task_completions`. This variant exists for external
                // callers (e.g., RPC) that need to signal completion without
                // going through the completion channel. To avoid a double
                // decrement of `num_commands`, we do NOT decrement here.
                debug!(
                    gid = gid.value(),
                    "Received TaskCompleted via engine command channel (external signal)"
                );
            }

            EngineCommand::PauseAll => {
                let man = &ctx.group_man;
                man.pause_all();
            }

            EngineCommand::ForcePauseAll => {
                let man = &ctx.group_man;
                man.force_pause_all();
                // Like ForcePause, tasks are left to terminate on their own
                // via the Paused status so num_commands stays balanced and
                // the groups can return to the reserved queue.
            }

            EngineCommand::UnpauseAll => {
                let man = &ctx.group_man;
                man.unpause_all();
            }

            EngineCommand::HaltAll { reason } => {
                let man = &ctx.group_man;
                man.halt_all(reason);
                *halt_requested = true;
            }

            EngineCommand::ForceHaltAll { reason } => {
                let man = &ctx.group_man;
                man.force_halt_all(reason);
                let removed = man.force_remove_reserved();
                if removed > 0 {
                    mark_session_dirty(ctx);
                }
                *force_halt_requested = true;

                // Allocation waiters are not driven by the protocol
                // cancellation token. Wake them before waiting for the
                // owning task, then repeat after the wait for allocations
                // queued during task teardown.
                cancel_running_file_allocations(ctx, running_downloads).await;
                for (gid, running) in running_downloads.iter_mut() {
                    let generation = running.generation;
                    let completed = request_shutdown_and_wait(running, FORCE_SHUTDOWN_WAIT).await;
                    if !completed {
                        // A timed-out task is aborted and cannot publish its
                        // normal completion. Feed the same completion path so
                        // command accounting and group demotion stay correct.
                        let _ = completion_tx.send((*gid, generation, TaskResult::Cancelled));
                    }
                }
                cancel_running_file_allocations(ctx, running_downloads).await;
                // Every entry has either completed or been explicitly
                // aborted above. The completion queue still owns lifecycle
                // accounting; removing the handles here lets the engine
                // reach the force-halt exit check in the same pass.
                running_downloads.clear();
            }

            EngineCommand::SetMaxConcurrent { max } => {
                let man = &ctx.group_man;
                let old_max = man.max_concurrent();
                man.set_max_concurrent(max);
                info!(
                    "Max concurrent downloads set to {}",
                    if max == 0 {
                        "unlimited".to_string()
                    } else {
                        max.to_string()
                    }
                );

                // Mirrors C++ `RequestGroupMan::reduceActiveDownloadsToLimit()`.
                // When the limit is reduced at runtime (via changeGlobalOption),
                // immediately pause excess active downloads.
                if max > 0 && (old_max == 0 || (max as usize) < old_max) {
                    let paused = man.reduce_to_limit();
                    if paused > 0 {
                        info!(
                            paused,
                            "Paused excess active downloads after max-concurrent reduction"
                        );
                    }
                }
            }

            EngineCommand::SetGlobalRateLimit {
                download_limit,
                upload_limit,
            } => {
                let limiter = ctx
                    .global_limiter
                    .get_or_insert_with(RateLimiter::unlimited);
                limiter.set_download_rate(download_limit);
                limiter.set_upload_rate(upload_limit);

                // Keep the manager's option snapshot aligned with the live
                // limiter. This is also used by status/reporting code.
                let man = &ctx.group_man;
                man.set_global_speed_limit(download_limit, upload_limit);
                info!(
                    download_limit = ?download_limit,
                    upload_limit = ?upload_limit,
                    "Global speed limits updated"
                );
            }

            #[cfg(feature = "bittorrent")]
            EngineCommand::SetPublicTrackerSources { sources } => {
                let mut config = ctx.public_tracker_catalog.config().await;
                config.sources = sources
                    .split([',', '\n'])
                    .map(str::trim)
                    .filter(|source| !source.is_empty())
                    .map(str::to_string)
                    .collect();
                ctx.public_tracker_catalog.set_config(config).await;
                info!("Public tracker sources updated at runtime");
            }

            #[cfg(feature = "bittorrent")]
            EngineCommand::SetPublicTrackerUpdateInterval { seconds } => {
                let mut config = ctx.public_tracker_catalog.config().await;
                config.update_interval = Duration::from_secs(seconds.max(1));
                ctx.public_tracker_catalog.set_config(config).await;
                info!(seconds, "Public tracker update interval changed at runtime");
            }

            #[cfg(feature = "bittorrent")]
            EngineCommand::SetPublicTrackersEnabled { enabled } => {
                let mut config = ctx.public_tracker_catalog.config().await;
                config.enabled = enabled;
                ctx.public_tracker_catalog.set_config(config).await;
                info!(
                    enabled,
                    "Public tracker catalog enabled state changed at runtime"
                );
            }
        }
    }
    processed
}

/// Process all pending task completion notifications.
fn map_error_code(error: &Aria2Error) -> DownloadResultCode {
    match error {
        Aria2Error::Recoverable(RecoverableError::Timeout) => DownloadResultCode::TimeOut,
        Aria2Error::Checksum(_) => DownloadResultCode::ChecksumError,
        Aria2Error::JsonParse(_) => DownloadResultCode::JsonParseError,
        Aria2Error::MetalinkParse(_) => DownloadResultCode::MetalinkParseError,
        Aria2Error::BencodeParse(_) => DownloadResultCode::BencodeParseError,
        Aria2Error::BittorrentParse(_) => DownloadResultCode::BittorrentParseError,
        Aria2Error::MagnetParse(_) => DownloadResultCode::MagnetParseError,
        Aria2Error::Recoverable(RecoverableError::CannotResume) => DownloadResultCode::CannotResume,
        Aria2Error::FtpProtocol(_) => DownloadResultCode::FtpProtocolError,
        Aria2Error::HttpProtocol(_) => DownloadResultCode::HttpProtocolError,
        Aria2Error::Recoverable(RecoverableError::FtpProtocolError { .. }) => {
            DownloadResultCode::FtpProtocolError
        }
        Aria2Error::Recoverable(RecoverableError::HttpProtocolError { .. }) => {
            DownloadResultCode::HttpProtocolError
        }
        Aria2Error::Recoverable(RecoverableError::ResourceNotFound) => {
            DownloadResultCode::ResourceNotFound
        }
        Aria2Error::Recoverable(RecoverableError::MaxFileNotFound) => {
            DownloadResultCode::MaxFileNotFound
        }
        Aria2Error::Recoverable(RecoverableError::HttpAuthFailed { .. }) => {
            DownloadResultCode::HttpAuthFailed
        }
        Aria2Error::Recoverable(RecoverableError::HttpTooManyRedirects { .. }) => {
            DownloadResultCode::HttpTooManyRedirects
        }
        Aria2Error::Recoverable(RecoverableError::ServerError { code })
            if *code == 401 || *code == 407 =>
        {
            DownloadResultCode::HttpAuthFailed
        }
        Aria2Error::Recoverable(RecoverableError::ServerError { code })
            if matches!(*code, 502..=504) =>
        {
            DownloadResultCode::HttpServiceUnavailable
        }
        Aria2Error::Recoverable(RecoverableError::ServerError { code }) if *code == 404 => {
            DownloadResultCode::ResourceNotFound
        }
        Aria2Error::Recoverable(RecoverableError::ServerError { code }) if *code == 500 => {
            DownloadResultCode::HttpProtocolError
        }
        Aria2Error::Recoverable(RecoverableError::ServerError { code }) if *code == 503 => {
            DownloadResultCode::HttpServiceUnavailable
        }
        Aria2Error::Recoverable(RecoverableError::ServerError { .. }) => {
            DownloadResultCode::NetworkProblem
        }
        Aria2Error::Network(_) => DownloadResultCode::NetworkProblem,
        Aria2Error::FileOpen(_) => DownloadResultCode::FileOpenError,
        Aria2Error::FileCreate(_) => DownloadResultCode::FileCreateError,
        Aria2Error::FileIo(_) => DownloadResultCode::FileIoError,
        Aria2Error::DirCreate(_) => DownloadResultCode::DirCreateError,
        Aria2Error::NameResolve(_) => DownloadResultCode::NameResolveError,
        Aria2Error::Io(_) => DownloadResultCode::FileIoError,
        Aria2Error::InvalidArgument(_) => DownloadResultCode::OptionError,
        Aria2Error::Parse(_) => DownloadResultCode::UnknownError,
        Aria2Error::Fatal(crate::error::FatalError::Config(_)) => DownloadResultCode::OptionError,
        Aria2Error::Fatal(crate::error::FatalError::DiskSpaceExhausted) => {
            DownloadResultCode::NotEnoughDiskSpace
        }
        Aria2Error::Recoverable(_) => DownloadResultCode::NetworkProblem,
        _ => DownloadResultCode::UnknownError,
    }
}

trait CompletionQueue {
    fn try_completion(&mut self) -> Result<(GroupId, CommandGeneration, TaskResult), ()>;
}

impl CompletionQueue for mpsc::Receiver<(GroupId, CommandGeneration, TaskResult)> {
    fn try_completion(&mut self) -> Result<(GroupId, CommandGeneration, TaskResult), ()> {
        mpsc::Receiver::try_recv(self).map_err(|_| ())
    }
}

impl CompletionQueue for mpsc::UnboundedReceiver<(GroupId, CommandGeneration, TaskResult)> {
    fn try_completion(&mut self) -> Result<(GroupId, CommandGeneration, TaskResult), ()> {
        mpsc::UnboundedReceiver::try_recv(self).map_err(|_| ())
    }
}

struct PrefetchedCompletion<'a, R> {
    first: Option<(GroupId, CommandGeneration, TaskResult)>,
    receiver: &'a mut R,
}

impl<R: CompletionQueue> CompletionQueue for PrefetchedCompletion<'_, R> {
    fn try_completion(&mut self) -> Result<(GroupId, CommandGeneration, TaskResult), ()> {
        self.first
            .take()
            .map_or_else(|| self.receiver.try_completion(), Ok)
    }
}

async fn process_task_completions<R: CompletionQueue>(
    ctx: &EngineLoopContext,
    completion_rx: &mut R,
    running_downloads: &mut Vec<(GroupId, RunningDownload)>,
    completed_generations: &mut HashSet<CommandGeneration>,
) -> bool {
    let mut processed = false;
    while let Ok((gid, generation, result)) = completion_rx.try_completion() {
        // A task may race with force-remove/timeout cleanup and publish more
        // than one terminal notification. Account for exactly one completion.
        if !completed_generations.insert(generation) {
            debug!(
                gid = gid.value(),
                generation, "Ignoring duplicate task completion"
            );
            continue;
        }
        processed = true;

        // A task finished: its status/progress changed, so persist it.
        mark_session_dirty(ctx);

        // Remove only this command instance. A RequestGroup may have several
        // active commands, just as C++ tracks several AbstractCommand objects
        // under one RequestGroup.
        running_downloads.retain(|(id, running)| *id != gid || running.generation != generation);

        // Decrement num_commands and update group status.
        let man = &ctx.group_man;
        if let Some(group) = man.find_group(gid) {
            let prev = group.recover().dec_commands();
            let last_command = prev == 1;
            debug!(
                gid = gid.value(),
                prev, last_command, "Task completed, decremented num_commands"
            );

            let result = match result {
                TaskResult::FailedWithContext {
                    error,
                    connection_context,
                } => {
                    let use_async_dns = group.recover().options().async_dns;
                    mark_failed_connection(
                        &ctx.dns_cache,
                        &error,
                        &connection_context,
                        use_async_dns,
                    )
                    .await;
                    ProcessedTaskResult::Failed(error)
                }
                TaskResult::Success => ProcessedTaskResult::Success,
                TaskResult::Failed(error) => ProcessedTaskResult::Failed(error),
                TaskResult::Cancelled => ProcessedTaskResult::Cancelled,
            };

            match result {
                ProcessedTaskResult::Success if last_command => {
                    let had_failure = group
                        .recover()
                        .command_failure
                        .load(std::sync::atomic::Ordering::Acquire);
                    if had_failure {
                        let message = group.recover().get_last_error_message();
                        let code = group.recover().get_last_error_code();
                        group.recover().mark_error_with_code(code, message);
                    } else {
                        let group_state = group.recover();
                        let was_pause_requested =
                            group_state.is_pause_requested() || group_state.is_paused_flag();
                        let halt_reason = group_state.get_halt_reason();
                        drop(group_state);

                        if matches!(halt_reason, HaltReason::None) && was_pause_requested {
                            // A pause can race with a command finishing cleanly.
                            // Preserve the resumable state instead of turning
                            // the pause into a terminal completion.
                            group.recover().mark_paused();
                        } else {
                            match halt_reason {
                                crate::request::request_group::HaltReason::UserRequest => {
                                    group.recover().mark_removed();
                                }
                                crate::request::request_group::HaltReason::Timeout => {
                                    group.recover().mark_timeout();
                                }
                                crate::request::request_group::HaltReason::ShutdownSignal => {}
                                crate::request::request_group::HaltReason::None => {
                                    group.recover_mut().mark_complete();
                                }
                            }
                        }
                    }
                }
                ProcessedTaskResult::Success => {
                    // C++ removes a RequestGroup only after its final
                    // AbstractCommand is destroyed. Keep the group active
                    // while other command instances are still running.
                }
                ProcessedTaskResult::Failed(e) if !last_command => {
                    // A non-final command failure is recorded for the group,
                    // but terminal state is deferred until all commands have
                    // exited, matching C++ numCommand_ semantics.
                    let message = e.to_string();
                    let code = map_error_code(&e);
                    group.recover().set_last_error(code, message);
                    group
                        .recover()
                        .command_failure
                        .store(true, std::sync::atomic::Ordering::Release);
                }
                ProcessedTaskResult::Failed(e) => {
                    // Handle failures from the final command, including pause-induced
                    // termination, before treating them as errors.
                    // (`aria2.pause` / `aria2.forcePause`
                    // marks the group Paused and the download loop aborts via
                    // check_cancelled) must leave the group Paused — resumable —
                    // rather than recording an Error that can never be unpaused.
                    // Mirrors C++ where pause-requested groups return to the
                    // reserved queue.
                    let group_state = group.recover();
                    let was_pause_requested =
                        group_state.is_pause_requested() || group_state.is_paused_flag();
                    let is_pause_error = matches!(
                        &e,
                        Aria2Error::DownloadFailed(msg) if msg == "Download paused"
                    );
                    let halt_reason = group_state.get_halt_reason();
                    drop(group_state);

                    match halt_reason {
                        // A user removal is terminal even when a pause command
                        // reached the group first. The halt reason is the
                        // stronger lifecycle signal and must win over the
                        // resumable Paused status.
                        HaltReason::UserRequest => group.recover().mark_removed(),
                        HaltReason::Timeout => group.recover().mark_timeout(),
                        HaltReason::ShutdownSignal => {
                            // A shutdown halt remains non-terminal so its
                            // result maps to IN_PROGRESS after cleanup.
                        }
                        HaltReason::None if was_pause_requested => {
                            group.recover_mut().mark_paused();
                        }
                        HaltReason::None if is_pause_error => {
                            // A pause was requested and then undone (`unpause`)
                            // before the task fully exited. Leave the group
                            // Waiting so the demotion layer re-queues it and
                            // promotion re-spawns the download.
                            let status = group.recover().status();
                            if !matches!(
                                status,
                                DownloadStatus::Complete
                                    | DownloadStatus::Error(_)
                                    | DownloadStatus::Removed
                            ) {
                                group.recover().mark_waiting();
                            }
                        }
                        HaltReason::None => group
                            .recover()
                            .mark_error_with_code(map_error_code(&e), e.to_string()),
                    }
                    group
                        .recover()
                        .command_failure
                        .store(false, std::sync::atomic::Ordering::Release);
                }
                ProcessedTaskResult::Cancelled => {
                    // Synthetic cancellation is emitted before Tokio abort, so
                    // finalize the group here rather than relying on the
                    // cancelled task to mutate its status.
                    let group_state = group.recover();
                    let was_pause_requested =
                        group_state.is_pause_requested() || group_state.is_paused_flag();
                    let halt_reason = group_state.get_halt_reason();
                    drop(group_state);

                    if matches!(halt_reason, HaltReason::UserRequest | HaltReason::Timeout) {
                        // Removal/timeout is terminal even if the task was
                        // paused when the force-halt arrived.
                        if last_command {
                            match halt_reason {
                                HaltReason::UserRequest => group.recover().mark_removed(),
                                HaltReason::Timeout => group.recover().mark_timeout(),
                                _ => unreachable!(),
                            }
                        } else {
                            group
                                .recover()
                                .command_failure
                                .store(true, std::sync::atomic::Ordering::Release);
                        }
                    } else if was_pause_requested {
                        group.recover_mut().mark_paused();
                    } else if !last_command {
                        group
                            .recover()
                            .command_failure
                            .store(true, std::sync::atomic::Ordering::Release);
                    }
                }
            }
        }
    }
    processed
}

/// Return the earliest maintenance deadline that can be derived from live
/// engine state. With no inactivity timeout and no pending save, the engine has
/// no maintenance timer and waits only for notifications.
async fn next_maintenance_deadline(
    ctx: &EngineLoopContext,
    running_downloads: &[(GroupId, RunningDownload)],
) -> Option<Instant> {
    let timeout_deadline = running_downloads
        .iter()
        .filter_map(|(_, running)| {
            running
                .timeout
                .and_then(|timeout| running.last_activity.checked_add(timeout))
        })
        .min();

    let has_pending_downloads = !ctx.group_man.download_finished() || !running_downloads.is_empty();
    let save_deadline = if let Some(auto_save) = &ctx.auto_save {
        let save = auto_save.lock().await;
        save.next_deadline(has_pending_downloads)
    } else {
        None
    };

    [timeout_deadline, save_deadline]
        .into_iter()
        .flatten()
        .chain(ctx.server_stat_next_save)
        .min()
}

async fn wait_for_deadline(deadline: Option<Instant>) {
    match deadline {
        Some(deadline) => {
            tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;
        }
        None => std::future::pending::<()>().await,
    }
}

/// Run maintenance work whose deadline has fired.
///
/// Timeouts and both persistence features are scheduled at their configured
/// deadlines. There is deliberately no fixed-rate scan here: after the work
/// is handled, the next loop iteration recomputes the next actual deadline.
async fn run_deadline_maintenance(
    ctx: &mut EngineLoopContext,
    running_downloads: &mut [(GroupId, RunningDownload)],
) {
    // ── Timeout enforcement ──────────────────────────────────────────────
    // Abort tasks whose configured inactivity timeout has elapsed. The
    // timestamp comes from the protocol data path, not from disk progress;
    // payload may be buffered, verified, or waiting for a writer.
    let now = Instant::now();
    let mut timed_out = Vec::new();
    for (gid, rd) in running_downloads.iter_mut() {
        let last_network_activity = ctx
            .group_man
            .find_group(*gid)
            .map(|group| group.recover().last_network_activity());
        if let Some(last_network_activity) = last_network_activity
            && last_network_activity > rd.last_activity
        {
            rd.last_activity = last_network_activity;
        }

        if let Some(timeout) = rd.timeout
            && now.duration_since(rd.last_activity) >= timeout
        {
            // The group is now responsible for graceful shutdown. Clear the
            // deadline so a slow cleanup cannot turn the event loop into a
            // tight retry loop while the task winds down.
            rd.timeout = None;
            timed_out.push(*gid);
        }
    }

    if !timed_out.is_empty() {
        let man = &ctx.group_man;
        for gid in timed_out {
            if let Some(group) = man.get_group(gid) {
                let request_context = group.recover().latest_connection_context();
                let uris = group.recover().get_all_uris();
                if let Some(uri) = uris.first()
                    && let Ok(parsed) = reqwest::Url::parse(uri)
                    && let Some(host) = parsed.host_str()
                {
                    let protocol = parsed.scheme().to_ascii_lowercase();
                    ctx.server_stat_man
                        .mark_failure_with_protocol(host, &protocol, 408);
                    if let Some(context) = request_context
                        && group.recover().options().async_dns
                    {
                        let mut dns = ctx.dns_cache.lock().await;
                        dns.mark_bad_context(&context);
                        if !dns.has_good_address(&context.endpoint) {
                            dns.remove_cached(context.endpoint.hostname(), context.endpoint.port());
                        }
                    }
                }
            }
            if man.timeout_group(gid) {
                // Timeout is a graceful halt: the command observes the halt
                // flag, flushes its writer, saves resumable progress, and
                // publishes the single completion used for accounting. Do not
                // abort here; aborting would bypass protocol-specific cleanup
                // and can leave buffered bytes newer than the control file.
                warn!(
                    gid = gid.value(),
                    "Download task timed out, requesting graceful halt"
                );
            }
        }
    }

    // ── Unified persistence deadlines ───────────────────────────────────
    let has_pending_downloads = !ctx.group_man.download_finished() || !running_downloads.is_empty();
    if let Some(ref auto_save) = ctx.auto_save {
        let mut save = auto_save.lock().await;
        save.run_due(has_pending_downloads).await;
    }

    if let (Some(path), Some(interval), Some(deadline)) = (
        ctx.server_stat_save_path.as_ref(),
        ctx.server_stat_save_interval,
        ctx.server_stat_next_save,
    ) && now >= deadline
    {
        ctx.server_stat_next_save = Some(now + interval);
        match ctx.server_stat_man.save_to_file_async(path).await {
            Ok(count) => debug!(count, path = %path.display(), "Saved server statistics"),
            Err(error) => warn!(%error, path = %path.display(), "Failed to save server statistics"),
        }
    }
}

/// Perform cleanup that is caused by a completed download event.
///
/// These stores are bounded or event-owned, so scanning them on every idle
/// engine wake is unnecessary. A demotion is the natural point to prune old
/// results, stale server statistics, and idle FTP connections.
async fn run_event_cleanup(ctx: &EngineLoopContext) {
    let pruned = ctx.group_man.prune_stopped_results(MAX_STOPPED_RESULTS);
    if pruned > 0 {
        debug!("Pruned {} excess stopped results", pruned);
    }

    // aria2_original removes statistics older than the configured freshness
    // window from the long-lived ServerStatMan.
    let stale_stats = ctx
        .server_stat_max_age
        .map(|max_age| ctx.server_stat_man.remove_stale(max_age))
        .unwrap_or(0);
    if stale_stats > 0 {
        debug!("Removed {} stale server statistics", stale_stats);
    }

    // reqwest owns the HTTP/TLS pool and enforces its idle timeout internally.
    // The FTP pool is engine-owned, so clean it when a download event gives
    // the engine a useful point to do the bounded scan.
    let evicted = ctx.ftp_pool.cleanup_stale_count().await;
    if evicted > 0 {
        debug!("Evicted {} stale FTP connections", evicted);
    }
}

async fn request_shutdown_and_wait(running: &mut RunningDownload, wait: Duration) -> bool {
    if let Some(shutdown) = running.shutdown.take() {
        shutdown.cancel();
    }
    let completed = match tokio::time::timeout(wait, &mut running._handle).await {
        Ok(Ok(())) => true,
        Ok(Err(error)) => {
            warn!(%error, "Download task panicked during shutdown");
            false
        }
        Err(_) => {
            warn!("Download task shutdown timed out");
            running._handle.abort();
            false
        }
    };
    if !completed {
        // A previously-consumed shutdown token must not turn cleanup into a
        // no-op. Force the same bounded lifecycle regardless of token state.
        running._handle.abort();
    }
    completed
}

/// Wake allocation waiters before waiting for their owning download task.
///
/// A download command may be suspended inside `enqueue_path` or
/// `enqueue_multi`. Those functions wait on the allocation manager's result,
/// so cancelling the protocol task first cannot wake them promptly.
async fn cancel_running_file_allocations(
    ctx: &EngineLoopContext,
    running_downloads: &[(GroupId, RunningDownload)],
) {
    for (gid, _) in running_downloads {
        let cancelled =
            crate::filesystem::file_allocation_man::cancel_gid(&ctx.file_alloc_man, gid.value())
                .await;
        if cancelled > 0 {
            debug!(
                gid = gid.value(),
                cancelled, "Cancelled file allocations for running task"
            );
        }
    }
}

/// Cleanup on engine exit.
///
/// Mirrors C++ `onEndOfRun()`: remove stopped groups, close files, save.
async fn on_end_of_run(
    ctx: &EngineLoopContext,
    running_downloads: &mut Vec<(GroupId, RunningDownload)>,
) {
    info!("Engine loop cleanup: removing stopped groups and saving state");

    // Cancel only allocations owned by this engine. The allocation manager is
    // process-wide, so cancelling every entry here would interrupt a
    // download running in another engine.
    let allocation_gids: Vec<u64> = running_downloads
        .iter()
        .map(|(gid, _)| gid.value())
        .collect();
    for gid in allocation_gids {
        let cancelled =
            crate::filesystem::file_allocation_man::cancel_gid(&ctx.file_alloc_man, gid).await;
        if cancelled > 0 {
            debug!(
                gid,
                cancelled, "Cancelled file allocations during engine cleanup"
            );
        }
    }

    // Demote any remaining stopped groups.
    let demoted = {
        let man = &ctx.group_man;
        man.remove_stopped_groups(Some(&ctx.event_hooks))
    };
    if !demoted.is_empty() {
        info!("Demoted {} final groups on shutdown", demoted.len());
    }

    // Request protocol-level shutdown and wait for each task before dropping
    // the engine, bounded so a broken command cannot hang engine teardown.
    for (gid, mut rd) in running_downloads.drain(..) {
        let completed = request_shutdown_and_wait(&mut rd, SHUTDOWN_WAIT).await;
        debug!(
            gid = gid.value(),
            completed, "Finished running task shutdown"
        );
    }

    #[cfg(feature = "bittorrent")]
    {
        ctx.lpd_manager.stop_background_announce();
        ctx.lpd_manager.stop_receive_loop().await;
    }

    // Final control-file and session saves.
    if let Some(ref auto_save) = ctx.auto_save {
        let mut save = auto_save.lock().await;
        save.force_save().await;
    }

    if let Some(path) = &ctx.server_stat_save_path {
        match ctx.server_stat_man.save_to_file_async(path).await {
            Ok(count) => {
                debug!(count, path = %path.display(), "Saved server statistics on shutdown")
            }
            Err(error) => {
                warn!(%error, path = %path.display(), "Failed to save server statistics on shutdown")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::request_group::{DownloadOptions, DownloadStatus, HaltReason};

    /// Build a context with no downloads queued. `keep_alive` mirrors
    /// `--enable-rpc`, which is where the halt semantics used to break.
    fn test_ctx(keep_alive: bool) -> EngineLoopContext {
        EngineLoopContext {
            group_man: Arc::new(RequestGroupMan::new()),
            ftp_pool: Arc::new(FtpConnectionPool::new(1)),
            dns_cache: Arc::new(tokio::sync::Mutex::new(DnsCache::new())),
            auto_save: None,
            auto_save_dirty_signal: None,
            event_hooks: Arc::new(DownloadEventHooks::new()),
            file_alloc_man: Arc::new(tokio::sync::RwLock::new(FileAllocationMan::new())),
            keep_alive,
            server_stat_man: ServerStatMan::shared().clone(),
            server_stat_max_age: Some(Duration::from_secs(24 * 60 * 60)),
            server_stat_save_path: None,
            server_stat_save_interval: None,
            server_stat_next_save: None,
            global_limiter: None,
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: Arc::new(
                aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList::new(),
            ),
            #[cfg(feature = "bittorrent")]
            bt_registry: Arc::new(std::sync::RwLock::new(
                crate::engine::bt_registry::BtRegistry::new(),
            )),
            #[cfg(feature = "bittorrent")]
            bt_listener: Arc::new(crate::engine::bt_peer_listener::BtPeerListenerManager::new()),
            #[cfg(feature = "bittorrent")]
            lpd_manager: Arc::new(crate::engine::lpd_manager::LpdManager::new()),
        }
    }

    /// Drive the loop until it exits, failing the test if it outlives
    /// `budget`. Guards the exact regression this suite exists for: a halt
    /// that never converges would otherwise hang CI instead of failing.
    async fn run_until_exit(
        ctx: EngineLoopContext,
        cmd_rx: mpsc::UnboundedReceiver<EngineCommand>,
        shutdown_rx: tokio::sync::oneshot::Receiver<()>,
        budget: Duration,
    ) {
        let loop_fut = run_engine_loop(ctx, cmd_rx, shutdown_rx);
        tokio::time::timeout(budget, loop_fut)
            .await
            .expect("engine loop failed to terminate after halt");
    }

    #[tokio::test]
    async fn graceful_halt_exits_even_in_keep_alive_mode() {
        // Regression: `halt_requested` used to be write-only, so the exit
        // condition `(all_done && !keep_alive) || force_halt` could never fire
        // under `--enable-rpc` and `aria2.shutdown` hung forever.
        let (tx, rx) = mpsc::unbounded_channel();
        let (_sd_tx, sd_rx) = tokio::sync::oneshot::channel();

        tx.send(EngineCommand::HaltAll {
            reason: HaltReason::ShutdownSignal,
        })
        .unwrap();

        run_until_exit(test_ctx(true), rx, sd_rx, Duration::from_secs(5)).await;
    }

    #[tokio::test]
    async fn force_halt_exits_in_keep_alive_mode() {
        let (tx, rx) = mpsc::unbounded_channel();
        let (_sd_tx, sd_rx) = tokio::sync::oneshot::channel();

        tx.send(EngineCommand::ForceHaltAll {
            reason: HaltReason::ShutdownSignal,
        })
        .unwrap();

        run_until_exit(test_ctx(true), rx, sd_rx, Duration::from_secs(5)).await;
    }

    #[tokio::test]
    async fn force_halt_removes_reserved_groups_before_exit() {
        let ctx = test_ctx(true);
        let gid = ctx
            .group_man
            .add_group(
                vec!["http://example.com/queued-before-force-halt.bin".to_string()],
                DownloadOptions::default(),
            )
            .unwrap();
        let group_man = Arc::clone(&ctx.group_man);

        let (tx, rx) = mpsc::unbounded_channel();
        let (_sd_tx, sd_rx) = tokio::sync::oneshot::channel();
        tx.send(EngineCommand::ForceHaltAll {
            reason: HaltReason::ShutdownSignal,
        })
        .unwrap();

        run_until_exit(ctx, rx, sd_rx, Duration::from_secs(5)).await;

        assert_eq!(group_man.count(), 0, "force halt must remove queued groups");
        assert!(group_man.find_group(gid).is_none());
        assert_eq!(group_man.stopped_results_len(), 1);
        let result = group_man
            .find_stopped_result(&gid.to_hex_string())
            .expect("queued force-halted group should have a stopped result");
        assert_eq!(result.status, DownloadStatus::Removed);
        assert_eq!(result.code, DownloadResultCode::Removed);
    }

    #[tokio::test]
    async fn force_halt_wakes_file_allocation_waiter_before_protocol_timeout() {
        use crate::filesystem::file_allocation::AllocationStrategy;
        use crate::filesystem::file_allocation_man::enqueue_path;
        use tokio::sync::oneshot;

        let mut ctx = test_ctx(true);
        let file_alloc_man = Arc::new(tokio::sync::RwLock::new(FileAllocationMan::new()));
        ctx.file_alloc_man = Arc::clone(&file_alloc_man);
        let gid = GroupId::new(703);
        let path = std::env::temp_dir().join(format!(
            "aria2-force-halt-allocation-{}",
            std::process::id()
        ));
        let (done_tx, done_rx) = oneshot::channel();
        let allocation_task = tokio::spawn({
            let file_alloc_man = Arc::clone(&file_alloc_man);
            async move {
                let result = enqueue_path(
                    &file_alloc_man,
                    &path,
                    4096,
                    AllocationStrategy::Trunc,
                    false,
                    gid.value(),
                )
                .await;
                let _ = done_tx.send(result.is_err());
            }
        });

        tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                if file_alloc_man.read().await.is_queued_gid(gid.value()) {
                    break;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("allocation waiter should enter the queue");

        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
        cmd_tx
            .send(EngineCommand::ForceHaltAll {
                reason: HaltReason::ShutdownSignal,
            })
            .unwrap();
        let mut cmd_rx = EngineCommandReceiver::from_unbounded(cmd_rx);
        let (completion_tx, _completion_rx) = mpsc::unbounded_channel();
        let mut running_downloads = vec![(
            gid,
            RunningDownload {
                _handle: allocation_task,
                shutdown: Some(CancellationToken::new()),
                generation: 1,
                last_activity: Instant::now(),
                timeout: None,
            },
        )];
        let mut halt_requested = false;
        let mut force_halt_requested = false;

        tokio::time::timeout(
            Duration::from_millis(500),
            process_engine_commands(
                &mut ctx,
                &mut cmd_rx,
                &mut running_downloads,
                &mut halt_requested,
                &mut force_halt_requested,
                &completion_tx,
            ),
        )
        .await
        .expect("force halt must wake allocation waiters before timeout");

        assert!(
            done_rx
                .await
                .expect("allocation task should report cancellation")
        );
        assert!(running_downloads.is_empty());
        assert!(!file_alloc_man.read().await.is_queued_gid(gid.value()));
    }

    #[tokio::test]
    async fn force_halt_accounts_for_aborted_running_task() {
        let mut ctx = test_ctx(true);
        let gid = ctx
            .group_man
            .add_group(
                vec!["http://example.com/force-halt-running.bin".to_string()],
                DownloadOptions::default(),
            )
            .unwrap();
        let group = ctx.group_man.fill_from_reserver().remove(0);
        group.recover().inc_commands();

        let handle = tokio::spawn(async {
            std::future::pending::<()>().await;
        });
        let mut running_downloads = vec![(
            gid,
            RunningDownload {
                _handle: handle,
                shutdown: Some(CancellationToken::new()),
                generation: 41,
                last_activity: Instant::now(),
                timeout: None,
            },
        )];
        let (completion_tx, mut completion_rx) = mpsc::unbounded_channel();
        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
        cmd_tx
            .send(EngineCommand::ForceHaltAll {
                reason: HaltReason::ShutdownSignal,
            })
            .unwrap();
        let mut cmd_rx = EngineCommandReceiver::from_unbounded(cmd_rx);
        let mut halt_requested = false;
        let mut force_halt_requested = false;

        process_engine_commands(
            &mut ctx,
            &mut cmd_rx,
            &mut running_downloads,
            &mut halt_requested,
            &mut force_halt_requested,
            &completion_tx,
        )
        .await;

        let mut completed_generations = HashSet::new();
        let processed = process_task_completions(
            &ctx,
            &mut completion_rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;
        assert!(processed);
        assert!(running_downloads.is_empty());
        assert_eq!(completed_generations.get(&41), Some(&41));
        assert_eq!(
            ctx.group_man
                .find_group(gid)
                .unwrap()
                .recover()
                .num_commands(),
            0
        );
    }

    #[tokio::test]
    async fn shutdown_signal_exits_in_keep_alive_mode() {
        // The Ctrl+C path sets `halt_requested` directly rather than going
        // through an EngineCommand, so it needs its own coverage.
        let (_tx, rx) = mpsc::unbounded_channel();
        let (sd_tx, sd_rx) = tokio::sync::oneshot::channel();

        sd_tx.send(()).unwrap();

        run_until_exit(test_ctx(true), rx, sd_rx, Duration::from_secs(5)).await;
    }

    #[tokio::test]
    async fn shutdown_signal_preserves_active_group_for_resume() {
        let ctx = test_ctx(true);
        let gid = ctx
            .group_man
            .add_group(
                vec!["http://example.com/shutdown-resume.bin".to_string()],
                DownloadOptions::default(),
            )
            .unwrap();
        ctx.group_man.fill_from_reserver();
        let group_man = Arc::clone(&ctx.group_man);

        // Deliver the shutdown signal before the first engine wait.
        // The group is already active but has no command, so the test isolates
        // the shutdown reason from protocol-specific cancellation behavior.
        let (sd_tx, sd_rx) = tokio::sync::oneshot::channel();
        sd_tx.send(()).unwrap();
        let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
        run_engine_loop(ctx, cmd_rx, sd_rx).await;

        let group = group_man
            .find_group(gid)
            .expect("group should remain visible");
        assert_eq!(
            group.recover().get_halt_reason(),
            HaltReason::ShutdownSignal
        );
        assert_ne!(
            group.recover().status(),
            DownloadStatus::Removed,
            "shutdown must not turn a resumable group into a user removal"
        );
        assert_eq!(
            group.recover().create_download_result().code,
            DownloadResultCode::InProgress
        );
    }

    #[tokio::test]
    async fn keep_alive_without_halt_does_not_exit() {
        // The flip side: keep-alive must still hold the loop open when no halt
        // was requested, otherwise an idle RPC server would shut itself down.
        let (_tx, rx) = mpsc::unbounded_channel();
        let (_sd_tx, sd_rx) = tokio::sync::oneshot::channel();

        let loop_fut = run_engine_loop(test_ctx(true), rx, sd_rx);
        assert!(
            tokio::time::timeout(Duration::from_millis(200), loop_fut)
                .await
                .is_err(),
            "keep-alive loop exited without a halt request"
        );
    }

    #[tokio::test]
    async fn idle_loop_exits_without_keep_alive() {
        let (_tx, rx) = mpsc::unbounded_channel();
        let (_sd_tx, sd_rx) = tokio::sync::oneshot::channel();

        run_until_exit(test_ctx(false), rx, sd_rx, Duration::from_secs(5)).await;
    }

    #[tokio::test]
    async fn server_stat_interval_persists_through_engine_maintenance() {
        let dir = tempfile::tempdir().expect("server-stat output directory");
        let path = dir.path().join("server-stat.json");
        let mut ctx = test_ctx(false);
        ctx.server_stat_man = Arc::new(ServerStatMan::new());
        ctx.server_stat_man
            .update_with_protocol("interval.example", "http", 1024, false);
        ctx.server_stat_save_path = Some(path.clone());
        ctx.server_stat_save_interval = Some(Duration::from_secs(60));
        ctx.server_stat_next_save = Some(Instant::now() - Duration::from_secs(1));

        run_deadline_maintenance(&mut ctx, &mut []).await;

        let content = tokio::fs::read_to_string(&path)
            .await
            .expect("server-stat interval must write its configured output");
        assert!(content.contains("interval.example"));
        assert!(
            ctx.server_stat_next_save
                .is_some_and(|deadline| deadline > Instant::now()),
            "server-stat interval must schedule its next save"
        );
    }

    #[tokio::test]
    async fn server_stat_timeout_controls_stale_cleanup() {
        let dir = tempfile::tempdir().expect("server-stat input directory");
        let path = dir.path().join("stale-server-stat.json");
        let file = crate::selector::server_stat_man::ServerStatFile {
            version: "1.0".to_string(),
            saved_at: 1,
            servers: vec![crate::selector::server_stat::ServerStatSnapshot {
                host: "stale.example".to_string(),
                protocol: "http".to_string(),
                download_speed: 1,
                single_connection_avg_speed: 1,
                multi_connection_avg_speed: 0,
                last_updated: 1,
                status: 0,
                counter: 1,
                last_error_time: None,
                last_error_code: 0,
                consecutive_failures: 0,
            }],
        };
        tokio::fs::write(&path, serde_json::to_vec(&file).unwrap())
            .await
            .expect("write stale server-stat fixture");

        let mut ctx = test_ctx(false);
        ctx.server_stat_man = Arc::new(ServerStatMan::new());
        ctx.server_stat_man
            .load_from_file_async(&path)
            .await
            .expect("load stale server-stat fixture");
        ctx.server_stat_max_age = Some(Duration::from_secs(1));
        assert_eq!(ctx.server_stat_man.count(), 1);

        run_event_cleanup(&ctx).await;

        assert_eq!(
            ctx.server_stat_man.count(),
            0,
            "configured server-stat timeout must remove stale entries"
        );
    }

    /// Regression for the periodic auto-save being dead: `mark_session_dirty`
    /// had no callers, so the dirty flag stayed `false` and `save_if_dirty`
    /// never wrote the session file. This test drives a state-changing
    /// `EngineCommand` through `process_engine_commands` and verifies the
    /// session is marked dirty AND that `save_if_dirty` then writes the file.
    #[tokio::test]
    async fn state_changing_command_marks_dirty_and_persists() {
        use crate::request::request_group::{GroupId, RequestGroup};
        use crate::session::auto_save_coordinator::AutoSaveCoordinator;

        let man = Arc::new(RequestGroupMan::new());
        let dir = std::env::temp_dir();
        let path = dir.join(format!("test_engine_autosave_{}.sess", std::process::id()));
        let _ = tokio::fs::remove_file(&path).await;

        let auto_save = Arc::new(tokio::sync::Mutex::new(AutoSaveCoordinator::new(
            man.clone(),
            Some((path.clone(), Duration::from_millis(0))),
            None,
        )));
        let auto_save_dirty_signal = auto_save.lock().await.dirty_signal();

        // The auto-save must share the SAME group manager that the engine
        // commands mutate, otherwise it serializes a stale/empty snapshot.
        let mut ctx = EngineLoopContext {
            group_man: man,
            ftp_pool: Arc::new(FtpConnectionPool::new(1)),
            dns_cache: Arc::new(tokio::sync::Mutex::new(DnsCache::new())),
            auto_save: Some(auto_save.clone()),
            auto_save_dirty_signal: Some(auto_save_dirty_signal),
            event_hooks: Arc::new(DownloadEventHooks::new()),
            file_alloc_man: Arc::new(tokio::sync::RwLock::new(FileAllocationMan::new())),
            keep_alive: false,
            server_stat_man: Arc::new(ServerStatMan::new()),
            server_stat_max_age: Some(Duration::from_secs(24 * 60 * 60)),
            server_stat_save_path: None,
            server_stat_save_interval: None,
            server_stat_next_save: None,
            global_limiter: None,
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: Arc::new(
                aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList::new(),
            ),
            #[cfg(feature = "bittorrent")]
            bt_registry: Arc::new(std::sync::RwLock::new(
                crate::engine::bt_registry::BtRegistry::new(),
            )),
            #[cfg(feature = "bittorrent")]
            bt_listener: Arc::new(crate::engine::bt_peer_listener::BtPeerListenerManager::new()),
            #[cfg(feature = "bittorrent")]
            lpd_manager: Arc::new(crate::engine::lpd_manager::LpdManager::new()),
        };

        // Send an AddDownload command through the engine-command channel.
        let (tx, rx) = mpsc::unbounded_channel();
        let group = Arc::new(std::sync::RwLock::new(RequestGroup::new(
            GroupId::new(42),
            vec!["http://example.com/engine-autosave.bin".to_string()],
            DownloadOptions::default(),
        )));
        tx.send(EngineCommand::AddDownload { group }).unwrap();
        let mut rx = EngineCommandReceiver::from_unbounded(rx);

        let mut halt_requested = false;
        let mut force_halt_requested = false;
        let (completion_tx, _completion_rx) = mpsc::unbounded_channel();
        // Hold the coordinator lock while the command mutates state. The
        // engine must retain the dirty notification instead of dropping it
        // because the autosave writer is busy.
        let auto_save_guard = auto_save.lock().await;
        process_engine_commands(
            &mut ctx,
            &mut rx,
            &mut Vec::new(),
            &mut halt_requested,
            &mut force_halt_requested,
            &completion_tx,
        )
        .await;
        drop(auto_save_guard);

        // The AddDownload command must have flipped the dirty flag.
        assert!(
            auto_save.lock().await.is_session_dirty(),
            "AddDownload should mark the session dirty"
        );

        // With interval=0 and dirty=true, save_if_dirty() writes the file.
        auto_save.lock().await.save_if_dirty().await;
        assert!(path.exists(), "save_if_dirty should write the session file");
        let content = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(
            content.contains("http://example.com/engine-autosave.bin"),
            "session file should contain the added URI"
        );

        let _ = tokio::fs::remove_file(&path).await;
    }

    #[tokio::test]
    async fn global_rate_limit_command_updates_shared_limiter_and_snapshot() {
        let mut ctx = test_ctx(false);
        let (tx, rx) = mpsc::unbounded_channel();
        tx.send(EngineCommand::SetGlobalRateLimit {
            download_limit: Some(2_000),
            upload_limit: Some(1_000),
        })
        .unwrap();
        let mut rx = EngineCommandReceiver::from_unbounded(rx);

        let mut running_downloads = Vec::new();
        let mut halt_requested = false;
        let mut force_halt_requested = false;
        let (completion_tx, _completion_rx) = mpsc::unbounded_channel();
        process_engine_commands(
            &mut ctx,
            &mut rx,
            &mut running_downloads,
            &mut halt_requested,
            &mut force_halt_requested,
            &completion_tx,
        )
        .await;

        let limiter = ctx
            .global_limiter
            .as_ref()
            .expect("runtime updates should create the shared limiter")
            .clone();
        let config = limiter.config().await;
        assert_eq!(config.download_rate(), Some(2_000));
        assert_eq!(config.upload_rate(), Some(1_000));

        let man = &ctx.group_man;
        assert_eq!(man.global_download_limit(), Some(2_000));
        assert_eq!(man.global_upload_limit(), Some(1_000));
    }

    // ── Pause semantics ─────────────────────────────────────────────────
    // Regression: a paused download's command terminates with
    // TaskResult::Failed("Download paused") (the download loop observes the
    // Paused status via check_cancelled). Before the fix the engine recorded
    // an Error, which is terminal and can never be unpaused.

    #[tokio::test]
    async fn paused_task_failure_keeps_group_paused() {
        let ctx = test_ctx(false);

        let gid = {
            let man = &ctx.group_man;
            man.add_group(
                vec!["http://example.com/file.bin".to_string()],
                DownloadOptions::default(),
            )
            .unwrap()
        };

        // Promote to active (fill_from_reserver calls start() → Active).
        {
            let man = &ctx.group_man;
            let promoted = man.fill_from_reserver();
            assert_eq!(promoted.len(), 1);
            assert!(man.find_group(gid).is_some());
        }

        // aria2.pause marks the group Paused.
        {
            let man = &ctx.group_man;
            man.pause_group(gid).unwrap();
            let g = man.find_group(gid).unwrap();
            assert!(g.recover().status().is_paused());
            // Simulate a spawned task that has not yet reported completion.
            g.recover().inc_commands();
        }

        // The download command terminates because it observed the pause.
        let (completion_tx, mut completion_rx) =
            mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        completion_tx
            .send((
                gid,
                1,
                TaskResult::Failed(Aria2Error::DownloadFailed("Download paused".into())),
            ))
            .unwrap();

        let mut running_downloads = Vec::new();
        let mut completed_generations = HashSet::new();
        process_task_completions(
            &ctx,
            &mut completion_rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let status = {
            let man = &ctx.group_man;
            man.find_group(gid).unwrap().recover().status()
        };
        assert_eq!(
            status,
            DownloadStatus::Paused,
            "a pause-induced task failure must keep the group Paused (resumable), not Error"
        );
    }

    #[tokio::test]
    async fn paused_task_success_keeps_group_paused() {
        let ctx = test_ctx(false);
        let gid = {
            let man = &ctx.group_man;
            let gid = man
                .add_group(
                    vec!["http://example.com/file.bin".to_string()],
                    DownloadOptions::default(),
                )
                .unwrap();
            man.fill_from_reserver();
            man.pause_group(gid).unwrap();
            man.find_group(gid).unwrap().recover().inc_commands();
            gid
        };

        let (tx, mut rx) = mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        tx.send((gid, 1, TaskResult::Success)).unwrap();

        let mut running_downloads = Vec::new();
        let mut completed_generations = HashSet::new();
        process_task_completions(
            &ctx,
            &mut rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let status = ctx.group_man.find_group(gid).unwrap().recover().status();
        assert_eq!(
            status,
            DownloadStatus::Paused,
            "a clean command completion must not make a paused group terminal"
        );
    }

    #[tokio::test]
    async fn failed_network_task_marks_only_the_observed_dns_peer_bad() {
        let ctx = test_ctx(false);
        let gid = ctx
            .group_man
            .add_group(
                vec!["http://localhost/dns-peer.bin".to_string()],
                DownloadOptions::default(),
            )
            .unwrap();
        let group = ctx.group_man.find_group(gid).unwrap();
        group.recover().inc_commands();

        let cached = ctx
            .dns_cache
            .lock()
            .await
            .resolve("localhost", 80)
            .await
            .expect("localhost should resolve for the DNS cache fixture");
        let observed = cached[0];
        group
            .recover()
            .set_connection_context(ConnectionContext::new("localhost", 80, observed));

        let (tx, mut rx) = mpsc::unbounded_channel();
        tx.send((
            gid,
            1,
            TaskResult::FailedWithContext {
                error: Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                    message: "connection reset".into(),
                }),
                connection_context: ConnectionContext::new("localhost", 80, observed),
            },
        ))
        .unwrap();

        process_task_completions(&ctx, &mut rx, &mut Vec::new(), &mut HashSet::new()).await;

        let remaining = ctx
            .dns_cache
            .lock()
            .await
            .resolve_no_network("localhost", 80);
        if let Ok(addresses) = remaining {
            assert!(
                !addresses.contains(&observed),
                "the peer that actually failed must not remain a good candidate"
            );
        }
    }

    #[tokio::test]
    async fn async_dns_disabled_does_not_modify_shared_dns_cache_on_failure() {
        let ctx = test_ctx(false);
        let gid = ctx
            .group_man
            .add_group(
                vec!["http://localhost/dns-peer-disabled.bin".to_string()],
                DownloadOptions {
                    async_dns: false,
                    ..DownloadOptions::default()
                },
            )
            .unwrap();
        let group = ctx.group_man.find_group(gid).unwrap();
        group.recover().inc_commands();

        let cached = ctx
            .dns_cache
            .lock()
            .await
            .resolve("localhost", 80)
            .await
            .expect("localhost should resolve for the DNS cache fixture");
        let observed = cached[0];
        group
            .recover()
            .set_connection_context(ConnectionContext::new("localhost", 80, observed));

        let (tx, mut rx) = mpsc::unbounded_channel();
        tx.send((
            gid,
            1,
            TaskResult::FailedWithContext {
                error: Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                    message: "connection reset".into(),
                }),
                connection_context: ConnectionContext::new("localhost", 80, observed),
            },
        ))
        .unwrap();

        process_task_completions(&ctx, &mut rx, &mut Vec::new(), &mut HashSet::new()).await;

        let remaining = ctx
            .dns_cache
            .lock()
            .await
            .resolve_no_network("localhost", 80)
            .expect("async-dns=false must leave the cached address available");
        assert!(
            remaining.contains(&observed),
            "async-dns=false must not mark a failed connection bad in the shared cache"
        );
    }

    #[tokio::test]
    async fn user_removal_wins_over_paused_status_on_cancelled_task() {
        let ctx = test_ctx(false);
        let gid = {
            let man = &ctx.group_man;
            let gid = man
                .add_group(
                    vec!["http://example.com/file.bin".to_string()],
                    DownloadOptions::default(),
                )
                .unwrap();
            man.fill_from_reserver();
            let group = man.find_group(gid).unwrap();
            group.recover_mut().pause().unwrap();
            group.recover().inc_commands();
            // Force removal can arrive after a pause command has already
            // published the Paused status. The user halt reason is terminal.
            group.recover().request_force_halt(HaltReason::UserRequest);
            gid
        };

        let (completion_tx, mut completion_rx) =
            mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        completion_tx.send((gid, 1, TaskResult::Cancelled)).unwrap();

        let mut running_downloads = Vec::new();
        let mut completed_generations = HashSet::new();
        process_task_completions(
            &ctx,
            &mut completion_rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let status = ctx.group_man.find_group(gid).unwrap().recover().status();
        assert_eq!(status, DownloadStatus::Removed);
    }

    #[tokio::test]
    async fn duplicate_completion_decrements_command_once() {
        let ctx = test_ctx(false);
        let gid = {
            let man = &ctx.group_man;
            let gid = man
                .add_group(
                    vec!["http://example.com/file.bin".to_string()],
                    DownloadOptions::default(),
                )
                .unwrap();
            man.fill_from_reserver();
            man.find_group(gid).unwrap().recover().inc_commands();
            gid
        };

        let (tx, mut rx) = mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        tx.send((
            gid,
            1,
            TaskResult::Failed(Aria2Error::Network("failed".into())),
        ))
        .unwrap();
        tx.send((
            gid,
            1,
            TaskResult::Failed(Aria2Error::Network("duplicate".into())),
        ))
        .unwrap();

        let mut running_downloads: Vec<(GroupId, RunningDownload)> = Vec::new();
        let mut completed_generations: HashSet<CommandGeneration> = HashSet::new();
        process_task_completions(
            &ctx,
            &mut rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let man = &ctx.group_man;
        let group = man.find_group(gid).unwrap();
        assert_eq!(group.recover().num_commands(), 0);
        assert_eq!(completed_generations.len(), 1);
    }

    #[tokio::test]
    async fn same_gid_commands_have_independent_completion_generations() {
        let ctx = test_ctx(false);
        let gid = {
            let man = &ctx.group_man;
            let gid = man
                .add_group(
                    vec!["http://example.com/file.bin".to_string()],
                    DownloadOptions::default(),
                )
                .unwrap();
            man.fill_from_reserver();
            let group = man.find_group(gid).unwrap();
            group.recover().inc_commands();
            group.recover().inc_commands();
            gid
        };

        let (tx, mut rx) = mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        tx.send((
            gid,
            1,
            TaskResult::Failed(Aria2Error::Network("first command".into())),
        ))
        .unwrap();
        tx.send((
            gid,
            2,
            TaskResult::Failed(Aria2Error::Network("second command".into())),
        ))
        .unwrap();

        let mut running_downloads = Vec::new();
        let mut completed_generations = HashSet::new();
        process_task_completions(
            &ctx,
            &mut rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let man = &ctx.group_man;
        assert_eq!(man.find_group(gid).unwrap().recover().num_commands(), 0);
        assert_eq!(completed_generations.len(), 2);
    }

    #[tokio::test]
    async fn non_final_command_failure_waits_for_final_completion() {
        let ctx = test_ctx(false);
        let gid = {
            let man = &ctx.group_man;
            let gid = man
                .add_group(
                    vec!["http://example.com/file.bin".to_string()],
                    DownloadOptions::default(),
                )
                .unwrap();
            man.fill_from_reserver();
            let group = man.find_group(gid).unwrap();
            group.recover().inc_commands();
            group.recover().inc_commands();
            gid
        };

        let (tx, mut rx) = mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        tx.send((
            gid,
            1,
            TaskResult::Failed(Aria2Error::Network("first command failed".into())),
        ))
        .unwrap();

        let mut running_downloads = Vec::new();
        let mut completed_generations = HashSet::new();
        process_task_completions(
            &ctx,
            &mut rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        {
            let man = &ctx.group_man;
            let group = man.find_group(gid).unwrap();
            assert_eq!(group.recover().num_commands(), 1);
            assert!(matches!(group.recover().status(), DownloadStatus::Active));
        }

        tx.send((gid, 2, TaskResult::Success)).unwrap();
        process_task_completions(
            &ctx,
            &mut rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let man = &ctx.group_man;
        let group = man.find_group(gid).unwrap();
        assert_eq!(group.recover().num_commands(), 0);
        assert!(matches!(group.recover().status(), DownloadStatus::Error(_)));
    }

    #[test]
    fn error_code_mapping_preserves_aria2_semantics() {
        assert_eq!(
            map_error_code(&Aria2Error::Recoverable(RecoverableError::Timeout)),
            DownloadResultCode::TimeOut
        );
        assert_eq!(
            map_error_code(&Aria2Error::Recoverable(RecoverableError::CannotResume)),
            DownloadResultCode::CannotResume
        );
        assert_eq!(
            map_error_code(&Aria2Error::Recoverable(RecoverableError::ServerError {
                code: 404
            })),
            DownloadResultCode::ResourceNotFound
        );
        assert_eq!(
            map_error_code(&Aria2Error::Recoverable(RecoverableError::ServerError {
                code: 500
            })),
            DownloadResultCode::HttpProtocolError
        );
        for code in [502, 503, 504] {
            assert_eq!(
                map_error_code(&Aria2Error::Recoverable(RecoverableError::ServerError {
                    code
                })),
                DownloadResultCode::HttpServiceUnavailable
            );
        }
        for code in [401, 407] {
            assert_eq!(
                map_error_code(&Aria2Error::Recoverable(RecoverableError::ServerError {
                    code
                })),
                DownloadResultCode::HttpAuthFailed
            );
        }
        assert_eq!(
            map_error_code(&Aria2Error::Recoverable(
                RecoverableError::HttpTooManyRedirects { count: 20 }
            )),
            DownloadResultCode::HttpTooManyRedirects
        );
        assert_eq!(
            map_error_code(&Aria2Error::Checksum("bad digest".into())),
            DownloadResultCode::ChecksumError
        );
        assert_eq!(
            map_error_code(&Aria2Error::Recoverable(
                RecoverableError::FtpProtocolError {
                    message: "550".into(),
                }
            )),
            DownloadResultCode::FtpProtocolError
        );
        assert_eq!(
            map_error_code(&Aria2Error::Io("disk write".into())),
            DownloadResultCode::FileIoError
        );
        assert_eq!(
            map_error_code(&Aria2Error::Fatal(
                crate::error::FatalError::DiskSpaceExhausted
            )),
            DownloadResultCode::NotEnoughDiskSpace
        );
        assert_eq!(
            map_error_code(&Aria2Error::HttpProtocol("bad status".into())),
            DownloadResultCode::HttpProtocolError
        );
        assert_eq!(
            map_error_code(&Aria2Error::FtpProtocol("bad PASV".into())),
            DownloadResultCode::FtpProtocolError
        );
        assert_eq!(
            map_error_code(&Aria2Error::DirCreate("permission denied".into())),
            DownloadResultCode::DirCreateError
        );
        assert_eq!(
            map_error_code(&Aria2Error::FileOpen("cannot open".into())),
            DownloadResultCode::FileOpenError
        );
    }

    #[tokio::test]
    async fn genuine_task_failure_still_marks_error() {
        let ctx = test_ctx(false);

        let gid = {
            let man = &ctx.group_man;
            man.add_group(
                vec!["http://example.com/file.bin".to_string()],
                DownloadOptions::default(),
            )
            .unwrap()
        };
        {
            let man = &ctx.group_man;
            let promoted = man.fill_from_reserver();
            assert_eq!(promoted.len(), 1);
            let g = man.find_group(gid).unwrap();
            g.recover().inc_commands();
        }

        let (completion_tx, mut completion_rx) =
            mpsc::unbounded_channel::<(GroupId, CommandGeneration, TaskResult)>();
        completion_tx
            .send((
                gid,
                1,
                TaskResult::Failed(Aria2Error::Network("connection refused".into())),
            ))
            .unwrap();

        let mut running_downloads = Vec::new();
        let mut completed_generations = HashSet::new();
        process_task_completions(
            &ctx,
            &mut completion_rx,
            &mut running_downloads,
            &mut completed_generations,
        )
        .await;

        let status = {
            let man = &ctx.group_man;
            man.find_group(gid).unwrap().recover().status()
        };
        assert!(
            matches!(status, DownloadStatus::Error(_)),
            "a genuine network failure must still record an Error, got {:?}",
            status
        );
    }

    #[tokio::test]
    async fn engine_cleanup_cancels_only_its_running_gids() {
        use crate::filesystem::file_allocation::AllocationStrategy;
        use crate::filesystem::file_allocation_man::{FileAllocationEntry, FileAllocationProtocol};
        use tokio::sync::oneshot;

        let mut ctx = test_ctx(false);
        let file_alloc_man = Arc::new(tokio::sync::RwLock::new(FileAllocationMan::new()));
        let (target_tx, target_rx) = oneshot::channel();
        let (other_tx, mut other_rx) = oneshot::channel();

        {
            let mut man = file_alloc_man.write().await;
            man.push_entry(FileAllocationEntry::single(
                701,
                std::path::PathBuf::from("/tmp/engine-cleanup-target"),
                100,
                AllocationStrategy::Trunc,
                false,
                FileAllocationProtocol::Http,
                target_tx,
            ));
            man.push_entry(FileAllocationEntry::single(
                702,
                std::path::PathBuf::from("/tmp/engine-cleanup-other"),
                100,
                AllocationStrategy::Trunc,
                false,
                FileAllocationProtocol::Http,
                other_tx,
            ));
        }
        ctx.file_alloc_man = Arc::clone(&file_alloc_man);

        let handle = tokio::spawn(async {});
        let mut running_downloads = vec![(
            GroupId::new(701),
            RunningDownload {
                _handle: handle,
                shutdown: Some(CancellationToken::new()),
                generation: 1,
                last_activity: Instant::now(),
                timeout: None,
            },
        )];

        on_end_of_run(&ctx, &mut running_downloads).await;

        assert!(target_rx.await.unwrap().is_err());
        assert!(other_rx.try_recv().is_err());
        file_alloc_man.write().await.cancel_all();
        assert!(other_rx.await.unwrap().is_err());
    }
}