diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 4224601c3..fec5d14ac 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -644,7 +644,7 @@ dependencies = [ [[package]] name = "par-rs" version = "0.2.0" -source = "git+https://github.com/Appz4Fun/par-rs?rev=b60bfd151784903dbced37cff165006754f81fe9#b60bfd151784903dbced37cff165006754f81fe9" +source = "git+https://github.com/Appz4Fun/par-rs?rev=2524277d7c74db8a256617e75c28bf0872a04462#2524277d7c74db8a256617e75c28bf0872a04462" dependencies = [ "crc32fast", "libc", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 6e0426cf1..ef5b414d8 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -20,7 +20,7 @@ bench = false doctest = false [dependencies] -par-rs = { git = "https://github.com/Appz4Fun/par-rs", rev = "b60bfd151784903dbced37cff165006754f81fe9" } +par-rs = { git = "https://github.com/Appz4Fun/par-rs", rev = "2524277d7c74db8a256617e75c28bf0872a04462" } zipfast = { git = "https://github.com/Appz4Fun/zipfast", rev = "ed2ee346a5b18724c55aec6a90c73e86d5909614", features = ["persistent-partials"] } vidmatch = { git = "https://github.com/Appz4Fun/vidmatch", rev = "636facc1223d2a87e5ca7a43bc1d2e169c39deb6" } zipview = { git = "https://github.com/xbmc4lyfe/zipview", rev = "2c3d73a06b29987cea1510e903e437a482076745" } diff --git a/rust/src/articledl.rs b/rust/src/articledl.rs index f995e3deb..221eb44a6 100644 --- a/rust/src/articledl.rs +++ b/rust/src/articledl.rs @@ -7,7 +7,7 @@ use crate::options::OptStr; use std::ffi::{c_char, c_int, c_void, CStr, CString}; use std::io::{Seek, SeekFrom, Write}; use std::os::fd::{FromRawFd, IntoRawFd, RawFd}; -use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex}; use crate::artwritercore::{ @@ -658,6 +658,33 @@ pub(crate) fn shutdown_daemon_article_cache() { DAEMON_CACHE_RUNNING.store(false, Ordering::SeqCst); } +/// Test hook (functional harness only): `RUSTYGET_TEST_FLUSH_HOLD_MS` keeps each cache flush +/// holding its file's flush lock that long before it writes, as a slow disk at line speed +/// does, so articles of that file finish and are captured while it is flushed. Logged once +/// when set; unset (production) it costs one load. +fn flush_test_hold() { + static HOLD_MS: std::sync::LazyLock = std::sync::LazyLock::new(|| { + let ms = std::env::var("RUSTYGET_TEST_FLUSH_HOLD_MS") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(0, |ms| ms.min(1000)); + if ms > 0 { + crate::log::log_active_bytes( + MK_WARNING, + format!("Test hook RUSTYGET_TEST_FLUSH_HOLD_MS: each cache flush waits {ms} ms").as_bytes(), + ); + } + ms + }); + if *HOLD_MS > 0 { + std::thread::sleep(std::time::Duration::from_millis(*HOLD_MS)); + } +} + +/// Articles live PAR copied from the article cache while a flush of their file ran (all jobs; +/// before, those were refused and read back from disk). For the live PAR I/O line. +pub(crate) static SNAPSHOTS_DURING_FLUSH: AtomicU64 = AtomicU64::new(0); + /// Whether a cache flush of a file hands its written bytes to live PAR: only while a session /// runs, and never for a par2 file. A par2 file is no source of the live set, and resolving /// it against the live namespace invalidates the namespace, which stops live PAR for the job @@ -774,6 +801,7 @@ fn daemon_article_cache_check_flush(allocated: usize, flush_everything: bool) -> cache_unlock_flush(); return true; }; + flush_test_hold(); let items: Vec> = metas .iter() @@ -2513,6 +2541,14 @@ impl RsArticleWriter { .clone() .filter(|_| !self.proc_raw_article && !self.proc_skip_disk_write) .filter(|live| crate::parchecker::streaming_session_wants_recovery_bytes(live.nzb_id)); + // A data file's cached articles written here are their last time in RAM: live PAR + // keeps a copy for each one it has not captured yet (`articles_written`), so a + // capture that comes after this write never has par-rs read it back. + let live_source = self + .proc_live + .clone() + .filter(|live| !live.par_file && !self.proc_raw_article && !self.proc_skip_disk_write) + .filter(|live| crate::parchecker::streaming_session_has_session(live.nzb_id)); let held = std::cell::RefCell::new(Vec::<(u64, Vec)>::new()); let held_bytes = std::cell::Cell::new(0u64); let (crc, commit_err, failed_delta, short_copies) = article_writer_process_articles_counted( @@ -2543,6 +2579,20 @@ impl RsArticleWriter { .map_or(0, |f| f.write_bytes(buf)) }, |item_idx| { + if let (Some(live), Some(content)) = + (live_source.as_ref(), items[item_idx].segment_content) + { + if let Ok(offset) = u64::try_from(items[item_idx].segment_offset) { + // Not "in the file" yet: the write may still sit in the output + // buffer until the file closes, so nothing is handed over as readable. + crate::parchecker::streaming_session_articles_completed( + live.nzb_id, + (Some(live.file_id), &live.filename, &live.hash16k), + false, + &[(offset, content)], + ); + } + } if let (Some(live), Some(content)) = (live.as_ref(), items[item_idx].segment_content) { if let Ok(offset) = u64::try_from(items[item_idx].segment_offset) { if live.par_file && live.decoded_size > 0 { diff --git a/rust/src/parchecker.rs b/rust/src/parchecker.rs index a08fc2195..9d9195915 100644 --- a/rust/src/parchecker.rs +++ b/rust/src/parchecker.rs @@ -742,7 +742,14 @@ fn build_streaming_session_with( base_dir: base_dir.to_path_buf(), par_name: Mutex::new(Vec::new()), catchup_source_bytes: AtomicU64::new(0), - metrics: live_metrics::LiveMetricCounters::default(), + metrics: { + let metrics = live_metrics::LiveMetricCounters::default(); + metrics.flush_snapshots_base.store( + crate::articledl::SNAPSHOTS_DURING_FLUSH.load(Ordering::Relaxed), + Ordering::Relaxed, + ); + metrics + }, last_error: Mutex::new(None), warning_reported: AtomicBool::new(false), refusals: Mutex::new(Vec::new()), @@ -889,6 +896,12 @@ impl ActiveStreamingSession { /// This is the one place a cache write meets live PAR. fn articles_written(&self, id: FileId, in_file: bool, items: &[(u64, &[u8])]) -> usize { self.backfill_held(&id, items); + self.hand_over_written(id, in_file, items) + } + + /// [`Self::articles_written`] without keeping bytes for a pending back-fill: for a writer + /// that keeps those itself (file completion joins whole runs for it). + fn hand_over_written(&self, id: FileId, in_file: bool, items: &[(u64, &[u8])]) -> usize { // Committed gaps of staged slices may be readable now: the next drain finishes them. if !items.is_empty() { self.staged_due.store(true, Ordering::Release); @@ -2067,6 +2080,11 @@ pub(crate) fn streaming_session_defer_committed_article( bytes: None, committed: true, }); + // Taken as written: a later write of it (rare: the cache dropped it unwritten) + // must not keep a copy that no capture ever takes. + if queue.captured.len() < LIVE_MARK_LIMIT { + queue.captured.insert((id, offset)); + } entry .metrics .committed_articles @@ -2327,6 +2345,32 @@ pub(crate) fn streaming_session_articles_written( entry.articles_written(id, in_file, items) } +/// File completion wrote `items` (offset, bytes) of a data file's cached articles, into its +/// DirectWrite file when `in_file`, and frees them next: live PAR keeps what it has not +/// captured yet, as for a cache flush (`articles_written`), except bytes for a pending +/// back-fill (the completion keeps those itself). No I/O. +pub(crate) fn streaming_session_articles_completed( + nzb_id: i32, + identity: (Option, &[u8], &[u8]), + in_file: bool, + items: &[(u64, &[u8])], +) -> usize { + if let Some(queue_id) = identity.0 { + let offsets: Vec = items.iter().map(|&(offset, _)| offset).collect(); + presession_drop(nzb_id, queue_id, &offsets); + } + let Some(entry) = active_streaming_session(nzb_id) else { + return 0; + }; + if entry.session.is_cancelled() || items.is_empty() { + return 0; + } + let Ok(id) = live_source_id(&entry, identity.0, identity.1, identity.2) else { + return 0; + }; + entry.hand_over_written(id, in_file, items) +} + /// Bytes RustyGet wrote for a job before its live session could take them: articles written /// before the session started (the par2 index has to arrive and be parsed first), and /// recovery volume articles written before the volume's size was known. Kept, within @@ -2338,6 +2382,8 @@ pub(crate) fn streaming_session_articles_written( struct PresessionKept { jobs: HashMap, bytes: u64, + /// Jobs whose bytes passed [`PRESESSION_LIMIT`] (logged once each). + overflowed: std::collections::HashSet, } struct PresessionJob { @@ -2373,6 +2419,7 @@ pub(crate) fn presession_keep(nzb_id: i32, file_id: i32, items: &[(u64, &[u8])]) }); kept.bytes -= freed; let mut added = 0u64; + let mut refused = 0usize; for &(offset, bytes) in items { let size = bytes.len() as u64; // A copy of an earlier write of this article is stale now: never hand it over. @@ -2381,7 +2428,11 @@ pub(crate) fn presession_keep(nzb_id: i32, file_id: i32, items: &[(u64, &[u8])]) .get_mut(&nzb_id) .and_then(|job| job.articles.remove(&(file_id, offset))); kept.bytes -= stale.map_or(0, |b| b.len() as u64); - if size == 0 || kept.bytes.saturating_add(size) > PRESESSION_LIMIT { + if size == 0 { + continue; + } + if kept.bytes.saturating_add(size) > PRESESSION_LIMIT { + refused += 1; continue; } let job = kept.jobs.entry(nzb_id).or_insert_with(|| PresessionJob { @@ -2394,6 +2445,16 @@ pub(crate) fn presession_keep(nzb_id: i32, file_id: i32, items: &[(u64, &[u8])]) added += size; } kept.jobs.retain(|_, job| !job.articles.is_empty()); + let first_overflow = refused > 0 && kept.overflowed.len() < 4096 && kept.overflowed.insert(nzb_id); + drop(kept); + if first_overflow { + // The fallback is a read back from disk once the session starts: say so, once a job. + let message = format!( + "Live PAR (job {nzb_id}): bytes written before its session passed the {} MB kept for it; par-rs reads the articles past that back from disk", + PRESESSION_LIMIT >> 20 + ); + crate::log::log_active_bytes(crate::queuesubsys_host::MK_DETAIL, message.as_bytes()); + } added } @@ -2482,6 +2543,7 @@ fn presession_volume(nzb_id: i32, file_id: i32, len: u64) -> Option> { /// Drops what is kept for job `nzb_id` (its session ended, or the job left the queue). pub(crate) fn presession_forget(nzb_id: i32) { let mut kept = PRESESSION.lock().unwrap_or_else(|e| e.into_inner()); + kept.overflowed.remove(&nzb_id); if let Some(job) = kept.jobs.remove(&nzb_id) { kept.bytes -= job.articles.values().map(|b| b.len() as u64).sum::(); } diff --git a/rust/src/parchecker/live_lifecycle_tests.rs b/rust/src/parchecker/live_lifecycle_tests.rs index 43d4e2e7e..530dcf0b1 100644 --- a/rust/src/parchecker/live_lifecycle_tests.rs +++ b/rust/src/parchecker/live_lifecycle_tests.rs @@ -2019,6 +2019,69 @@ fn live_flush_before_capture_lends_for_the_kept_bytes() { streaming_session_forget(id); } +/// File completion writes a data file's last cached articles and frees them; captures that +/// come after it take the copies it handed over (`streaming_session_articles_completed`), so +/// par-rs reads nothing back. Unlike a cache flush, it keeps nothing for a back-fill here. +#[test] +fn live_completion_write_hands_its_bytes_to_later_captures() { + let fx = Fixture::new(); + let set = fx.set(); + let id = -1909015; // unique: sessions are process-wide + streaming_session_start_bounded(id, &fx.0.join("testfile.par2"), &fx.0, 500 * 1024 * 1024) + .unwrap(); + let files = written_copies(&fx, &set); + let entry = active_streaming_session(id).unwrap(); + for (name, _, bytes) in &files { + for (i, chunk) in bytes.chunks(1000).enumerate() { + streaming_session_articles_completed(id, (None, name, &[]), true, &[((i * 1000) as u64, chunk)]); + } + } + assert_eq!(entry.held_backfill.lock().unwrap().1, 0); + for (name, path, bytes) in &files { + defer_uncached(id, name, path, bytes, (0, bytes.len()), 1000); + } + streaming_session_drain_articles(id).unwrap().unwrap(); + let status = streaming_session_status(id).unwrap(); + assert_eq!(status.verified, status.total); + assert_eq!(streaming_session_io_stats(id).unwrap().source_bytes_read, 0); + assert_eq!(entry.metrics.committed_articles.load(Ordering::Relaxed), 0); + assert!(entry.metrics.stashed_articles.load(Ordering::Relaxed) > 0); + assert_eq!(entry.articles.lock().unwrap().bytes, 0); + drop(entry); + streaming_session_forget(id); +} + +/// An article taken as written (RAM had no copy: par-rs reads it from its file) and written +/// again later keeps no copy: no capture would ever take it, and it would hold ParBuffer +/// until its file completed. +#[test] +fn live_article_taken_as_written_keeps_no_copy_of_a_later_write() { + let fx = Fixture::new(); + let set = fx.set(); + let id = -1909016; // unique: sessions are process-wide + streaming_session_start_bounded(id, &fx.0.join("testfile.par2"), &fx.0, 500 * 1024 * 1024) + .unwrap(); + let files = written_copies(&fx, &set); + let entry = active_streaming_session(id).unwrap(); + let (name, path, bytes) = &files[0]; + defer_uncached(id, name, path, bytes, (0, bytes.len()), 1000); + let items: Vec<(u64, &[u8])> = bytes + .chunks(1000) + .enumerate() + .map(|(i, chunk)| ((i * 1000) as u64, chunk)) + .collect(); + streaming_session_articles_written(id, (None, name, &[]), true, &items); + { + let queue = entry.articles.lock().unwrap(); + assert!(queue.stash.is_empty(), "no copy kept"); + } + streaming_session_drain_articles(id).unwrap().unwrap(); + assert_eq!(entry.articles.lock().unwrap().bytes, 0); + assert_eq!(entry.metrics.stash_refusals.load(Ordering::Relaxed), 0); + drop(entry); + streaming_session_forget(id); +} + /// Articles written before the job's live session started (the par2 index arrives first and /// is parsed off the queue) are kept for it: the catch-up capture finds them gone from the /// cache and takes the kept bytes, so par-rs reads nothing back. Recovery volume articles diff --git a/rust/src/parchecker/live_metrics.rs b/rust/src/parchecker/live_metrics.rs index c218d9e83..b9af78a5a 100644 --- a/rust/src/parchecker/live_metrics.rs +++ b/rust/src/parchecker/live_metrics.rs @@ -26,6 +26,9 @@ pub(super) struct LiveMetricCounters { pub presession_articles: AtomicU64, /// Articles that waited for the cache write, handed over with the bytes it wrote. pub written_handoffs: AtomicU64, + /// `articledl::SNAPSHOTS_DURING_FLUSH` when the session started: the I/O line reports + /// the articles copied from the cache during a flush of their file since then. + pub flush_snapshots_base: AtomicU64, /// Obfuscated queue files bound to their par2 file by their first article's 16k hash. pub bound_by_first_article: AtomicU64, /// Verified slices folded into recovery slots added later from bytes still in RAM @@ -142,7 +145,7 @@ impl ActiveStreamingSession { let replay = self.catchup_source_bytes.load(Ordering::Relaxed); let mb = |bytes: u64| format!("{:.1}", bytes as f64 / (1024.0 * 1024.0)); format!( - "Live PAR (job {nzb_id}) I/O: source_bytes_read {} MB (par-rs {} MB, RustyGet replay {} MB), backfill_bytes_read {} MB, recovery_bytes_read {} MB, target_verification_bytes_read {} MB, ram_bytes_verified {} MB, ram_backfilled_slices {}, recovery volumes from RAM {} ({} MB), trusted slice checks {}; {} cache miss(es), {} article(s) read from their file by par-rs, {} waited for the cache flush, {} still waiting, {} handed over with the bytes written, {} taken from bytes kept at write, {} file(s) matched by their first article, {} not kept at write (no room), {} taken from bytes kept before the session, {} slice(s) rebuilt ahead ({} re-verified at completion)", + "Live PAR (job {nzb_id}) I/O: source_bytes_read {} MB (par-rs {} MB, RustyGet replay {} MB), backfill_bytes_read {} MB, recovery_bytes_read {} MB, target_verification_bytes_read {} MB, ram_bytes_verified {} MB, ram_backfilled_slices {}, recovery volumes from RAM {} ({} MB), trusted slice checks {}; {} cache miss(es), {} article(s) read from their file by par-rs, {} waited for the cache flush, {} still waiting, {} handed over with the bytes written, {} taken from bytes kept at write, {} file(s) matched by their first article, {} not kept at write (no room), {} taken from bytes kept before the session, {} slice(s) rebuilt ahead ({} re-verified at completion), {} copied from the cache during a flush (all jobs)", mb(io.source_bytes_read.saturating_add(replay)), mb(io.source_bytes_read), mb(replay), @@ -165,6 +168,9 @@ impl ActiveStreamingSession { self.metrics.presession_articles.load(Ordering::Relaxed), self.metrics.rebuilt_ahead_slices.load(Ordering::Relaxed), self.metrics.rebuilt_rechecked.load(Ordering::Relaxed), + crate::articledl::SNAPSHOTS_DURING_FLUSH + .load(Ordering::Relaxed) + .saturating_sub(self.metrics.flush_snapshots_base.load(Ordering::Relaxed)), ) } } diff --git a/rust/src/parchecker/live_trust_tests.rs b/rust/src/parchecker/live_trust_tests.rs index 939140e51..c90b4dd48 100644 --- a/rust/src/parchecker/live_trust_tests.rs +++ b/rust/src/parchecker/live_trust_tests.rs @@ -453,10 +453,13 @@ fn a_ram_article_completing_a_committed_slice_raises_no_transient_damage() { } /// The hazard M6f's caution names, at the par-rs boundary: a committed range reported -/// before its write reads the preallocated zeros and shows the slice damaged. RustyGet's -/// capture never reports a committed article before its write (test above). +/// before its write reads the preallocated zeros. Since par-rs 2524277 (#145) that slice is +/// not damaged: the zeros do not match the CRC the article was reported with, so the slice +/// waits, and once the bytes land the next `complete_staged_slices` (RustyGet runs it after +/// each flush, `staged_due`) verifies it. RustyGet's capture never reports a committed +/// article before its write (test above); this is the safety net for a write-back cache. #[test] -fn a_committed_range_reported_before_its_write_reads_zeros() { +fn a_committed_range_reported_before_its_write_waits_for_it() { let f = fixture(0x7a75_0009, 6, 2, 2); let path = f.dir.join("part01.rar"); std::fs::write(&path, vec![0u8; f.data.len()]).unwrap(); @@ -477,8 +480,20 @@ fn a_committed_range_reported_before_its_write_reads_zeros() { outcome .events .iter() - .any(|e| e.state == SliceState::Damaged), - "the zero gap fails the slice" + .all(|e| e.state != SliceState::Damaged), + "the zero gap does not match its article CRC: the slice waits" + ); + // The write lands; the staged check after the flush verifies the slice. + let mut bytes = std::fs::read(&path).unwrap(); + bytes[..half].copy_from_slice(a); + std::fs::write(&path, &bytes).unwrap(); + let done = entry.session.complete_staged_slices().unwrap(); + assert!( + done.events + .iter() + .any(|e| e.slice_idx == 0 && e.state == SliceState::VerifiedGood), + "{:?}", + done.events ); } @@ -611,7 +626,7 @@ fn decode_ahead_rebuilds_a_lost_slice_before_the_download_ends() { assert_eq!(hashes.unwrap().crc32, par_rs::crc::crc32(&f.data)); assert!(entry .io_stats_line(f.nzb_id) - .ends_with("1 slice(s) rebuilt ahead (1 re-verified at completion)")); + .contains("1 slice(s) rebuilt ahead (1 re-verified at completion), ")); } /// The write order of decode-ahead: a late write of a corrupt copy into a slice rebuilt diff --git a/rust/src/qfile.rs b/rust/src/qfile.rs index c22fd883f..84cbfbfda 100644 --- a/rust/src/qfile.rs +++ b/rust/src/qfile.rs @@ -746,11 +746,18 @@ pub(crate) unsafe fn host_cache_op( } }; match a1 { - // copy the article's cached data out + // copy the article's cached data out, also while a flush of the file runs: its + // segments are freed only under the cache content lock (sub-op 6, output op 9/5), + // which the caller holds, so a non-null pointer stays valid for the copy. Refusing + // during a flush made live PAR read every article finishing then back from disk. 1 => { let data = art(null_l, p2, 110, 0, null_i, null_l.cast(), null_s) as *const u8; - if file.get(FLUSH_LOCKED) == 0 && !data.is_null() && a2 > 0 { + if !data.is_null() && a2 > 0 { unsafe { ptr::copy_nonoverlapping(data, *i64s as usize as *mut u8, a2 as usize) }; + if file.get(FLUSH_LOCKED) != 0 { + crate::articledl::SNAPSHOTS_DURING_FLUSH + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } 1 } else { 0 @@ -845,7 +852,10 @@ pub(crate) unsafe fn host_cache_op( let parking = !nzb.is_null() && unsafe { (*nzb).parking }; return usize::from(file.get(DELETED) != 0 && !parking); } - art(null_l, p2, 111, 0, null_i, null_l.cast(), null_s); + // Under the content lock: a snapshot (sub-op 1) may be copying it right now. + crate::articledl::with_cache_content_lock(|| { + art(null_l, p2, 111, 0, null_i, null_l.cast(), null_s); + }); 0 } 7 => { @@ -1157,16 +1167,19 @@ pub(crate) unsafe fn host_output_op( null_l.cast(), null_s, ); - art_op( - null_l, - pa, - 111, - 0, - ptr::null(), - null_i, - null_l.cast(), - null_s, - ); + // Under the content lock: a live PAR snapshot may be copying it right now. + crate::articledl::with_cache_content_lock(|| { + art_op( + null_l, + pa, + 111, + 0, + ptr::null(), + null_i, + null_l.cast(), + null_s, + ); + }); 0 } 6 => { @@ -1468,6 +1481,62 @@ mod tests { assert!(FILE_IDS.last() >= 9000); } + /// A live PAR snapshot (cache sub-op 1) copies a cached article also while a flush of its + /// file runs (the flush lock is set): articles finishing during a flush used to be refused + /// and read back from disk by par-rs. Once the flush frees the segment (sub-op 6, under the + /// content lock), the snapshot finds nothing. + #[test] + fn snapshot_copies_a_cached_article_while_its_file_is_flushed() { + let f = nzbget_rs_file_new(0); + let (ni, nl, ns) = ( + ptr::null_mut::(), + ptr::null_mut::(), + ptr::null_mut::<*const c_char>(), + ); + let data: Vec = (0..64u8).collect(); + let mid = CString::new("a@b").unwrap(); + unsafe { + let list = (*f).articles; + crate::qarticle::nzbget_rs_article_host( + list, ptr::null_mut(), 11, 1, 64, mid.as_ptr(), ni, nl, ns, + ); + let pa = crate::qarticle::nzbget_rs_article_host( + list, ptr::null_mut(), 106, 0, 0, ptr::null(), ni, nl, ns, + ); + assert_ne!(pa, 0); + // allocation 0: the test owns `data`, the discard frees nothing + let mut ints = [0 as c_int, 64]; + let mut i64s = [0i64, data.as_ptr() as usize as i64]; + crate::qarticle::nzbget_rs_article_host( + ptr::null_mut(), + pa as *mut _, + 112, + 0, + 0, + ptr::null(), + ints.as_mut_ptr(), + i64s.as_mut_ptr(), + ns, + ); + nzbget_rs_file_set(f, field::FLUSH_LOCKED, 1); + let snapshot = |out: &mut Vec| { + let mut dst = [out.as_mut_ptr() as usize as i64]; + crate::articledl::with_cache_content_lock(|| { + host_cache_op(f, 1, 64, pa, ptr::null(), ni, dst.as_mut_ptr(), ns) + }) + }; + let mut out = vec![0u8; 64]; + assert_eq!(snapshot(&mut out), 1, "copied during the flush"); + assert_eq!(out, data); + // the flush frees it after writing + host_cache_op(f, 6, 1, pa, ptr::null(), ni, nl, ns); + let mut out = vec![0u8; 64]; + assert_eq!(snapshot(&mut out), 0, "freed: nothing to copy"); + nzbget_rs_file_set(f, field::FLUSH_LOCKED, 0); + nzbget_rs_file_free(f); + } + } + #[test] fn typed_setters_keep_the_download_counts() { let n = crate::qnzb::nzbget_rs_nzb_scalars_new(); diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index e1023467e..6ad0136df 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -12662,6 +12662,10 @@ def _livepar_io(t, timeout=30): r'before the session', t.read_file('nzbget.log').decode(errors='replace')) if kept: io.update({'not_kept': int(kept[-1][0]), 'presession': int(kept[-1][1])}) + during = re.findall(r'(\d+) copied from the cache during a flush', + t.read_file('nzbget.log').decode(errors='replace')) + if during: + io['during_flush'] = int(during[-1]) stashed = re.findall(r'(\d+) taken from bytes kept at write', t.read_file('nzbget.log').decode(errors='replace')) if stashed: @@ -12671,8 +12675,8 @@ def _livepar_io(t, timeout=30): return {} -def _livepar_run(daemon, t, tag, seed, missing, recovery, volumes=1, block=524288): - members, payloads = _livepar_release(t, tag, seed, missing, recovery, block=block, +def _livepar_run(daemon, t, tag, seed, missing, recovery, volumes=1, block=524288, size=2_000_000): + members, payloads = _livepar_release(t, tag, seed, missing, recovery, size=size, block=block, volumes=volumes) api = daemon.wait_ready() daemon.append(api, 'Live', build_multi_nzb(members), False, tag + '-key', 100) @@ -12835,6 +12839,32 @@ def scenario_liveparzeroreads(daemon, t): % (h['Status'], intact, live, batch, io)) +def scenario_liveparflushrace(daemon, t): + """liveparzeroreads at line speed with the cache flushing the files being downloaded: + a 1 MB article cache (it flushes everything, files with downloads running included, + whenever it is nearly full), 16 connections, and each flush holding its file's flush lock 150 ms before it + writes (RUSTYGET_TEST_FLUSH_HOLD_MS, as a busy disk does). Articles that finish while + their file is flushed are still in the cache: live PAR copies them there (the cache's + snapshot no longer refuses during a flush), takes the bytes a flush or the file's + completion wrote before its capture, and par-rs reads no source byte back + (source_bytes_read 0, no article read from its file). Before: every article finishing + during a flush of its file was read back (6790: 437 articles, 335.8 MB of a 3.3 GB + set), and its later write kept a copy no capture took. The I/O line's "copied from the + cache during a flush" count proves the race happened (main on this scenario: 35 + articles read back, 2.5 MB).""" + h, intact, io = _livepar_run(daemon, t, 'lfr', 12560, {1: {6}, 4: {17}, 6: {29}}, 8, volumes=4, + size=6_000_000) + live = _grep_log(t, 'as the download ended') + batch = _grep_log(t, 'PAR repair timings for') + flushes = _grep_log(t, 'Flushing cache for') + ok = (h['Status'].startswith('SUCCESS') and intact and live >= 1 and batch == 0 and bool(io) + and flushes >= 4 and io.get('during_flush', 0) > 0 + and io['source_mb'] == 0.0 and io['read_by_parrs'] == 0 + and io['backfill_mb'] == 0.0 and io.get('not_kept', 99) == 0) + return ('liveparflushrace', ok, 'status=%s intact=%s live_repairs=%d batch_repairs=%d flushes=%d io=%s' + % (h['Status'], intact, live, batch, flushes, io)) + + def scenario_liveparheldvolume(daemon, t): """The planned recovery volumes cover the damage, but the volume past the plan is never fetched for it (6790, PR #729: a volume past the plan was fetched after ~620 of 634 slices @@ -15551,6 +15581,7 @@ def scenario_dupausedunpack(daemon, t): 'liveparplanned': scenario_liveparplanned, 'livepargrow': scenario_livepargrow, 'liveparzeroreads': scenario_liveparzeroreads, + 'liveparflushrace': scenario_liveparflushrace, 'liveparheldvolume': scenario_liveparheldvolume, 'livepardecodeahead': scenario_livepardecodeahead, 'livepartrusted': scenario_livepartrusted, @@ -15702,6 +15733,9 @@ def scenario_dupausedunpack(daemon, t): 'persistdeadprimary': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, 'persistrestart': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, 'persistrestartdamaged': {'RUSTYGET_PERSISTENT_UNPACK': '1'}, + # Each cache flush holds its file's flush lock 150 ms before writing (articledl.rs + # `flush_test_hold`): captures land while their file is flushed. + 'liveparflushrace': {'RUSTYGET_TEST_FLUSH_HOLD_MS': '150'}, } SCENARIO_ENV_KEYS = sorted({k for env in SCENARIO_ENV.values() for k in env}) @@ -16018,6 +16052,8 @@ def scenario_dupausedunpack(daemon, t): 'liveparplanned': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], 'livepargrow': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], 'liveparzeroreads': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], + 'liveparflushrace': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=1', 'DirectWrite=yes', + 'Server1.Connections=16'], 'liveparheldvolume': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], 'livepardecodeahead': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'], 'livepartrusted': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes'],