From a49e04f30d292b15c2b3c690f5c477733512410f Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:32:38 -0800 Subject: [PATCH 1/9] Test hook for slow state-file syncs and the queuesyncslow scenario RUSTYGET_TEST_STATE_SYNC_DELAY_MS delays every sync of a saved state file and of its directory, as a disk busy with a post-processing move does (6790: 0.4-3.5 s per fdatasync). queuesyncslow downloads six files with that delay at 1 s and FlushQueue=yes and bounds the time: while the queue coordinator waits for those syncs it hands out no articles. This commit alone shows the slowdown; the fix follows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/diskstate_format.rs | 19 ++++++++++++++++ tests/functional/dupefallback/harness.py | 28 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index dc3765054..46ca46098 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -4520,6 +4520,23 @@ struct RsStateFile { file_version: i32, } +/// Test hook: `RUSTYGET_TEST_STATE_SYNC_DELAY_MS` delays every sync of a saved state +/// file and of its directory by that many milliseconds, as a disk busy with another +/// job does (6790: 0.4-3.5 s per fdatasync during a post-processing move). The +/// queuesyncslow scenario sets it; unset, it costs one load. +pub(crate) fn test_state_sync_delay() { + static DELAY_MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let ms = *DELAY_MS.get_or_init(|| { + std::env::var("RUSTYGET_TEST_STATE_SYNC_DELAY_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0) + }); + if ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(ms)); + } +} + impl RsStateFile { fn new( qdir: &[u8], @@ -4615,6 +4632,7 @@ impl RsStateFile { ); let mut errmsg = Vec::new(); let fd = std::os::unix::io::AsRawFd::as_raw_fd(w.get_ref()); + test_state_sync_delay(); if !crate::fsops::flush_file_buffers(fd, &mut errmsg) { emit_log_parts( env, @@ -4659,6 +4677,7 @@ impl RsStateFile { ], ); let mut errmsg = Vec::new(); + test_state_sync_delay(); if !crate::fsops::flush_dir_buffers(&self.dest_c, self.sep, &mut errmsg) { emit_log_parts( env, diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index e1023467e..1250b429f 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -1803,6 +1803,29 @@ def scenario_truncatedstate(daemon, t): state, h['Status'], integ, _grep_log(t, 'Discarding damaged download state'))) +def scenario_queuesyncslow(daemon, t): + """Every sync of a saved state file takes a second (RUSTYGET_TEST_STATE_SYNC_DELAY_MS, + as on 6790 while a post-processing move saturated the queue disk with FlushQueue=yes). + The queue coordinator saves the partial states and the progress once a second; it must + not wait for those syncs, or no articles are handed out meanwhile and the rate falls + to a fraction (6790: 108 MB/s to 4-20 MB/s, 10-50 of 205 connections busy). Six files + of 30 articles each, every article delayed 0.3 s by the proxy, 6 connections: about + 9 s of transfer. Waiting for the syncs (two or more seconds of every second) makes it + take several times that; the bound is 30 s.""" + seg, size, nfiles = 100_000, 3_000_000, 6 + members = [] + for i in range(nfiles): + data = _payload(size, 4400 + i) + members.append((_place_copy(t, 'qsA', data, 'f%d.bin' % i), 'qs%d.bin' % i, size, seg, set())) + api = daemon.wait_ready() + start = time.time() + daemon.append(api, 'RelQS', build_multi_nzb(members), False, 'qs-key', 100) + h = daemon.wait_history(api, 'RelQS', timeout=240) + elapsed = time.time() - start + ok = h['Status'].startswith('SUCCESS') and elapsed < 30.0 + return ('queuesyncslow', ok, 'status=%s elapsed=%.1fs bound=30s' % (h['Status'], elapsed)) + + def scenario_streamtimeout(daemon, t): """DupeStreamTimeout: the only duplicate is stalled (every request for its articles waits 8 s, longer than the timeout), so the repair of the @@ -15265,6 +15288,7 @@ def scenario_dupausedunpack(daemon, t): 'manydonors': scenario_manydonors, 'stream': scenario_stream, 'truncatedstate': scenario_truncatedstate, + 'queuesyncslow': scenario_queuesyncslow, 'streamrestartcredit': scenario_streamrestartcredit, 'streamtimeout': scenario_streamtimeout, 'streamdeaddonor': scenario_streamdeaddonor, @@ -15702,6 +15726,8 @@ def scenario_dupausedunpack(daemon, t): 'persistdeadprimary': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, 'persistrestart': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, 'persistrestartdamaged': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, + # each state-file sync takes 1 s (diskstate_format::test_state_sync_delay) + 'queuesyncslow': {'RUSTYGET_TEST_STATE_SYNC_DELAY_MS': '1000'}, } SCENARIO_ENV_KEYS = sorted({k for env in SCENARIO_ENV.values() for k in env}) @@ -15753,6 +15779,7 @@ def scenario_dupausedunpack(daemon, t): 'jsonpoff': ['DupeArticleFallback=yes', 'Server1.Password=harness-secret'], 'stream': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'truncatedstate': ['ContinuePartial=yes', 'FlushQueue=yes', 'Server1.Connections=1'], + 'queuesyncslow': ['ContinuePartial=yes', 'FlushQueue=yes', 'Server1.Connections=6'], 'streamrestartcredit': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'streamdeaddonor': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'rejectnextserver': ['DupeArticleFallback=article', 'ArticleRetries=0'], @@ -16209,6 +16236,7 @@ def _promote_fallback(options, mode): 'directunpackkeep': [(b'rel.part03', 2.0)], 'directunpackkeepnointer': [(b'rel.part03', 2.0)], 'truncatedstate': [(b'tsA/', 0.5)], + 'queuesyncslow': [(b'qsA/', 0.3)], 'reloadmidrepair': [(b'rlDon/', 2.0)], 'streamrestartcredit': [(b'srSlow/', 3.0)], 'restartfailover': [(b'rfA/', 0.4)], From b5648192cf84121272f35b513f798a402c840efd Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:39:13 -0800 Subject: [PATCH 2/9] Write the queue state files on a background thread The queue coordinator saves the partial states, the progress and the queue once a second under the queue lock. With FlushQueue=yes each save syncs the file and its directory; on 6790 a post-processing move kept the queue disk busy, a single fdatasync took 0.4-3.5 s, and while the coordinator waited it handed out no articles (108 MB/s fell to 4-20 MB/s, 10-50 of 205 connections busy). The content is still serialized under the lock, so every file is a consistent snapshot, but the write, the sync, the rename and the directory sync now run on a queue-saver thread (statesaver.rs) for the coordinator thread. Jobs run first in, first out; a newer save of a file still queued replaces its content in place, so partial states, progress and queue land in the order they were saved, and a delete goes behind the writes it follows. Crash safety is as before: .new, sync, rename, directory sync. Other threads write inline as before, after the jobs queued for the same file. Readers (restart, a file's article list reloaded) first run or wait for the file's queued job and read with no save touching it. The coordinator drains the saver before it exits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/diskstate_format.rs | 284 +++++++++++++-------- rust/src/lib.rs | 1 + rust/src/queuecoord.rs | 6 + rust/src/statesaver.rs | 471 +++++++++++++++++++++++++++++++++++ 4 files changed, 652 insertions(+), 110 deletions(-) create mode 100644 rust/src/statesaver.rs diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index 46ca46098..31f22bfa5 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2111,18 +2111,28 @@ fn queue_file_path(qdir: &[u8], sep: u8, name: &[u8]) -> Vec { crate::artwritercore::article_writer_format_dest_file_path(qdir, sep, name) } +/// Deletes a queue-dir file, in order with the saves queued for it (statesaver). fn remove_queue_file(qdir: &[u8], sep: u8, name: &[u8]) { let p = queue_file_path(qdir, sep, name); - let _ = std::fs::remove_file(crate::fsops::path(&p)); + let job = crate::statesaver::Job { + temp: p.clone(), + path: p, + sep, + kind: crate::statesaver::JobKind::Delete { temp_too: false }, + }; + crate::statesaver::submit(job, &mut active_disk_log_cb); } fn queue_file_exists(qdir: &[u8], sep: u8, name: &[u8]) -> bool { - crate::fsops::posix_stat(&queue_file_path(qdir, sep, name)) == 1 + let p = queue_file_path(qdir, sep, name); + crate::statesaver::settled(&p, || crate::fsops::posix_stat(&p) == 1) } /// `DiscardDownloadQueue`: removes the queue and history files and every /// numbered file (with its `s` and `c` companions) in the queue dir. pub fn discard_queue_files(qdir: &[u8], sep: u8) { + // The listing below must see every file a queued save still creates. + crate::statesaver::drain(); remove_queue_file(qdir, sep, b"queue"); remove_queue_file(qdir, sep, b"history"); for entry in crate::fsops::list_dir_entries(qdir) { @@ -4537,6 +4547,124 @@ pub(crate) fn test_state_sync_delay() { } } +/// Writes or deletes one state file as `RsStateFile` always has: a transactional write +/// goes to `.new`, is synced (FlushQueue), renamed over the file, and the +/// directory synced. Runs inline or on the `queue-saver` thread (statesaver). +pub(crate) fn run_state_job( + job: &crate::statesaver::Job, + log: &mut dyn FnMut(DiskLogLevel, &[u8]), +) -> bool { + let dest_c = bytes_to_cstring_trunc(&job.path); + let temp_c = bytes_to_cstring_trunc(&job.temp); + let (bytes, transactional, sync) = match &job.kind { + crate::statesaver::JobKind::Delete { temp_too } => { + crate::fsops::delete_file(&dest_c); + if *temp_too { + crate::fsops::delete_file(&temp_c); + } + return true; + } + crate::statesaver::JobKind::Write { + bytes, + transactional, + sync, + } => (bytes, *transactional, *sync), + }; + let fd = crate::fsops::open_cloexec_fd(&temp_c, 2, 0, 1, 2); + if fd == -1 { + let err = crate::fsops::error_message(crate::fsops::last_errno()); + log( + DiskLogLevel::Error, + &[ + b"Error saving diskstate: Could not create file ", + &job.temp[..], + b": ", + &err, + ] + .concat(), + ); + return false; + } + let mut file: std::fs::File = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(fd) }; + let _ = file.write_all(bytes); + if !transactional { + return true; + } + + if sync { + log( + DiskLogLevel::Debug, + &[ + &b"Flushing data for file "[..], + crate::nserv::base_file_name(&job.temp), + ] + .concat(), + ); + let mut errmsg = Vec::new(); + let fd = std::os::unix::io::AsRawFd::as_raw_fd(&file); + test_state_sync_delay(); + if !crate::fsops::flush_file_buffers(fd, &mut errmsg) { + log( + DiskLogLevel::Warning, + &[ + b"Could not flush file ", + &job.temp[..], + b" into disk: ", + &errmsg, + ] + .concat(), + ); + } + } + + drop(file); + + crate::fsops::delete_file(&dest_c); + if !crate::fsops::move_file(&temp_c, &dest_c) { + let err = crate::fsops::error_message(crate::fsops::last_errno()); + log( + DiskLogLevel::Error, + &[ + b"Error saving diskstate: Could not rename file ", + &job.temp[..], + b" to ", + &job.path, + b": ", + &err, + ] + .concat(), + ); + return false; + } + + if sync { + log( + DiskLogLevel::Debug, + &[ + &b"Flushing directory for file "[..], + crate::nserv::base_file_name(&job.path), + ] + .concat(), + ); + let mut errmsg = Vec::new(); + test_state_sync_delay(); + if !crate::fsops::flush_dir_buffers(&dest_c, job.sep, &mut errmsg) { + log( + DiskLogLevel::Warning, + &[ + b"Could not flush directory buffers for file ", + &job.path[..], + b" into disk: ", + &errmsg, + ] + .concat(), + ); + } + } + + true +} + impl RsStateFile { fn new( qdir: &[u8], @@ -4573,129 +4701,64 @@ impl RsStateFile { } fn discard(&self) { - crate::fsops::delete_file(&self.dest_c); - if self.transactional { - crate::fsops::delete_file(&self.temp_c); - } + let job = crate::statesaver::Job { + path: self.dest.clone(), + temp: self.temp.clone(), + sep: self.sep, + kind: crate::statesaver::JobKind::Delete { + temp_too: self.transactional, + }, + }; + crate::statesaver::submit(job, &mut active_disk_log_cb); } fn file_exists(&self) -> bool { - crate::fsops::posix_stat(&self.dest) == 1 - || (self.transactional && crate::fsops::posix_stat(&self.temp) == 1) + crate::statesaver::settled(&self.dest, || { + crate::fsops::posix_stat(&self.dest) == 1 + || (self.transactional && crate::fsops::posix_stat(&self.temp) == 1) + }) } - unsafe fn begin_write( - &self, - env: &NzbgetRsDiskStateEnv, - ) -> Option> { - let fd = crate::fsops::open_cloexec_fd(&self.temp_c, 2, 0, 1, 2); - if fd == -1 { - let err = crate::fsops::error_message(crate::fsops::last_errno()); - emit_log_parts( - env, - DiskLogLevel::Error, - &[ - b"Error saving diskstate: Could not create file ", - &self.temp, - b": ", - &err, - ], - ); - return None; - } - let file = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(fd) }; - let mut w = std::io::BufWriter::new(file); + /// The buffer a save is serialized into, starting with the version line; the + /// caller fills it (under the queue lock) and hands it to `finish_write`. + unsafe fn begin_write(&self, _env: &NzbgetRsDiskStateEnv) -> Option> { + let mut w = Vec::with_capacity(4096); let _ = writeln!(w, "nzbget diskstate file version {}", self.format_version); Some(w) } + /// Writes the serialized `w` to the file (`run_state_job`): inline, or on the + /// `queue-saver` thread when called by the queue coordinator (statesaver). unsafe fn finish_write( &self, env: &NzbgetRsDiskStateEnv, - mut w: std::io::BufWriter, + w: Vec, flush_queue: bool, ) -> bool { - let _ = w.flush(); - if !self.transactional { - drop(w); - return true; - } - - if self.flush && flush_queue { - emit_log_parts( - env, - DiskLogLevel::Debug, - &[ - b"Flushing data for file ", - crate::nserv::base_file_name(&self.temp), - ], - ); - let mut errmsg = Vec::new(); - let fd = std::os::unix::io::AsRawFd::as_raw_fd(w.get_ref()); - test_state_sync_delay(); - if !crate::fsops::flush_file_buffers(fd, &mut errmsg) { - emit_log_parts( - env, - DiskLogLevel::Warning, - &[ - b"Could not flush file ", - &self.temp, - b" into disk: ", - &errmsg, - ], - ); - } - } - - drop(w); - - crate::fsops::delete_file(&self.dest_c); - if !crate::fsops::move_file(&self.temp_c, &self.dest_c) { - let err = crate::fsops::error_message(crate::fsops::last_errno()); - emit_log_parts( - env, - DiskLogLevel::Error, - &[ - b"Error saving diskstate: Could not rename file ", - &self.temp, - b" to ", - &self.dest, - b": ", - &err, - ], - ); - return false; - } - - if self.flush && flush_queue { - emit_log_parts( - env, - DiskLogLevel::Debug, - &[ - b"Flushing directory for file ", - crate::nserv::base_file_name(&self.dest), - ], - ); - let mut errmsg = Vec::new(); - test_state_sync_delay(); - if !crate::fsops::flush_dir_buffers(&self.dest_c, self.sep, &mut errmsg) { - emit_log_parts( - env, - DiskLogLevel::Warning, - &[ - b"Could not flush directory buffers for file ", - &self.dest, - b" into disk: ", - &errmsg, - ], - ); - } - } - - true + let job = crate::statesaver::Job { + path: self.dest.clone(), + temp: self.temp.clone(), + sep: self.sep, + kind: crate::statesaver::JobKind::Write { + bytes: w, + transactional: self.transactional, + sync: self.flush && flush_queue, + }, + }; + crate::statesaver::submit(job, &mut |level, msg| emit_log(env, level, msg)) } + /// Opens the file for reading once the saves queued for it are on disk, with no + /// save touching it meanwhile (statesaver). unsafe fn begin_read(&mut self, env: &NzbgetRsDiskStateEnv) -> Option { + let dest = self.dest.clone(); + crate::statesaver::settled(&dest, || unsafe { self.begin_read_settled(env) }) + } + + unsafe fn begin_read_settled( + &mut self, + env: &NzbgetRsDiskStateEnv, + ) -> Option { let dest_exists = crate::fsops::posix_stat(&self.dest) == 1; let temp_exists = crate::fsops::posix_stat(&self.temp) == 1; if self.transactional && dest_exists && temp_exists { @@ -4822,7 +4885,7 @@ impl TrailerAccum { unsafe fn save_nzb_section( env: &NzbgetRsDiskStateEnv, - w: &mut std::io::BufWriter, + w: &mut Vec, source: NzbSource, header_count: i32, ) { @@ -4834,7 +4897,7 @@ unsafe fn save_nzb_section( let _ = writeln!(w, "{header_count}"); struct SinkState<'a> { - w: &'a mut std::io::BufWriter, + w: &'a mut Vec, source: NzbSource, remaining_progress: i32, trailer: TrailerAccum, @@ -6066,6 +6129,7 @@ pub unsafe fn diskstate_exec(op: DiskOp, env: &NzbgetRsDiskStateEnv) -> c_int { DiskOp::WriteCacheFlag => { let flag_p = crate::artwritercore::article_writer_format_dest_file_path(qdir, sep, b"acache"); + crate::statesaver::settle(&flag_p); let flag_c = bytes_to_cstring_trunc(&flag_p); let fd = crate::fsops::open_cloexec_fd(&flag_c, 2, 0, 1, 2); if fd == -1 { diff --git a/rust/src/lib.rs b/rust/src/lib.rs index f043fac62..ac736120c 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -116,6 +116,7 @@ pub mod wildmask; pub mod artwritercore; pub mod diskstate_format; +pub(crate) mod statesaver; pub(crate) mod donorkind; pub mod dupefallback; pub mod dupeidentity; diff --git a/rust/src/queuecoord.rs b/rust/src/queuecoord.rs index 29e2277ec..041bce9dc 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -2393,6 +2393,10 @@ impl NzbgetRsQueueCoordinator { crate::queuesubsys_host::MK_DEBUG, b"Entering QueueCoordinator-loop", ); + // The state saves of this thread (partial states, progress, queue) are written, + // synced and renamed on the queue-saver thread: a slow disk must not stop the + // handing out of articles (statesaver). + let async_saves = crate::statesaver::AsyncSaves::enter(); self.load(host); self.adjust_downloads_limit(host); let mut was_standby = true; @@ -2515,6 +2519,8 @@ impl NzbgetRsQueueCoordinator { self.save_all_partial_state(host); self.save_queue_if_changed(host); self.save_all_file_state(host); + drop(async_saves); + crate::statesaver::drain(); host.log( crate::queuesubsys_host::MK_DEBUG, diff --git a/rust/src/statesaver.rs b/rust/src/statesaver.rs new file mode 100644 index 000000000..28715a762 --- /dev/null +++ b/rust/src/statesaver.rs @@ -0,0 +1,471 @@ +//! Writes the queue's state files (queue, progress, partial states `s`, ...) on a +//! background thread, `queue-saver`, so the queue coordinator never waits for a disk +//! sync. On 6790 a post-processing move kept the queue disk busy and each fdatasync +//! of the once-a-second saves took 0.4-3.5 s; the coordinator held the queue lock and +//! handed out no articles meanwhile (108 MB/s fell to 4-20 MB/s). +//! +//! The content is still serialized by the caller, under the queue lock, so each file is +//! a consistent snapshot; only the write, the sync, the rename and the directory sync +//! move here. Only the thread inside an [`AsyncSaves`] scope (the coordinator) queues its +//! saves; every other caller writes inline as before, after the jobs queued for the same +//! file. Queued jobs run first in, first out; a newer write of a file still queued +//! replaces its content in place (latest content, first position: partial states, then +//! progress, then queue, as they were saved). A delete goes to the back, behind the +//! writes it follows. Readers call [`settle`] first, so they see the latest content. + +use crate::diskstate_format::DiskLogLevel; +use std::collections::VecDeque; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; + +/// What a job does to its file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum JobKind { + /// Write `bytes`; `transactional` writes `temp` and renames it over the file, + /// `sync` (FlushQueue) syncs the data before the rename and the directory after. + Write { + bytes: Vec, + transactional: bool, + sync: bool, + }, + /// Delete the file, and `temp` too when `temp_too`. + Delete { temp_too: bool }, +} + +/// One state file to write or delete. `path` identifies it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Job { + pub path: Vec, + pub temp: Vec, + pub sep: u8, + pub kind: JobKind, +} + +pub(crate) type Log<'a> = &'a mut dyn FnMut(DiskLogLevel, &[u8]); +type Exec = dyn Fn(&Job, Log<'_>) -> bool + Send + Sync; + +#[derive(Default)] +struct State { + queue: VecDeque, + /// Files whose job runs right now, on the saver thread or inline in a caller. + in_flight: Vec>, + thread_started: bool, +} + +pub(crate) struct Saver { + state: Mutex, + cv: Condvar, + exec: Box, +} + +thread_local! { + static ASYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While alive, this thread's state saves are queued for the saver thread. +pub(crate) struct AsyncSaves(bool); + +impl AsyncSaves { + pub(crate) fn enter() -> Self { + Self(ASYNC.with(|a| a.replace(true))) + } +} + +impl Drop for AsyncSaves { + fn drop(&mut self) { + let prev = self.0; + ASYNC.with(|a| a.set(prev)); + } +} + +fn active_log(level: DiskLogLevel, msg: &[u8]) { + crate::log::log_active_bytes(level.kind() as i32, msg); +} + +impl Saver { + pub(crate) fn new(exec: Box) -> Arc { + Arc::new(Self { + state: Mutex::new(State::default()), + cv: Condvar::new(), + exec, + }) + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait<'a>(&self, st: MutexGuard<'a, State>) -> MutexGuard<'a, State> { + self.cv.wait(st).unwrap_or_else(|e| e.into_inner()) + } + + /// Queues `job` when this thread saves asynchronously (true), else runs it now + /// and returns its result. + pub(crate) fn submit(self: &Arc, job: Job, log: Log<'_>) -> bool { + if ASYNC.with(|a| a.get()) { + self.enqueue(job); + true + } else { + let mut st = self.lock(); + // This newer content (or delete) replaces a queued one. + st.queue.retain(|j| j.path != job.path); + self.run_marked(st, job, log) + } + } + + /// Queues `job` for the saver thread, coalescing with a queued job for its file. + pub(crate) fn enqueue(self: &Arc, job: Job) { + let mut st = self.lock(); + match st.queue.iter().position(|j| j.path == job.path) { + Some(i) + if matches!(st.queue[i].kind, JobKind::Write { .. }) + && matches!(job.kind, JobKind::Write { .. }) => + { + st.queue[i] = job; + } + Some(i) => { + st.queue.remove(i); + st.queue.push_back(job); + } + None => st.queue.push_back(job), + } + if !st.thread_started { + let me = Arc::clone(self); + if std::thread::Builder::new() + .name("queue-saver".into()) + .spawn(move || me.worker()) + .is_ok() + { + st.thread_started = true; + } else { + // No thread: run the queue here, as before. + drop(st); + self.run_queue_inline(); + return; + } + } + self.cv.notify_all(); + } + + /// Waits for a job running for the same file, then runs `job` in this thread. + fn run_marked(&self, st: MutexGuard<'_, State>, job: Job, log: Log<'_>) -> bool { + let _mark = self.mark(st, &job.path); + (self.exec)(&job, log) + } + + /// Waits until no job runs for `path`, then marks it running until the guard drops. + fn mark<'a>(&'a self, mut st: MutexGuard<'_, State>, path: &'a [u8]) -> Mark<'a> { + while st.in_flight.iter().any(|p| p == path) { + st = self.wait(st); + } + st.in_flight.push(path.to_vec()); + Mark { saver: self, path } + } + + fn next_job(&self, st: &mut State) -> Option { + let i = st + .queue + .iter() + .position(|j| !st.in_flight.contains(&j.path))?; + st.queue.remove(i) + } + + fn worker(&self) { + loop { + let mut st = self.lock(); + let job = loop { + if let Some(job) = self.next_job(&mut st) { + break job; + } + st = self.wait(st); + }; + self.run_marked(st, job, &mut active_log); + } + } + + fn run_queue_inline(&self) { + loop { + let mut st = self.lock(); + let Some(job) = self.next_job(&mut st) else { + return; + }; + self.run_marked(st, job, &mut active_log); + } + } + + /// Makes the latest content of `path` reach the disk before a caller reads, + /// stats or deletes it: runs its queued job now, in this thread, or waits for + /// the one running. + pub(crate) fn settle(&self, path: &[u8]) { + self.settled(path, || ()); + } + + /// [`Saver::settle`], then runs `f` while no job can touch `path`: a reader that + /// checks the file and its `.new` never sees the moment of a rename. + pub(crate) fn settled(&self, path: &[u8], f: impl FnOnce() -> R) -> R { + let mut st = self.lock(); + let pending = st + .queue + .iter() + .position(|j| j.path == path) + .and_then(|i| st.queue.remove(i)); + let _mark = self.mark(st, path); + if let Some(job) = pending { + (self.exec)(&job, &mut active_log); + } + f() + } + + /// Waits until every queued job has run (the coordinator's exit). + pub(crate) fn drain(&self) { + let mut st = self.lock(); + while !st.queue.is_empty() || !st.in_flight.is_empty() { + st = self.wait(st); + } + } + + #[cfg(test)] + fn queued_paths(&self) -> Vec> { + self.lock().queue.iter().map(|j| j.path.clone()).collect() + } +} + +/// A file marked running; unmarks it and wakes the waiters on drop. +struct Mark<'a> { + saver: &'a Saver, + path: &'a [u8], +} + +impl Drop for Mark<'_> { + fn drop(&mut self) { + let mut st = self.saver.lock(); + if let Some(i) = st.in_flight.iter().position(|p| p == self.path) { + st.in_flight.swap_remove(i); + } + self.saver.cv.notify_all(); + } +} + +/// The daemon's saver, writing with `diskstate_format::run_state_job`. +pub(crate) fn global() -> &'static Arc { + static SAVER: OnceLock> = OnceLock::new(); + SAVER.get_or_init(|| Saver::new(Box::new(crate::diskstate_format::run_state_job))) +} + +/// [`Saver::submit`] on the daemon's saver. +pub(crate) fn submit(job: Job, log: Log<'_>) -> bool { + global().submit(job, log) +} + +/// [`Saver::settle`] on the daemon's saver. +pub(crate) fn settle(path: &[u8]) { + global().settle(path) +} + +/// [`Saver::settled`] on the daemon's saver. +pub(crate) fn settled(path: &[u8], f: impl FnOnce() -> R) -> R { + global().settled(path, f) +} + +/// [`Saver::drain`] on the daemon's saver. +pub(crate) fn drain() { + global().drain() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// A saver that records the jobs it runs and holds the job of file `hold` while `gate` + /// is set. + fn recording() -> (Arc, Arc>>, Arc) { + let done = Arc::new(Mutex::new(Vec::new())); + let gate = Arc::new(AtomicBool::new(false)); + let (d, g) = (Arc::clone(&done), Arc::clone(&gate)); + let saver = Saver::new(Box::new(move |job: &Job, _log: Log<'_>| { + while job.path == b"hold" && g.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + d.lock().unwrap().push(job.clone()); + true + })); + (saver, done, gate) + } + + fn write(path: &str, content: &str) -> Job { + Job { + path: path.as_bytes().to_vec(), + temp: format!("{path}.new").into_bytes(), + sep: b'/', + kind: JobKind::Write { + bytes: content.as_bytes().to_vec(), + transactional: true, + sync: true, + }, + } + } + + fn delete(path: &str) -> Job { + Job { + kind: JobKind::Delete { temp_too: true }, + ..write(path, "") + } + } + + fn summary(done: &Mutex>) -> Vec { + done.lock() + .unwrap() + .iter() + .map(|j| match &j.kind { + JobKind::Write { bytes, .. } => format!( + "{}={}", + String::from_utf8_lossy(&j.path), + String::from_utf8_lossy(bytes) + ), + JobKind::Delete { .. } => format!("-{}", String::from_utf8_lossy(&j.path)), + }) + .collect() + } + + /// Holds the worker on a first job so the next ones stay queued. + fn hold(saver: &Arc, gate: &AtomicBool) { + gate.store(true, Ordering::SeqCst); + saver.enqueue(write("hold", "0")); + while !saver.queued_paths().is_empty() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + #[test] + fn runs_in_order_and_coalesces_writes_in_first_position() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + saver.enqueue(write("1s", "a")); + saver.enqueue(write("progress", "p1")); + saver.enqueue(write("queue", "q1")); + saver.enqueue(write("1s", "b")); + saver.enqueue(write("progress", "p2")); + assert_eq!(saver.queued_paths().len(), 3); + gate.store(false, Ordering::SeqCst); + saver.drain(); + assert_eq!( + summary(&done), + ["hold=0", "1s=b", "progress=p2", "queue=q1"] + ); + } + + #[test] + fn a_delete_goes_behind_the_writes_it_follows() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + saver.enqueue(write("progress", "p1")); + saver.enqueue(write("queue", "q1")); + saver.enqueue(delete("progress")); + saver.enqueue(write("2s", "x")); + gate.store(false, Ordering::SeqCst); + saver.drain(); + assert_eq!(summary(&done), ["hold=0", "queue=q1", "-progress", "2s=x"]); + } + + #[test] + fn drain_waits_for_every_queued_job() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + for i in 0..20 { + saver.enqueue(write(&format!("{i}s"), "c")); + } + let releaser = { + let gate = Arc::clone(&gate); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(50)); + gate.store(false, Ordering::SeqCst); + }) + }; + saver.drain(); + assert_eq!(done.lock().unwrap().len(), 21); + assert!(saver.queued_paths().is_empty()); + releaser.join().unwrap(); + } + + #[test] + fn settle_runs_a_queued_write_now_and_waits_for_a_running_one() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + saver.enqueue(write("3s", "pending")); + saver.enqueue(write("queue", "q")); + // The worker is held on "hold"; the reader of 3s runs its job itself. + saver.settle(b"3s"); + assert_eq!(summary(&done), ["3s=pending"]); + assert_eq!(saver.queued_paths(), [b"queue".to_vec()]); + // "hold" is running: settling it waits until it is done. + let releaser = { + let gate = Arc::clone(&gate); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(30)); + gate.store(false, Ordering::SeqCst); + }) + }; + saver.settle(b"hold"); + assert!(summary(&done).contains(&"hold=0".to_string())); + releaser.join().unwrap(); + saver.drain(); + assert_eq!(summary(&done), ["3s=pending", "hold=0", "queue=q"]); + } + + #[test] + fn only_an_async_scope_queues_and_an_inline_write_supersedes_a_queued_one() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + { + let _scope = AsyncSaves::enter(); + assert!(saver.submit(write("4s", "old"), &mut |_, _| {})); + assert_eq!(saver.queued_paths(), [b"4s".to_vec()]); + } + // Outside the scope: runs now, and the queued older content is dropped. + assert!(saver.submit(write("4s", "new"), &mut |_, _| {})); + assert!(saver.queued_paths().is_empty()); + assert_eq!(summary(&done), ["4s=new"]); + gate.store(false, Ordering::SeqCst); + saver.drain(); + assert_eq!(summary(&done), ["4s=new", "hold=0"]); + } + + /// The real job writer: a queued save is on disk, readable, after `settle`, + /// and its temporary file is gone. + #[test] + fn read_after_pending_write_sees_the_latest_content() { + use std::os::unix::ffi::OsStrExt; + let dir = std::env::temp_dir().join(format!( + "rg-statesaver-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let saver = Saver::new(Box::new(crate::diskstate_format::run_state_job)); + let path = dir.join("5s"); + let job = |content: &str| Job { + path: path.as_os_str().as_bytes().to_vec(), + temp: dir.join("5s.new").as_os_str().as_bytes().to_vec(), + sep: b'/', + kind: JobKind::Write { + bytes: content.as_bytes().to_vec(), + transactional: true, + sync: true, + }, + }; + { + let _scope = AsyncSaves::enter(); + saver.submit(job("first"), &mut |_, _| {}); + saver.submit(job("second"), &mut |_, _| {}); + } + saver.settle(path.as_os_str().as_bytes()); + assert_eq!(std::fs::read(&path).unwrap(), b"second"); + assert!(!dir.join("5s.new").exists()); + saver.drain(); + assert_eq!(std::fs::read(&path).unwrap(), b"second"); + let _ = std::fs::remove_dir_all(&dir); + } +} From fc8f84264eb874283498430fe97f5d220eb76112 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:46:34 -0800 Subject: [PATCH 3/9] Saver review fixes: survive a panicking save, message log deleted inline A panic in a background save no longer kills the queue-saver thread (later saves and the coordinator's drain would wait for it forever). The message log n.log is appended and read directly, so its delete stays inline instead of queueing behind other saves. The module doc states what crash-time ordering across files is (not) kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/diskstate_format.rs | 4 +++- rust/src/statesaver.rs | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index 31f22bfa5..69efb0ae4 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2180,8 +2180,10 @@ pub fn cache_was_active(qdir: &[u8], sep: u8) -> bool { } /// Removes the message log `n.log`. +/// Deleted inline, not through statesaver: the log is appended and read directly. pub fn delete_nzb_log(qdir: &[u8], sep: u8, nzb_id: i32) { - remove_queue_file(qdir, sep, format!("n{nzb_id}.log").as_bytes()); + let p = queue_file_path(qdir, sep, format!("n{nzb_id}.log").as_bytes()); + let _ = std::fs::remove_file(crate::fsops::path(&p)); } /// The highest nzb and file ids found in the `ids` file and the file names diff --git a/rust/src/statesaver.rs b/rust/src/statesaver.rs index 28715a762..981380583 100644 --- a/rust/src/statesaver.rs +++ b/rust/src/statesaver.rs @@ -12,6 +12,12 @@ //! replaces its content in place (latest content, first position: partial states, then //! progress, then queue, as they were saved). A delete goes to the back, behind the //! writes it follows. Readers call [`settle`] first, so they see the latest content. +//! +//! Across files there is no crash-time ordering beyond that: after a crash the disk +//! can hold a newer `progress` next to an older `queue`, and a queue save whose write +//! fails on this thread has already queued the delete of `progress` behind it. The +//! loader never relied on more (a partial state could already be newer than `queue`, +//! `files` is checked against the queued file count, `ids` is a floor written inline). use crate::diskstate_format::DiskLogLevel; use std::collections::VecDeque; @@ -178,7 +184,16 @@ impl Saver { } st = self.wait(st); }; - self.run_marked(st, job, &mut active_log); + // A panicking job must not kill the thread: later jobs and `drain` wait for it. + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + self.run_marked(st, job, &mut active_log) + })); + if ran.is_err() { + active_log( + DiskLogLevel::Error, + b"Error saving diskstate: a save panicked", + ); + } } } From 8f4157a096d6c4ed4a3bed8fa8b0f36eaf21524f Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:06:09 -0800 Subject: [PATCH 4/9] Queue every thread's state saves while the coordinator runs queuesyncslow still took 37-41 s (bound 30 s, 86 s before) on Linux x86_64, arm64 and macOS: other threads (the API adding an NZB, post- processing, twin and dupe work, file completion) save the queue and the file infos inline under the queue lock, and the coordinator waits for that lock; and a coordinator reading a file whose save was queued ran that save, sync included, itself. While the coordinator runs, the saves of every thread are now queued; before and after (startup, the final saves of a shutdown) they run inline as before, and leaving the scope drains the queue. A reader of a file whose write is queued reads that content from memory instead of waiting for the sync; a queued delete runs at once (no sync). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/diskstate_format.rs | 44 ++++++++++++---- rust/src/queuecoord.rs | 2 +- rust/src/statesaver.rs | 99 +++++++++++++++++++++++++----------- 3 files changed, 103 insertions(+), 42 deletions(-) diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index 69efb0ae4..27d81d27f 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2125,7 +2125,8 @@ fn remove_queue_file(qdir: &[u8], sep: u8, name: &[u8]) { fn queue_file_exists(qdir: &[u8], sep: u8, name: &[u8]) -> bool { let p = queue_file_path(qdir, sep, name); - crate::statesaver::settled(&p, || crate::fsops::posix_stat(&p) == 1) + crate::statesaver::pending_content(&p).is_some() + || crate::statesaver::settled(&p, || crate::fsops::posix_stat(&p) == 1) } /// `DiscardDownloadQueue`: removes the queue and history files and every @@ -4407,7 +4408,7 @@ fn call_ctrl(env: &NzbgetRsDiskStateEnv, cmd: DiskCtrl<'_>) -> i32 { } struct RsStateReader { - reader: std::io::BufReader, + reader: std::io::BufReader>, raw_buf: Vec, cstr_buf: Vec, } @@ -4418,12 +4419,21 @@ impl RsStateReader { if fd == -1 { return Err(crate::fsops::last_errno()); } - let file = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(fd) }; - Ok(Self { - reader: std::io::BufReader::new(file), + let file: std::fs::File = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(fd) }; + Ok(Self::from_reader(Box::new(file))) + } + + /// The content of a save still queued (statesaver), read like the file. + fn from_bytes(bytes: Vec) -> Self { + Self::from_reader(Box::new(std::io::Cursor::new(bytes))) + } + + fn from_reader(reader: Box) -> Self { + Self { + reader: std::io::BufReader::new(reader), raw_buf: Vec::with_capacity(1024), cstr_buf: Vec::with_capacity(1024), - }) + } } fn read_line(&mut self, max_size: usize) -> Option<&[u8]> { @@ -4715,6 +4725,9 @@ impl RsStateFile { } fn file_exists(&self) -> bool { + if crate::statesaver::pending_content(&self.dest).is_some() { + return true; + } crate::statesaver::settled(&self.dest, || { crate::fsops::posix_stat(&self.dest) == 1 || (self.transactional && crate::fsops::posix_stat(&self.temp) == 1) @@ -4730,7 +4743,7 @@ impl RsStateFile { } /// Writes the serialized `w` to the file (`run_state_job`): inline, or on the - /// `queue-saver` thread when called by the queue coordinator (statesaver). + /// `queue-saver` thread while the queue coordinator runs (statesaver). unsafe fn finish_write( &self, env: &NzbgetRsDiskStateEnv, @@ -4750,10 +4763,13 @@ impl RsStateFile { crate::statesaver::submit(job, &mut |level, msg| emit_log(env, level, msg)) } - /// Opens the file for reading once the saves queued for it are on disk, with no - /// save touching it meanwhile (statesaver). + /// Reads the content of a save still queued for the file from memory, else opens + /// the file with no save touching it meanwhile (statesaver). unsafe fn begin_read(&mut self, env: &NzbgetRsDiskStateEnv) -> Option { let dest = self.dest.clone(); + if let Some(bytes) = crate::statesaver::pending_content(&dest) { + return unsafe { self.read_signature(env, RsStateReader::from_bytes(bytes)) }; + } crate::statesaver::settled(&dest, || unsafe { self.begin_read_settled(env) }) } @@ -4794,7 +4810,7 @@ impl RsStateFile { } } - let mut reader = match RsStateReader::open(&self.dest_c) { + let reader = match RsStateReader::open(&self.dest_c) { Ok(r) => r, Err(errno) => { let err = crate::fsops::error_message(errno); @@ -4811,7 +4827,15 @@ impl RsStateFile { return None; } }; + unsafe { self.read_signature(env, reader) } + } + /// Reads the version line; refuses a file newer than this build reads. + unsafe fn read_signature( + &mut self, + env: &NzbgetRsDiskStateEnv, + mut reader: RsStateReader, + ) -> Option { let sig = reader.read_line(128).unwrap_or(b""); self.file_version = parse_format_version(sig); if self.file_version > self.read_version { diff --git a/rust/src/queuecoord.rs b/rust/src/queuecoord.rs index 041bce9dc..3e3a5a4a5 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -2519,8 +2519,8 @@ impl NzbgetRsQueueCoordinator { self.save_all_partial_state(host); self.save_queue_if_changed(host); self.save_all_file_state(host); + // Saves run inline again; the queued ones reach the disk before the loop exits. drop(async_saves); - crate::statesaver::drain(); host.log( crate::queuesubsys_host::MK_DEBUG, diff --git a/rust/src/statesaver.rs b/rust/src/statesaver.rs index 981380583..a8bd4ae43 100644 --- a/rust/src/statesaver.rs +++ b/rust/src/statesaver.rs @@ -6,12 +6,16 @@ //! //! The content is still serialized by the caller, under the queue lock, so each file is //! a consistent snapshot; only the write, the sync, the rename and the directory sync -//! move here. Only the thread inside an [`AsyncSaves`] scope (the coordinator) queues its -//! saves; every other caller writes inline as before, after the jobs queued for the same -//! file. Queued jobs run first in, first out; a newer write of a file still queued +//! move here. While the coordinator runs (its [`AsyncSaves`] scope) every thread's saves +//! are queued: a save made by another thread under the queue lock would otherwise keep +//! the coordinator waiting for that lock. Before and after (startup, the final saves of +//! a shutdown) saves run inline as before, after the jobs queued for the same file. +//! Queued jobs run first in, first out; a newer write of a file still queued //! replaces its content in place (latest content, first position: partial states, then //! progress, then queue, as they were saved). A delete goes to the back, behind the -//! writes it follows. Readers call [`settle`] first, so they see the latest content. +//! writes it follows. A reader gets the content of a queued write from memory +//! ([`Saver::pending_content`]) and otherwise reads the file once no job touches it +//! ([`settled`]), so it sees the latest content without waiting for a sync. //! //! Across files there is no crash-time ordering beyond that: after a crash the disk //! can hold a newer `progress` next to an older `queue`, and a queue save whose write @@ -55,6 +59,8 @@ struct State { /// Files whose job runs right now, on the saver thread or inline in a caller. in_flight: Vec>, thread_started: bool, + /// Saves are queued (the coordinator runs), else run inline. + queue_saves: bool, } pub(crate) struct Saver { @@ -63,23 +69,22 @@ pub(crate) struct Saver { exec: Box, } -thread_local! { - static ASYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// While alive, this thread's state saves are queued for the saver thread. -pub(crate) struct AsyncSaves(bool); +/// While alive, every thread's state saves are queued for the saver thread; on drop, +/// saves run inline again and the queued ones are drained. +pub(crate) struct AsyncSaves(&'static Saver); impl AsyncSaves { pub(crate) fn enter() -> Self { - Self(ASYNC.with(|a| a.replace(true))) + let saver: &'static Saver = global(); + saver.lock().queue_saves = true; + Self(saver) } } impl Drop for AsyncSaves { fn drop(&mut self) { - let prev = self.0; - ASYNC.with(|a| a.set(prev)); + self.0.lock().queue_saves = false; + self.0.drain(); } } @@ -104,14 +109,14 @@ impl Saver { self.cv.wait(st).unwrap_or_else(|e| e.into_inner()) } - /// Queues `job` when this thread saves asynchronously (true), else runs it now - /// and returns its result. + /// Queues `job` while saves are queued (true), else runs it now and returns its + /// result. pub(crate) fn submit(self: &Arc, job: Job, log: Log<'_>) -> bool { - if ASYNC.with(|a| a.get()) { - self.enqueue(job); + let mut st = self.lock(); + if st.queue_saves { + self.enqueue_locked(st, job); true } else { - let mut st = self.lock(); // This newer content (or delete) replaces a queued one. st.queue.retain(|j| j.path != job.path); self.run_marked(st, job, log) @@ -119,8 +124,13 @@ impl Saver { } /// Queues `job` for the saver thread, coalescing with a queued job for its file. - pub(crate) fn enqueue(self: &Arc, job: Job) { - let mut st = self.lock(); + #[cfg(test)] + fn enqueue(self: &Arc, job: Job) { + let st = self.lock(); + self.enqueue_locked(st, job); + } + + fn enqueue_locked(self: &Arc, mut st: MutexGuard<'_, State>, job: Job) { match st.queue.iter().position(|j| j.path == job.path) { Some(i) if matches!(st.queue[i].kind, JobKind::Write { .. }) @@ -230,6 +240,19 @@ impl Saver { f() } + /// The content of a queued write of `path`, for a reader: the file on disk is older. + /// A queued delete runs now (no sync), so the reader finds the file gone. + pub(crate) fn pending_content(&self, path: &[u8]) -> Option> { + let mut st = self.lock(); + let i = st.queue.iter().position(|j| j.path == path)?; + if let JobKind::Write { bytes, .. } = &st.queue[i].kind { + return Some(bytes.clone()); + } + let job = st.queue.remove(i).expect("position is in range"); + self.run_marked(st, job, &mut active_log); + None + } + /// Waits until every queued job has run (the coordinator's exit). pub(crate) fn drain(&self) { let mut st = self.lock(); @@ -281,6 +304,11 @@ pub(crate) fn settled(path: &[u8], f: impl FnOnce() -> R) -> R { global().settled(path, f) } +/// [`Saver::pending_content`] on the daemon's saver. +pub(crate) fn pending_content(path: &[u8]) -> Option> { + global().pending_content(path) +} + /// [`Saver::drain`] on the daemon's saver. pub(crate) fn drain() { global().drain() @@ -428,14 +456,14 @@ mod tests { } #[test] - fn only_an_async_scope_queues_and_an_inline_write_supersedes_a_queued_one() { + fn saves_queue_only_in_a_scope_and_an_inline_write_supersedes_a_queued_one() { let (saver, done, gate) = recording(); hold(&saver, &gate); - { - let _scope = AsyncSaves::enter(); - assert!(saver.submit(write("4s", "old"), &mut |_, _| {})); - assert_eq!(saver.queued_paths(), [b"4s".to_vec()]); - } + saver.lock().queue_saves = true; + assert!(saver.submit(write("4s", "old"), &mut |_, _| {})); + assert_eq!(saver.queued_paths(), [b"4s".to_vec()]); + assert_eq!(saver.pending_content(b"4s"), Some(b"old".to_vec())); + saver.lock().queue_saves = false; // Outside the scope: runs now, and the queued older content is dropped. assert!(saver.submit(write("4s", "new"), &mut |_, _| {})); assert!(saver.queued_paths().is_empty()); @@ -445,6 +473,18 @@ mod tests { assert_eq!(summary(&done), ["4s=new", "hold=0"]); } + #[test] + fn a_reader_of_a_queued_delete_runs_it_now() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + saver.enqueue(delete("6s")); + assert_eq!(saver.pending_content(b"6s"), None); + assert_eq!(summary(&done), ["-6s"]); + assert!(saver.queued_paths().is_empty()); + gate.store(false, Ordering::SeqCst); + saver.drain(); + } + /// The real job writer: a queued save is on disk, readable, after `settle`, /// and its temporary file is gone. #[test] @@ -471,11 +511,8 @@ mod tests { sync: true, }, }; - { - let _scope = AsyncSaves::enter(); - saver.submit(job("first"), &mut |_, _| {}); - saver.submit(job("second"), &mut |_, _| {}); - } + saver.enqueue(job("first")); + saver.enqueue(job("second")); saver.settle(path.as_os_str().as_bytes()); assert_eq!(std::fs::read(&path).unwrap(), b"second"); assert!(!dir.join("5s.new").exists()); From 49ea0df88a2f1315497431b13fa97863005b10d7 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:33:04 -0800 Subject: [PATCH 5/9] A save made under the queue lock is on disk when its thread goes on historyeditlist failed at 6846969d (x86_64 and arm64): an API edit's queue save was queued, the call answered, and a kill right after lost the change. Queuing every thread's saves made acknowledged changes non-durable, even against a plain process crash. Now only the coordinator's saves are queued and never waited for. A save another thread makes under the queue lock is queued too, and that thread waits for it right after it releases the lock (qqueue::CurrentQueueLock drop -> statesaver::queue_lock_released): the coordinator never waits for the lock during someone's sync, and an edit or an added NZB is on disk, synced as before, when the caller gets its answer. A write coalesced into a queued one keeps the older sequence number, so a waiter for the older save waits for the newer. Other saves (no queue lock held) run inline as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/diskstate_format.rs | 3 + rust/src/qqueue.rs | 3 + rust/src/statesaver.rs | 165 +++++++++++++++++++++++++++++------ 3 files changed, 143 insertions(+), 28 deletions(-) diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index 27d81d27f..510c72782 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2115,6 +2115,7 @@ fn queue_file_path(qdir: &[u8], sep: u8, name: &[u8]) -> Vec { fn remove_queue_file(qdir: &[u8], sep: u8, name: &[u8]) { let p = queue_file_path(qdir, sep, name); let job = crate::statesaver::Job { + seq: 0, temp: p.clone(), path: p, sep, @@ -4714,6 +4715,7 @@ impl RsStateFile { fn discard(&self) { let job = crate::statesaver::Job { + seq: 0, path: self.dest.clone(), temp: self.temp.clone(), sep: self.sep, @@ -4751,6 +4753,7 @@ impl RsStateFile { flush_queue: bool, ) -> bool { let job = crate::statesaver::Job { + seq: 0, path: self.dest.clone(), temp: self.temp.clone(), sep: self.sep, diff --git a/rust/src/qqueue.rs b/rust/src/qqueue.rs index 334ad7759..e5ad6a32e 100644 --- a/rust/src/qqueue.rs +++ b/rust/src/qqueue.rs @@ -140,6 +140,7 @@ impl CurrentQueueLock { if let Some(q) = unsafe { q.as_ref() } { q.lock.lock(); } + crate::statesaver::queue_lock_acquired(); Self(q) } @@ -154,6 +155,8 @@ impl Drop for CurrentQueueLock { if let Some(q) = unsafe { self.0.as_ref() } { q.lock.unlock(); } + // Saves queued under the lock reach the disk before this thread goes on. + crate::statesaver::queue_lock_released(); } } diff --git a/rust/src/statesaver.rs b/rust/src/statesaver.rs index a8bd4ae43..4a13d97d4 100644 --- a/rust/src/statesaver.rs +++ b/rust/src/statesaver.rs @@ -6,10 +6,13 @@ //! //! The content is still serialized by the caller, under the queue lock, so each file is //! a consistent snapshot; only the write, the sync, the rename and the directory sync -//! move here. While the coordinator runs (its [`AsyncSaves`] scope) every thread's saves -//! are queued: a save made by another thread under the queue lock would otherwise keep -//! the coordinator waiting for that lock. Before and after (startup, the final saves of -//! a shutdown) saves run inline as before, after the jobs queued for the same file. +//! move here. While the coordinator runs (its [`AsyncSaves`] scope) the coordinator's +//! saves are queued and it never waits for them. Another thread's save made under the +//! queue lock is queued too, and that thread waits for it once it releases the lock +//! (`queue_lock_released`): the coordinator never waits for that lock during a sync, and +//! the save is still on disk when the thread's caller (an API edit, an added NZB) gets +//! its answer. Other saves, and all saves before and after the coordinator runs, run +//! inline as before, after the jobs queued for the same file. //! Queued jobs run first in, first out; a newer write of a file still queued //! replaces its content in place (latest content, first position: partial states, then //! progress, then queue, as they were saved). A delete goes to the back, behind the @@ -44,6 +47,9 @@ pub(crate) enum JobKind { /// One state file to write or delete. `path` identifies it. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Job { + /// Order of submission, set by the saver; a write coalesced into a queued one keeps + /// the older number, so a thread waiting for the older save waits for the newer. + pub seq: u64, pub path: Vec, pub temp: Vec, pub sep: u8, @@ -57,8 +63,9 @@ type Exec = dyn Fn(&Job, Log<'_>) -> bool + Send + Sync; struct State { queue: VecDeque, /// Files whose job runs right now, on the saver thread or inline in a caller. - in_flight: Vec>, + in_flight: Vec<(Vec, u64)>, thread_started: bool, + next_seq: u64, /// Saves are queued (the coordinator runs), else run inline. queue_saves: bool, } @@ -69,7 +76,17 @@ pub(crate) struct Saver { exec: Box, } -/// While alive, every thread's state saves are queued for the saver thread; on drop, +thread_local! { + /// This thread is the coordinator: its saves are queued and never waited for. + static COORDINATOR: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How deep this thread holds the queue lock (`qqueue::CurrentQueueLock`). + static QUEUE_LOCK_DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Saves this thread queued under the queue lock: (file, seq), waited for on release. + static TICKETS: std::cell::RefCell, u64)>> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +/// While alive (the coordinator's loop), saves are queued for the saver thread; on drop, /// saves run inline again and the queued ones are drained. pub(crate) struct AsyncSaves(&'static Saver); @@ -77,17 +94,40 @@ impl AsyncSaves { pub(crate) fn enter() -> Self { let saver: &'static Saver = global(); saver.lock().queue_saves = true; + COORDINATOR.with(|c| c.set(true)); Self(saver) } } impl Drop for AsyncSaves { fn drop(&mut self) { + COORDINATOR.with(|c| c.set(false)); self.0.lock().queue_saves = false; self.0.drain(); } } +/// `qqueue::CurrentQueueLock` took the queue lock. +pub(crate) fn queue_lock_acquired() { + QUEUE_LOCK_DEPTH.with(|d| d.set(d.get() + 1)); +} + +/// `qqueue::CurrentQueueLock` released the queue lock: once this thread holds it no more, +/// it waits for the saves it queued meanwhile, so they are on disk when it goes on. +pub(crate) fn queue_lock_released() { + let depth = QUEUE_LOCK_DEPTH.with(|d| { + let v = d.get().saturating_sub(1); + d.set(v); + v + }); + if depth == 0 { + let tickets = TICKETS.with(|t| std::mem::take(&mut *t.borrow_mut())); + if !tickets.is_empty() { + global().wait_for(&tickets); + } + } +} + fn active_log(level: DiskLogLevel, msg: &[u8]) { crate::log::log_active_bytes(level.kind() as i32, msg); } @@ -109,41 +149,62 @@ impl Saver { self.cv.wait(st).unwrap_or_else(|e| e.into_inner()) } - /// Queues `job` while saves are queued (true), else runs it now and returns its - /// result. - pub(crate) fn submit(self: &Arc, job: Job, log: Log<'_>) -> bool { + /// Queues `job` while saves are queued and this thread is the coordinator (true), + /// or holds the queue lock (true; waited for on release, `queue_lock_released`); + /// else runs it now and returns its result. + pub(crate) fn submit(self: &Arc, mut job: Job, log: Log<'_>) -> bool { let mut st = self.lock(); - if st.queue_saves { - self.enqueue_locked(st, job); + let coordinator = COORDINATOR.with(|c| c.get()); + let under_lock = QUEUE_LOCK_DEPTH.with(|d| d.get() > 0); + if st.queue_saves && (coordinator || under_lock) { + let path = job.path.clone(); + let seq = self.enqueue_locked(st, job); + if !coordinator { + TICKETS.with(|t| t.borrow_mut().push((path, seq))); + } true } else { - // This newer content (or delete) replaces a queued one. - st.queue.retain(|j| j.path != job.path); + st.next_seq += 1; + job.seq = st.next_seq; + // This newer content (or delete) replaces a queued one, and whoever waits + // for that one waits for this. + if let Some(i) = st.queue.iter().position(|j| j.path == job.path) { + job.seq = st.queue.remove(i).expect("position is in range").seq; + } self.run_marked(st, job, log) } } /// Queues `job` for the saver thread, coalescing with a queued job for its file. #[cfg(test)] - fn enqueue(self: &Arc, job: Job) { + fn enqueue(self: &Arc, job: Job) -> u64 { let st = self.lock(); - self.enqueue_locked(st, job); + self.enqueue_locked(st, job) } - fn enqueue_locked(self: &Arc, mut st: MutexGuard<'_, State>, job: Job) { - match st.queue.iter().position(|j| j.path == job.path) { + /// Queues `job`; returns the seq a waiter for it waits for. + fn enqueue_locked(self: &Arc, mut st: MutexGuard<'_, State>, mut job: Job) -> u64 { + st.next_seq += 1; + job.seq = st.next_seq; + let seq = match st.queue.iter().position(|j| j.path == job.path) { Some(i) if matches!(st.queue[i].kind, JobKind::Write { .. }) && matches!(job.kind, JobKind::Write { .. }) => { + job.seq = st.queue[i].seq; st.queue[i] = job; + st.queue[i].seq } Some(i) => { st.queue.remove(i); st.queue.push_back(job); + st.next_seq } - None => st.queue.push_back(job), - } + None => { + st.queue.push_back(job); + st.next_seq + } + }; if !st.thread_started { let me = Arc::clone(self); if std::thread::Builder::new() @@ -156,24 +217,41 @@ impl Saver { // No thread: run the queue here, as before. drop(st); self.run_queue_inline(); - return; + return seq; } } self.cv.notify_all(); + seq + } + + /// Waits until none of `tickets` (file, seq) is queued or running. + fn wait_for(&self, tickets: &[(Vec, u64)]) { + let mut st = self.lock(); + loop { + let busy = tickets.iter().any(|(p, s)| { + st.queue.iter().any(|j| j.path == *p && j.seq <= *s) + || st.in_flight.iter().any(|(fp, fs)| fp == p && fs <= s) + }); + if !busy { + return; + } + st = self.wait(st); + } } /// Waits for a job running for the same file, then runs `job` in this thread. fn run_marked(&self, st: MutexGuard<'_, State>, job: Job, log: Log<'_>) -> bool { - let _mark = self.mark(st, &job.path); + let _mark = self.mark(st, &job.path, job.seq); (self.exec)(&job, log) } - /// Waits until no job runs for `path`, then marks it running until the guard drops. - fn mark<'a>(&'a self, mut st: MutexGuard<'_, State>, path: &'a [u8]) -> Mark<'a> { - while st.in_flight.iter().any(|p| p == path) { + /// Waits until no job runs for `path`, then marks it running (as save `seq`; a + /// reader marks with `u64::MAX`, which no waiter waits for) until the guard drops. + fn mark<'a>(&'a self, mut st: MutexGuard<'_, State>, path: &'a [u8], seq: u64) -> Mark<'a> { + while st.in_flight.iter().any(|(p, _)| p == path) { st = self.wait(st); } - st.in_flight.push(path.to_vec()); + st.in_flight.push((path.to_vec(), seq)); Mark { saver: self, path } } @@ -181,7 +259,7 @@ impl Saver { let i = st .queue .iter() - .position(|j| !st.in_flight.contains(&j.path))?; + .position(|j| !st.in_flight.iter().any(|(p, _)| *p == j.path))?; st.queue.remove(i) } @@ -233,7 +311,8 @@ impl Saver { .iter() .position(|j| j.path == path) .and_then(|i| st.queue.remove(i)); - let _mark = self.mark(st, path); + let seq = pending.as_ref().map_or(u64::MAX, |j| j.seq); + let _mark = self.mark(st, path, seq); if let Some(job) = pending { (self.exec)(&job, &mut active_log); } @@ -276,7 +355,7 @@ struct Mark<'a> { impl Drop for Mark<'_> { fn drop(&mut self) { let mut st = self.saver.lock(); - if let Some(i) = st.in_flight.iter().position(|p| p == self.path) { + if let Some(i) = st.in_flight.iter().position(|(p, _)| p == self.path) { st.in_flight.swap_remove(i); } self.saver.cv.notify_all(); @@ -337,6 +416,7 @@ mod tests { fn write(path: &str, content: &str) -> Job { Job { + seq: 0, path: path.as_bytes().to_vec(), temp: format!("{path}.new").into_bytes(), sep: b'/', @@ -460,7 +540,13 @@ mod tests { let (saver, done, gate) = recording(); hold(&saver, &gate); saver.lock().queue_saves = true; + // Neither the coordinator nor under the queue lock: inline. + assert!(saver.submit(write("7s", "inline"), &mut |_, _| {})); + assert_eq!(summary(&done), ["7s=inline"]); + done.lock().unwrap().clear(); + COORDINATOR.with(|c| c.set(true)); assert!(saver.submit(write("4s", "old"), &mut |_, _| {})); + COORDINATOR.with(|c| c.set(false)); assert_eq!(saver.queued_paths(), [b"4s".to_vec()]); assert_eq!(saver.pending_content(b"4s"), Some(b"old".to_vec())); saver.lock().queue_saves = false; @@ -485,6 +571,28 @@ mod tests { saver.drain(); } + #[test] + fn a_save_queued_under_the_queue_lock_is_waited_for_after_the_lock() { + let (saver, done, gate) = recording(); + hold(&saver, &gate); + let first = saver.enqueue(write("queue", "q1")); + let second = saver.enqueue(write("queue", "q2")); + assert_eq!( + first, second, + "a coalesced write keeps its place and number" + ); + let releaser = { + let gate = Arc::clone(&gate); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(30)); + gate.store(false, Ordering::SeqCst); + }) + }; + saver.wait_for(&[(b"queue".to_vec(), first)]); + assert_eq!(summary(&done), ["hold=0", "queue=q2"]); + releaser.join().unwrap(); + } + /// The real job writer: a queued save is on disk, readable, after `settle`, /// and its temporary file is gone. #[test] @@ -502,6 +610,7 @@ mod tests { let saver = Saver::new(Box::new(crate::diskstate_format::run_state_job)); let path = dir.join("5s"); let job = |content: &str| Job { + seq: 0, path: path.as_os_str().as_bytes().to_vec(), temp: dir.join("5s.new").as_os_str().as_bytes().to_vec(), sep: b'/', From 7fb1871248cbc91694e2df412f059d130ce0df75 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:42:21 -0800 Subject: [PATCH 6/9] Saver: take a job off the queue only once its file is idle settled(), an inline save superseding a queued one and a reader running a queued delete took the job off the queue and then waited, with the saver lock released, for an older save of the same file. In that gap the job was neither queued nor running, so a thread waiting for its save could return before the content was on disk. They now wait until the file is idle first and take and mark the job in one hold. Also fixes the indentation of one Job literal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/diskstate_format.rs | 2 +- rust/src/statesaver.rs | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index 510c72782..1ca1bc4d2 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2115,7 +2115,7 @@ fn queue_file_path(qdir: &[u8], sep: u8, name: &[u8]) -> Vec { fn remove_queue_file(qdir: &[u8], sep: u8, name: &[u8]) { let p = queue_file_path(qdir, sep, name); let job = crate::statesaver::Job { - seq: 0, + seq: 0, temp: p.clone(), path: p, sep, diff --git a/rust/src/statesaver.rs b/rust/src/statesaver.rs index 4a13d97d4..fca7289be 100644 --- a/rust/src/statesaver.rs +++ b/rust/src/statesaver.rs @@ -164,6 +164,8 @@ impl Saver { } true } else { + // Taken off the queue and marked running in one hold (see `idle`). + st = self.idle(st, &job.path); st.next_seq += 1; job.seq = st.next_seq; // This newer content (or delete) replaces a queued one, and whoever waits @@ -239,6 +241,16 @@ impl Saver { } } + /// Waits until no job runs for `path`. A caller that takes a job of `path` off the + /// queue does so after this, in the same hold as `mark`, so the job is never out of + /// both the queue and the running list (where `wait_for` could miss it). + fn idle<'a>(&self, mut st: MutexGuard<'a, State>, path: &[u8]) -> MutexGuard<'a, State> { + while st.in_flight.iter().any(|(p, _)| p == path) { + st = self.wait(st); + } + st + } + /// Waits for a job running for the same file, then runs `job` in this thread. fn run_marked(&self, st: MutexGuard<'_, State>, job: Job, log: Log<'_>) -> bool { let _mark = self.mark(st, &job.path, job.seq); @@ -305,7 +317,7 @@ impl Saver { /// [`Saver::settle`], then runs `f` while no job can touch `path`: a reader that /// checks the file and its `.new` never sees the moment of a rename. pub(crate) fn settled(&self, path: &[u8], f: impl FnOnce() -> R) -> R { - let mut st = self.lock(); + let mut st = self.idle(self.lock(), path); let pending = st .queue .iter() @@ -327,6 +339,11 @@ impl Saver { if let JobKind::Write { bytes, .. } = &st.queue[i].kind { return Some(bytes.clone()); } + st = self.idle(st, path); + let i = st.queue.iter().position(|j| j.path == path)?; + if let JobKind::Write { bytes, .. } = &st.queue[i].kind { + return Some(bytes.clone()); + } let job = st.queue.remove(i).expect("position is in range"); self.run_marked(st, job, &mut active_log); None From 414838f154335124d0a58fbf5722f3df2e8a380d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:26:53 -0800 Subject: [PATCH 7/9] Test hook for a slow coordinator pass and the queuebatchstart scenario RUSTYGET_TEST_COORD_PASS_DELAY_MS sleeps after each pass of the queue coordinator loop, as a long queue and queue-lock waits slow it on 6790. queuebatchstart (30 connections, 1 s per article, 100 ms per pass) asserts that at least 24 articles are in flight at once and that a small first item and a second item download together. Starting one article per pass, this commit alone stays near 10 in flight; the fix follows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/queuecoord.rs | 17 +++++++++++ tests/functional/dupefallback/harness.py | 38 ++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/rust/src/queuecoord.rs b/rust/src/queuecoord.rs index 3e3a5a4a5..93af452eb 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -839,6 +839,22 @@ pub(crate) fn backup_may_lend_while_extracting( ) } +/// Test hook: `RUSTYGET_TEST_COORD_PASS_DELAY_MS` sleeps that long after each pass of +/// the coordinator loop (outside the queue lock), as a pass slowed by a long queue and +/// lock waits is (6790). The queuebatchstart scenario sets it; unset, it costs one load. +fn test_coord_pass_delay() { + static DELAY_MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let ms = *DELAY_MS.get_or_init(|| { + std::env::var("RUSTYGET_TEST_COORD_PASS_DELAY_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0) + }); + if ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(ms)); + } +} + /// Set while the download next in line waits for its dead-pick probe's connection (see /// `dupeprobe::probe_waiting_for_connection`): the queue has work left, so it neither idles /// nor, in standalone mode, ends with the download unfinished. @@ -2462,6 +2478,7 @@ impl NzbgetRsQueueCoordinator { } } }); + test_coord_pass_delay(); crate::parchecker::streaming_session_retry_completion_tick(); self.drain_live_par_completed_files(host); diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index 1250b429f..e06e485da 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -1803,6 +1803,39 @@ def scenario_truncatedstate(daemon, t): state, h['Status'], integ, _grep_log(t, 'Discarding damaged download state'))) +def scenario_queuebatchstart(daemon, t): + """Each pass of the queue coordinator takes 100 ms (RUSTYGET_TEST_COORD_PASS_DELAY_MS, + as a long queue and lock waits make it on 6790) and each article 1 s (proxy). Started + one per pass, at most about 10 articles are ever in flight however many connections + there are (6790: 117 of 345); started in a batch per pass, the 30 connections fill. + A small item (6 articles) comes first: the second item must start in the same passes, + so both download at once.""" + seg = 50_000 + small = _payload(6 * seg, 5100) + big = _payload(90 * seg, 5101) + pa = _place_copy(t, 'qbA', small, 'a.bin') + pb = _place_copy(t, 'qbB', big, 'b.bin') + api = daemon.wait_ready() + daemon.append(api, 'RelQBA', build_nzb(pa, 'qba.bin', len(small), seg, set()), False, 'qba-key', 100) + daemon.append(api, 'RelQBB', build_nzb(pb, 'qbb.bin', len(big), seg, set()), False, 'qbb-key', 100) + peak, both = 0, False + deadline = time.time() + 120 + while time.time() < deadline: + groups = api.listgroups() + active = {g['NZBName']: g.get('ActiveDownloads', 0) for g in groups} + peak = max(peak, sum(active.values())) + both |= active.get('RelQBA', 0) > 0 and active.get('RelQBB', 0) > 0 + if not groups: + break + time.sleep(0.1) + ha = daemon.wait_history(api, 'RelQBA', timeout=60) + hb = daemon.wait_history(api, 'RelQBB', timeout=60) + ok = (ha['Status'].startswith('SUCCESS') and hb['Status'].startswith('SUCCESS') + and peak >= 24 and both) + return ('queuebatchstart', ok, 'status=%s/%s peak_in_flight=%d of 30 (need 24) both_at_once=%s' % ( + ha['Status'], hb['Status'], peak, both)) + + def scenario_queuesyncslow(daemon, t): """Every sync of a saved state file takes a second (RUSTYGET_TEST_STATE_SYNC_DELAY_MS, as on 6790 while a post-processing move saturated the queue disk with FlushQueue=yes). @@ -15289,6 +15322,7 @@ def scenario_dupausedunpack(daemon, t): 'stream': scenario_stream, 'truncatedstate': scenario_truncatedstate, 'queuesyncslow': scenario_queuesyncslow, + 'queuebatchstart': scenario_queuebatchstart, 'streamrestartcredit': scenario_streamrestartcredit, 'streamtimeout': scenario_streamtimeout, 'streamdeaddonor': scenario_streamdeaddonor, @@ -15728,6 +15762,8 @@ def scenario_dupausedunpack(daemon, t): 'persistrestartdamaged': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, # each state-file sync takes 1 s (diskstate_format::test_state_sync_delay) 'queuesyncslow': {'RUSTYGET_TEST_STATE_SYNC_DELAY_MS': '1000'}, + # each pass of the queue coordinator takes 100 ms (queuecoord::test_coord_pass_delay) + 'queuebatchstart': {'RUSTYGET_TEST_COORD_PASS_DELAY_MS': '100'}, } SCENARIO_ENV_KEYS = sorted({k for env in SCENARIO_ENV.values() for k in env}) @@ -15780,6 +15816,7 @@ def scenario_dupausedunpack(daemon, t): 'stream': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'truncatedstate': ['ContinuePartial=yes', 'FlushQueue=yes', 'Server1.Connections=1'], 'queuesyncslow': ['ContinuePartial=yes', 'FlushQueue=yes', 'Server1.Connections=6'], + 'queuebatchstart': ['Server1.Connections=30'], 'streamrestartcredit': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'streamdeaddonor': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'rejectnextserver': ['DupeArticleFallback=article', 'ArticleRetries=0'], @@ -16237,6 +16274,7 @@ def _promote_fallback(options, mode): 'directunpackkeepnointer': [(b'rel.part03', 2.0)], 'truncatedstate': [(b'tsA/', 0.5)], 'queuesyncslow': [(b'qsA/', 0.3)], + 'queuebatchstart': [(b'qbA/', 1.0), (b'qbB/', 1.0)], 'reloadmidrepair': [(b'rlDon/', 2.0)], 'streamrestartcredit': [(b'srSlow/', 3.0)], 'restartfailover': [(b'rfA/', 0.4)], From 255b0d8b1d58ee0ff80614ebfeef354069ff479d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:27:01 -0800 Subject: [PATCH 8/9] Start up to 64 articles per coordinator pass Each pass of the queue coordinator took the queue lock, scanned the queue, started at most one article, then ran the live drains and slept 5 ms when nothing started. In flight = start rate x article time, so a slow pass (a long queue, lock waits) capped the articles in flight: 6790 held about 117 of 345 connections busy on one item while 148 items waited, and 10-58 earlier. Within one hold of the queue lock the coordinator now keeps starting articles while one is assignable, a connection is free and the downloads limit allows, up to 64. The pick is unchanged per article (get_next_article: fleet rules, dupe gate, held donors), a pick held for its dead-pick probe ends the batch, and a second item starts in the same pass once the first has nothing assignable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/queuecoord.rs | 110 +++++++++++++++++++++++------------------ 1 file changed, 63 insertions(+), 47 deletions(-) diff --git a/rust/src/queuecoord.rs b/rust/src/queuecoord.rs index 93af452eb..a458b17ad 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -839,6 +839,9 @@ pub(crate) fn backup_may_lend_while_extracting( ) } +/// Articles the coordinator starts at most in one hold of the queue lock. +const MAX_STARTS_PER_PASS: usize = 64; + /// Test hook: `RUSTYGET_TEST_COORD_PASS_DELAY_MS` sleeps that long after each pass of /// the coordinator loop (outside the queue lock), as a pass slowed by a long queue and /// lock waits is (6790). The queuebatchstart scenario sets it; unset, it costs one load. @@ -2425,57 +2428,70 @@ impl NzbgetRsQueueCoordinator { let mut downloads_checked = false; let mut download_started = false; + // Start articles while one is assignable, a connection is free and the limit + // allows, up to MAX_STARTS_PER_PASS in one hold of the queue lock: one start per + // pass (each pass taking the lock, scanning the queue and running the live + // drains) capped the start rate, and so the articles in flight (6790: 117 of + // 345 connections busy on one item while 148 waited). host.with_locked_queue(|dq_ptr| { let opts = host.opts(); - let next_pair = self.get_next_article(host, &opts, dq_ptr); - // The download next in line waits while its dead-pick probe waits for a - // connection (see `dupeprobe::probe_waiting_for_connection`): the connection it - // would take goes to the probe. Nothing of lower priority takes it meanwhile - // (a fleet's primary stays first), and the queue stays busy (`PROBE_HELD`). - let held = next_pair.as_ref().is_some_and(|(file, _)| { - crate::dupeprobe::probe_waiting_for_connection( - host.nzb_snap(file.nzb_ptr, false).id, - ) - }); - PROBE_HELD.store(held, std::sync::atomic::Ordering::Relaxed); - let next_pair = if held { None } else { next_pair }; - let has_more_articles = next_pair.is_some() || held; - let active_len = host.active_downloads_len(); - article_downloads_running = active_len > 0; - host.self_set_has_more_jobs(has_more_articles || article_downloads_running); - - let dl_limit = self - .downloads_limit - .load(std::sync::atomic::Ordering::Relaxed); - let effective_limit = host.effective_downloads_limit(dl_limit); - let can_proceed = !host.self_is_stopped() && (active_len as i32) < effective_limit; - - if let Some((file, art)) = next_pair { - if can_proceed && (!opts.download_held || file.extra_priority) { - let nzb = host.nzb_snap(file.nzb_ptr, false); - let conn_ptr = host.server_pool_get_connection( - nzb.has_desired_server, - nzb.desired_server_id, + for _ in 0..MAX_STARTS_PER_PASS { + let next_pair = self.get_next_article(host, &opts, dq_ptr); + // The download next in line waits while its dead-pick probe waits for a + // connection (see `dupeprobe::probe_waiting_for_connection`): the connection it + // would take goes to the probe. Nothing of lower priority takes it meanwhile + // (a fleet's primary stays first), and the queue stays busy (`PROBE_HELD`). + let held = next_pair.as_ref().is_some_and(|(file, _)| { + crate::dupeprobe::probe_waiting_for_connection( + host.nzb_snap(file.nzb_ptr, false).id, + ) + }); + PROBE_HELD.store(held, std::sync::atomic::Ordering::Relaxed); + let next_pair = if held { None } else { next_pair }; + let has_more_articles = next_pair.is_some() || held; + let active_len = host.active_downloads_len(); + article_downloads_running = active_len > 0; + host.self_set_has_more_jobs(has_more_articles || article_downloads_running); + + let dl_limit = self + .downloads_limit + .load(std::sync::atomic::Ordering::Relaxed); + let effective_limit = host.effective_downloads_limit(dl_limit); + let can_proceed = + !host.self_is_stopped() && (active_len as i32) < effective_limit; + + let Some((file, art)) = next_pair else { + break; + }; + if !(can_proceed && (!opts.download_held || file.extra_priority)) { + break; + } + let nzb = host.nzb_snap(file.nzb_ptr, false); + let conn_ptr = host.server_pool_get_connection( + nzb.has_desired_server, + nzb.desired_server_id, + ); + if conn_ptr != 0 { + downloads_checked = true; + article_downloads_running = true; + download_started = true; + self.start_dead_pick_probe(host, &opts, dq_ptr, &nzb); + self.start_article_download(host, &opts, &nzb, &file, &art, conn_ptr); + continue; + } else if nzb.has_desired_server { + let mut dbg = b"Could not start download for ".to_vec(); + dbg.extend_from_slice(&nzb.name); + dbg.extend_from_slice( + format!( + ": desired server {} has no available connections", + nzb.desired_server_id + ) + .as_bytes(), ); - if conn_ptr != 0 { - downloads_checked = true; - article_downloads_running = true; - download_started = true; - self.start_dead_pick_probe(host, &opts, dq_ptr, &nzb); - self.start_article_download(host, &opts, &nzb, &file, &art, conn_ptr); - } else if nzb.has_desired_server { - let mut dbg = b"Could not start download for ".to_vec(); - dbg.extend_from_slice(&nzb.name); - dbg.extend_from_slice( - format!( - ": desired server {} has no available connections", - nzb.desired_server_id - ) - .as_bytes(), - ); - host.log(crate::queuesubsys_host::MK_DEBUG, &dbg); - } + host.log(crate::queuesubsys_host::MK_DEBUG, &dbg); } + // No connection free: the rest waits for the next pass. + break; } }); test_coord_pass_delay(); From d63364dacd399ee30d0da573d231a624a0745ce4 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:42:45 -0800 Subject: [PATCH 9/9] Batch starts: stop a pass after 5 ms as well One hold of the queue lock could cover 64 picks, each a queue scan; on a long queue the API and edits would wait for the lock meanwhile. A pass now also stops starting once 5 ms have gone by (the next pass goes on at once, with no sleep, when it started something). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/queuecoord.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/rust/src/queuecoord.rs b/rust/src/queuecoord.rs index a458b17ad..3bd504e74 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -839,8 +839,11 @@ pub(crate) fn backup_may_lend_while_extracting( ) } -/// Articles the coordinator starts at most in one hold of the queue lock. +/// Articles the coordinator starts at most in one hold of the queue lock ... const MAX_STARTS_PER_PASS: usize = 64; +/// ... and the time it goes on starting more in one hold (a long queue makes each pick +/// a scan; the API and edits wait for the lock meanwhile). +const MAX_START_PASS_TIME: std::time::Duration = std::time::Duration::from_millis(5); /// Test hook: `RUSTYGET_TEST_COORD_PASS_DELAY_MS` sleeps that long after each pass of /// the coordinator loop (outside the queue lock), as a pass slowed by a long queue and @@ -2435,7 +2438,11 @@ impl NzbgetRsQueueCoordinator { // 345 connections busy on one item while 148 waited). host.with_locked_queue(|dq_ptr| { let opts = host.opts(); - for _ in 0..MAX_STARTS_PER_PASS { + let pass_start = std::time::Instant::now(); + for n in 0..MAX_STARTS_PER_PASS { + if n > 0 && pass_start.elapsed() >= MAX_START_PASS_TIME { + break; + } let next_pair = self.get_next_article(host, &opts, dq_ptr); // The download next in line waits while its dead-pick probe waits for a // connection (see `dupeprobe::probe_waiting_for_connection`): the connection it