Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
314 changes: 286 additions & 28 deletions rust/src/liveorder.rs

Large diffs are not rendered by default.

19 changes: 18 additions & 1 deletion rust/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1804,7 +1804,7 @@ pub(crate) fn known_enum_names(option: &str) -> Option<&'static [&'static CStr]>
/// Emits all default option `(name, value)` pairs for `Options::InitDefaults`.
pub fn init_defaults_with(disable_curses: bool, mut set_opt: impl FnMut(&CStr, &CStr)) {
let output_mode = if disable_curses { c"color" } else { c"curses" };
let defaults: [(&CStr, &CStr); 136] = [
let defaults: [(&CStr, &CStr); 138] = [
(c"MainDir", c"~/downloads"),
(c"WebDir", c""),
(c"ConfigTemplate", c""),
Expand Down Expand Up @@ -1918,6 +1918,8 @@ pub fn init_defaults_with(disable_curses: bool, mut set_opt: impl FnMut(&CStr, &
(c"DirectUnpack", c"yes"),
(c"FeedThreads", c"0"),
(c"UnpackSlots", c"0"),
(c"UnpackPacing", c"yes"),
(c"UnpackPacingLag", c"1536"),
(c"UseTempUnpackDir", c"yes"),
(c"UnpackCleanupDisk", c"yes"),
(c"UnrarCmd", c""),
Expand Down Expand Up @@ -2220,6 +2222,10 @@ pub struct NzbgetRsParsedOptions {
pub feed_threads: i32,
/// Extractions that run at once (`unpackslots::capacity_for`): 0 is one, n is n (at most 64).
pub unpack_slots: i32,
/// Option `UnpackPacing`: pace a download to its direct unpack (`liveorder`).
pub unpack_pacing: bool,
/// Option `UnpackPacingLag` (MB): the lead past which pacing starts.
pub unpack_pacing_lag: i32,
}

impl NzbgetRsParsedOptions {
Expand Down Expand Up @@ -2751,6 +2757,11 @@ pub fn init_scalar_options_host<H: OptionsHost>(
.clamp(0, crate::light_pool::LIGHT_MAX);
s.feed_threads = host.parse_int_value(c"FeedThreads", 10).clamp(0, 64);
s.unpack_slots = host.parse_int_value(c"UnpackSlots", 10).clamp(0, 64);
s.unpack_pacing = host.parse_bool_value(c"UnpackPacing");
s.unpack_pacing_lag = host.parse_int_value(c"UnpackPacingLag", 10).clamp(
crate::liveorder::UNPACK_PACING_LAG_MIN_MB as i32,
crate::liveorder::UNPACK_PACING_LAG_MAX_MB as i32,
);
s.url_force = i32::from(host.parse_bool_value(c"UrlForce"));
s.cert_check = i32::from(host.parse_bool_value(c"CertCheck"));
s.reorder_files = i32::from(host.parse_bool_value(c"ReorderFiles"));
Expand Down Expand Up @@ -4557,6 +4568,8 @@ pub(crate) fn set_active_options(opts: &std::sync::Arc<NzbgetRsOptions>) {
if let Ok(mut g) = ACTIVE_OPTIONS.write() {
*g = Some(std::sync::Arc::downgrade(opts));
}
let sc = opts.scalars();
crate::liveorder::configure_unpack_pacing(sc.unpack_pacing, i64::from(sc.unpack_pacing_lag));
}

/// Monotonic counter incremented every time configuration is hot-reloaded or reset on boot.
Expand Down Expand Up @@ -5784,6 +5797,10 @@ fn build_options(
if let Ok(mut g) = ACTIVE_OPTIONS.write() {
*g = Some(std::sync::Arc::downgrade(&arc));
}
crate::liveorder::configure_unpack_pacing(
arc.scalars.unpack_pacing,
i64::from(arc.scalars.unpack_pacing_lag),
);
// "detect" tests the intermediate folder's disk once per process, in the background.
if arc.daemon_subsystems && !arc.no_disk_access && par_preset() == crate::parpreset::DETECT {
crate::parpreset::start_probe(
Expand Down
231 changes: 209 additions & 22 deletions rust/src/queuecoord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,25 @@ struct LiveOrder {
has_urgent: bool,
is_unpack_pacing: bool,
unpack_waiting: bool,
/// Pacing holds this download's volumes ahead of unpack back (see `liveorder`).
pace_active: bool,
}

impl LiveOrder {
/// Whether the volume named `filename` stays exempt from unpack pacing: the volume
/// unpack is reading, or (while unpack waits for network data) one in the window.
fn pace_exempt(&self, filename: &[u8]) -> Option<bool> {
let r = self.ranks.of(filename)?;
Some(
self.unpack_rank == Some(r)
|| (self.unpack_waiting
&& (self
.unpack_rank
.is_some_and(|f| crate::liveorder::in_window(r, f))
|| self.window_rank(filename).is_some())),
)
}

/// The rank of the file named `filename` when it is a volume within the window.
fn window_rank(&self, filename: &[u8]) -> Option<usize> {
let rank = self.ranks.of(filename)?;
Expand Down Expand Up @@ -247,6 +263,7 @@ fn cached_live_order<'c>(
has_urgent: snap.has_urgent,
is_unpack_pacing: snap.is_unpack_pacing,
unpack_waiting: snap.unpack_waiting,
pace_active: snap.pace_active,
}
});
cache.push((nzb_id, order));
Expand Down Expand Up @@ -4543,6 +4560,32 @@ impl NzbgetRsQueueCoordinator {
) -> Option<(
crate::queuesubsys_host::FileSnap,
crate::queuesubsys_host::ArticleSnap,
)> {
let mut yielded: Vec<(i32, NzbRef)> = Vec::new();
let picked = self.pick_next_article(host, opts, dq_ptr, &mut yielded);
// Another download took a connection a paced download passed over: that one's
// articles in flight stop sleeping at unpack speed for a while (`liveorder`).
if let Some((f, _)) = &picked {
for &(id, ptr) in &yielded {
if ptr != f.nzb_ptr {
crate::liveorder::note_unpack_yield(id);
}
}
}
picked
}

/// `get_next_article`'s pick; `yielded` gets the downloads paced to their direct unpack
/// whose volumes it passed over for another download's.
fn pick_next_article(
&self,
host: &crate::queuesubsys_host::QueueSubsysHost,
opts: &crate::queuesubsys_host::GlobalOptsSnap,
dq_ptr: usize,
yielded: &mut Vec<(i32, NzbRef)>,
) -> Option<(
crate::queuesubsys_host::FileSnap,
crate::queuesubsys_host::ArticleSnap,
)> {
let mut checked_files: Vec<FileRef> = Vec::new();
let cur_date = opts.cur_time;
Expand All @@ -4568,6 +4611,10 @@ impl NzbgetRsQueueCoordinator {
let mut copies_by_key: Option<CopiesByKey> = None;
// Downloads the InterDir budget holds this call: the pick goes round without them.
let mut budget_held: Vec<NzbRef> = Vec::new();
// A download paced to its direct unpack gives its connections to the rest of the queue
// (its volumes ahead of unpack are passed over) while another download can use them.
// When nothing else can, the pick goes round once more with pacing as before.
let mut yield_paced = true;

loop {
let mut best_file: Option<(
Expand Down Expand Up @@ -4627,14 +4674,9 @@ impl NzbgetRsQueueCoordinator {
}
let propagation_delay = opts.propagation_delay;
let order = cached_live_order(&mut orders, host, nzb_ptr, nzb.id);
let (unpack_pace_cap, unpack_rank, has_urgent, unpack_waiting) = match order {
Some(o) => (
o.unpack_pace_cap,
o.unpack_rank,
o.has_urgent,
o.unpack_waiting,
),
None => (None, None, false, false),
let (unpack_pace_cap, has_urgent, pace_active) = match order {
Some(o) => (o.unpack_pace_cap, o.has_urgent, o.pace_active),
None => (None, false, false),
};
// A par2 file with articles to fetch seen earlier in the list: the window
// does not go ahead of it (live PAR reads it early).
Expand All @@ -4656,25 +4698,24 @@ impl NzbgetRsQueueCoordinator {
// dispatches for archive volumes ahead of unpack while leaving par2,
// extra-priority, urgent, the volume unpack is actually reading (and
// lookahead window volumes while unpack is waiting) unthrottled.
// While another download can use the connections, a paced
// download's volumes ahead of unpack are passed over entirely.
if !has_urgent
&& !par_file
&& !f.extra_priority
&& unpack_pace_cap.is_some_and(|cap| nzb.active_downloads >= cap)
&& ((yield_paced && pace_active)
|| unpack_pace_cap
.is_some_and(|cap| nzb.active_downloads >= cap))
&& order.as_ref().and_then(|o| o.pace_exempt(&f.filename))
== Some(false)
Comment on lines +4706 to +4710

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fall back when the replacement download cannot get a connection

When the next queued download is pinned to an active desired server whose connections are exhausted, this condition skips the paced download even if connections usable by that paced download are free. The replacement still counts as a successful pick, so the second pass never runs; subsequently, run() fails server_pool_get_connection() and breaks without trying the passed-over download. Repeated passes therefore leave usable connections idle until unpack reduces the lead below the pacing threshold, instead of retaining the previous paced throughput. Make yielding conditional on the replacement actually being dispatchable, or retry the paced candidates when connection acquisition fails.

Useful? React with 👍 / 👎.

{
let vol_rank = order.as_ref().and_then(|o| o.ranks.of(&f.filename));
let exempt = vol_rank.is_some_and(|r| {
unpack_rank == Some(r)
|| (unpack_waiting
&& (unpack_rank
.is_some_and(|f| crate::liveorder::in_window(r, f))
|| order
.as_ref()
.and_then(|o| o.window_rank(&f.filename))
.is_some()))
});
if vol_rank.is_some() && !exempt {
continue;
if yield_paced
&& pace_active
&& !yielded.iter().any(|&(id, _)| id == nzb.id)
{
yielded.push((nzb.id, nzb.ptr));
}
continue;
}
// A volume of a set extracted live, within the window: taken in
// extraction order before the download's other files (a par2
Expand Down Expand Up @@ -4710,6 +4751,15 @@ impl NzbgetRsQueueCoordinator {
}

let Some((mut nzb, mut file, _)) = best_file else {
// Nothing else can use the connections: pace the passed-over downloads as
// before (their articles go out and sleep at unpack speed).
if yield_paced && !yielded.is_empty() {
yield_paced = false;
for (id, _) in yielded.drain(..) {
crate::liveorder::clear_unpack_yield(id);
}
continue;
}
if let Some((pw_nzb, pw_file)) = prop_wait_file {
let prev_logged = self
.propagation_wait_logged_id
Expand Down Expand Up @@ -11757,6 +11807,143 @@ mod tests {
assert!(super::should_probe_first_article(true, false, b"Show.vol-02.PAR2"));
}

/// Adds a download of two 2-article RAR volumes named `<base>.partNN.rar` to the queue.
#[cfg(unix)]
fn add_two_volume_download(
host: &crate::queuesubsys_host::QueueSubsysHost,
base: &str,
) -> (crate::queuesubsys_host::NzbRef, i32, Vec<FileRef>) {
use crate::qnzb::{self, ParsedFile};
use crate::qqueue;
use crate::queuesubsys_host::NzbRef;
use std::ffi::CString;

let (hn, nzb_addr) = qqueue::new_nzb_handle();
let nzb = NzbRef::from_addr(nzb_addr);
qqueue::with_current_locked(|dq| unsafe {
qqueue::queue_add_handle(dq, hn);
});
let nzb_id = host.nzb_snap(nzb, false).id;
let parts = [1i32, 2i32];
let sizes = [700_000i64, 700_000i64];
let mut files = Vec::new();
for vol in 1..=2 {
let name = CString::new(format!("{base}.part0{vol}.rar")).unwrap();
let m1 = CString::new(format!("<{base}{vol}a@example>")).unwrap();
let m2 = CString::new(format!("<{base}{vol}b@example>")).unwrap();
let msg_ids = [m1.as_ptr(), m2.as_ptr()];
files.push(qnzb::add_parsed_file(
nzb,
&ParsedFile {
id: 0,
subject: name.as_ptr(),
filename: name.as_ptr(),
time: 0,
size: 1_400_000,
remaining_size: 1_400_000,
missed_size: 0,
total_articles: 2,
missed_articles: 0,
par_file: false,
groups: &[],
article_parts: &parts,
article_sizes: &sizes,
article_msg_ids: &msg_ids,
},
));
}
(nzb, nzb_id, files)
}

#[cfg(unix)]
#[test]
fn paced_download_gives_its_connections_to_the_next_queued_download() {
use crate::qqueue;
use crate::queuesubsys_host::QueueSubsysHost;

let _s = qqueue::tests::serial();
qqueue::daemon_queue_init();
let opts_guard = crate::options::test_options(&[c"WriteLog=none", c"LogBuffer=100"]);
let host = QueueSubsysHost::active();
let qc = super::NzbgetRsQueueCoordinator::new();
let pick = |qc: &super::NzbgetRsQueueCoordinator| {
host.with_locked_queue(|dq_ptr| {
let opts = host.opts();
qc.get_next_article(&host, &opts, dq_ptr)
.map(|(f, _)| f.nzb_ptr)
})
};

let (nzb_a, id_a, files_a) = add_two_volume_download(&host, "PacedA");
crate::liveorder::set_order(
id_a,
&[b"PacedA.part01.rar".to_vec(), b"PacedA.part02.rar".to_vec()],
);
// Unpack at 45 MB/s, the download 1.7 GB ahead of it: paced. Unpack reads part01.
crate::liveorder::test_force_paced(id_a, 45.0 * 1048576.0, 1700 << 20);
assert!(crate::liveorder::is_unpack_pacing(id_a));
// The articles of part01 (the volume unpack reads, never passed over) are in flight.
let set_vol1 = |status: i32| {
for i in 0..2 {
let art = host.article_at(files_a[0], i).ptr;
host.article_edit(art, crate::qarticle::ArticleEdit::Status(status));
}
};
set_vol1(crate::qarticle::AI_RUNNING);

// 1. Alone in the queue, the paced download still gets articles of the volume ahead
// (paced as before: they sleep at unpack speed).
assert_eq!(pick(&qc), Some(nzb_a));
assert_eq!(crate::liveorder::unpack_rank(id_a), Some(0));
assert!(!crate::liveorder::is_unpack_yielding(id_a));
assert!(
crate::liveorder::unpack_pace_delay(id_a, b"PacedA.part02.rar", 8 << 20)
> std::time::Duration::from_millis(50)
);

// 2. A second queued download gets the connections; the paced one's articles in
// flight stop sleeping in their slots.
let (nzb_b, _id_b, files_b) = add_two_volume_download(&host, "NextB");
assert_eq!(pick(&qc), Some(nzb_b));
assert!(crate::liveorder::is_unpack_yielding(id_a));
assert_eq!(
crate::liveorder::unpack_pace_delay(id_a, b"PacedA.part02.rar", 8 << 20),
std::time::Duration::ZERO
);
assert!(crate::liveorder::unpack_pace_status(id_a).is_some_and(|s| s.yielding));

// 2b. The other download's work runs out: the paced download is paced again at once.
for i in 0..2 {
for f in &files_b {
let art = host.article_at(*f, i).ptr;
host.article_edit(art, crate::qarticle::ArticleEdit::Status(crate::qarticle::AI_RUNNING));
}
}
assert_eq!(pick(&qc), Some(nzb_a));
assert!(!crate::liveorder::is_unpack_yielding(id_a));
for i in 0..2 {
for f in &files_b {
let art = host.article_at(*f, i).ptr;
host.article_edit(art, crate::qarticle::ArticleEdit::Status(crate::qarticle::AI_UNDEFINED));
}
}
assert_eq!(pick(&qc), Some(nzb_b));

// 3. The volume unpack is reading still goes to the paced download first.
set_vol1(crate::qarticle::AI_UNDEFINED);
assert_eq!(pick(&qc), Some(nzb_a));
set_vol1(crate::qarticle::AI_RUNNING);

// 4. UnpackPacing=no: queue order again, nothing passed over.
crate::liveorder::test_set_pacing_off(true);
let off_pick = pick(&qc);
crate::liveorder::test_set_pacing_off(false);
assert_eq!(off_pick, Some(nzb_a));

crate::liveorder::clear(id_a);
drop(opts_guard);
}

#[cfg(unix)]
#[test]
fn waiting_stragglers_are_hedged_after_floor_and_guarded_against_races() {
Expand Down
Loading
Loading