diff --git a/CHANGELOG.md b/CHANGELOG.md index b015469..f87f9e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,30 @@ All notable changes to the AVA1 crates and C library. The wire format is version 1 throughout; see [README](README.md#versions). +## 1.0.10 + +Fixes from a review of the read-back added in 1.0.8 and 1.0.9. Nothing changes on the wire format, on +disk or in the public API. + +C library: + +- Read-back: a block of a large file that was sent twice (a duplicate chunk), + with the second copy written while the first was still being made durable, was read back before + the second copy was on the drive and not again. It is now read back again once the second copy is + durable, as §13.5 says, so a fault in that second write is found. + +Rust receiver: + +- A `JobOpen` with a flag the receiver does not know is refused with `ERR_PROTOCOL`, as §11.8 says + and the C node does. It used to be accepted and the flag ignored, so a client that asked a Rust + node for read-back (`JF_READBACK`) was not told it would not get it. + +Other: + +- `docs/c-library.md` says how a node offers read-back (`AVA1_CAP_READBACK`). +- The Rust tests remove their temp folders when they finish (a full run left about 1 GB behind). +- `toml` 1.2.1 and `cc` 1.11.1 (build and code-generation dependencies). + ## 1.0.9 Read-back while the file arrives. Nothing changes on the wire format. diff --git a/Cargo.lock b/Cargo.lock index a1f9ca7..42afea8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -55,7 +55,7 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "ava1" -version = "1.0.9" +version = "1.0.10" dependencies = [ "ava1-chaos", "blake2 0.11.0", @@ -74,14 +74,14 @@ dependencies = [ [[package]] name = "ava1-chaos" -version = "1.0.9" +version = "1.0.10" dependencies = [ "tokio", ] [[package]] name = "ava1-ctest" -version = "1.0.9" +version = "1.0.10" dependencies = [ "ava1", "ava1-chaos", @@ -93,7 +93,7 @@ dependencies = [ [[package]] name = "ava1-gen" -version = "1.0.9" +version = "1.0.10" dependencies = [ "serde", "toml", diff --git a/Cargo.toml b/Cargo.toml index 8b33c3e..fc67407 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ resolver = "3" [workspace.package] edition = "2021" license = "MIT OR Apache-2.0" -version = "1.0.9" +version = "1.0.10" # File::lock (1.89). CI builds the published crates with exactly this version. rust-version = "1.89" repository = "https://github.com/phantomptr/ava1" diff --git a/c/ava1_apply.c b/c/ava1_apply.c index e28476d..a9de3b9 100644 --- a/c/ava1_apply.c +++ b/c/ava1_apply.c @@ -2652,6 +2652,14 @@ static void sync_batch(ava1_job_t *j) { for (i = 0; i < ng; i++) { ava1_lfile_t *lf = j->lf[rg[i].file_id]; if (!lf) continue; + /* Durable before and written again: a duplicate whose write was recorded while the batch that first + * made these bytes durable was still running (write_chunk saw nothing durable there yet, so it voided + * nothing). What was read back of them since read the duplicate's bytes before this batch synced + * them: it counts for nothing, nor does a read-back of the file in flight (see "read-back"). */ + if (ava1_rset_overlaps(&lf->durable, rg[i].offset, rg[i].offset + rg[i].len)) { + if (ava1_rset_remove(&lf->rb_done, rg[i].offset, rg[i].offset + rg[i].len) < 0) ava1_rset_clear(&lf->rb_done); + lf->rb_gen++; + } (void)ava1_rset_add(&lf->durable, rg[i].offset, rg[i].offset + rg[i].len); /* JF_READBACK: durable now, so the live read-back may take them (out of memory: the commit does). */ if (j->readback && groups_of(j->m.e[rg[i].file_id].size) >= 2 && !lf->committed && !lf->committing && @@ -2960,7 +2968,9 @@ static int read_root(ava1_job_t *j, uint32_t id, uint8_t root[32]) { * reads faster than the network delivers they keep up with the write front. Lanes write out of order: * rb_todo is a range set, so any order is fine. A write over durable bytes (a late duplicate) takes its * range out of rb_todo and rb_done and bumps lf->rb_gen, which voids any read-back of the file in flight: - * those bytes are read again once their own batch has made them durable. A reset does the same. A + * those bytes are read again once their own batch has made them durable (a batch that makes bytes + * durable a second time voids the same, for the duplicate recorded while their first batch ran). A + * reset does the same. A * mismatch is not acted on there (an old sender does not expect a FileRetry for a file it is still * sending): it is recorded (rb_found) and the commit acts on it as on its own. * diff --git a/crates/ava1-ctest/csrc/test_shim.c b/crates/ava1-ctest/csrc/test_shim.c index dd8f13b..588f75d 100644 --- a/crates/ava1-ctest/csrc/test_shim.c +++ b/crates/ava1-ctest/csrc/test_shim.c @@ -1158,6 +1158,8 @@ static int g_hold_commit; /* commits wait at COMMIT_VE static int g_corrupt_n; /* commits that find one byte of their part file flipped */ static uint64_t g_corrupt_at; /* ... at this offset */ static uint32_t g_prealloc_fault = UINT32_MAX - 1; /* a file whose preallocation answers ENOSPC */ +static int g_hold_synced; /* batches wait at BATCH_SYNCED (data fsynced, nothing recorded yet) while set */ +static uint32_t g_synced_held; /* batches waiting there now */ static void t_hook(ava1_job_t *j, int point, uint32_t id) { if (point == __atomic_load_n(&g_arm_point, __ATOMIC_SEQ_CST)) { /* fsync fault, armed for this point */ ava1_fsync_test_errno = g_arm_errno; @@ -1185,6 +1187,12 @@ static void t_hook(ava1_job_t *j, int point, uint32_t id) { } } } + if (point == AVA1_HOOK_BATCH_SYNCED && __atomic_load_n(&g_hold_synced, __ATOMIC_SEQ_CST)) { + __atomic_add_fetch(&g_synced_held, 1, __ATOMIC_SEQ_CST); + while (__atomic_load_n(&g_hold_synced, __ATOMIC_SEQ_CST) && !__atomic_load_n(&j->stopping, __ATOMIC_SEQ_CST)) + ava1_platform_sleep_ms(2); + __atomic_sub_fetch(&g_synced_held, 1, __ATOMIC_SEQ_CST); + } if (point == AVA1_HOOK_BATCH_DIR_SYNCED) dir_hook_note(j, 0); if (point == AVA1_HOOK_PREP_DIR_SYNCED) dir_hook_note(j, 1); if (point == AVA1_HOOK_COMMIT_VERIFIED) { @@ -1313,6 +1321,17 @@ uint32_t ava1_test_apply_segments(void) { closedir(dp); return n; } +void ava1_test_hold_batch_synced(int on) { __atomic_store_n(&g_hold_synced, on, __ATOMIC_SEQ_CST); } +uint32_t ava1_test_batch_synced_held(void) { return __atomic_load_n(&g_synced_held, __ATOMIC_SEQ_CST); } +/* File data the job has written so far (duplicates included). */ +uint64_t ava1_test_apply_bytes_received(void) { + uint64_t n; + if (!g_job) return 0; + pthread_mutex_lock(&g_job->mu); + n = g_job->bytes_received; + pthread_mutex_unlock(&g_job->mu); + return n; +} void ava1_test_apply_hold_commit(int on) { __atomic_store_n(&g_hold_commit, on, __ATOMIC_SEQ_CST); } /* The next `n` commits (at COMMIT_VERIFIED, before any read-back) find the part file's byte at `at` changed * on the drive. */ diff --git a/crates/ava1-ctest/tests/readback.rs b/crates/ava1-ctest/tests/readback.rs index 0f10960..aa3c618 100644 --- a/crates/ava1-ctest/tests/readback.rs +++ b/crates/ava1-ctest/tests/readback.rs @@ -26,6 +26,10 @@ extern "C" { fn ava1_test_rb_stats(out: *mut u64); fn ava1_test_chunk_delay(ms: u32); fn ava1_test_apply_summary(out: *mut u8, cap: usize) -> usize; + fn ava1_test_hold_batch_synced(on: i32); + fn ava1_test_batch_synced_held() -> u32; + fn ava1_test_apply_bytes_received() -> u64; + fn ava1_test_apply_hold(on: i32); } const G: usize = GROUP as usize; @@ -137,6 +141,8 @@ impl Drop for Knobs { ava1_test_rb_hold(0); ava1_test_chunk_delay(0); ava1_test_set_pwrite_max(0); + ava1_test_hold_batch_synced(0); + ava1_test_apply_hold(0); } } } @@ -511,6 +517,47 @@ fn a_group_written_again_is_read_back_again() { assert_eq!(st[0] + st[1], d.len() as u64 + GROUP, "{st:?}"); } +/// A duplicate written while the batch that first makes its group durable is still running: the batch +/// ends, the group is read back (the duplicate's bytes, not yet synced), and only the next batch makes +/// the duplicate durable. The group is read back again after that batch, here by the commit, which +/// finds the byte that changed on the drive in between. +#[test] +fn a_group_written_again_during_its_first_batch_is_read_back_again() { + let _k = Knobs; + let t = tmp("live-dup-batch"); + let root = t.join("dest"); + std::fs::create_dir_all(&root).unwrap(); + let d = data(8 * G + 5, 21); + let m = Manifest { + entries: vec![file("big.bin", d.len() as u64)], + }; + let job = CApplyJob::begin(&t.join("jobs"), &root, gen::JF_READBACK, &m, 0); + unsafe { ava1_test_hold_batch_synced(1) }; + send_groups(&job, 0, &d, &(0..4).collect::>()); + wait_until("the first batch synced", 10_000, || unsafe { + ava1_test_batch_synced_held() == 1 && ava1_test_apply_bytes_received() == 4 * GROUP + }); + send_groups(&job, 0, &d, &[1]); // the duplicate: written and recorded while that batch waits + wait_until("the duplicate written", 10_000, || unsafe { + ava1_test_apply_bytes_received() == 5 * GROUP + }); + unsafe { + ava1_test_apply_hold(1); // no second batch yet + ava1_test_hold_batch_synced(0); + } + wait_until("the live read-back", 10_000, || rb_stats()[0] == 4 * GROUP); + unsafe { ava1_test_corrupt_at_commit(1, GROUP + 7) }; // flipped as the commit's read-back begins + send_groups(&job, 0, &d, &(4..9).collect::>()); + job.root(0, *blake3::hash(&d).as_bytes()); + unsafe { ava1_test_apply_hold(0) }; + job.wait_event("retry 0 1", 10_000); + assert_eq!(rb_stats()[3], 1); + assert!(!root.join("big.bin").exists(), "nothing was committed"); + send_large(&job, 0, &d); + assert_eq!(job.wait(10_000), 0, "{}", job.events()); + assert_eq!(std::fs::read(root.join("big.bin")).unwrap(), d); +} + /// A group found wrong while the file arrives and then written again (a duplicate the sender had in /// flight) is judged by its new bytes: read back again, right this time, and the file commits. #[test] diff --git a/crates/ava1/src/host.rs b/crates/ava1/src/host.rs index b90afe4..7b77102 100644 --- a/crates/ava1/src/host.rs +++ b/crates/ava1/src/host.rs @@ -70,6 +70,9 @@ impl JobHost for FolderHost { .await; return; }; + if crate::recv::refuse_unknown_flags(&mut link, &open).await { + return; + } match open.kind { gen::JOB_UPLOAD => { let single = open.flags & gen::JF_SINGLE_FILE != 0; diff --git a/crates/ava1/src/recv.rs b/crates/ava1/src/recv.rs index c816d39..b401ee9 100644 --- a/crates/ava1/src/recv.rs +++ b/crates/ava1/src/recv.rs @@ -1151,15 +1151,47 @@ pub async fn download_job( download_run(link, m, None, sink, o).await } +/// The `JobOpen` flags this implementation knows (SPEC.md §11.8). `JF_OVERWRITE` is a `job.copy` +/// flag and `JF_READBACK` needs `CAP_READBACK`, which this receiver does not advertise. +pub(crate) const KNOWN_OPEN_FLAGS: u32 = + gen::JF_SINGLE_FILE | gen::JF_ORDERED | gen::JF_UNSAFE_READ | gen::JF_MOVE; + +/// Answers a `JobOpen` that carries a flag this receiver does not know with +/// `JobOpenAck{ERR_PROTOCOL}` (SPEC.md §11.8). `true` when it refused. +pub(crate) async fn refuse_unknown_flags(link: &mut JobLink, open: &JobOpen) -> bool { + if open.flags & !KNOWN_OPEN_FLAGS == 0 { + return false; + } + let _ = link + .control + .send(&JobOpenAck { + job_id: open.job_id, + status: gen::ERR_PROTOCOL, + credit: 0, + staged: 0, + workers: 0, + message: Some("unknown job flags".into()), + }) + .await; + true +} + /// The responder side of an upload (a host for uploads): the JobOpen already arrived. /// The ack carries the job's absolute grant (the extra credit note: `Credit` frames are /// incremental; only the ack sets the sender's window). +/// A `JobOpen` with a flag this receiver does not know is refused with `ERR_PROTOCOL` (§11.8). pub async fn receive_job( link: &mut JobLink, open: JobOpen, sink: Arc, mut o: RecvOptions, ) -> Result { + if refuse_unknown_flags(link, &open).await { + return Err(SendError::Refused { + status: gen::ERR_PROTOCOL, + message: "unknown job flags".into(), + }); + } o.flags = open.flags; // The journal's Open records the job's flags link.control .send(&JobOpenAck { diff --git a/crates/ava1/tests/common/mod.rs b/crates/ava1/tests/common/mod.rs index af85b84..ef05646 100644 --- a/crates/ava1/tests/common/mod.rs +++ b/crates/ava1/tests/common/mod.rs @@ -191,9 +191,38 @@ pub fn temp_dir(tag: &str) -> std::path::PathBuf { )); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); + sweep::add(&d); d } +/// The folders `temp_dir` made are removed when the test binary exits (a full run used to +/// leave about 1 GB of them in the system's temp folder). +mod sweep { + use std::path::{Path, PathBuf}; + use std::sync::Mutex; + + static DIRS: Mutex> = Mutex::new(Vec::new()); + + pub fn add(d: &Path) { + let mut dirs = DIRS.lock().unwrap_or_else(|e| e.into_inner()); + #[cfg(unix)] + if dirs.is_empty() { + // SAFETY: `at_exit` is an `extern "C"` function that does not unwind. + unsafe { libc::atexit(at_exit) }; + } + dirs.push(d.to_path_buf()); + } + + #[cfg(unix)] + extern "C" fn at_exit() { + if let Ok(dirs) = DIRS.try_lock() { + for d in dirs.iter() { + let _ = std::fs::remove_dir_all(d); + } + } + } +} + /// The code the console shows for the session of `key` (its screen: the one place the code /// exists). Waits for the session to be registered after its Welcome. pub async fn console_code(ctx: &ServerCtx, key: &[u8; 32]) -> u32 { diff --git a/crates/ava1/tests/data_rust.rs b/crates/ava1/tests/data_rust.rs index fd87833..ab7937a 100644 --- a/crates/ava1/tests/data_rust.rs +++ b/crates/ava1/tests/data_rust.rs @@ -364,6 +364,49 @@ async fn a_download_of_a_path_outside_the_share_is_refused_too() { ); } +/// SPEC.md §11.8: a receiver answers `ERR_PROTOCOL` to a job flag it does not know, upload or +/// download. `JF_READBACK` is one here: this receiver does not advertise `CAP_READBACK`. +#[tokio::test(flavor = "multi_thread")] +async fn a_host_refuses_job_flags_it_does_not_know() { + let d = common::temp_dir("rr-flags"); + std::fs::create_dir_all(d.join("share")).unwrap(); + let host = Arc::new(FolderHost { + root: d.join("share"), + jobs_dir: d.join("hjobs"), + }); + let (addr, _ctx, id, peers) = + common::paired_ctx(|c| c.with_jobs(host).with_timing(common::transfer())).await; + let s = connect(&addr.to_string(), id, peers, "client", common::transfer()) + .await + .unwrap(); + for (n, (kind, flags)) in [ + (gen::JOB_UPLOAD, gen::JF_READBACK), + (gen::JOB_UPLOAD, 1 << 20), + (gen::JOB_DOWNLOAD, gen::JF_READBACK), + ] + .into_iter() + .enumerate() + { + let job = [0x50 + n as u8; 16]; + let mut link = s.job(job); + link.control + .send(&JobOpen { + job_id: job, + kind, + policy: 0, + flags, + root: "x".into(), + src: None, + credit: Some(1 << 20), + }) + .await + .unwrap(); + let ack: JobOpenAck = next_control(&mut link).await.decode().unwrap(); + assert_eq!(ack.status, gen::ERR_PROTOCOL, "kind {kind} flags {flags}"); + } + assert!(!d.join("share/x").exists()); +} + /// SPEC.md §12.4: a frame larger than the credit still outstanding is refused with the /// sealed Error(ERR_CREDIT) on the offending lane, and only that lane ends: the session and /// the job stay, and a second lane still delivers (Received). Nothing of the refused frame diff --git a/docs/c-library.md b/docs/c-library.md index ed490a3..499fab5 100644 --- a/docs/c-library.md +++ b/docs/c-library.md @@ -51,7 +51,9 @@ these. 4. **The data plane.** Fill an `ava1_data_cfg_t`: the jobs folder (journals live there), and `may_write` / `may_read` / `same_device` callbacks that decide which absolute paths clients may touch. `ava1_data_start(&dc)`, then `cfg.data = ava1_data_hooks()` and add - `AVA1_CAP_DATA_PLANE` to `cfg.caps`. + `AVA1_CAP_DATA_PLANE` to `cfg.caps`. Add `AVA1_CAP_READBACK` too to let clients ask for + read-back verification (`JF_READBACK`, SPEC.md §13.5): the node then reads each large file back + from its drive before it commits it. 5. **RPC.** `cfg.rpc` runs on a worker thread for every request. Call `ava1_data_rpc` first (it answers the protocol's own methods and returns -1 for anything else), then answer `node.info` and your application's methods, or return `AVA1_ERR_UNKNOWN_METHOD`.