diff --git a/rust/src/diskstate_format.rs b/rust/src/diskstate_format.rs index dc3765054..1ca1bc4d2 100644 --- a/rust/src/diskstate_format.rs +++ b/rust/src/diskstate_format.rs @@ -2111,18 +2111,30 @@ 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 { + seq: 0, + 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::pending_content(&p).is_some() + || 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) { @@ -2170,8 +2182,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 @@ -4395,7 +4409,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, } @@ -4406,12 +4420,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]> { @@ -4520,6 +4543,141 @@ 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)); + } +} + +/// 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], @@ -4556,127 +4714,72 @@ 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 { + seq: 0, + 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) + 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) + }) } - 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 while the queue coordinator runs (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()); - 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; - } + let job = crate::statesaver::Job { + seq: 0, + 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)) + } - 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(); - 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, - ], - ); - } + /// 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)) }; } - - true + crate::statesaver::settled(&dest, || unsafe { self.begin_read_settled(env) }) } - unsafe fn begin_read(&mut self, env: &NzbgetRsDiskStateEnv) -> Option { + 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 { @@ -4710,7 +4813,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); @@ -4727,7 +4830,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 { @@ -4803,7 +4914,7 @@ impl TrailerAccum { unsafe fn save_nzb_section( env: &NzbgetRsDiskStateEnv, - w: &mut std::io::BufWriter, + w: &mut Vec, source: NzbSource, header_count: i32, ) { @@ -4815,7 +4926,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, @@ -6047,6 +6158,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/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/queuecoord.rs b/rust/src/queuecoord.rs index 29e2277ec..3bd504e74 100644 --- a/rust/src/queuecoord.rs +++ b/rust/src/queuecoord.rs @@ -839,6 +839,28 @@ 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; +/// ... 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 +/// 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. @@ -2393,6 +2415,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; @@ -2405,59 +2431,77 @@ 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, + 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 + // 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(); crate::parchecker::streaming_session_retry_completion_tick(); self.drain_live_par_completed_files(host); @@ -2515,6 +2559,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); 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..fca7289be --- /dev/null +++ b/rust/src/statesaver.rs @@ -0,0 +1,649 @@ +//! 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. 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 +//! 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 +//! 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; +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 { + /// 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, + 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<(Vec, u64)>, + thread_started: bool, + next_seq: u64, + /// Saves are queued (the coordinator runs), else run inline. + queue_saves: bool, +} + +pub(crate) struct Saver { + state: Mutex, + cv: Condvar, + exec: Box, +} + +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); + +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); +} + +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` 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(); + 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 { + // 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 + // 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) -> u64 { + let st = self.lock(); + self.enqueue_locked(st, job) + } + + /// 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); + st.next_seq + } + }; + 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 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 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); + (self.exec)(&job, log) + } + + /// 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(), seq)); + Mark { saver: self, path } + } + + fn next_job(&self, st: &mut State) -> Option { + let i = st + .queue + .iter() + .position(|j| !st.in_flight.iter().any(|(p, _)| *p == 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); + }; + // 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", + ); + } + } + } + + 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.idle(self.lock(), path); + let pending = st + .queue + .iter() + .position(|j| j.path == path) + .and_then(|i| st.queue.remove(i)); + 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); + } + 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()); + } + 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 + } + + /// 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::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() +} + +#[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 { + seq: 0, + 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 saves_queue_only_in_a_scope_and_an_inline_write_supersedes_a_queued_one() { + 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; + // 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"]); + } + + #[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(); + } + + #[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] + 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 { + 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'/', + kind: JobKind::Write { + bytes: content.as_bytes().to_vec(), + transactional: true, + sync: true, + }, + }; + 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()); + saver.drain(); + assert_eq!(std::fs::read(&path).unwrap(), b"second"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index e1023467e..e06e485da 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -1803,6 +1803,62 @@ 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). + 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 +15321,8 @@ def scenario_dupausedunpack(daemon, t): 'manydonors': scenario_manydonors, 'stream': scenario_stream, 'truncatedstate': scenario_truncatedstate, + 'queuesyncslow': scenario_queuesyncslow, + 'queuebatchstart': scenario_queuebatchstart, 'streamrestartcredit': scenario_streamrestartcredit, 'streamtimeout': scenario_streamtimeout, 'streamdeaddonor': scenario_streamdeaddonor, @@ -15702,6 +15760,10 @@ 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'}, + # 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}) @@ -15753,6 +15815,8 @@ 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'], + 'queuebatchstart': ['Server1.Connections=30'], 'streamrestartcredit': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'streamdeaddonor': ['DupeArticleFallback=stream', 'ParCheck=auto'], 'rejectnextserver': ['DupeArticleFallback=article', 'ArticleRetries=0'], @@ -16209,6 +16273,8 @@ 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)], + 'queuebatchstart': [(b'qbA/', 1.0), (b'qbB/', 1.0)], 'reloadmidrepair': [(b'rlDon/', 2.0)], 'streamrestartcredit': [(b'srSlow/', 3.0)], 'restartfailover': [(b'rfA/', 0.4)],