aria2-core 0.3.4

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
//! Single-mirror concurrent download loop.
//!
//! Contains the execute function that runs the pooled segment download
//! pipeline for a single URI.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use tokio::sync::mpsc;

use crate::constants;
use crate::engine::command::WRITE_CHANNEL_CAPACITY;
use crate::engine::concurrent_segment_manager::ConcurrentSegmentManager;
use crate::engine::http_adaptive_concurrency::{AdaptiveOutcome, HttpAdaptiveConcurrency};
use crate::engine::http_segment_downloader::{SegmentProgress, SegmentProgressTracker, WriteChunk};
use crate::engine::http_segment_request_executor::{
    HttpSegmentRequest, HttpSegmentRequestExecutor, authority_key,
};
use crate::engine::retry_policy::RetryPolicy;
use crate::error::{Aria2Error, RecoverableError, Result};
use crate::filesystem::control_file::ControlFile;
use crate::filesystem::disk_writer::{CachedDiskWriter, SeekableDiskWriter};
use crate::filesystem::resume_helper::ResumeState;
use crate::rate_limiter::{RateLimiter, RateLimiterConfig};
use crate::request::request_group::ActiveConnectionGuard;
use crate::util::rwlock_ext::RwLockRecover;

use super::{ConcurrentDownloadResult, ConcurrentDownloader, effective_segment_count};

/// Run the single-mirror concurrent download pipeline.
///
/// Schedules segments onto a long-lived HTTP connection pool, drains write
/// chunks via tokio::select!, and handles 416-based fallback detection.
pub async fn execute(
    dl: &mut ConcurrentDownloader,
    uri: &str,
    total_length: u64,
    resume_state: &ResumeState,
    max_retries_per_segment: u32,
) -> Result<ConcurrentDownloadResult> {
    {
        dl.group.recover().set_total_length(total_length);
    }

    let options = dl.group.recover().options_arc();
    let requested_split = options.split.unwrap_or(constants::DEFAULT_SPLIT);
    let min_split_size = dl.group.recover().effective_min_split_size();
    let split = effective_segment_count(total_length, requested_split, min_split_size);
    let max_conn = options
        .max_connection_per_server
        .unwrap_or(constants::DEFAULT_MAX_CONNECTION_PER_SERVER as u16)
        .clamp(1, 16) as usize;
    let retry_policy = RetryPolicy::new(
        max_retries_per_segment,
        options.retry_wait.saturating_mul(1000),
    );
    let authority_key = authority_key(uri).unwrap_or_else(|| uri.to_string());
    let mut adaptive = HttpAdaptiveConcurrency::new(max_conn, options.retry_wait);
    let seg_size = total_length.div_ceil(split as u64).max(1);

    tracing::info!(
        "Concurrent download started: split={}, requested_split={}, min_split_size={}, max_conn={}, segment_size={} bytes, total={}",
        split,
        requested_split,
        min_split_size,
        max_conn,
        seg_size,
        total_length
    );

    let mut manager =
        ConcurrentSegmentManager::new(total_length, vec![uri.to_string()], Some(seg_size));
    // MirrorState is only a segment-selection capacity. The actual server
    // limit is enforced by HttpSegmentRequestExecutor, which also merges
    // multiple URLs sharing one authority.
    manager.set_max_connections_per_mirror(split);
    manager.set_max_retries(max_retries_per_segment);

    let mut consecutive_416_count = 0u32;
    let mut total_416_count = 0u32;
    let fallback_threshold_consecutive = 3u32;
    let fallback_threshold_ratio = 0.2f64;
    let mut should_fallback = false;

    if resume_state.should_resume {
        manager.mark_completed_up_to(resume_state.start_offset, resume_state.existing_length);
        dl.progress_updater.reset(resume_state.start_offset);
        tracing::debug!(
            "Resume: marked {} bytes as completed, continuing from offset {}",
            resume_state.existing_length,
            resume_state.start_offset
        );
    } else {
        dl.progress_updater.reset(0);
    }

    let cookie_hdr = dl.cookie_helper.build_cookie_header(uri);

    let use_mmap = dl.file_allocation == "mmap" && total_length >= dl.mmap_threshold;
    let mut writer = CachedDiskWriter::new_with_mmap_bytes(
        &dl.output_path,
        Some(total_length),
        options.disk_cache_size_bytes(),
        use_mmap,
    );

    let limiter = options
        .max_download_limit
        .filter(|&r| r > 0)
        .map(|r| RateLimiter::new(&RateLimiterConfig::new(Some(r), None)));
    if let Some(ref limiter) = limiter {
        let g = dl.group.recover();
        g.set_rate_limiter(limiter.clone());
    }

    // ADR-0001: Create a control file so pause-resume works reliably.
    // Without a control file, ResumeHelper cannot distinguish a
    // preallocated file from a complete one, causing "unpause shows
    // completed". The control file stores completed_length and a
    // piece bitfield that survive across process restarts.
    let num_pieces = manager.num_segments().max(1);
    let ctrl_path = ControlFile::control_path_for(&dl.output_path);
    dl.group.recover().set_control_file_path(ctrl_path.clone());
    let mut ctrl_file =
        match ControlFile::open_or_create(&ctrl_path, total_length, num_pieces).await {
            Ok(cf) => Some(cf),
            Err(e) => {
                tracing::warn!(
                    "Failed to create control file {}: {}. Resume will be less reliable.",
                    ctrl_path.display(),
                    e
                );
                None
            }
        };
    // If resuming, update the control file with existing progress
    if let Some(ref mut cf) = ctrl_file {
        if resume_state.should_resume && resume_state.start_offset > 0 {
            cf.update_completed_length(resume_state.start_offset);
        }
        if let Err(e) = cf.save().await {
            tracing::warn!("Failed to save initial control file: {}", e);
        }
    }
    // Track how many bytes have been saved to the control file so we
    // only write it periodically (every CTRL_SAVE_INTERVAL_BYTES) rather
    // than after every single chunk.
    let ctrl_save_interval = total_length / num_pieces.max(1) as u64;
    let mut ctrl_bytes_since_save: u64 = 0;

    let mut active_segs: HashMap<u32, (u64, u64)> = HashMap::new();
    let initial_completed = if resume_state.should_resume {
        resume_state.start_offset
    } else {
        0
    };
    let progress_tracker = SegmentProgressTracker::new(initial_completed, Arc::clone(&dl.progress));
    let mut segment_progress: HashMap<u32, Arc<SegmentProgress>> = HashMap::new();
    let mut completed_bytes = initial_completed;
    let segment_stall_timeout =
        Duration::from_secs(constants::HTTP_DEFAULT_SEGMENT_STALL_TIMEOUT_SECS);
    let stall_check_interval = Duration::from_secs(1);
    let mut stall_check = tokio::time::interval(stall_check_interval);
    stall_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    super::flush_requested_control_file(dl, &mut writer, &mut ctrl_file, completed_bytes).await?;

    // Write channel: segment futures send chunks as they arrive,
    // the main loop drains them to disk via tokio::select!
    let (write_tx, mut write_rx) = mpsc::channel::<WriteChunk>(WRITE_CHANNEL_CAPACITY);
    let mut executor = HttpSegmentRequestExecutor::new(
        &dl.client,
        dl.request_policy.clone(),
        dl.cookie_helper.clone(),
        dl.auth_options.clone(),
        dl.netrc_path.clone(),
        split,
        std::slice::from_ref(&authority_key),
        max_conn,
    );
    let connection_guard = ActiveConnectionGuard::new(Arc::clone(&dl.group));

    // Lifecycle changes wake the scheduler even when all segment requests are
    // blocked on slow network reads.
    let lifecycle_notify = dl.group.recover().lifecycle_notifier();

    loop {
        let lifecycle_changed = lifecycle_notify.notified();
        tokio::pin!(lifecycle_changed);
        lifecycle_changed.as_mut().enable();

        // Check whether the task was removed. This is the primary
        // cancellation signal: aria2.remove / aria2.forceRemove sets
        // the RequestGroup status to Removed, which is_removed()
        // observes without blocking. We check at the top of the loop so a
        // cancellation is detected before spawning new segment fetches and
        // before awaiting the next segment completion.
        if let Err(e) = dl.check_cancelled() {
            cancel_and_persist(
                executor,
                &mut write_rx,
                &mut writer,
                limiter.as_ref(),
                dl.global_limiter.as_ref(),
                &mut ctrl_file,
                completed_bytes,
            )
            .await?;
            return Err(e);
        }

        while adaptive.can_start(executor.in_flight_for(&authority_key)) {
            match manager.next_pending_segment_for_mirror(0) {
                Some((seg_idx, offset, length)) => {
                    let progress = progress_tracker.new_segment();
                    segment_progress.insert(seg_idx, Arc::clone(&progress));
                    active_segs.insert(seg_idx, (offset, 0));

                    let submitted = executor.try_submit(HttpSegmentRequest {
                        mirror_index: 0,
                        segment_index: seg_idx,
                        authority_key: authority_key.clone(),
                        url: uri.to_string(),
                        offset,
                        length,
                        cookie_header: cookie_hdr.clone(),
                        progress,
                        write_tx: write_tx.clone(),
                        expected_entity_length: total_length,
                    });
                    let Some(task_id) = submitted else {
                        active_segs.remove(&seg_idx);
                        segment_progress.remove(&seg_idx);
                        manager.requeue_segment(seg_idx);
                        break;
                    };
                    if let Some(active) = active_segs.get_mut(&seg_idx) {
                        active.1 = task_id;
                    }
                    connection_guard.set(executor.in_flight());
                    tracing::debug!(
                        seg_idx = seg_idx,
                        offset = offset,
                        length = length,
                        "Submitted segment to HTTP connection pool"
                    );
                }
                None => break,
            }
        }

        if executor.in_flight() == 0 {
            // Drain any remaining write chunks before checking completion
            while let Ok(WriteChunk { offset, data }) = write_rx.try_recv() {
                if let Some(ref lim) = limiter {
                    lim.acquire_download(data.len() as u64).await;
                }
                if let Some(ref gl) = dl.global_limiter
                    && gl.is_download_limited()
                {
                    gl.acquire_download(data.len() as u64).await;
                }
                writer.write_bytes_at(offset, data).await.map_err(|e| {
                    Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                        "Write failed: {}",
                        e
                    )))
                })?;
            }
            if manager.is_complete() {
                tracing::debug!("All segments complete");
                break;
            }
            if let Some(new_target) = adaptive.finish_round() {
                executor.set_target(&authority_key, new_target);
                tracing::info!(
                    old_target = adaptive.hard_limit().min(max_conn),
                    new_target,
                    "HTTP adaptive concurrency reduced after 429/503"
                );
            }
            if let Some(wait) = adaptive.cooldown_remaining() {
                dl.wait_for_retry(wait).await?;
                continue;
            }
            if manager.has_failed_segments() && !manager.has_pending_segments() {
                return Err(Aria2Error::Recoverable(
                    RecoverableError::TemporaryNetworkFailure {
                        message: "Concurrent download: all segments failed".into(),
                    },
                ));
            }
            tracing::warn!(
                "Concurrent download stuck: no active or pending segments but not complete"
            );
            break;
        }

        // Drain any pending writes first (non-blocking)
        while let Ok(WriteChunk { offset, data }) = write_rx.try_recv() {
            if let Some(ref lim) = limiter {
                lim.acquire_download(data.len() as u64).await;
            }
            if let Some(ref gl) = dl.global_limiter
                && gl.is_download_limited()
            {
                gl.acquire_download(data.len() as u64).await;
            }
            writer.write_bytes_at(offset, data).await.map_err(|e| {
                Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                    "Write failed: {}",
                    e
                )))
            })?;
        }
        super::flush_requested_control_file(dl, &mut writer, &mut ctrl_file, completed_bytes)
            .await?;

        // Use tokio::select! to drain writes concurrently while waiting
        // for segment completions — prevents chunks from piling up in the
        // channel while other segments are still downloading.
        tokio::select! {
            // A segment completed
            Some(pool_result) = executor.next_result() => {
                connection_guard.set(executor.in_flight());
                let seg_idx = pool_result.segment_index;
                let Some((_, active_task_id)) = active_segs.get(&seg_idx).copied() else {
                    continue;
                };
                if active_task_id != pool_result.task_id {
                    continue;
                }
                let result = pool_result.result;
                let peer_addr = pool_result.peer_addr;
                if let Some(peer_addr) = peer_addr
                    && let Ok(url) = reqwest::Url::parse(uri)
                        && let Some(host) = url.host_str()
                    {
                        dl.group.recover().set_connection_context(
                            crate::network::ConnectionContext::new(
                                host,
                                url.port_or_known_default().unwrap_or(80),
                                peer_addr,
                            ),
                        );
                    }
                // Drain writes again after a segment completes
                while let Ok(WriteChunk { offset, data }) = write_rx.try_recv() {
                    if let Some(ref lim) = limiter {
                        lim.acquire_download(data.len() as u64).await;
                    }
                    if let Some(ref gl) = dl.global_limiter
                        && gl.is_download_limited() {
                            gl.acquire_download(data.len() as u64).await;
                        }
                    writer.write_bytes_at(offset, data).await.map_err(|e| {
                        Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                            "Write failed: {}",
                            e
                        )))
                    })?;
                }

                let _offset = active_segs
                    .remove(&seg_idx)
                    .map(|(offset, _)| offset)
                    .unwrap_or(0);

                // The request has emitted its completion only after all
                // progress writes, so the atomic segment handle is already
                // fully reconciled here.
                let segment_progress_for_result = segment_progress.remove(&seg_idx);

                match result {
                    Ok(total_written) => {
                        adaptive.record(AdaptiveOutcome::Success);
                        manager.complete_segment(seg_idx, total_written as usize);
                        completed_bytes += total_written;

                        // ADR-0001: Update control file with segment progress.
                        // Mark the piece done and periodically save to disk.
                        if let Some(ref mut cf) = ctrl_file {
                            cf.mark_piece_done(seg_idx as usize);
                            ctrl_bytes_since_save += total_written;
                            if ctrl_bytes_since_save >= ctrl_save_interval {
                                cf.update_completed_length(completed_bytes);
                                if let Err(e) = cf.save().await {
                                    tracing::warn!("Control file save failed: {}", e);
                                }
                                ctrl_bytes_since_save = 0;
                            }
                        }
                        // Use the atomic total for progress updates so that
                        // in-flight progress from concurrent segments is not
                        // overwritten by the committed-only value.
                        let display_total = progress_tracker.total();

                        dl.progress_updater
                            .update_progress(
                                display_total,
                                constants::PROGRESS_UPDATE_BYTES as u64,
                                constants::HTTP_SPEED_UPDATE_INTERVAL_MS,
                            )
                            .await;
                        super::flush_requested_control_file(
                            dl,
                            &mut writer,
                            &mut ctrl_file,
                            completed_bytes,
                        )
                        .await?;
                    }
                    Err(e) => {
                        if let Some(progress) = segment_progress_for_result {
                            progress.rollback();
                        }
                        let e = if matches!(
                            &e,
                            Aria2Error::Recoverable(RecoverableError::ResourceNotFound)
                        ) {
                            dl.group.recover().file_not_found_error()
                        } else {
                            e
                        };
                        tracing::warn!(seg_idx = seg_idx, error = %e, "Segment download failed");
                        let is_file_not_found = matches!(
                            &e,
                            Aria2Error::Recoverable(
                                RecoverableError::ResourceNotFound
                                    | RecoverableError::MaxFileNotFound
                            )
                        );
                        let file_not_found_retry_allowed = !matches!(
                            &e,
                            Aria2Error::Recoverable(RecoverableError::MaxFileNotFound)
                        ) && dl.group.recover().can_retry_file_not_found();
                        if is_file_not_found && !file_not_found_retry_allowed {
                            cancel_and_persist(
                                executor,
                                &mut write_rx,
                                &mut writer,
                                limiter.as_ref(),
                                dl.global_limiter.as_ref(),
                                &mut ctrl_file,
                                completed_bytes,
                            )
                            .await?;
                            return Err(e);
                        }
                        let is_capacity_limited = matches!(
                            &e,
                            Aria2Error::Recoverable(RecoverableError::ServerError { code })
                                if matches!(*code, 429 | 503)
                        );
                        adaptive.record(if is_capacity_limited {
                            AdaptiveOutcome::CapacityLimited
                        } else {
                            AdaptiveOutcome::OtherFailure
                        });
                        let is_416 = matches!(
                            &e,
                            Aria2Error::Recoverable(RecoverableError::RangeNotSatisfiable { .. })
                        );
                        if is_416 {
                            consecutive_416_count += 1;
                            total_416_count += 1;
                            tracing::warn!(
                                seg_idx = seg_idx,
                                consecutive_416 = consecutive_416_count,
                                total_416 = total_416_count,
                                "RangeNotSatisfiable (416) detected"
                            );
                            let failure_ratio = total_416_count as f64 / split as f64;
                            let threshold_exceeded = consecutive_416_count
                                >= fallback_threshold_consecutive
                                || failure_ratio >= fallback_threshold_ratio;
                            if threshold_exceeded {
                                tracing::warn!(
                                    uri = uri,
                                    consecutive_416 = consecutive_416_count,
                                    failure_ratio = failure_ratio,
                                    "Fallback to sequential mode triggered due to RangeNotSatisfiable errors"
                                );
                                should_fallback = true;
                                break;
                            }
                        } else {
                            consecutive_416_count = 0;
                        }
                        let retry_count = manager.segment_retry_count(seg_idx);
                        let retry_allowed = super::should_retry_segment(
                            &retry_policy,
                            retry_count,
                            &e,
                            file_not_found_retry_allowed,
                        );
                        if !retry_allowed {
                            cancel_and_persist(
                                executor,
                                &mut write_rx,
                                &mut writer,
                                limiter.as_ref(),
                                dl.global_limiter.as_ref(),
                                &mut ctrl_file,
                                completed_bytes,
                            )
                            .await?;
                            return Err(e);
                        }
                        if is_capacity_limited && adaptive.preserve_retry_budget() {
                            manager.requeue_segment(seg_idx);
                        } else {
                            manager.fail_segment(seg_idx);
                        }
                    }
                }
            }
            // A write chunk arrived while segments are still running
            Some(WriteChunk { offset, data }) = write_rx.recv() => {
                if let Some(ref lim) = limiter {
                    lim.acquire_download(data.len() as u64).await;
                }
                if let Some(ref gl) = dl.global_limiter
                    && gl.is_download_limited() {
                        gl.acquire_download(data.len() as u64).await;
                    }
                writer.write_bytes_at(offset, data).await.map_err(|e| {
                    Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                        "Write failed: {}",
                        e
                    )))
                })?;
                super::flush_requested_control_file(
                    dl,
                    &mut writer,
                    &mut ctrl_file,
                    completed_bytes,
                )
                .await?;
            }
            // Lifecycle changes wake the loop immediately, even when segment
            // futures are blocked on slow network reads.
            _ = &mut lifecycle_changed => {
                super::flush_requested_control_file(
                    dl,
                    &mut writer,
                    &mut ctrl_file,
                    completed_bytes,
                )
                .await?;
                if let Err(e) = dl.check_cancelled() {
                    cancel_and_persist(
                        executor,
                        &mut write_rx,
                        &mut writer,
                        limiter.as_ref(),
                        dl.global_limiter.as_ref(),
                        &mut ctrl_file,
                        completed_bytes,
                    )
                    .await?;
                    return Err(e);
                }
            }
            _ = stall_check.tick() => {
                let stalled_segment = active_segs.keys().find_map(|seg_idx| {
                    segment_progress
                        .get(seg_idx)
                        .filter(|progress| progress.is_stalled(segment_stall_timeout))
                        .map(|_| *seg_idx)
                });
                if let Some(seg_idx) = stalled_segment
                    && executor.abort_segment(seg_idx).await
                {
                    connection_guard.set(executor.in_flight());
                    active_segs.remove(&seg_idx);
                    if let Some(progress) = segment_progress.remove(&seg_idx) {
                        progress.rollback();
                    }
                    manager.fail_segment(seg_idx);
                    tracing::warn!(
                        seg_idx,
                        stall_timeout_secs = segment_stall_timeout.as_secs(),
                        "Reclaimed stalled HTTP Range request"
                    );
                }
            }
        }
    }

    // Stop workers before the final drain. This is immediate on Range
    // fallback so cancelled requests cannot enqueue more chunks afterward.
    if should_fallback {
        executor.cancel().await;
    } else {
        executor.shutdown().await;
    }

    // Final drain: ensure all pending write chunks are flushed to disk
    while let Ok(WriteChunk { offset, data }) = write_rx.try_recv() {
        if let Some(ref lim) = limiter {
            lim.acquire_download(data.len() as u64).await;
        }
        if let Some(ref gl) = dl.global_limiter
            && gl.is_download_limited()
        {
            gl.acquire_download(data.len() as u64).await;
        }
        writer.write_bytes_at(offset, data).await.map_err(|e| {
            Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                "Write failed: {}",
                e
            )))
        })?;
    }

    writer.flush().await.map_err(|e| {
        Aria2Error::Fatal(crate::error::FatalError::Config(format!(
            "Flush failed: {}",
            e
        )))
    })?;

    if should_fallback {
        // Only fully completed segments are reusable. Any bytes already
        // written for an active/failed segment remain outside this list
        // and are deliberately covered by the subsequent full gap.
        let completed_ranges = manager.completed_ranges();
        // ADR-0001: Save control file on fallback so progress is preserved.
        if let Some(ref mut cf) = ctrl_file {
            cf.update_completed_length(completed_bytes);
            if let Err(e) = cf.save().await {
                tracing::warn!("Control file save on fallback failed: {}", e);
            }
        }
        tracing::warn!(
            "Fallback: {} completed ranges will be preserved",
            completed_ranges.len()
        );
        return Ok(ConcurrentDownloadResult::Fallback { completed_ranges });
    }

    let final_speed = {
        let g = dl.group.recover();
        let elapsed = g.elapsed_time();
        match elapsed {
            Some(d) if d.as_secs_f64() > 0.0 => (completed_bytes as f64 / d.as_secs_f64()) as u64,
            _ => 0,
        }
    };
    {
        dl.progress.set_completed_length(completed_bytes);
        dl.progress.set_download_speed(final_speed);
        dl.progress.set_upload_speed(0);
        let mut g = dl.group.recover_mut();
        g.complete()?;
    }

    tracing::info!(
        "Concurrent download complete: {} ({} bytes)",
        dl.output_path.display(),
        completed_bytes
    );
    let progress_stats = progress_tracker.stats();
    tracing::debug!(
        segments = progress_stats.segments,
        progress_updates = progress_stats.updates,
        progress_rollbacks = progress_stats.rollbacks,
        "HTTP segment progress aggregation summary"
    );
    // ADR-0001: Delete control file on successful completion.
    // The download is done; the .aria2 file is no longer needed.
    drop(ctrl_file);
    if ctrl_path.exists()
        && let Err(e) = tokio::fs::remove_file(&ctrl_path).await
    {
        tracing::debug!("Failed to delete control file on completion: {}", e);
    }
    dl.cookie_helper.save_cookies_if_configured();
    Ok(ConcurrentDownloadResult::Complete)
}

#[allow(clippy::too_many_arguments)]
pub(super) async fn cancel_and_persist(
    executor: HttpSegmentRequestExecutor,
    write_rx: &mut mpsc::Receiver<WriteChunk>,
    writer: &mut CachedDiskWriter,
    limiter: Option<&RateLimiter>,
    global_limiter: Option<&RateLimiter>,
    ctrl_file: &mut Option<ControlFile>,
    completed_bytes: u64,
) -> Result<()> {
    executor.cancel().await;

    while let Ok(WriteChunk { offset, data }) = write_rx.try_recv() {
        if let Some(limiter) = limiter {
            limiter.acquire_download(data.len() as u64).await;
        }
        if let Some(global_limiter) = global_limiter
            && global_limiter.is_download_limited()
        {
            global_limiter.acquire_download(data.len() as u64).await;
        }
        writer.write_bytes_at(offset, data).await.map_err(|error| {
            Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                "Write failed while cancelling: {error}"
            )))
        })?;
    }

    writer.flush().await.map_err(|error| {
        Aria2Error::Fatal(crate::error::FatalError::Config(format!(
            "Flush failed while cancelling: {error}"
        )))
    })?;

    if let Some(ctrl_file) = ctrl_file {
        ctrl_file.update_completed_length(completed_bytes);
        if let Err(error) = ctrl_file.save().await {
            tracing::warn!("Control file save on pause/remove failed: {error}");
        }
    }

    Ok(())
}