Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
52 changes: 51 additions & 1 deletion rust/src/articledl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<u64> = std::sync::LazyLock::new(|| {
let ms = std::env::var("RUSTYGET_TEST_FLUSH_HOLD_MS")
.ok()
.and_then(|v| v.parse::<u64>().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
Expand Down Expand Up @@ -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<ArticleWriterFlushItem<'_>> = metas
.iter()
Expand Down Expand Up @@ -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<u8>)>::new());
let held_bytes = std::cell::Cell::new(0u64);
let (crc, commit_err, failed_delta, short_copies) = article_writer_process_articles_counted(
Expand Down Expand Up @@ -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 {
Expand Down
66 changes: 64 additions & 2 deletions rust/src/parchecker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<i32>, &[u8], &[u8]),
in_file: bool,
items: &[(u64, &[u8])],
) -> usize {
if let Some(queue_id) = identity.0 {
let offsets: Vec<u64> = 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
Expand All @@ -2338,6 +2382,8 @@ pub(crate) fn streaming_session_articles_written(
struct PresessionKept {
jobs: HashMap<i32, PresessionJob>,
bytes: u64,
/// Jobs whose bytes passed [`PRESESSION_LIMIT`] (logged once each).
overflowed: std::collections::HashSet<i32>,
}

struct PresessionJob {
Expand Down Expand Up @@ -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.
Expand All @@ -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 {
Expand All @@ -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
}

Expand Down Expand Up @@ -2482,6 +2543,7 @@ fn presession_volume(nzb_id: i32, file_id: i32, len: u64) -> Option<Vec<u8>> {
/// 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::<u64>();
}
Expand Down
63 changes: 63 additions & 0 deletions rust/src/parchecker/live_lifecycle_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 7 additions & 1 deletion rust/src/parchecker/live_metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand All @@ -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)),
)
}
}
Expand Down
27 changes: 21 additions & 6 deletions rust/src/parchecker/live_trust_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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
);
}

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading