~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

Commits waiting on one log are answered together when its sync ends

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:store/wal-wait
crates/pds-store/src/lib.rs+184−34
@@ -418,9 +418,12 @@ struct Shared {
compacted: Condvar,
/// Frames handed to the operating system.
written: AtomicU64,
/// Frames known to be on disk; the lock is held through each fsync.
synced: Mutex<u64>,
/// The same count, to read without waiting for an fsync in progress.
/// The syncs of written frames, one at a time; the lock is let go
/// through each, and held only to begin one, to end one and to wait.
synced: Mutex<Syncs>,
/// Signalled, with `synced`, when a sync ends.
sync_ended: Condvar,
/// Frames known to be on disk.
durable: AtomicU64,
/// The bytes recovery cut off when the log was opened: a torn tail, and
/// of a log with generations, the logs after one cut short or unsealed.
@@ -434,6 +437,51 @@ struct Shared {
trace: Mutex<Vec<String>>,
}
/// The syncs of a log's written frames.
#[derive(Default)]
struct Syncs {
/// Whether one is going on, and how many have begun.
going: bool,
begun: u64,
/// The last that failed.
failed: Option<Failed>,
}
/// A sync that failed: which it was, the frames it would have covered
/// (every one up to this number), and why.
struct Failed {
sync: u64,
covered: u64,
kind: io::ErrorKind,
why: String,
}
/// A sync going on, ended when this is dropped: noted if it failed, and
/// every waiter woken.
struct Ending<'a> {
shared: &'a Shared,
sync: u64,
covered: u64,
failed: Option<(io::ErrorKind, String)>,
}
impl Drop for Ending<'_> {
fn drop(&mut self) {
let mut syncs = lock(&self.shared.synced);
syncs.going = false;
if let Some((kind, why)) = self.failed.take() {
syncs.failed = Some(Failed {
sync: self.sync,
covered: self.covered,
kind,
why,
});
}
drop(syncs);
self.shared.sync_ended.notify_all();
}
}
impl Shared {
fn new(
dir: PathBuf,
@@ -451,7 +499,8 @@ impl Shared {
inner: Mutex::new(inner),
compacted: Condvar::new(),
written: AtomicU64::new(0),
synced: Mutex::new(0),
synced: Mutex::new(Syncs::default()),
sync_ended: Condvar::new(),
durable: AtomicU64::new(0),
dropped,
sync_first: Mutex::new(Vec::new()),
@@ -561,6 +610,38 @@ impl Shared {
synced
}
/// Make every frame written so far durable, with every file they rest
/// on: `covered` is told how many frames that is, as soon as it is known.
fn sync_written(self: &Arc<Self>, covered: &mut u64) -> io::Result<()> {
// Every frame up to `target` is in this file, in a sealed log not yet
// durable, or in one a rewrite or a sync before made durable.
let (file, sealed, generation) = {
let mut inner = lock(&self.inner);
*covered = self.written.load(Ordering::SeqCst);
(
self.file(&mut inner)?,
inner.unsynced.clone(),
inner.generation,
)
};
let target = *covered;
// Taken after `target`: every file given before a frame up to it.
self.sync_files_first()?;
// No frame of a generation is durable before the logs before it are,
// sealed, and the directory with it in: else a power cut could leave
// them unsealed, and it would be dropped at start.
self.sync_sealed(&sealed)?;
if !sealed.is_empty() {
lock(&self.inner)
.unsynced
.retain(|(g, _)| !sealed.iter().any(|(h, _)| h == g));
}
timed(|| file.sync_data())?;
self.note(|| format!("current {generation}"));
self.durable.fetch_max(target, Ordering::SeqCst);
Ok(())
}
/// Note an fsync, for tests to check their order.
fn note(&self, what: impl FnOnce() -> String) {
#[cfg(test)]
@@ -693,41 +774,48 @@ impl Wal {
}
/// Return once frame `seq` is on disk, and every file `sync_first` was
/// given before it. Waiters that queue behind one fsync find their frame
/// covered by it.
/// given before it. Waiters at once share a sync: one of them makes it,
/// of every frame written by then, and each it covers is answered when
/// it ends, as it ended; one it does not cover waits for the next, or
/// makes it. A sync that fails is the answer to each waiter it would
/// have covered, and leaves the log as it was, for the next to try again.
pub fn wait(&self, seq: u64) -> io::Result<()> {
let s = &self.0;
let mut synced = lock(&s.synced);
if *synced >= seq {
return Ok(());
let mut syncs = lock(&s.synced);
loop {
if s.durable.load(Ordering::SeqCst) >= seq {
return Ok(());
}
if !syncs.going {
break;
}
let following = syncs.begun;
syncs = s
.sync_ended
.wait(syncs)
.unwrap_or_else(PoisonError::into_inner);
if let Some(failed) = syncs.failed.as_ref().filter(|f| f.sync == following)
&& seq <= failed.covered
&& s.durable.load(Ordering::SeqCst) < seq
{
return Err(io::Error::new(failed.kind, failed.why.clone()));
}
}
// Every frame up to `target` is in this file, in a sealed log not yet
// durable, or in one a rewrite or a sync before made durable.
let (target, file, sealed, generation) = {
let mut inner = lock(&s.inner);
(
s.written.load(Ordering::SeqCst),
s.file(&mut inner)?,
inner.unsynced.clone(),
inner.generation,
)
syncs.going = true;
syncs.begun += 1;
// Ended, and those waiting on it woken, however this returns.
let mut ending = Ending {
shared: s,
sync: syncs.begun,
covered: 0,
failed: None,
};
// Taken after `target`: every file given before a frame up to it.
s.sync_files_first()?;
// No frame of a generation is durable before the logs before it are,
// sealed, and the directory with it in: else a power cut could leave
// them unsealed, and it would be dropped at start.
s.sync_sealed(&sealed)?;
if !sealed.is_empty() {
lock(&s.inner)
.unsynced
.retain(|(g, _)| !sealed.iter().any(|(h, _)| h == g));
drop(syncs);
let synced = s.sync_written(&mut ending.covered);
if let Err(e) = &synced {
ending.failed = Some((e.kind(), e.to_string()));
}
timed(|| file.sync_data())?;
s.note(|| format!("current {generation}"));
*synced = target;
s.durable.fetch_max(target, Ordering::SeqCst);
Ok(())
synced
}
/// Put in the log's place, durably, the frames `fold` makes of its frames,
@@ -892,4 +980,66 @@ mod tests {
assert_eq!(mode(&dir.join("a/b")), DIR_MODE);
let _ = std::fs::remove_dir_all(&dir);
}
/// Writers at once share syncs: every frame waited for is on disk, in
/// no more syncs than there are frames, and a frame on disk already
/// needs none.
#[test]
fn waiters_share_syncs() {
let dir = scratch("shared");
let (wal, _) = Wal::open(&dir.join("a.log"), None).unwrap();
std::thread::scope(|s| {
for t in 0..8 {
let wal = &wal;
s.spawn(move || {
for i in 0..20 {
let n = wal.append(&[json!([t, i])]).unwrap();
wal.wait(n).unwrap();
assert!(wal.is_durable(n));
}
});
}
});
let syncs = lock(&wal.0.trace).len();
assert!((1..=160).contains(&syncs), "{syncs} syncs of 160 frames");
wal.wait(wal.written()).unwrap();
assert_eq!(lock(&wal.0.trace).len(), syncs);
let (_, frames) = Wal::open(&dir.join("a.log"), None).unwrap();
assert_eq!(frames.len(), 160);
let _ = std::fs::remove_dir_all(&dir);
}
/// A sync that fails is the answer to every waiter it would have
/// covered, whichever of them made it, and leaves the log as it was:
/// the next sync is tried, and makes their frames durable once it can.
#[test]
fn a_failed_sync_fails_its_waiters() {
let dir = scratch("failed");
let (wal, _) = Wal::open(&dir.join("a.log"), None).unwrap();
// A file the frames rest on that cannot be opened: one under a file.
let blocker = dir.join("blocker");
std::fs::write(&blocker, b"").unwrap();
wal.sync_first([blocker.join("x")]);
let waited: Vec<(u64, io::Result<()>)> = std::thread::scope(|s| {
let waiters: Vec<_> = (0..8)
.map(|i| {
let wal = &wal;
s.spawn(move || {
let n = wal.append(&[json!(i)]).unwrap();
(n, wal.wait(n))
})
})
.collect();
waiters.into_iter().map(|w| w.join().unwrap()).collect()
});
for (n, answer) in &waited {
assert!(answer.is_err(), "frame {n} answered {answer:?}");
assert!(!wal.is_durable(*n));
}
assert!(wal.wait(wal.written()).is_err(), "tried again, and failed");
std::fs::remove_file(&blocker).unwrap();
wal.wait(wal.written()).unwrap();
assert!(waited.iter().all(|(n, _)| wal.is_durable(*n)));
let _ = std::fs::remove_dir_all(&dir);
}
}