diff --git a/rust/src/donorstore.rs b/rust/src/donorstore.rs new file mode 100644 index 000000000..35bc80ed2 --- /dev/null +++ b/rust/src/donorstore.rs @@ -0,0 +1,443 @@ +//! Donor articles fetched to map or sample a donor copy (a twin or alt), kept on disk by message-id so no +//! later pass fetches them again. +//! +//! Mapping an alt walks every volume of its container (`ContentMapper::build_map_with_tls`): +//! the first article of each volume, and the last one where the end-of-archive block lies. +//! TwinCheck sampling and the fleet intake read the same header and tail articles. Every +//! repair run of a download builds its donor's map again (one run per hole), and the borrow +//! starts with the header article of the volume it reads. The in-memory memo of recent +//! articles (`streamrepair_coord::RECENT_SINGLES`, 64 articles / 48 MB) holds less than one +//! walk of a large set (AltB: 85 volumes, 170 articles, 88 MB), so it evicted everything +//! before the next run asked again: on the 4 GiB alt failover run each of two runs fetched +//! all 170 articles (finding 6 of the 2026-11-26 audit). +//! +//! This store keeps those articles in files under `/rustyget-donor-articles-/` +//! and only their index in memory. A message-id names the same article bytes on every +//! server, so an article is served from here for any later run, check or borrow. Each entry +//! is owned by the downloads it was fetched for; [`forget`] drops a download's entries when +//! it leaves the queue (or starts over), and the whole store is capped at +//! [`STORE_MAX_BYTES`] and [`STORE_MAX_ARTICLES`] (oldest out first). +//! +//! Only articles that came back whole are kept; a failed or missing article is never stored. + +use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +/// Most bytes the store keeps on disk. +pub const STORE_MAX_BYTES: u64 = 512 << 20; +/// Most articles the store keeps. +pub const STORE_MAX_ARTICLES: usize = 4096; +/// An article bigger than this is not kept (news articles are well under 1 MB). +pub const STORE_MAX_ARTICLE: usize = 8 << 20; + +/// Owner of an entry fetched by a check that belongs to no download in particular: it goes +/// only when the caps push it out. +pub const NO_OWNER: i32 = -1; + +const DIR_PREFIX: &str = "rustyget-donor-articles-"; + +/// A stored article as it was fetched. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StoredArticle { + pub offset: i64, + pub file_size: i64, + pub data: Vec, +} + +struct Entry { + file: PathBuf, + len: u64, + offset: i64, + file_size: i64, + owners: BTreeSet, +} + +#[derive(Default)] +struct Store { + dir: Option, + next: u64, + bytes: u64, + entries: HashMap, Entry>, + order: VecDeque>, + /// Articles served from the store, and articles put into it (counters for logs and tests). + hits: u64, + puts: u64, +} + +static STORE: Mutex> = Mutex::new(None); + +fn lock() -> std::sync::MutexGuard<'static, Option> { + STORE.lock().unwrap_or_else(|e| e.into_inner()) +} + +#[cfg(unix)] +fn path_of(b: &[u8]) -> PathBuf { + use std::os::unix::ffi::OsStrExt; + PathBuf::from(std::ffi::OsStr::from_bytes(b)) +} + +#[cfg(not(unix))] +fn path_of(b: &[u8]) -> PathBuf { + PathBuf::from(String::from_utf8_lossy(b).into_owned()) +} + +fn base_dir() -> PathBuf { + if let Some(opts) = crate::options::active_options() { + let tmp = opts.str_bytes(crate::options::OptStr::TempDir); + if !tmp.is_empty() { + return path_of(tmp); + } + } + std::env::temp_dir() +} + +/// Removes the stores that earlier processes left behind (a crash, a kill): a directory of +/// this name whose process no longer runs. Another daemon sharing the temp folder keeps its own. +fn remove_stale(base: &Path) { + let Ok(rd) = std::fs::read_dir(base) else { + return; + }; + for de in rd.flatten() { + let name = de.file_name(); + // `-` + let Some(pid) = name + .to_str() + .and_then(|n| n.strip_prefix(DIR_PREFIX)) + .and_then(|p| p.split('-').next()) + .and_then(|p| p.parse::().ok()) + else { + continue; + }; + // One of this process id is from an earlier run (a container's daemon gets the same + // small id each start): this process makes its own only after this cleanup. + let own = pid as u32 == std::process::id(); + if pid <= 0 || (!own && process_alive(pid)) { + continue; + } + let path = de.path(); + // a real directory only, never one reached through a symlink + if std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) { + let _ = std::fs::remove_dir_all(&path); + } + } +} + +#[cfg(unix)] +fn process_alive(pid: i32) -> bool { + // SAFETY: signal 0 only checks that the process exists. + let r = unsafe { libc::kill(pid, 0) }; + r == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH) +} + +#[cfg(not(unix))] +fn process_alive(_pid: i32) -> bool { + true +} + +/// A new directory only this user can enter, named for this process and a nonce: never one +/// that exists already (another daemon's, a reused process id's, or one planted in a shared +/// temp folder), and never through a symlink. +fn create_private_dir(base: &Path) -> Option { + use std::hash::{BuildHasher, Hasher}; + for _ in 0..8 { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()), + ); + let dir = base.join(format!("{DIR_PREFIX}{}-{:016x}", std::process::id(), h.finish())); + let mut b = std::fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + b.mode(0o700); + } + match b.create(&dir) { + Ok(()) => return Some(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(_) => return None, + } + } + None +} + +fn store_dir(s: &mut Store) -> Option { + if let Some(d) = &s.dir { + return Some(d.clone()); + } + let dir = create_private_dir(&base_dir())?; + s.dir = Some(dir.clone()); + Some(dir) +} + +/// Stores of earlier processes are removed once, before the first article is kept, outside +/// the store's lock (a large one takes a while). +static CLEANED: std::sync::Once = std::sync::Once::new(); + +fn drop_entry(s: &mut Store, msg_id: &[u8]) { + if let Some(e) = s.entries.remove(msg_id) { + s.bytes = s.bytes.saturating_sub(e.len); + let _ = std::fs::remove_file(&e.file); + } +} + +/// The message-id without its angle brackets: callers name an article either way. +fn key(msg_id: &[u8]) -> &[u8] { + let m = msg_id.strip_prefix(b"<").unwrap_or(msg_id); + m.strip_suffix(b">").unwrap_or(m) +} + +/// The bytes of `path` as [`put`] wrote them for `msg_id` (the key's length in 4 bytes, the +/// key, then `len` article bytes), or `None` unless it is a regular file of exactly that size +/// holding that key: a file of another article is never served under this message-id. +fn read_bounded(path: &Path, msg_id: &[u8], len: u64) -> Option> { + let head = 4 + msg_id.len() as u64; + let mut f = std::fs::File::open(path).ok()?; + let meta = f.metadata().ok()?; + if !meta.is_file() || meta.len() != head + len { + return None; + } + let mut key_len = [0u8; 4]; + f.read_exact(&mut key_len).ok()?; + let mut stored_key = vec![0u8; usize::try_from(u32::from_le_bytes(key_len)).ok()?]; + if stored_key.len() != msg_id.len() { + return None; + } + f.read_exact(&mut stored_key).ok()?; + if stored_key != msg_id { + return None; + } + let mut data = vec![0u8; usize::try_from(len).ok()?]; + f.read_exact(&mut data).ok()?; + Some(data) +} + +/// The article stored under `msg_id`, now also owned by `owner`; `None` when none is held or +/// its file can no longer be read whole (the entry is dropped then). +pub fn get(owner: i32, msg_id: &[u8]) -> Option { + let msg_id = key(msg_id); + let (file, len, offset, file_size) = { + let mut g = lock(); + let s = g.as_mut()?; + let e = s.entries.get_mut(msg_id)?; + if owner != NO_OWNER { + e.owners.insert(owner); + } + (e.file.clone(), e.len, e.offset, e.file_size) + }; + match read_bounded(&file, msg_id, len) { + Some(data) => { + if let Some(s) = lock().as_mut() { + s.hits += 1; + } + Some(StoredArticle { + offset, + file_size, + data, + }) + } + None => { + if let Some(s) = lock().as_mut() { + // only the entry that pointed at this file + if s.entries.get(msg_id).is_some_and(|e| e.file == file) { + drop_entry(s, msg_id); + s.order.retain(|id| id.as_slice() != msg_id); + } + } + None + } + } +} + +/// True when an article is stored under `msg_id` (no file read). +pub fn contains(msg_id: &[u8]) -> bool { + let msg_id = key(msg_id); + lock() + .as_ref() + .is_some_and(|s| s.entries.contains_key(msg_id)) +} + +/// Keeps an article fetched whole for `owner`. One already held only gains the owner. +pub fn put(owner: i32, msg_id: &[u8], offset: i64, file_size: i64, data: &[u8]) { + let msg_id = key(msg_id); + if msg_id.is_empty() || msg_id.len() > 1024 || data.is_empty() || data.len() > STORE_MAX_ARTICLE { + return; + } + CLEANED.call_once(|| remove_stale(&base_dir())); + let file = { + let mut g = lock(); + let s = g.get_or_insert_with(Store::default); + if let Some(e) = s.entries.get_mut(msg_id) { + if owner != NO_OWNER { + e.owners.insert(owner); + } + return; + } + let Some(dir) = store_dir(s) else { + return; + }; + s.next += 1; + dir.join(format!("{}.art", s.next)) + }; + // written outside the lock; the entry appears only once the file is whole + let written = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&file) + .and_then(|mut f| { + let key_len = u32::try_from(msg_id.len()).unwrap_or(u32::MAX); + f.write_all(&key_len.to_le_bytes())?; + f.write_all(msg_id)?; + f.write_all(data) + }); + if written.is_err() { + let _ = std::fs::remove_file(&file); + return; + } + let len = data.len() as u64; + let mut g = lock(); + let Some(s) = g.as_mut() else { + let _ = std::fs::remove_file(&file); + return; + }; + if let Some(e) = s.entries.get_mut(msg_id) { + // another thread stored it meanwhile + if owner != NO_OWNER { + e.owners.insert(owner); + } + let _ = std::fs::remove_file(&file); + return; + } + while !s.order.is_empty() + && (s.entries.len() >= STORE_MAX_ARTICLES || s.bytes + len > STORE_MAX_BYTES) + { + if let Some(old) = s.order.pop_front() { + drop_entry(s, &old); + } + } + let mut owners = BTreeSet::new(); + if owner != NO_OWNER { + owners.insert(owner); + } + s.entries.insert( + msg_id.to_vec(), + Entry { + file, + len, + offset, + file_size, + owners, + }, + ); + s.order.push_back(msg_id.to_vec()); + s.bytes += len; + s.puts += 1; +} + +/// Drops `owner` from every entry; entries no other download owns go (the download left the +/// queue or starts over). Entries of [`NO_OWNER`] stay until the caps push them out. +pub fn forget(owner: i32) { + if owner == NO_OWNER { + return; + } + let mut g = lock(); + let Some(s) = g.as_mut() else { + return; + }; + let mut gone = Vec::new(); + for (id, e) in &mut s.entries { + if e.owners.remove(&owner) && e.owners.is_empty() { + gone.push(id.clone()); + } + } + for id in &gone { + drop_entry(s, id); + } + s.order.retain(|id| s.entries.contains_key(id)); +} + +/// (articles held, bytes held, articles served, articles stored) since the process started. +pub fn stats() -> (usize, u64, u64, u64) { + lock() + .as_ref() + .map_or((0, 0, 0, 0), |s| (s.entries.len(), s.bytes, s.hits, s.puts)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_returns_and_forgets_by_owner() { + let id = format!("", std::process::id()).into_bytes(); + let id2 = format!("", std::process::id()).into_bytes(); + assert!(get(7001, &id).is_none()); + put(7001, &id, 716_800, 51_200_000, b"header bytes"); + put(7002, &id2, 0, 51_200_000, b"tail bytes"); + assert!(contains(&id)); + let got = get(7003, &id).expect("stored"); + assert_eq!(got.offset, 716_800); + assert_eq!(got.file_size, 51_200_000); + assert_eq!(got.data, b"header bytes"); + // still owned by 7003 after 7001 forgets it + forget(7001); + assert!(contains(&id)); + forget(7003); + assert!(!contains(&id)); + assert!(contains(&id2)); + forget(7002); + assert!(!contains(&id2)); + } + + #[test] + fn a_stored_file_that_changed_size_is_not_served() { + let id = format!("", std::process::id()).into_bytes(); + put(7010, &id, 0, 10, b"0123456789"); + let file = lock() + .as_ref() + .and_then(|s| s.entries.get(key(&id)).map(|e| e.file.clone())) + .expect("entry"); + std::fs::write(&file, b"0123").unwrap(); + assert!(get(7010, &id).is_none()); + assert!(!contains(&id)); + } + + #[test] + fn a_file_of_another_article_is_never_served() { + let id = format!("", std::process::id()).into_bytes(); + put(7040, &id, 0, 4, b"abcd"); + let file = lock() + .as_ref() + .and_then(|s| s.entries.get(key(&id)).map(|e| e.file.clone())) + .expect("entry"); + // the same size, the bytes of an article under another message-id of equal length + let other = key(&id).iter().map(|&b| if b == b'k' { b'K' } else { b }).collect::>(); + let mut forged = (other.len() as u32).to_le_bytes().to_vec(); + forged.extend_from_slice(&other); + forged.extend_from_slice(b"wxyz"); + std::fs::write(&file, &forged).unwrap(); + assert!(get(7040, &id).is_none()); + assert!(!contains(&id)); + } + + #[test] + fn a_message_id_with_or_without_brackets_is_one_article() { + let bare = format!("donorstore-br-{}@x", std::process::id()); + put(7030, format!("<{bare}>").as_bytes(), 0, 3, b"abc"); + assert_eq!(get(7030, bare.as_bytes()).map(|a| a.data), Some(b"abc".to_vec())); + forget(7030); + assert!(!contains(bare.as_bytes())); + } + + #[test] + fn empty_and_oversized_articles_are_not_kept() { + let id = format!("", std::process::id()).into_bytes(); + put(7020, &id, 0, 0, b""); + assert!(!contains(&id)); + put(7020, &id, 0, 0, &vec![0u8; STORE_MAX_ARTICLE + 1]); + assert!(!contains(&id)); + } +} diff --git a/rust/src/dupesearch_coord.rs b/rust/src/dupesearch_coord.rs index a062bc8ce..d1696ac95 100644 --- a/rust/src/dupesearch_coord.rs +++ b/rust/src/dupesearch_coord.rs @@ -2139,6 +2139,16 @@ fn fetch_any_article_via_host( groups: &[String], deadline: i64, ) -> FetchedArticleResult { + // an article this process fetched already (a header or tail an earlier map, check or + // repair run read) is not fetched again + if let Some(held) = crate::donorstore::get(crate::donorstore::NO_OWNER, message_id) { + return FetchedArticleResult { + success: true, + offset: held.offset, + file_size: held.file_size, + data: held.data, + }; + } let Some(nntp_host) = get_nntp_fetch_host(host_ctx, host_cb) else { return FetchedArticleResult::default(); }; @@ -2166,6 +2176,9 @@ fn fetch_any_article_via_host( move |bracketed_id, grp_slice| { let g_vecs: Vec> = grp_slice.iter().map(|g| g.as_bytes().to_vec()).collect(); let art = fetcher.fetch(bracketed_id, &g_vecs); + if art.success { + crate::donorstore::put(crate::donorstore::NO_OWNER, bracketed_id, art.offset, art.file_size, &art.data); + } Ok(FetchedArticleResult { success: art.success, offset: art.offset, diff --git a/rust/src/historycoord.rs b/rust/src/historycoord.rs index 4f1a0cfa2..456c7ea85 100644 --- a/rust/src/historycoord.rs +++ b/rust/src/historycoord.rs @@ -2036,6 +2036,7 @@ mod native { self.nzb_set_int(nzb_ptr, NZB_INT_REPROCESS, c_int::from(reprocess)); self.nzb_set_str(nzb_ptr, NZB_STR_FINAL_DIR, b""); crate::postproc::forget_dead_volume_verdicts(nzb.id); + crate::donorstore::forget(nzb.id); crate::postproc::forget_put_back(nzb.id); self.history_return_to_queue(dq, hist, hidx as usize); } diff --git a/rust/src/lib.rs b/rust/src/lib.rs index ac736120c..3275e0d75 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -147,6 +147,7 @@ mod reload_ownership_tests; pub mod deadpostings; pub mod dupeintake; +pub mod donorstore; pub mod dupewatch; pub mod streamcompare; pub mod streampatchparts; diff --git a/rust/src/postproc.rs b/rust/src/postproc.rs index 7729880ad..f0d7598a8 100644 --- a/rust/src/postproc.rs +++ b/rust/src/postproc.rs @@ -4378,6 +4378,9 @@ fn kept_borrows() -> std::sync::MutexGuard< pub(crate) fn direct_unpack_forget_holds(nzb_id: i32) { note_dead_volume_borrow(nzb_id, false); forget_dead_volume_verdicts(nzb_id); + // The donor articles fetched for it go too. Not when post-processing still repairs it + // (`direct_unpack_forget_holds_keep_borrows`): its repair maps the donor again. + crate::donorstore::forget(nzb_id); let gone = direct_unpack_holds().remove(&nzb_id); let kept = kept_borrows().remove(&nzb_id); for v in gone diff --git a/rust/src/prepost.rs b/rust/src/prepost.rs index cdda88b6b..ebce87e7f 100644 --- a/rust/src/prepost.rs +++ b/rust/src/prepost.rs @@ -1800,6 +1800,7 @@ impl NzbgetRsPrePostProcessor { crate::parlive::forget_download_writes(nzb2.id); crate::livewrite::forget(nzb2.id); crate::postproc::forget_dead_volume_verdicts(nzb2.id); + crate::donorstore::forget(nzb2.id); crate::postproc::forget_put_back(nzb2.id); dupe_gate_forget(nzb2.id); crate::postproc::direct_unpack_join_live_par_repair(nzb2.id); diff --git a/rust/src/streamrepair_coord.rs b/rust/src/streamrepair_coord.rs index 3bb4f01f1..01efa83d3 100644 --- a/rust/src/streamrepair_coord.rs +++ b/rust/src/streamrepair_coord.rs @@ -543,7 +543,32 @@ fn recent_single(msg_id: &[u8]) -> Option { None } -fn keep_single(msg_id: &[u8], article: FetchedDonorArticle) { +/// An article already fetched: from the memos of recent articles, or else from the store of +/// donor articles fetched to map or sample a donor copy ([`crate::donorstore`], on disk, which +/// `owner`, the download repaired, now also owns). The flag is true when the store served it. +fn held_article(owner: i32, msg_id: &[u8]) -> Option<(FetchedDonorArticle, bool)> { + if let Some(hit) = recent_single(msg_id) { + return Some((hit, false)); + } + let stored = crate::donorstore::get(owner, msg_id)?; + Some(( + FetchedDonorArticle { + success: true, + offset: stored.offset, + file_size: stored.file_size, + data: stored.data, + }, + true, + )) +} + +/// Keeps a single fetch (archive headers and footers while the payload map is built, a +/// member's size) in memory and in the donor article store for `owner`: every later run of +/// the download maps its donor again and asks for the same articles. +fn keep_single(owner: i32, msg_id: &[u8], article: FetchedDonorArticle) { + if article.success { + crate::donorstore::put(owner, msg_id, article.offset, article.file_size, &article.data); + } keep_in(&RECENT_SINGLES, msg_id, article); } @@ -583,30 +608,41 @@ fn keep_in( true } -/// A donor article to fetch: its message-id and its groups. -type PrefetchId = (Vec, Arc>>); +/// A donor article to fetch: its message-id, its groups, and whether it is the first or last +/// article of its volume (the ones a payload map reads: kept in the donor article store too). +type PrefetchId = (Vec, Arc>>, bool); + +/// True when part `pi` of a volume of `parts` articles is its first or last (see [`PrefetchId`]). +fn is_edge_part(pi: usize, parts: usize) -> bool { + pi == 0 || pi + 1 == parts +} /// One article of an open prefetch batch, in delivery order: already held (fetched by an /// earlier repair run or check moments ago, so never fetched again), or still to come from /// the batch fetcher under this message-id. enum PrefetchSlot { - Held(FetchedDonorArticle), - Fetching(Vec), + /// Held already; true when the donor article store served it (not the memos). + Held(FetchedDonorArticle, bool), + /// To come from the batch fetcher; true for a volume's first or last article. + Fetching(Vec, bool), } /// The batch to fetch for `ids` (in delivery order) and the delivery plan: articles /// [`RECENT_SINGLES`] holds are served from it instead of the network. A borrow run, the /// identity check before it and the next run often want the same donor articles (the one /// straddling a dead volume's edge, a probe window); each is fetched once. -fn plan_prefetch(ids: Vec) -> (Vec, std::collections::VecDeque) { +fn plan_prefetch( + owner: i32, + ids: Vec, +) -> (Vec, std::collections::VecDeque) { expire_batched(); let mut requests = Vec::with_capacity(ids.len()); let mut plan = std::collections::VecDeque::with_capacity(ids.len()); - for (message_id, groups) in ids { - match recent_single(&message_id) { - Some(hit) => plan.push_back(PrefetchSlot::Held(hit)), + for (message_id, groups, edge) in ids { + match held_article(owner, &message_id) { + Some((hit, stored)) => plan.push_back(PrefetchSlot::Held(hit, stored)), None => { - plan.push_back(PrefetchSlot::Fetching(message_id.clone())); + plan.push_back(PrefetchSlot::Fetching(message_id.clone(), edge)); requests.push(BatchRequest { message_id, groups }); } } @@ -631,6 +667,9 @@ struct DonorFetchStats { /// Articles served from the memory of recent articles ([`RECENT_SINGLES`], /// [`RECENT_BATCHED`]) instead of the network: not in `singles` or `batch_parts`. from_memory: u32, + /// Articles served from the donor article store ([`crate::donorstore`]): fetched by an + /// earlier run, check or map of this process, so not fetched again. + from_store: u32, } impl DonorFetchStats { @@ -652,7 +691,7 @@ impl DonorFetchStats { msg.extend_from_slice(donor); msg.extend_from_slice( format!( - ": {:.1} MB in {:.1} s, waiting on the network {:.1} s; {} single fetch(es), {} batch(es) of {} article(s) ({} wave(s) of {} across volumes, largest {}), {} taken from memory, {} worker(s)", + ": {:.1} MB in {:.1} s, waiting on the network {:.1} s; {} single fetch(es), {} batch(es) of {} article(s) ({} wave(s) of {} across volumes, largest {}), {} taken from memory, {} from the fetched-article store, {} worker(s)", self.bytes as f64 / 1_000_000.0, elapsed.as_secs_f64(), self.waited.as_secs_f64(), @@ -663,6 +702,7 @@ impl DonorFetchStats { self.wave_parts, self.largest, self.from_memory, + self.from_store, workers, ) .as_bytes(), @@ -746,13 +786,18 @@ impl NzbgetRsStreamRepairCtrl { /// Bytes fetched count into `fetch_stats`, held ones do not. fn next_planned_article(&self) -> Option { let slot = self.prefetch_plan.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); - let message_id = match slot { - Some(PrefetchSlot::Held(hit)) => { - self.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()).from_memory += 1; + let (message_id, edge) = match slot { + Some(PrefetchSlot::Held(hit, stored)) => { + let mut st = self.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()); + if stored { + st.from_store += 1; + } else { + st.from_memory += 1; + } return Some(hit); } - Some(PrefetchSlot::Fetching(id)) => Some(id), - None => None, + Some(PrefetchSlot::Fetching(id, edge)) => (Some(id), edge), + None => (None, false), }; let fetched = self.batch_fetcher.next()?; self.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()).bytes += fetched.data.len() as u64; @@ -763,6 +808,10 @@ impl NzbgetRsStreamRepairCtrl { data: fetched.data, }; if let (true, Some(id)) = (article.success, message_id) { + if edge { + // a volume's first or last article: the next run's payload map reads it + crate::donorstore::put(self.nzb_id, &id, article.offset, article.file_size, &article.data); + } keep_batched(&id, article.clone()); } Some(article) @@ -1765,13 +1814,16 @@ impl NzbgetRsStreamRepairCtrl { let Some(df) = self.donor_files.get(donor_file_index as usize) else { return; }; + let parts = df.article_msg_ids.len(); let ids = part_indices .iter() .filter(|&&pi| pi >= 0) - .filter_map(|&pi| df.article_msg_ids.get(pi as usize)) - .map(|id| (id.clone(), Arc::clone(&df.groups))) + .filter_map(|&pi| { + let id = df.article_msg_ids.get(pi as usize)?; + Some((id.clone(), Arc::clone(&df.groups), is_edge_part(pi as usize, parts))) + }) .collect(); - let (requests, plan) = plan_prefetch(ids); + let (requests, plan) = plan_prefetch(self.ctrl.nzb_id, ids); *self.ctrl.prefetch_plan.lock().unwrap_or_else(|e| e.into_inner()) = plan; self.ctrl.batch_fetcher.begin(requests); } @@ -2103,14 +2155,20 @@ impl NzbgetRsStreamRepairCtrl { } let df = self.donor_files.get(member_index as usize)?; let msg_id = df.article_msg_ids.get(part_index as usize)?; - if let Some(hit) = recent_single(msg_id) { - self.ctrl.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()).from_memory += 1; + if let Some((hit, stored)) = held_article(self.ctrl.nzb_id, msg_id) { + let mut st = self.ctrl.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()); + if stored { + st.from_store += 1; + } else { + st.from_memory += 1; + } return Some(hit); } let started = std::time::Instant::now(); let fetched = self.ctrl.fetcher.fetch(msg_id, &df.groups); if fetched.success { keep_single( + self.ctrl.nzb_id, msg_id, FetchedDonorArticle { success: true, @@ -2141,13 +2199,16 @@ impl NzbgetRsStreamRepairCtrl { let Some(df) = self.donor_files.get(member_index as usize) else { return; }; + let parts = df.article_msg_ids.len(); let ids = part_indices .iter() .filter(|&&pi| pi >= 0) - .filter_map(|&pi| df.article_msg_ids.get(pi as usize)) - .map(|id| (id.clone(), Arc::clone(&df.groups))) + .filter_map(|&pi| { + let id = df.article_msg_ids.get(pi as usize)?; + Some((id.clone(), Arc::clone(&df.groups), is_edge_part(pi as usize, parts))) + }) .collect(); - let (requests, plan) = plan_prefetch(ids); + let (requests, plan) = plan_prefetch(self.ctrl.nzb_id, ids); { let mut st = self.ctrl.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()); st.count_batch(requests.len(), false); @@ -2163,8 +2224,10 @@ impl NzbgetRsStreamRepairCtrl { .ok() .and_then(|m| self.donor_files.get(m)) .and_then(|df| { - let id = df.article_msg_ids.get(usize::try_from(part).ok()?)?; - Some((id.clone(), Arc::clone(&df.groups))) + let pi = usize::try_from(part).ok()?; + let id = df.article_msg_ids.get(pi)?; + let edge = is_edge_part(pi, df.article_msg_ids.len()); + Some((id.clone(), Arc::clone(&df.groups), edge)) }); // Every part must map to a request, or the delivery order would shift. let Some(id) = msg else { @@ -2172,7 +2235,7 @@ impl NzbgetRsStreamRepairCtrl { }; ids.push(id); } - let (requests, plan) = plan_prefetch(ids); + let (requests, plan) = plan_prefetch(self.ctrl.nzb_id, ids); { let mut st = self.ctrl.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()); st.count_batch(requests.len(), true); @@ -2205,12 +2268,14 @@ impl NzbgetRsStreamRepairCtrl { let Some(df) = self.donor_files.get(member_index as usize) else { return; }; + let parts = df.article_msg_ids.len(); let ids = df .article_msg_ids .iter() - .map(|msg_id| (msg_id.clone(), Arc::clone(&df.groups))) + .enumerate() + .map(|(pi, msg_id)| (msg_id.clone(), Arc::clone(&df.groups), is_edge_part(pi, parts))) .collect(); - let (requests, plan) = plan_prefetch(ids); + let (requests, plan) = plan_prefetch(self.ctrl.nzb_id, ids); { let mut st = self.ctrl.fetch_stats.lock().unwrap_or_else(|e| e.into_inner()); st.count_batch(requests.len(), false); @@ -3420,14 +3485,14 @@ mod tests { keep_batched(&held, article); let groups = Arc::new(vec![b"alt.binaries.test".to_vec()]); let (requests, plan) = - plan_prefetch(vec![(fresh.clone(), Arc::clone(&groups)), (held.clone(), groups)]); + plan_prefetch(-1, vec![(fresh.clone(), Arc::clone(&groups), false), (held.clone(), groups, false)]); // Only the article not held goes to the network; delivery keeps the asked order. assert_eq!(requests.iter().map(|r| r.message_id.clone()).collect::>(), vec![fresh.clone()]); - assert!(matches!(plan.front(), Some(PrefetchSlot::Fetching(id)) if *id == fresh)); - assert!(matches!(plan.back(), Some(PrefetchSlot::Held(a)) if a.data == vec![7, 8, 9])); + assert!(matches!(plan.front(), Some(PrefetchSlot::Fetching(id, false)) if *id == fresh)); + assert!(matches!(plan.back(), Some(PrefetchSlot::Held(a, false)) if a.data == vec![7, 8, 9])); // A batch of many articles never pushes the headers' singles out. let header = b"".to_vec(); - keep_single(&header, FetchedDonorArticle { success: true, offset: 0, file_size: 1, data: vec![1] }); + keep_single(-1, &header, FetchedDonorArticle { success: true, offset: 0, file_size: 1, data: vec![1] }); for i in 0..RECENT_SINGLES_MAX * 2 { keep_batched( format!("").as_bytes(), @@ -3504,11 +3569,12 @@ mod tests { bytes: 30_000_000, waited: std::time::Duration::from_secs(9), from_memory: 41, + from_store: 170, }; let line = String::from_utf8(st.line(b"Copy.05", std::time::Duration::from_secs(12), 8)).unwrap(); assert_eq!( line, - "Fetch cost of borrowing from Copy.05: 30.0 MB in 12.0 s, waiting on the network 9.0 s; 3 single fetch(es), 2 batch(es) of 40 article(s) (1 wave(s) of 30 across volumes, largest 30), 41 taken from memory, 8 worker(s)" + "Fetch cost of borrowing from Copy.05: 30.0 MB in 12.0 s, waiting on the network 9.0 s; 3 single fetch(es), 2 batch(es) of 40 article(s) (1 wave(s) of 30 across volumes, largest 30), 41 taken from memory, 170 from the fetched-article store, 8 worker(s)" ); } diff --git a/rust/src/twin.rs b/rust/src/twin.rs index f0cb5732a..593f3f4bb 100644 --- a/rust/src/twin.rs +++ b/rust/src/twin.rs @@ -1955,10 +1955,26 @@ fn run_twin_job(token: usize, qdir: &[u8]) { ..Default::default() }); } + // a sample (a volume's header or tail among them) fetched by an earlier + // check, map or repair run of this process is not fetched again + if let Some(held) = crate::donorstore::get(spec.primary_id, id) { + return Some(crate::articlefetcher::FetchedArticle { + data: held.data, + offset: held.offset, + file_size: held.file_size, + success: true, + ..Default::default() + }); + } let groups: Vec> = e.groups.iter().map(|g| g.as_bytes().to_vec()).collect(); // (a fetch that every server answers 430 for is recorded, so // the next attempt skips it too) - Some(fetcher.fetch(id, &groups)) + let got = fetcher.fetch(id, &groups); + if got.success { + // kept for the payload map and the borrow that may follow + crate::donorstore::put(spec.primary_id, id, got.offset, got.file_size, &got.data); + } + Some(got) }; // both articles of a pair; the second only when the first was read, // since the pair can't be compared otherwise diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index d99e7e9d5..3495070c8 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -5268,6 +5268,78 @@ def scenario_deadvolumeunlabelled(daemon, t): % (hp['Status'], hb['Status'], failed_over, _grep_log(t, 'lends the lost parts'), late)) +def scenario_altfetchonce(daemon, t): + """Audit finding 6 (2026-11-26): borrowing from an alt fetched each donor article from the + network once. A stored rar set without par2 loses one volume whole and two articles of a + later one: two holes, so two repair runs, each of which maps the alt again (the first and + last article of every one of its 90 volumes: 180 articles, more than the 64-article memo + of recent articles holds, and the 72 MB the download fetches between the two runs pushes + them out of nntp-rs's 64 MB body cache too). The alt is the same 90 MB movie in another + stored rar (1 MB volumes, 50 KB articles; the download's are 3 MB and 100 KB), in + history, labelled an alt. Every donor article the maps, TwinCheck and the + borrows read must reach the network once (no message-id asked twice), and the donor bytes + fetched stay within the borrowed range plus one first and last article per donor volume, + plus the batch margin around each hole (DONOR_PATCH_MARGIN_PARTS articles each side, and + the article each hole edge falls in).""" + tag = 'afo' + seg = 100_000 + donor_seg = 50_000 + movie = _payload(90_000_000, 23090) + vols = generators.rar3_store_volumes_valid('movie.mkv', movie, 3_000_000) + dead_vol, holed_vol, holes = 3, 27, {10, 11} + members = [] + lost = 0 + for i, data in enumerate(vols): + name = 'Show.part%02d.rar' % (i + 1) + rel = '%sA/%s' % (tag, name) + t.write_file(os.path.join('data', rel), data) + parts = (len(data) + seg - 1) // seg + missing = set(range(1, parts + 1)) if i == dead_vol else (holes if i == holed_vol else set()) + lost += sum(min(seg, len(data) - (k - 1) * seg) for k in missing) + members.append((rel, name, len(data), seg, missing)) + alt = generators.rar3_store_volumes_valid('movie.mkv', movie, 1_000_000) + donor_members = [] + edges = 0 + for i, data in enumerate(alt): + name = 'Other.part%02d.rar' % (i + 1) + rel = '%sB/%s' % (tag, name) + t.write_file(os.path.join('data', rel), data) + donor_members.append((rel, name, len(data), donor_seg, set())) + parts = (len(data) + donor_seg - 1) // donor_seg + last = len(data) - (parts - 1) * donor_seg + edges += donor_seg + (last if parts > 1 else 0) + api = daemon.wait_ready() + daemon.append(api, 'Primary', build_multi_nzb(members), True, tag + '-key', 100) + _ds_append(api, 'Backup', build_multi_nzb(donor_members), tag + '-key', 90, paused=False, + params=[{'Name': 'DupeCopyKind', 'Value': 'borrowable'}, {'Name': 'DupeVideo', 'Value': 'same'}, + {'Name': 'DupeKind', 'Value': 'alt'}]) + daemon.wait_history(api, 'Backup', timeout=60) + api.editqueue('GroupResume', 0, '', [g['NZBID'] for g in api.listgroups() if g['NZBName'] == 'Primary']) + hp = daemon.wait_history(api, 'Primary', timeout=300) + integ = _verify_output(t, movie, '.mkv', dirs=(('main', 'dst'), ('main', 'inter'))) + ids = _failcont_requests(t) + served, count, again, _ = _failcont_bytes(ids, tag + 'B/') + donor_ids = [m for m in ids if m.startswith(tag + 'B/')] + twice = sorted({m for m in donor_ids if donor_ids.count(m) > 1}) + holes_n = 2 + margin = holes_n * (2 * 2 + 2) * donor_seg + bound = lost + edges + margin + runs = _grep_log(t, 'Fetch cost of borrowing from Backup') + stored = len(re.findall(r'[1-9]\d* from the fetched-article store', _log_text(t))) + # two repair runs at least (one per hole), and a later one served from the store: the + # case the store exists for was exercised, not avoided + ok = (integ and hp['Status'].startswith('SUCCESS') and again == 0 and not twice and served <= bound + and runs >= 2 and stored >= 1) + costs = [m.group(1, 2, 3, 4, 5) for m in re.finditer( + r'Fetch cost of borrowing from Backup: ([\d.]+) MB.*?; (\d+) single.*?of (\d+) article.*?' + r'(\d+) taken from memory(?:, (\d+) from the fetched-article store)?', _log_text(t))] + return ('altfetchonce', ok, + 'status=%s extracted_ok=%s donor_bytes=%d bound=%d (lost %d + edges %d + margin %d) ' + 'donor_articles=%d asked_twice=%d %s cost_lines=%d store_served_lines=%d costs=%s' + % (hp['Status'], integ, served, bound, lost, edges, margin, count, len(twice), twice[:4], runs, stored, + costs)) + + def scenario_deadvolumetwincheck(daemon, t): """deadvolumenestednopar without injected labels: TwinCheck itself must label the nested backup (another container, by its sampled articles: its @@ -15822,6 +15894,7 @@ def scenario_dupausedunpack(daemon, t): 'headlostvolumepar': scenario_headlostvolumepar, 'deadvolumeunlabelled': scenario_deadvolumeunlabelled, 'deadvolumetwincheck': scenario_deadvolumetwincheck, + 'altfetchonce': scenario_altfetchonce, 'deadvolumeothervideo': scenario_deadvolumeothervideo, 'deadvolumeothersize': scenario_deadvolumeothersize, 'deadvolumetwolenders': scenario_deadvolumetwolenders, @@ -16315,6 +16388,7 @@ def scenario_dupausedunpack(daemon, t): 'headlostvolumepar': PROD_OPTIONS + ['DownloadRate=4000'], 'deadvolumeunlabelled': PROD_OPTIONS + ['DownloadRate=4000'], 'deadvolumetwincheck': PROD_OPTIONS + ['DownloadRate=1000'], + 'altfetchonce': PROD_OPTIONS + ['DownloadRate=8000'], 'deadvolumeothervideo': PROD_OPTIONS + ['DownloadRate=1000'], 'deadvolumeothersize': PROD_OPTIONS + ['DownloadRate=1000'], 'deadvolumetwolenders': PROD_OPTIONS + ['DownloadRate=1000'], @@ -16365,7 +16439,7 @@ def _promote_fallback(options, mode): # finished job is rightly not redone FALLBACK_MODE_BOUND = {'livegate', 'streamrestartcredit', 'wholefilerestart', 'wholefilestale'} # scenarios that read nserv's request log (nserv.log) -CAPTURE_REQUESTS = {'repost', 'wholefileproofcost', 'dropnzbdir', 'fleetstaysqueued', 'fleetprimaryfirst'} | { +CAPTURE_REQUESTS = {'repost', 'altfetchonce', 'wholefileproofcost', 'dropnzbdir', 'fleetstaysqueued', 'fleetprimaryfirst'} | { 'failcont_twin25', 'failcont_twin50', 'failcont_twin90', 'failcont_alt25', 'failcont_alt50', 'failcont_altlive', 'failcont_alt90', 'failcont_aes25', 'failcont_aes50', 'failcont_aes90', 'failcont_compressed', 'failcont_othervideo', 'failcont_twinlabel', 'failcont_fleettwin', 'failcont_fleetalt', 'failcont_fleetaes', 'failcont_aestwin', 'failcont_aesalt', 'failcont_rar5m3', 'failcont_rar5m3aes', 'failcont_rar5m3other', 'failcont_lzma2', 'failcont_norestart', 'weakswitchalt', 'weakswitchtwin', 'weakswitchaes', 'weakswitchm3', 'failcont_aescontainer', 'failcont_alt25busy'} # extra nserv arguments per scenario (-w: response latency in ms) SCENARIO_NSERV_ARGS = {'streamtimeoutwrites': ['-w', '800'], 'fleetslowprobe': ['-x', '2000'], 'fleetprobespeed': ['-w', '300'], 'fleetprobebusy': ['-w', '300'], 'fleetprobehealthfail': ['-w', '800'], 'finaldeletemidway': ['-w', '300'], 'finaldeleterestart': ['-w', '300'], 'restartmidway': ['-w', '300'], 'xpacklatency': ['-w', '1000'], 'deadpickprobe': ['-w', '500'], 'deadpickafterreload': ['-w', '500'],