From 4b3f599aa87c3b1fdf6fefb40a3338001fd4563a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:33:40 -0800 Subject: [PATCH] Post-processing trusts live PAR's verified set: no second par verify, par2 index loaded once The 6790 audit (finding 3) saw par-rename report every volume missing after live PAR had verified or repaired the whole set, request a par-check, verify every file again and log "Repair not needed" (1.0x the set re-read, most of the 26-50 s tail on damaged 4 GiB sets). Cause: par-rename is handed the first-16-KiB MD5 the download computed for each file, but the queue stores it printed the nzbget way (bytes last to first). It was parsed in digest order, so every known hash was reversed and matched nothing: every file was "missing", on clean sets too (6790 job 3102). parrenamer::parse_printed_hash16k reads it back in digest order. Then, when live PAR has a complete verified state of the set, the par-check is not run: parchecker::streaming_session_verified_cover requires a current session on the download folder with trusted slices, every slice verified (or rebuilt and verified, rechecks done), none diverged, no fold pending, no file outside the recovery set, every file under its par2 name at its par2 length, the queue file whose bytes live PAR verified, and unchanged since post-processing first looked (inode, length, mtime). prepost takes it where the par-check would start (ParCheck=auto, health below 100% or a requested check; never after an unpack, for a forced check or repair, or a post-process again) and stores what nzbget stores after a quick par-check that needed no repair (ParStatus SUCCESS, par_full 0), erasing the stream-repair jobs of the verified files. Otherwise the normal par-check runs and the detail log says why. Post-processing now loads the par2 index once (par-rename); the par-check loaded the index and every recovery volume again. Harness: liveparrarclean, liveparrartrust (RAR set, production options, live PAR; damaged set with lost and corrupt articles) assert no par-check lines, no missing volumes, one par2 load and nzbget's statuses; liveparraroff is the control with live PAR off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gYUGuwLMB2hw7HQGbM --- rust/src/parchecker.rs | 151 +++++++++++++++++++++++ rust/src/parchecker/live_trust_tests.rs | 106 ++++++++++++++++ rust/src/parlive.rs | 2 +- rust/src/parlive/write_control.rs | 4 + rust/src/parrenamer.rs | 30 ++++- rust/src/postproc.rs | 18 ++- rust/src/prepost.rs | 114 +++++++++++++++++ tests/functional/dupefallback/harness.py | 130 +++++++++++++++++++ 8 files changed, 550 insertions(+), 5 deletions(-) diff --git a/rust/src/parchecker.rs b/rust/src/parchecker.rs index c3d1ed0cb..1efadfef6 100644 --- a/rust/src/parchecker.rs +++ b/rust/src/parchecker.rs @@ -235,6 +235,11 @@ struct ActiveStreamingSession { /// their lost articles, so the repair as the download ends still takes them and /// certifies them (see [`streaming_session_download_end_targets`]). rebuilt_files: Mutex>, + /// The set lists files outside its recovery set: live PAR never verifies those. + non_recoverable: bool, + /// Every file of the set as post-processing first found it fully verified (see + /// [`streaming_session_verified_cover`]): a later change to one ends the trust. + cover_seal: Mutex>>, // Drop last, after the session, queue and all owned metadata. Grows with // the syndrome slots as damage appears (see `grow_for_damage`). budget: Mutex, @@ -767,6 +772,8 @@ fn build_streaming_session_with( completed_sources: Mutex::new(HashSet::new()), rebuilt_recheck: Mutex::new(Vec::new()), rebuilt_files: Mutex::new(HashSet::new()), + non_recoverable: !main.non_recoverable_file_ids.is_empty(), + cover_seal: Mutex::new(None), })) } @@ -4678,6 +4685,150 @@ pub(crate) fn streaming_session_verified_target_crc( ) } +/// What live PAR proved about a download's par2 set by the time post-processing asks: see +/// [`streaming_session_verified_cover`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct LiveCover { + /// The par2 file the session was built from. + pub par_name: Vec, + /// Files of the set (every one of them verified). + pub files: usize, + /// The queue ids of those files. + pub queue_ids: Vec, +} + +/// Whether live PAR of job `nzb_id` has a complete verified state of its par2 set, so a +/// post-processing par-check would only read the set again to learn nothing new: +/// +/// - the session is current (not cancelled, stopped or replaced: every RustyGet writer into +/// a source either reported its write to live PAR or stopped it), repairs `dest_dir`, and +/// still takes verified slices as proof (`trust_revoked` unset: each verified byte is the +/// byte written); +/// - every slice of every file is verified, or was rebuilt by a live repair and verified, +/// none diverged after a patch, and no fold is pending; +/// - the set has no file outside its recovery set (live PAR never checks those); +/// - each file of the set is one of `files` (the download's completed queue files as +/// `(queue id, name in dest_dir)`), under its par2 name, the queue file whose bytes live +/// PAR verified for it (its binding, or no other queue file bound to it), and on disk at +/// its par2 length; +/// - and no file changed since the first call that found all this: that call records each +/// file's inode, length and modification time, later ones compare. +/// +/// `Err` says what is missing (for the log). Metadata only, at most one `stat` per file; +/// callers may hold the queue lock. +pub(crate) fn streaming_session_verified_cover( + nzb_id: i32, + dest_dir: &Path, + files: &[(i32, Vec)], +) -> Result { + let entry = active_streaming_session(nzb_id).ok_or("no live PAR session")?; + ensure_current_generation(nzb_id, &entry).map_err(|_| "live PAR stopped".to_string())?; + if entry.base_dir != dest_dir { + return Err("live PAR verified another folder".into()); + } + if entry.trust_revoked.load(Ordering::Acquire) { + return Err("a write into a file was not vouched for".into()); + } + if entry.non_recoverable { + return Err("the par2 set lists files outside its recovery set".into()); + } + let status = entry.session.status(); + if status.total == 0 + || status.verified != status.total + || status.damaged > 0 + || status.unarrived + status.partially_arrived > 0 + || status.pending_folds > 0 + { + return Err(format!( + "{} of {} slice(s) verified, {} damaged, {} not arrived", + status.verified, + status.total, + status.damaged, + status.unarrived + status.partially_arrived + )); + } + if !entry.session.diverged_slices().is_empty() { + return Err("a slice changed after it was verified".into()); + } + if !entry.rebuilt_recheck.lock().unwrap_or_else(|e| e.into_inner()).is_empty() { + return Err("a slice rebuilt ahead waits for its file to complete".into()); + } + if !entry.rebuilt_files.lock().unwrap_or_else(|e| e.into_inner()).is_empty() { + return Err("a file rebuilt ahead is not certified by the end repair yet".into()); + } + let bindings = entry + .queue_bindings + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(); + let bound_ids: HashSet = bindings.values().copied().collect(); + let mut stamps: Vec<(FileId, crate::parlive::FileStamp)> = + Vec::with_capacity(entry.target_names.len()); + let mut queue_ids = Vec::with_capacity(entry.target_names.len()); + for (queue_id, name) in files { + let Some(id) = entry.session.file_id_by_name(name) else { + continue; // not a file of this set, or not under its par2 name + }; + let par_name = entry + .target_names + .get(&id) + .map(|n| par_rs::filenames::os_str_bytes(n.as_os_str())); + if par_name.as_deref() != Some(name.as_slice()) { + continue; + } + let owned = match bindings.get(queue_id) { + Some(bound) => *bound == id, + None => !bound_ids.contains(&id), + }; + if !owned { + return Err(format!( + "{} is not the file live PAR verified under that name", + String::from_utf8_lossy(name) + )); + } + if stamps.iter().any(|(known, _)| *known == id) { + return Err(format!("two files named {}", String::from_utf8_lossy(name))); + } + let stamp = crate::parlive::FileStamp::of(&dest_dir.join(crate::fsops::path(name))) + .ok_or_else(|| format!("{} is not on disk", String::from_utf8_lossy(name)))?; + if Some(stamp.len()) != entry.file_lengths.get(&id).copied() { + return Err(format!("{} changed length", String::from_utf8_lossy(name))); + } + stamps.push((id, stamp)); + queue_ids.push(*queue_id); + } + if stamps.len() != entry.target_names.len() { + return Err(format!( + "{} of {} file(s) under their par2 names", + stamps.len(), + entry.target_names.len() + )); + } + stamps.sort_unstable_by_key(|(id, _)| id.0); + let mut seal = entry.cover_seal.lock().unwrap_or_else(|e| e.into_inner()); + match seal.as_ref() { + Some(sealed) if *sealed != stamps => { + return Err("a file changed after live PAR verified it".into()); + } + Some(_) => {} + None => *seal = Some(stamps), + } + drop(seal); + let par_name = entry.par_name.lock().unwrap_or_else(|e| e.into_inner()).clone(); + Ok(LiveCover { + par_name, + files: entry.target_names.len(), + queue_ids, + }) +} + +/// Whether [`streaming_session_verified_cover`] already recorded job `nzb_id`'s files. +pub(crate) fn streaming_session_cover_sealed(nzb_id: i32) -> bool { + active_streaming_session(nzb_id).is_some_and(|entry| { + entry.cover_seal.lock().unwrap_or_else(|e| e.into_inner()).is_some() + }) +} + /// A bounded count upper bound only: the helper must authenticate owned RAM and /// validate actual recovery rank before patching. This function performs no GF or I/O. pub(crate) fn streaming_session_can_schedule_repair(nzb_id: i32) -> bool { diff --git a/rust/src/parchecker/live_trust_tests.rs b/rust/src/parchecker/live_trust_tests.rs index 939140e51..60c55e2fe 100644 --- a/rust/src/parchecker/live_trust_tests.rs +++ b/rust/src/parchecker/live_trust_tests.rs @@ -817,6 +817,11 @@ fn a_file_rebuilt_ahead_is_certified_once_by_the_end_repair() { crate::parlive::reserve_control(f.nzb_id, 4096, 500 << 20).unwrap(), ) .unwrap(); + // Every slice verified, but the file is not certified yet: post-processing may not + // take live PAR's word for it until the end repair has. + let named = [(42, b"part01.rar".to_vec())]; + let early = streaming_session_verified_cover(f.nzb_id, &f.dir, &named).unwrap_err(); + assert!(early.contains("rebuilt ahead"), "{early}"); let lease = request.acquire().unwrap(); let (report, released) = lease .repair_and_publish(|verified| verified.len(), || ()) @@ -825,6 +830,7 @@ fn a_file_rebuilt_ahead_is_certified_once_by_the_end_repair() { assert_eq!(released, 1, "certified"); assert_eq!(streaming_session_download_end_targets(f.nzb_id), None); assert_eq!(std::fs::read(&path).unwrap(), f.data); + assert!(streaming_session_verified_cover(f.nzb_id, &f.dir, &named).is_ok()); } /// Feeds the set with slices `lost` failed for good (recovery first), repairs and publishes the @@ -934,3 +940,103 @@ fn a_live_repair_reads_nothing_back() { ); } } + +fn cover(f: &Fixture) -> Result { + streaming_session_verified_cover(f.nzb_id, &f.dir, &[(40, b"part01.rar".to_vec())]) +} + +/// Every slice verified, the file under its par2 name at its par2 length: post-processing +/// may take that instead of a par-check. Until then it may not. +#[cfg(unix)] +#[test] +fn verified_cover_needs_every_slice_verified() { + let f = fixture(0x7a75_0020, 6, 2, 2); + let entry = active_streaming_session(f.nzb_id).unwrap(); + let id = file_id(f.nzb_id); + let half = f.data.chunks(SLICE).count() / 2; + for (i, chunk) in f.data.chunks(SLICE).enumerate().take(half) { + entry + .session + .on_article_finished_memory_only( + &id, + (i * SLICE) as u64, + chunk, + par_rs::crc::crc32(chunk), + ) + .unwrap(); + } + let partial = cover(&f).unwrap_err(); + assert!(partial.contains("slice(s) verified"), "{partial}"); + feed_all(&f); + let full = cover(&f).unwrap(); + assert_eq!(full.files, 1); + assert_eq!(full.par_name, b"trust.par2".to_vec()); + // Asked again with nothing changed: still covered. + assert!(cover(&f).is_ok()); + // Not the folder live PAR verified, or no file under the par2 name: not covered. + let elsewhere = f.dir.join("x"); + let named = [(40, b"part01.rar".to_vec())]; + assert!(streaming_session_verified_cover(f.nzb_id, &elsewhere, &named).is_err()); + let obfuscated = [(40, b"q1w2e3".to_vec())]; + assert!(streaming_session_verified_cover(f.nzb_id, &f.dir, &obfuscated).is_err()); +} + +/// A file that changed after the cover was first taken (another inode, length or time) ends +/// the trust: the par-check runs. +#[cfg(unix)] +#[test] +fn verified_cover_ends_when_a_file_changes() { + let f = fixture(0x7a75_0021, 6, 2, 2); + feed_all(&f); + assert!(cover(&f).is_ok()); + let path = f.dir.join("part01.rar"); + let replacement = f.dir.join("part01.rar.new"); + std::fs::write(&replacement, &f.data).unwrap(); + std::fs::rename(&replacement, &path).unwrap(); + let changed = cover(&f).unwrap_err(); + assert!(changed.contains("changed after"), "{changed}"); + + let g = fixture(0x7a75_0022, 6, 2, 2); + feed_all(&g); + std::fs::write(g.dir.join("part01.rar"), &g.data[..g.data.len() - 1]).unwrap(); + let short = cover(&g).unwrap_err(); + assert!(short.contains("changed length"), "{short}"); +} + +/// A write live PAR could not vouch for (trust revoked) or a stopped session: no cover. +#[cfg(unix)] +#[test] +fn verified_cover_needs_trusted_slices_and_a_current_session() { + let f = fixture(0x7a75_0023, 6, 2, 2); + feed_all(&f); + streaming_session_distrust(f.nzb_id, "test"); + assert!(cover(&f).unwrap_err().contains("not vouched")); + + let g = fixture(0x7a75_0024, 6, 2, 2); + feed_all(&g); + streaming_session_cancel(g.nzb_id); + assert!(cover(&g).is_err()); +} + +/// The file under the par2 name must be the queue file whose bytes live PAR verified for it: +/// one bound to another par2 file, or an unbound one while another queue file holds the +/// binding (an obfuscated copy), is not covered. +#[cfg(unix)] +#[test] +fn verified_cover_needs_the_file_live_par_verified() { + let f = fixture(0x7a75_0025, 6, 2, 2); + feed_all(&f); + let entry = active_streaming_session(f.nzb_id).unwrap(); + let id = file_id(f.nzb_id); + entry.queue_bindings.lock().unwrap().insert(40, FileId([9; 16])); + assert!(cover(&f).unwrap_err().contains("is not the file")); + { + let mut bindings = entry.queue_bindings.lock().unwrap(); + bindings.clear(); + bindings.insert(41, id); + } + assert!(cover(&f).unwrap_err().contains("is not the file")); + let owner = [(41, b"part01.rar".to_vec())]; + let covered = streaming_session_verified_cover(f.nzb_id, &f.dir, &owner).unwrap(); + assert_eq!(covered.queue_ids, vec![41]); +} diff --git a/rust/src/parlive.rs b/rust/src/parlive.rs index 633ef10e2..ba8500043 100644 --- a/rust/src/parlive.rs +++ b/rust/src/parlive.rs @@ -347,7 +347,7 @@ fn reserve_control_inner( mod write_control; pub(crate) use write_control::{ - RepairWriteLease, WriteBlocked, WriteCoordinator, WriterIdentity, WriterTarget, + FileStamp, RepairWriteLease, WriteBlocked, WriteCoordinator, WriterIdentity, WriterTarget, }; #[cfg(all(test, unix))] diff --git a/rust/src/parlive/write_control.rs b/rust/src/parlive/write_control.rs index a6bcc877c..be39c67b4 100644 --- a/rust/src/parlive/write_control.rs +++ b/rust/src/parlive/write_control.rs @@ -61,6 +61,10 @@ impl FileStamp { pub(crate) fn of(_path: &std::path::Path) -> Option { None } + /// The file's length in bytes. + pub(crate) fn len(&self) -> u64 { + self.len + } } /// A leaf name whose identity a case-insensitive comparison proves on every supported file /// system: printable ASCII without separators or reserved characters, no trailing dot or diff --git a/rust/src/parrenamer.rs b/rust/src/parrenamer.rs index 4ea5e6612..1097e7161 100644 --- a/rust/src/parrenamer.rs +++ b/rust/src/parrenamer.rs @@ -225,8 +225,19 @@ pub fn execute_all( ) } -/// The MD5 of a file's first 16 KiB from the queue's `hash16k` (32 hex digits, as the -/// article analyzer stores it). None for anything else. +/// A queue file's 16k hash as the download stores it (`FileStr::Hash16k`, the article +/// analyzer's output): printed the way nzbget prints an MD5, its bytes last to first in +/// upper-case hex (`renameanalyzer::print`). Returns the digest in its own byte order, the +/// order par2 file descriptions and `par_rs` use. Before, the printed text was read as if it +/// were in digest order, so every known hash was reversed: par-rename reported every file +/// it had been told about as missing and asked for a par-check (6790 audit, finding 3). +pub fn parse_printed_hash16k(printed: &[u8]) -> Option<[u8; 16]> { + let mut hash = parse_hash16k(printed)?; + hash.reverse(); + Some(hash) +} + +/// 32 hex digits read as a 16-byte digest in the order written. None for anything else. pub fn parse_hash16k(hex: &[u8]) -> Option<[u8; 16]> { if hex.len() != 32 { return None; @@ -317,6 +328,21 @@ mod tests { use super::*; use md5::{Digest, Md5}; + /// The analyzer prints a digest backwards; read back, it is the digest a par2 file + /// description holds. + #[test] + fn printed_hash16k_reads_back_in_digest_order() { + let bytes: Vec = (0..20_000u32).map(|i| (i * 7 + 3) as u8).collect(); + let digest: [u8; 16] = Md5::digest(&bytes[..16384]).into(); + let mut analyzer = crate::renameanalyzer::Analyzer::default(); + analyzer.append(&bytes[..9000]); + analyzer.append(&bytes[9000..]); + let printed = analyzer.finish(); + assert_eq!(parse_printed_hash16k(&printed[..32]), Some(digest)); + assert_ne!(parse_hash16k(&printed[..32]), Some(digest)); + assert_eq!(parse_printed_hash16k(b"not a hash"), None); + } + #[test] fn splitted_fragments() { assert!(is_splitted_fragment(b"/d/movie.mkv.001", b"movie.mkv")); diff --git a/rust/src/postproc.rs b/rust/src/postproc.rs index a0c1d8e44..7729880ad 100644 --- a/rust/src/postproc.rs +++ b/rust/src/postproc.rs @@ -3625,6 +3625,19 @@ pub(crate) fn live_repair_should_defer_post(nzb_id: i32) -> bool { false } +/// No live PAR work of `nzb_id` is running or still due: no repair helper (download-end or +/// of held direct-unpack volumes) and no completed file waiting to be folded in. Read-only: +/// unlike [`live_repair_should_defer_post`] it starts no clock and cancels nothing. +#[cfg(unix)] +pub(crate) fn live_par_work_idle(nzb_id: i32) -> bool { + !live_end_repair_running(nzb_id) + && !direct_unpack_holds() + .get(&nzb_id) + .is_some_and(|state| state.live_repair_running) + && !crate::parchecker::streaming_session_pending_completed_jobs().contains(&nzb_id) + && !crate::parchecker::streaming_session_completion_drain_active(nzb_id) +} + /// Within `limit` of the last progress at `since`: post-processing still waits. #[cfg(unix)] fn live_defer_within(since: std::time::Instant, now: std::time::Instant, limit: Duration) -> bool { @@ -6114,7 +6127,8 @@ impl NzbgetRsPostJob { let n = self.nzb_ptr(host); let ns = host.nzb_snap(n, false); // The first-16-KiB MD5 of every file downloaded whole, as its first article - // gave it: par-rename identifies those without reading them. + // gave it (stored printed, bytes last to first): par-rename identifies those + // without reading them. // (The analyzer sets hash16k only for a first article whose NZB size is at // least 16 KiB, or a file's only article: the MD5 of min(16 KiB, file size), // except for a first article that decodes to just under 16 KiB, where the @@ -6123,7 +6137,7 @@ impl NzbgetRsPostJob { let mut known: Vec<(Vec, [u8; 16])> = (0..host.nzb_completed_files_len(n)) .map(|i| host.nzb_completed_file_at(n, i)) .filter(|f| f.status == crate::queuesubsys_host::CF_SUCCESS && !f.par_file) - .filter_map(|f| Some((f.filename, crate::parrenamer::parse_hash16k(&f.hash16k)?))) + .filter_map(|f| Some((f.filename, crate::parrenamer::parse_printed_hash16k(&f.hash16k)?))) .collect(); let names: Vec> = known.iter().map(|(name, _)| name.clone()).collect(); known.retain(|(name, _)| names.iter().filter(|other| *other == name).count() == 1); diff --git a/rust/src/prepost.rs b/rust/src/prepost.rs index 2f86615bd..cdda88b6b 100644 --- a/rust/src/prepost.rs +++ b/rust/src/prepost.rs @@ -887,6 +887,104 @@ fn has_main_pars(dest_dir: &[u8]) -> bool { crate::parparser::find_main_pars(bytes_to_path(dest_dir), false, |_| {}) } +/// Live PAR's verified cover of the download, when post-processing may take it instead of a +/// par-check (`parchecker::streaming_session_verified_cover`: every slice of every file +/// verified or rebuilt and verified, every file under its par2 name at its par2 length and +/// unchanged since). Only with ParCheck=auto (always and force ask for a par-check of every +/// download), not for a post-process-again, not for a par-check asked for after an unpack +/// (it failed: the files on disk may not be the bytes live PAR verified) or a forced full +/// check or repair, not while live PAR still works on the download, and only when the folder +/// holds that one par2 set: a second set was never verified live. `Err` says why not. +#[cfg(unix)] +fn live_par_cover( + host: &crate::queuesubsys_host::QueueSubsysHost, + nzb: &crate::queuesubsys_host::NzbSnap, + ps: &crate::queuesubsys_host::PostSnap, +) -> Result { + if host.opts().par_check != crate::queuesubsys_host::PC_AUTO { + return Err("ParCheck asks for a par-check of every download".into()); + } + if nzb.reprocess { + return Err("post-processing again".into()); + } + if nzb.unpack_tried || ps.force_par_full || ps.force_repair { + return Err("a full par-check was asked for".into()); + } + if !crate::postproc::live_par_work_idle(nzb.id) { + return Err("live PAR is still working".into()); + } + let par_name = crate::parchecker::streaming_session_par_filename(nzb.id) + .ok_or("no live PAR session")?; + let dir = bytes_to_path(&nzb.dest_dir); + let mut mains: Vec> = Vec::new(); + crate::parparser::find_main_pars(dir, true, |name| mains.push(name.to_vec())); + match mains.as_slice() { + [main] if crate::parparser::same_par_collection(main, &par_name, true) => {} + [_] => return Err("the folder's par2 set is not the one live PAR verified".into()), + _ => return Err(format!("{} par2 sets in the folder", mains.len())), + } + let count = host.nzb_completed_files_len(nzb.ptr); + if count > 4096 { + return Err("too many files".into()); + } + let files: Vec<(i32, Vec)> = (0..count) + .map(|index| host.nzb_completed_file_at(nzb.ptr, index)) + .filter(|file| !file.par_file) + .map(|file| (file.id, file.filename)) + .collect(); + crate::parchecker::streaming_session_verified_cover(nzb.id, dir, &files) +} + +/// Takes live PAR's verified cover instead of the par-check post-processing was about to run +/// for `nzb` (see [`live_par_cover`]): the job gets what nzbget stores after a quick +/// par-check that found nothing to repair (ParStatus SUCCESS, not a full check), the +/// stream-repair jobs of the verified files go as a verified file's do, and no byte of the +/// set is read again. False, with the reason in the detail log, when the cover is not +/// complete: the normal par-check runs. +#[cfg(unix)] +fn trust_live_par( + host: &crate::queuesubsys_host::QueueSubsysHost, + nzb: &crate::queuesubsys_host::NzbSnap, + ps: &crate::queuesubsys_host::PostSnap, +) -> bool { + use crate::queuesubsys_host::{MK_DETAIL, MK_INFO, NZB_INT_CHANGED, NZB_INT_PAR_FULL}; + let cover = match live_par_cover(host, nzb, ps) { + Ok(cover) => cover, + Err(why) => { + if crate::parchecker::streaming_session_has_session(nzb.id) { + let mut msg = b"Live PAR does not cover ".to_vec(); + msg.extend_from_slice(&nzb.name); + msg.extend_from_slice(format!(" ({why}): par-check runs").as_bytes()); + host.nzb_print_message(nzb.ptr, MK_DETAIL, &msg); + } + return false; + } + }; + let mut msg = b"Skipping par-check for ".to_vec(); + msg.extend_from_slice(&nzb.name); + msg.extend_from_slice(b": live PAR verified every file of "); + msg.extend_from_slice(&cover.par_name); + msg.extend_from_slice( + format!(" ({} file(s), every slice checked or repaired as it downloaded)", cover.files) + .as_bytes(), + ); + host.nzb_print_message(nzb.ptr, MK_INFO, &msg); + host.nzb_set_par_status(nzb.ptr, NzbParStatus::Success); + // A par-check that quick-verified any file stores par_full 0 (`ParChecker`); a failed + // unpack then still asks for a full par-check. + host.nzb_set_int(nzb.ptr, NZB_INT_PAR_FULL, 0); + // As `RepairController::register_verified_file` does for each verified file: nothing + // is left for stream repair to fetch for them. + for index in (0..host.nzb_stream_repair_jobs_len(nzb.ptr)).rev() { + let job = host.nzb_stream_repair_job_detail(nzb.ptr, index); + if cover.queue_ids.contains(&job.file_id) { + host.nzb_stream_repair_erase_job(nzb.ptr, index, true); + } + } + host.nzb_set_int(nzb.ptr, NZB_INT_CHANGED, 1); + true +} + #[cfg(unix)] fn has_completed_archive_files( host: &crate::queuesubsys_host::QueueSubsysHost, @@ -2084,6 +2182,16 @@ impl NzbgetRsPrePostProcessor { } host.post_reset_stage_progress(post_ptr, opts.cur_time); + if nzb.par_status <= NzbParStatus::Skipped + && nzb.delete_status == DeleteStatus::None + && crate::parchecker::streaming_session_has_session(nzb.id) + && !crate::parchecker::streaming_session_cover_sealed(nzb.id) + { + // Seals live PAR's cover (its files as they are now) before any stage may touch + // them, so the par decision below sees a change made in between. + let _ = live_par_cover(host, &nzb, &ps); + } + if nzb.par_rename_status == RS_NONE && nzb.delete_status == DeleteStatus::None && opts.par_rename @@ -2251,6 +2359,9 @@ impl NzbgetRsPrePostProcessor { if nzb.par_status == NzbParStatus::None && nzb.delete_status == DeleteStatus::None { if has_main_pars(&nzb.dest_dir) { + if trust_live_par(host, &nzb, &ps) { + return; + } if !allow_par { host.post_set_int(post_ptr, POST_INT_NEED_PAR_CHECK, 1); return; @@ -2298,6 +2409,9 @@ impl NzbgetRsPrePostProcessor { } host.nzb_set_par_status(nzb.ptr, NzbParStatus::Failure); } else { + if trust_live_par(host, &nzb, &ps) { + return; + } let h_s = fmt_tenths(nzb.health); let mut msg = b"Collection ".to_vec(); msg.extend_from_slice(&nzb.name); diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index e06e485da..d99e7e9d5 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -12938,6 +12938,130 @@ def scenario_livepardecodeahead(daemon, t): return ('livepardecodeahead', ok, 'status=%s intact=%s rebuilt_ahead=%s end_repaired=%s ' 'before_end=%s before_last_data=%s batch_repairs=%d io=%s' % (h['Status'], intact, rebuilt, ended, before_end, before_last, batch, io)) +def _livepar_rar_run(daemon, t, tag, seed, missing, corrupt=None, recovery=24): + """A RAR set under the production options with live PAR: 8 store-mode volumes of + movie.mkv (real CRCs, so direct unpack extracts it while it downloads) and a par2 set of + 64 KiB blocks with recovery blocks in two volumes. maps a volume + number to the article numbers it loses; = (volume, article) is served from a + copy of the volume with 4 KiB XOR-ed, its yEnc CRC still valid (a provider's bad copy: + only par2 or the archive checksums catch it). Returns (history, extracted intact, + post-processing par-check lines, par-rename missing lines, post-processing loads of the + par2 index, seconds from the end of the download to the history entry).""" + import subprocess as _sp + seg = 100_000 + movie = _payload(6_000_000, seed) + vols = generators.rar3_store_volumes_valid('movie.mkv', movie, 800_000) + work = t.path('data', tag) + os.makedirs(work, exist_ok=True) + names = [] + for i, data in enumerate(vols): + name = 'Rel.part%02d.rar' % (i + 1) + t.write_file(os.path.join('data', tag, name), data) + names.append(name) + _sp.run(['par2', 'create', '-q', '-q', '-s65536', '-c%d' % recovery, '-n2', '-a', 'Rel', + 'Rel.par2'] + names, cwd=work, check=True, capture_output=True) + members = [('%s/%s' % (tag, n), n, os.path.getsize(os.path.join(work, n)), seg, set()) + for n in sorted(n for n in os.listdir(work) if n.endswith('.par2'))] + members += [('%s/%s' % (tag, n), n, len(vols[i]), seg, set(missing.get(i, ()))) + for i, n in enumerate(names)] + nzb = build_multi_nzb(members) + if corrupt: + vol, part = corrupt + bad = bytearray(vols[vol]) + start = (part - 1) * seg + 1000 + for k in range(start, start + 4096): + bad[k] ^= 0x5A + t.write_file(os.path.join('data', tag, 'bad%d' % vol), bytes(bad)) + old = '>%s/%s?%d=' % (tag, names[vol], part) + assert old in nzb + nzb = nzb.replace(old, '>%s/bad%d?%d=' % (tag, vol, part)) + api = daemon.wait_ready() + name = 'Rel' + tag + daemon.append(api, name, nzb, False, tag + '-key', 100) + deadline = time.time() + 300 + end = None + h = None + while time.time() < deadline: + h = next((x for x in api.history() if x.get('NZBName') == name), None) + if h: + break + g = next((g for g in api.listgroups() if g['NZBName'] == name), None) + if end is None and (g is None or str(g.get('Status', '')).startswith('PP_')): + end = time.time() + time.sleep(0.1) + if h is None: + raise RuntimeError('timeout waiting for %s in history' % name) + done = time.time() + intact = _verify_output(t, movie, '.mkv', dirs=(('main', 'dst'), ('main', 'inter'))) + log = t.read_file('nzbget.log').decode(errors='replace') + # The par-check's own lines: "Verifying /" when it starts, "Repair not + # needed for /" when it found nothing to repair. + verify = log.count('Verifying %s/' % name) + log.count('Repair not needed for %s/' % name) + missing_lines = len(re.findall(r'File Rel\.part\d+\.rar is missing', log)) + # Post-processing loads of the par2 index: par-rename's ("Loaded par2-file") and the + # par-check's ("Loading file X.par2"). Once is par-rename alone. + loads = len(re.findall(r'Loaded par2-file [^\n]* for par-rename', log)) + \ + len(re.findall(r'Loading file [^\n]*\.par2', log)) + return h, intact, verify, missing_lines, loads, (round(done - end, 2) if end else None) + + +def scenario_liveparrarclean(daemon, t): + """A clean RAR set with live PAR on (6790 audit, finding 3): every slice verified as + it arrived, direct unpack extracted it while it downloaded. Post-processing runs no + par-check (no "Verifying"/"Repair not needed" for the set), par-rename reports no + volume missing (it read the queue's printed 16k hashes backwards before) and loads the + par2 index once, and the statuses are nzbget's for a clean download with ParCheck=auto: + SUCCESS, ParStatus NONE (par-check not needed), UnpackStatus SUCCESS.""" + h, intact, verify, missing, loads, end_s = _livepar_rar_run(daemon, t, 'lrc', 13710, {}) + trusted = _grep_log(t, 'live PAR verified every file') + ok = (h['Status'].startswith('SUCCESS') and intact and verify == 0 and missing == 0 + and loads == 1 and trusted == 0 and h['ParStatus'] == 'NONE' + and h['UnpackStatus'] == 'SUCCESS') + return ('liveparrarclean', ok, 'status=%s par=%s unpack=%s intact=%s par_check_lines=%d ' + 'missing_lines=%d par2_loads=%d end_to_history_s=%s' + % (h['Status'], h['ParStatus'], h['UnpackStatus'], intact, verify, missing, loads, end_s)) + + +def scenario_liveparrartrust(daemon, t): + """A damaged RAR set with live PAR on (6790 audit, finding 3): three articles lost in + two volumes and one served corrupt (valid yEnc CRC) in a third, so direct unpack stops + at the bad bytes. Live PAR verifies every slice as it arrives and repairs the damage + as the download ends; post-processing trusts that verified state: no par-check reads + the set again (no "Verifying"/"Repair not needed" for the set; before, par-rename + reported the volumes missing and a full par verify of every volume followed), par-rename + reports no volume missing, the par2 index is loaded once (by par-rename; before, the + par-check loaded it and both recovery volumes again), and the statuses are what nzbget + shows after a par-repair: + SUCCESS, ParStatus SUCCESS, UnpackStatus SUCCESS, the movie byte-exact.""" + h, intact, verify, missing, loads, end_s = _livepar_rar_run(daemon, t, 'lrt', 13720, + {1: {3}, 4: {2, 6}}, corrupt=(6, 4)) + live = _grep_log(t, 'Live par-repair for Rellrt') + trusted = _grep_log(t, 'live PAR verified every file') + ok = (h['Status'].startswith('SUCCESS') and intact and verify == 0 and missing == 0 + and live >= 1 and trusted == 1 and loads == 1 + and h['ParStatus'] == 'SUCCESS' and h['UnpackStatus'] == 'SUCCESS') + return ('liveparrartrust', ok, 'status=%s par=%s unpack=%s intact=%s live_repairs=%d trusted=%d ' + 'par_check_lines=%d missing_lines=%d par2_loads=%d end_to_history_s=%s' + % (h['Status'], h['ParStatus'], h['UnpackStatus'], intact, live, trusted, verify, missing, + loads, end_s)) + + +def scenario_liveparraroff(daemon, t): + """The control for liveparrartrust: the same damaged RAR set with live PAR off. The + par-check runs and the counters see it (its "Verifying"/"Repair..." lines, the par2 index + and recovery volumes loaded by it besides par-rename), it repairs the set, and the + statuses are the same: SUCCESS, ParStatus SUCCESS, UnpackStatus SUCCESS, byte-exact.""" + h, intact, verify, missing, loads, end_s = _livepar_rar_run(daemon, t, 'lro', 13720, + {1: {3}, 4: {2, 6}}, corrupt=(6, 4)) + trusted = _grep_log(t, 'live PAR verified every file') + repaired = _grep_log(t, 'Successfully repaired Rellro/') + ok = (h['Status'].startswith('SUCCESS') and intact and verify >= 1 and loads >= 2 + and trusted == 0 and repaired >= 1 and missing == 0 + and h['ParStatus'] == 'SUCCESS' and h['UnpackStatus'] == 'SUCCESS') + return ('liveparraroff', ok, 'status=%s par=%s unpack=%s intact=%s repaired=%d trusted=%d ' + 'par_check_lines=%d missing_lines=%d par2_loads=%d end_to_history_s=%s' + % (h['Status'], h['ParStatus'], h['UnpackStatus'], intact, repaired, trusted, verify, + missing, loads, end_s)) def scenario_parinplace(daemon, t): @@ -15611,6 +15735,9 @@ def scenario_dupausedunpack(daemon, t): 'liveparzeroreads': scenario_liveparzeroreads, 'liveparheldvolume': scenario_liveparheldvolume, 'livepardecodeahead': scenario_livepardecodeahead, + 'liveparrarclean': scenario_liveparrarclean, + 'liveparrartrust': scenario_liveparrartrust, + 'liveparraroff': scenario_liveparraroff, 'livepartrusted': scenario_livepartrusted, 'livepartrustedtemp': scenario_livepartrustedtemp, 'parinplace': scenario_parinplace, @@ -16086,6 +16213,9 @@ def scenario_dupausedunpack(daemon, t): 'livepardecodeahead': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], 'livepartrusted': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], 'livepartrustedtemp': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=0', 'DirectWrite=no'], + 'liveparrarclean': PROD_OPTIONS + ['LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], + 'liveparrartrust': PROD_OPTIONS + ['LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], + 'liveparraroff': PROD_OPTIONS + ['LiveParRepair=no', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], 'parinplace': ['ParCheck=auto', 'LiveParRepair=no'], 'parlesscritical': ['HealthCheck=dupe', 'DupeArticleFallback=no'], 'parlesstwin': ['HealthCheck=dupe', 'DupeArticleFallback=no'],