Skip to content
Merged
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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@
All notable changes to the AVA1 crates and C library. The wire format is version 1 throughout;
see [README](README.md#versions).

## 1.0.11

Read-back of a resumed file while it arrives. Nothing changes on the wire format, on disk or in the
public API.

C library:

- Read-back: a large file resumed from the journal (a stop and a resume, a restarted node) had what it
held durable from before read back only after its last byte, while the sender had nothing left to
send; for a big file that was minutes of finishing with the upload done. Those bytes are now read
back while the rest of the file arrives, like the bytes of this run, and one that reads back wrong
still has the file sent again (§13.5).

Rust sender:

- A cancel while the up-front free-space check runs ends the job at once and tells the receiver. It
used to wait for the check's answer first.

## 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
Expand Down
8 changes: 4 additions & 4 deletions 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ resolver = "3"
[workspace.package]
edition = "2021"
license = "MIT OR Apache-2.0"
version = "1.0.10"
version = "1.0.11"
# File::lock (1.89). CI builds the published crates with exactly this version.
rust-version = "1.89"
repository = "https://github.com/phantomptr/ava1"
Expand Down
77 changes: 74 additions & 3 deletions c/ava1_apply.c
Original file line number Diff line number Diff line change
Expand Up @@ -2974,9 +2974,13 @@ static int read_root(ava1_job_t *j, uint32_t id, uint8_t root[32]) {
* 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.
*
* - At the commit, every group the live part did not read (the last batch's, those it had no time for,
* all of a file made durable before this process started) is read back as before, in stripes on a few
* threads of its own: the last file of a job has nothing left to overlap with.
* What a file held durable before this process took the job up (a resume from the journal) is handed
* over the same way when the job is prepared (ava1_apply_readback_resumed), so it is read while the rest
* of the file arrives.
*
* - At the commit, every group the live part did not read (the last batch's, those it had no time for) is
* read back as before, in stripes on a few threads of its own: the last file of a job has nothing left
* to overlap with.
*
* So every group is read back once after it was last made durable, and a byte that changes on the drive
* before its group is read back is found. One that changes after its group was read back (while the rest
Expand Down Expand Up @@ -3273,6 +3277,73 @@ static void rb_live_kick(ava1_job_t *j) {
j->id[1], j->id[2], j->id[3], n);
}

/* Caller holds j->mu. Hands what file `id` holds durable and nobody has read back (nor is to: rb_todo) to the
* live read-back; returns those bytes. */
static uint64_t rb_hand_over(ava1_job_t *j, uint32_t id) {
ava1_lfile_t *lf = id < j->m.n ? j->lf[id] : NULL;
uint64_t bytes = 0;
size_t r, d = 0;
/* rb_busy: a read of this file is in flight, its groups in neither set. They would be handed over a
* second time, so the file is left as it is (whatever is not read live, the commit reads). */
if (!lf || !lf->durable.n || lf->rb_busy || lf->committed || lf->committing || ava1_bits_get(&j->done, id) ||
groups_of(j->m.e[id].size) < 2)
return 0;
for (r = 0; r < lf->durable.n; r++) {
uint64_t a = lf->durable.v[2 * r], b = lf->durable.v[2 * r + 1];
while (a < b) { /* the pieces of [a, b) that are not in rb_done (sorted and disjoint, as durable is) */
uint64_t e = b;
while (d < lf->rb_done.n && lf->rb_done.v[2 * d + 1] <= a) d++;
if (d < lf->rb_done.n && lf->rb_done.v[2 * d] <= a) {
a = lf->rb_done.v[2 * d + 1];
continue;
}
if (d < lf->rb_done.n && lf->rb_done.v[2 * d] < b) e = lf->rb_done.v[2 * d];
/* out of memory: the commit reads them */
if (!ava1_rset_covers(&lf->rb_todo, a, e) && ava1_rset_add(&lf->rb_todo, a, e) == 0) {
__atomic_add_fetch(&j->rb_todo_ranges, 1, __ATOMIC_RELAXED);
bytes += e - a;
}
a = e;
}
}
return bytes;
}

/* JF_READBACK, job thread, each time the job's map is answered. What a large file holds durable without
* having been read back by this process is handed to the live read-back:
*
* - A job taken up again from its journal (a Stop then a resume, a node that was restarted, a job parked past
* its age): its durable bytes were written by an earlier run. Left to the commit, all of them were read
* after the file's last byte, while the sender had nothing left to send (a 60 GiB file resumed at half:
* 30 GiB read back with the upload showing as finished). Now they are read while the rest of the file
* arrives, like the bytes of this run.
* - A job still in memory whose new JobOpen turns the read-back on: the bytes it made durable without it.
*
* It only queues: the reads start with the file's next batch (rb_live_kick), once a chunk has opened its
* part file, they stop with the job as any live read does, and a mismatch is acted on at the commit as any
* found live is. Nothing is reported to the sender (no Durable goes out for these ranges). It may run any
* number of times: a range read back, waiting to be, or being read is not handed over again. A job taken up
* a second time starts from nothing read back (the journal records what is durable, not what was read). */
void ava1_apply_readback_resumed(ava1_job_t *j) {
uint64_t bytes = 0;
uint32_t k, files = 0;
pthread_mutex_lock(&j->mu);
if (j->readback && j->lf && j->prepared && !j->finished && !j->final_status && !j->stopping) {
uint32_t n = j->lfl_all ? j->m.n : j->lfl_n;
for (k = 0; k < n; k++) {
uint64_t got = rb_hand_over(j, j->lfl_all ? k : j->lfl[k]);
bytes += got;
if (got) files++;
}
}
pthread_mutex_unlock(&j->mu);
if (bytes)
fprintf(stderr,
"[ava1] job %02x%02x%02x%02x: read-back: %llu MiB of %u files, durable before, are read back while the rest "
"arrives\n",
j->id[0], j->id[1], j->id[2], j->id[3], (unsigned long long)(bytes >> 20), files);
}

/* ---- the commit's read-back ---- */

typedef struct {
Expand Down
3 changes: 3 additions & 0 deletions c/ava1_apply.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ int ava1_apply_quiesce(ava1_job_t *j); /* 0, or an errno when the unswept files
/* Queues the commit of every large file whose ranges and root are all durable onto the
* workers and returns at once (a commit is four fsyncs; it must not stop the job thread). */
void ava1_apply_commit_ready(ava1_job_t *j);
/* JF_READBACK: hands the durable ranges nobody has read back (those a job found in its journal) to the
* live read-back. Job thread, once the job is prepared; does nothing without the read-back. */
void ava1_apply_readback_resumed(ava1_job_t *j);
/* One line: where the job's time went, as a share of its wall time (scan, data fsync, directory
* fsyncs, journal on the job thread; commit and preallocate summed over workers, so they can pass
* 100% together). Printed once when the job ends, always. Returns the length written. */
Expand Down
8 changes: 4 additions & 4 deletions c/ava1_job.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ typedef struct { /* one large file being assembled */
uint8_t held; /* descriptors counted against the large-file budget (0, 1 or 2) */
uint8_t rb_bad; /* read-backs (JF_READBACK) that found the drive's bytes wrong; the file fails at AVA1_READBACK_TRIES */
/* JF_READBACK while the file arrives (SPEC.md §13.5; ava1_apply.c, "read-back"), under j->mu.
* rb_todo: durable bytes nobody has read back yet (a sync batch adds what it made durable, a write
* takes its range out again). rb_done: read back and right since they were last made durable.
* rb_todo: durable bytes nobody has read back yet (a sync batch adds what it made durable, a resumed
* job's map adds what the journal holds durable, a write takes its range out again). rb_done: read back and right since they were last made durable.
* rb_gen: bumped by a reset and by a write over durable bytes, so a read-back in flight across
* either counts for nothing. rb_busy: read-backs of this file in flight. rb_found: one found the
* drive's bytes wrong at group rb_found_g; the commit acts on it (unless that group is written again). */
Expand Down Expand Up @@ -229,8 +229,8 @@ struct ava1_job {
uint32_t rb_th_n;
pthread_cond_t rb_cv;
uint32_t rb_live_run; /* live reads in flight (under mu): ava1_apply_quiesce waits for none */
uint64_t rb_todo_ranges, rb_live_reads, rb_live_crowded; /* atomics, for the end-of-job line: ranges batches handed
* over, live reads done, of those with chunks waiting */
uint64_t rb_todo_ranges, rb_live_reads, rb_live_crowded; /* atomics, for the end-of-job line: ranges batches (and a
* resume) handed over, live reads done, of those with chunks waiting */
/* Reading from the drive, not the page cache (atomics): reads whose pages were dropped from the cache
* first (asked / done), reads made with O_DIRECT; the one line per job that says how. */
uint64_t rb_drops, rb_drops_ok, rb_direct_reads;
Expand Down
3 changes: 3 additions & 0 deletions c/ava1_recv.c
Original file line number Diff line number Diff line change
Expand Up @@ -1293,6 +1293,9 @@ static void answer(ava1_job_t *j) {
/* Files every byte and root of which are durable commit now: no sync batch may come to
* trigger it (nothing is left to send). */
ava1_apply_commit_ready(j);
/* JF_READBACK: what the other files hold durable from before (the journal's ranges of a job taken up
* again) is read back while the rest of them arrives, not all of it after their last byte. */
ava1_apply_readback_resumed(j);
}

/* A new or changed manifest becomes the job's: written, then journaled. */
Expand Down
87 changes: 87 additions & 0 deletions crates/ava1-ctest/tests/readback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,93 @@ fn a_stop_during_a_live_read_back_is_prompt_and_the_resume_reads_back_the_rest()
assert_eq!(st[3], 0);
}

/// Writes groups `0..half` of `d` with the read-back on, waits until they are durable (read back live),
/// and restarts the payload: the resumed job holds them durable from its journal, read back by nobody
/// in this process.
fn interrupted_half_way(t: &TempDir, d: &[u8], m: &Manifest, half: usize) -> CRecv {
let r = CRecv::open(
&t.join("jobs"),
&t.join("dest"),
gen::JF_READBACK,
gen::POLICY_REPLACE,
0,
);
r.manifest(m);
r.wait_event("map status=0", 5000);
send_groups(&r, 0, d, &(0..half).collect::<Vec<_>>());
wait_until("the first half read back", 10_000, || {
rb_stats()[0] == (half * G) as u64
});
let r = r.restart(0);
assert_eq!(unsafe { ava1_test_job_readback() }, 1);
r.manifest(m);
let ev = r.wait_event("map status=0", 5000);
assert!(ev.contains("partial=1"), "the durable half was kept: {ev}");
r
}

/// A file interrupted half way and resumed: what it held durable before is read back while the rest
/// arrives, not after its last byte. Before 1.0.11 the commit read all of it once the last byte was in
/// (on a console, minutes of "finalizing" for a large file).
#[test]
fn a_resumed_file_is_read_back_while_the_rest_arrives() {
let _k = Knobs;
let t = tmp("resumed");
std::fs::create_dir_all(t.join("dest")).unwrap();
let d = data(40 * G + 123, 18);
let m = Manifest {
entries: vec![file("big", d.len() as u64)],
};
let r = interrupted_half_way(&t, &d, &m, 20);
send_groups(&r, 0, &d, &(20..30).collect::<Vec<_>>());
// no root yet, so nothing commits: the live read-back alone reads the first half and the new groups
wait_until("the resumed half read back live", 10_000, || {
rb_stats()[0] == (30 * G) as u64
});
send_groups(&r, 0, &d, &(30..41).collect::<Vec<_>>());
r.root(0, *blake3::hash(&d).as_bytes());
assert_eq!(r.wait(10_000), 0, "{}", r.events());
assert_eq!(std::fs::read(t.join("dest/big")).unwrap(), d);
let st = rb_stats();
assert_eq!(st[0] + st[1], d.len() as u64, "every byte once: {st:?}");
assert!(
st[1] <= (11 * G) as u64,
"{} bytes read back after the last byte; the resumed part is {}: {st:?}",
st[1],
20 * G
);
assert_eq!(st[3], 0, "{st:?}");
}

/// A byte of the part written before the interruption that changed on the drive is found by the live
/// read-back of the resumed job, before the last byte arrives, and the file is sent again as for any
/// group found wrong while the file arrives.
#[test]
fn a_byte_changed_before_the_interruption_is_found_while_the_resumed_file_arrives() {
let _k = Knobs;
let t = tmp("resumed-bad");
std::fs::create_dir_all(t.join("dest")).unwrap();
let d = data(12 * G + 41, 19);
let m = Manifest {
entries: vec![file("big", d.len() as u64)],
};
let r = interrupted_half_way(&t, &d, &m, 6);
unsafe { ava1_test_rb_corrupt(1, 2 * GROUP + 9) };
send_groups(&r, 0, &d, &(6..9).collect::<Vec<_>>());
wait_until("the changed byte read back live", 10_000, || unsafe {
ava1_test_rb_corrupt_left() == 0
});
assert!(!r.events().contains("retry"), "{}", r.events());
send_groups(&r, 0, &d, &(9..13).collect::<Vec<_>>());
r.root(0, *blake3::hash(&d).as_bytes());
r.wait_event("retry 0 1", 10_000);
assert_eq!(rb_stats()[3], 1);
assert!(!t.join("dest/big").exists(), "nothing was committed");
send_large(&r, 0, &d);
assert_eq!(r.wait(10_000), 0, "{}", r.events());
assert_eq!(std::fs::read(t.join("dest/big")).unwrap(), d);
}

/// Ending a job (a cancel) while a live read-back is reading does not wait for it either.
#[test]
fn ending_a_job_during_a_live_read_back_is_prompt() {
Expand Down
86 changes: 83 additions & 3 deletions crates/ava1/src/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1641,9 +1641,26 @@ pub async fn run_upload(
// already has is credited (design 015/02), the rest must fit.
if let Some(gate) = opts.space_gate.clone() {
let figures = SpaceFigures::of(&manifest, &need, opts.cutoff)?;
let verdict = tokio::task::spawn_blocking(move || gate(&figures))
.await
.map_err(|e| SendError::Protocol(format!("the space check failed: {e}")))?;
let mut check = tokio::task::spawn_blocking(move || gate(&figures));
// A slow check (a drive that answers late) does not hold up a cancel: the flag is
// polled while it runs, as the data loop does. The check's thread ends on its own and
// its answer is dropped.
let verdict = loop {
if opts.cancel.load(Ordering::Relaxed) {
let _ = link
.control
.send(&gen::JobCancel {
job_id,
reason: gen::ERR_CANCELLED,
})
.await;
return Err(SendError::Cancelled);
}
if let Ok(r) = tokio::time::timeout(Duration::from_millis(100), &mut check).await {
break r
.map_err(|e| SendError::Protocol(format!("the space check failed: {e}")))?;
}
};
if let Err(why) = verdict {
let _ = link
.control
Expand Down Expand Up @@ -4330,6 +4347,69 @@ mod tests {
assert_eq!(active.load(Ordering::Relaxed), 0, "a reader thread leaked");
}

#[tokio::test(flavor = "multi_thread")]
async fn a_cancel_during_a_slow_space_check_ends_the_job_at_once() {
// The space check runs before any byte is sent and may take long (a slow drive). A
// cancel then ends the job within the poll, and the receiver is told; before, the
// sender waited for the check's answer first.
let rcv = FakeReceiver {
credit: 4 << 20,
..Default::default()
};
let cancel_seen = rcv.cancel_seen.clone();
let (mut link, _lane_seen, _keep) = fake_link(rcv, None);
let size = 8usize << 20;
let src: Arc<dyn Source> = Arc::new(MemSource(vec![0x5a; size]));
let m = Arc::new(Manifest {
entries: vec![Entry {
kind: gen::ENTRY_FILE,
mode: 0o644,
size: size as u64,
mtime: 1,
path: "big".into(),
root: None,
}],
});
let (entered, release) = (
Arc::new(AtomicBool::new(false)),
Arc::new(AtomicBool::new(false)),
);
let (e2, r2) = (entered.clone(), release.clone());
let cancel = Arc::new(AtomicBool::new(false));
let mut opts = SendOptions::upload("dest");
opts.cancel = cancel.clone();
opts.space_gate = Some(Arc::new(move |_: &SpaceFigures| {
e2.store(true, Ordering::SeqCst);
let t0 = Instant::now();
while !r2.load(Ordering::SeqCst) && t0.elapsed() < Duration::from_secs(20) {
std::thread::sleep(Duration::from_millis(10));
}
Ok(())
}));
let job_task = tokio::spawn(async move { send_job(&mut link, m, src, opts).await });
tokio::time::timeout(Duration::from_secs(10), async {
while !entered.load(Ordering::SeqCst) {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the space check ran");
cancel.store(true, Ordering::Relaxed);
let result = tokio::time::timeout(Duration::from_secs(3), job_task).await;
release.store(true, Ordering::SeqCst); // let the check's thread end either way
let result = result
.expect("the cancel did not wait for the space check")
.expect("the sender task did not panic");
assert!(matches!(result, Err(SendError::Cancelled)), "{result:?}");
tokio::time::timeout(Duration::from_secs(5), async {
while cancel_seen.load(Ordering::SeqCst) != gen::ERR_CANCELLED as u32 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the receiver was told");
}

/// A source whose reads park on something outside the disk (a relay waiting for
/// another connection) until `close` wakes them.
struct ParkedSource {
Expand Down
Loading
Loading