~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
3097 lines · 121.0 KB Raw History
//! The journal: one log for every log of a data directory, whose sync is
//! what a write waits for (`PDS_SYNC` `together`; `spec/DURABILITY.md`,
//! "Writes waiting at once").
//!
//! A log given a journal (`Files::with_journal`, `Wal::use_journal`) writes
//! each frame to its own file at its offset, as any log does, and then a
//! record of it to the journal, under the log's lock: the path of the log's
//! file relative to the data directory, the offset and the frame's bytes.
//! So a log's records are in the journal in the order of their offsets. A
//! wait on the log syncs the files its frames rest on and its sealed logs
//! with the directory, each by itself, as without a journal, and then waits
//! for the journal to be durable up to the log's last record, in place of a
//! sync of the log's own file. Waiters on the journal share its syncs,
//! whichever logs they wait on: one sync covers every record appended
//! before it began, and a wait whose record an earlier sync covered makes
//! none.
//!
//! **The files.** `<data dir>/journal/<n>.log`, `n` decimal and only
//! growing, each a segment: `MAGIC`, then records `[len u32 LE][check u64
//! LE][body]`, the check XXH3-64 over `len` and the body. A body is a kind,
//! the record's number (the first record a journal takes is 1, and each
//! after it the next), the path, and of a frame its offset and bytes. A
//! header of zeros is the end of a segment: after its records it holds
//! room, zeros written ahead as a log's room is, so that a sync carries no
//! change of the file's size; as much as the segment holds already, at
//! least `ROOM_LEAST` and at most `ROOM_MOST` at once. An empty segment is
//! its magic alone. Every file is `0600`, the directory `0700`.
//!
//! **What is on disk.** A record is counted durable, and its frame
//! answered, only once it is on disk in the journal with every record
//! before it: by a wait's sync of the current segment, which takes in
//! first every earlier segment whose records may not be on disk; or by a
//! checkpoint, which syncs the segments it leaves behind before it counts
//! their records. So no record of a segment is answered while an earlier
//! one holds a record not on disk, and a `forget` whose wait has returned
//! is on disk before what it is for is done. Of the records, those on
//! disk after a power cut are those up to the last synced, and then any
//! run of those after, each whole, which the system may have written out
//! in any order, of one segment or of the next: a start takes the records
//! in their order up to the first that is not whole or whose number is not
//! the one after the last, and nothing after it, none of which was
//! answered. Such a gap is what a power cut leaves of records no sync
//! covered, and so it ends what is taken with nothing said: it cannot be
//! told from records written out of order, and refusing the start on it
//! would refuse what every power cut during a run of writes leaves.
//!
//! **A checkpoint**, on a thread of the journal's own, when the current
//! segment holds more than `SEGMENT` bytes of records, or `QUIET` after the
//! last append (or, after a start that adopted segments, `QUIET` after the
//! open where nothing is appended), or once the records appended since the
//! checkpoint before name `FILES` logs, or when asked
//! (`close`): a new segment is made and synced,
//! with the directory, and appends go to it from then on; the segments
//! before it are synced; each log appended to since the checkpoint before
//! is opened by its path and handed to the drive (`flush_file`), then one
//! sync reaches the disk (`sync_dir`), or on Linux one sync of the data
//! directory's file system (`sync_filesystem`) does all of that, and only
//! then are the records before
//! the new segment counted durable; the segments before it are deleted,
//! the directory synced. One that fails leaves its segments, and its logs
//! for the next. A log is opened by path, not through its `Wal`, which
//! takes no log's lock and holds no file a pool may want to close; one gone
//! since is one whose frames are durable elsewhere (a compaction's table)
//! or that a `forget` covers.
//!
//! **A start** (`redo`), before any log of the data directory is opened:
//! each record taken is put back where its file does not hold it, and a
//! file written to cut at the end of the last record taken of it. A record
//! of a file not there is skipped: its log was folded away since, its
//! table durable before it went, or its file's making was never durable,
//! and then none of its frames was answered. A record of a path before a
//! later `forget` of it, or of a directory it is in, is skipped: the file
//! there now is another. A file shorter than a record's offset is `cannot
//! recover`: a frame before it is missing. Then, where every record in the
//! segments was taken, nothing after the last of each segment's but zeros
//! (`Redo::Adopting`; what a kill leaves), the start syncs nothing and
//! deletes nothing: the journal opened next adopts the segments as its
//! earlier ones (`Journal::open`), numbers its records on from their
//! last, and its first checkpoint, at once, on its thread, makes them
//! durable with every log they name and deletes them; until then a wait's
//! sync takes them in first, as it does a checkpoint's swapped-out
//! segments, and a `forget` in them keeps its meaning for a later start,
//! the segments there in order. Where a record was not taken (a torn one;
//! records after a gap in the numbers), or a start asks for it
//! (`Redo::Eager`), every file named is made durable (on Linux one sync of
//! the data directory's file system, elsewhere each file handed to the
//! drive and one sync of the directory) and the segments deleted, lowest
//! first, the directory synced after each: records never taken are never
//! left where a later start could read them after newer ones.
//!
//! **A sync that failed** is never taken back: a later sync of the same
//! file may succeed though what the failed one was to write never reached
//! the disk. One of a segment, by a wait or a checkpoint, fails the journal
//! for the run: every wait from then on fails with its error, so that no
//! write is answered, no record is taken, and no segment is deleted; the
//! next start redoes from the segments. A checkpoint's flush of a log, or
//! its sync of the directory, failing ends the checkpoints for the run:
//! no segment is deleted from then on, and the journal goes on taking
//! records and syncing them, growing until the next start. Each is said
//! once (`on_error`). A log a checkpoint could not open, before any flush
//! of it was tried, is tried again by the next.
//!
//! **A path used again.** A log's file is replaced only by `Wal::rewrite`,
//! and a directory of logs removed only with its account; before either,
//! `forget` puts a record of it in the journal, durably, so that what the
//! journal holds of the file before is never written into the one after.

use crate::{Syncs, lock, make_dirs, open_locked, report, room, sync_data, sync_dir, wait_shared};
use std::collections::BTreeSet;
use std::fs::{File, OpenOptions};
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use xxhash_rust::xxh3::Xxh3;

/// The journal's directory in the data directory.
pub const DIR: &str = "journal";
/// What every segment begins with: its format.
pub const MAGIC: [u8; 8] = *b"PDSJNL01";
const MAGIC_LEN: u64 = MAGIC.len() as u64;
/// The bytes of a record's header: its body's length and check.
const HEADER: usize = 12;
/// A record's kinds.
const FRAME: u8 = 0;
const FORGET: u8 = 1;
/// The bytes of records a segment holds before a checkpoint starts the next.
pub const SEGMENT: u64 = 16 << 20;
/// The least and the most room a segment is given at once.
const ROOM_LEAST: u64 = 64 << 10;
const ROOM_MOST: u64 = 16 << 20;
/// How long after the last append a checkpoint runs.
pub const QUIET: Duration = Duration::from_secs(2);
/// How many logs appended to since the checkpoint before make the next due:
/// a start opens each file the journal names, so what it costs follows
/// them as well as the bytes.
pub const FILES: usize = 1024;

fn check(len: u32, body: &[u8]) -> u64 {
    let mut h = Xxh3::new();
    h.update(&len.to_le_bytes());
    h.update(body);
    h.digest()
}

fn invalid(why: String) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, why)
}

fn segment_path(dir: &Path, n: u64) -> PathBuf {
    dir.join(format!("{n}.log"))
}

/// The segments in `dir`, by number; none if there is no `dir`.
fn segments(dir: &Path) -> io::Result<Vec<u64>> {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };
    let mut found = Vec::new();
    for e in entries {
        let name = e?.file_name();
        let Some(n) = name
            .to_str()
            .and_then(|s| s.strip_suffix(".log"))
            .filter(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
            .and_then(|s| s.parse::<u64>().ok())
        else {
            continue;
        };
        found.push(n);
    }
    found.sort_unstable();
    Ok(found)
}

/// A record read from a segment.
#[derive(Debug, PartialEq, Eq)]
enum Record<'a> {
    Frame {
        path: &'a Path,
        offset: u64,
        bytes: &'a [u8],
    },
    Forget {
        path: &'a Path,
    },
}

/// Write the record of `kind` numbered `n` into `buf`, header and all.
fn encode(
    buf: &mut Vec<u8>,
    kind: u8,
    n: u64,
    path: &Path,
    offset: u64,
    frame: &[u8],
) -> io::Result<()> {
    let p = path.as_os_str().as_bytes();
    let plen = u16::try_from(p.len())
        .map_err(|_| invalid(format!("{}: a path too long to journal", path.display())))?;
    buf.clear();
    buf.resize(HEADER, 0);
    buf.push(kind);
    buf.extend_from_slice(&n.to_le_bytes());
    buf.extend_from_slice(&plen.to_le_bytes());
    buf.extend_from_slice(p);
    if kind == FRAME {
        buf.extend_from_slice(&offset.to_le_bytes());
        buf.extend_from_slice(frame);
    }
    let len = u32::try_from(buf.len() - HEADER)
        .map_err(|_| invalid(format!("{}: a frame too long to journal", path.display())))?;
    let c = check(len, &buf[HEADER..]);
    buf[..4].copy_from_slice(&len.to_le_bytes());
    buf[4..HEADER].copy_from_slice(&c.to_le_bytes());
    Ok(())
}

/// A record's body: its number and what it says, if it is one.
fn decode(body: &[u8]) -> Option<(u64, Record<'_>)> {
    let (&kind, rest) = body.split_first()?;
    let n = u64::from_le_bytes(rest.get(..8)?.try_into().ok()?);
    let plen = u16::from_le_bytes(rest.get(8..10)?.try_into().ok()?) as usize;
    let path = Path::new(std::ffi::OsStr::from_bytes(rest.get(10..10 + plen)?));
    let rest = &rest[10 + plen..];
    match kind {
        FRAME => {
            let offset = u64::from_le_bytes(rest.get(..8)?.try_into().ok()?);
            Some((
                n,
                Record::Frame {
                    path,
                    offset,
                    bytes: &rest[8..],
                },
            ))
        }
        FORGET if rest.is_empty() => Some((n, Record::Forget { path })),
        _ => None,
    }
}

/// The records of a segment's bytes after its magic, each with its
/// number, up to the first place that holds no whole record: with where
/// they end.
#[cfg(test)]
fn records(data: &[u8]) -> (Vec<(u64, Record<'_>)>, usize) {
    let mut out = Vec::new();
    let mut pos = 0;
    while data.len() - pos >= HEADER {
        let len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap());
        let c = u64::from_le_bytes(data[pos + 4..pos + HEADER].try_into().unwrap());
        let end = pos + HEADER + len as usize;
        if len == 0 || end > data.len() || check(len, &data[pos + HEADER..end]) != c {
            break;
        }
        let Some(r) = decode(&data[pos + HEADER..end]) else {
            break;
        };
        out.push(r);
        pos = end;
    }
    (out, pos)
}

/// Where each whole record of a segment's bytes ends, in them.
#[cfg(test)]
pub(crate) fn ends(segment: &[u8]) -> Vec<usize> {
    let data = &segment[MAGIC.len()..];
    let mut out = Vec::new();
    let mut pos = 0;
    for _ in records(data).0 {
        let len = u32::from_le_bytes(data[pos..pos + 4].try_into().unwrap()) as usize;
        pos += HEADER + len;
        out.push(MAGIC.len() + pos);
    }
    out
}

/// A segment of these frames' records, numbered from 1: each its file's
/// path relative to the data directory, its offset and its bytes.
#[cfg(test)]
pub(crate) fn segment_of(frames: &[(&str, u64, &[u8])]) -> Vec<u8> {
    let mut out = MAGIC.to_vec();
    let mut buf = Vec::new();
    for (i, (path, offset, bytes)) in frames.iter().enumerate() {
        encode(
            &mut buf,
            FRAME,
            i as u64 + 1,
            Path::new(path),
            *offset,
            bytes,
        )
        .unwrap();
        out.extend_from_slice(&buf);
    }
    out
}

/// Which way a start's `redo` may go once it has put back what the logs'
/// files do not hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Redo {
    /// Adopt the segments where every record in them was taken, for the
    /// journal opened next (`Journal::open`) to make durable and let go;
    /// else as `Eager`.
    Adopting,
    /// Make every file named durable and delete the segments, always: for
    /// a start with no journal to adopt them into, or one that changes the
    /// logs' files after.
    Eager,
}

/// What a start put back from the journal (`redo`).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Redone {
    /// The segments read: adopted, or deleted.
    pub segments: usize,
    /// The records taken: those up to the first not whole.
    pub records: u64,
    /// The frames written where their files did not hold them.
    pub written: u64,
    /// The files the start synced: every one a record named that is
    /// there where the segments were deleted, none where they were adopted.
    pub files: usize,
    /// The segments adopted, for `Journal::open`: none where they were
    /// deleted, or where there were none.
    pub adopted: Option<Adopted>,
}

/// The segments a start adopted (`Redo::Adopting`), every record in them
/// taken, none of them synced or deleted: what `Journal::open` holds as
/// its earlier segments.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Adopted {
    /// Each segment, lowest first.
    segments: Vec<Kept>,
    /// The number of the last record taken.
    last: u64,
    /// The bytes of the records the segments hold.
    bytes: u64,
    /// The paths their frames name, relative to the data directory.
    paths: BTreeSet<PathBuf>,
}

/// A segment adopted.
#[derive(Debug, PartialEq, Eq)]
struct Kept {
    number: u64,
    /// The number of its last record, or of the last before it where it
    /// holds none.
    upto: u64,
    /// Where its records end, magic and all.
    end: u64,
}

/// Put back from the journal in the data directory `root` whatever its
/// logs' files do not hold: before any log of `root` is opened, as every
/// start does, whichever way it syncs. Then, with `Redo::Adopting`, where
/// every record in the segments was taken, nothing after the last of them
/// in any segment but zeros, the segments are adopted (`Redone::adopted`):
/// nothing is synced, nothing deleted. Else every file named is made
/// durable and the segments deleted, so that no record left untaken is
/// read after newer ones by a later start. Nothing to do where there is no
/// journal, or no segment in it. A segment of another format refuses the
/// start, cut or deleted in no part; so does a file shorter than the
/// offset of a frame the journal holds of it (`InvalidData`).
pub fn redo(root: &Path, way: Redo) -> io::Result<Redone> {
    let dir = root.join(DIR);
    let numbers = segments(&dir)?;
    let mut done = Redone {
        segments: numbers.len(),
        ..Redone::default()
    };
    if numbers.is_empty() {
        return Ok(done);
    }
    let paths: Vec<PathBuf> = numbers.iter().map(|&n| segment_path(&dir, n)).collect();
    // Every segment of this format, before anything is done.
    for path in &paths {
        Reader::open(path).map_err(|e| named(path, e))?;
    }
    // 1. The records taken, up to the first not whole or not the one after
    // the record before it, read one at a time: their count, the `forget`s
    // among them with their numbers, and of each path its frames' places
    // in the segments, in order, each with its number; and adopting,
    // whether every record in the segments was taken. A record's bytes are
    // not kept: a place is a few bytes, a path held once.
    let mut forgets: Vec<(u64, PathBuf)> = Vec::new();
    let mut places: std::collections::BTreeMap<PathBuf, Vec<Place>> =
        std::collections::BTreeMap::new();
    let kept = each_taken(&paths, way == Redo::Adopting, |p, r| {
        done.records += 1;
        match r {
            Record::Forget { path } => forgets.push((p.n, path.to_path_buf())),
            Record::Frame { path, .. } => match places.get_mut(path) {
                Some(v) => v.push(p),
                None => {
                    places.insert(path.to_path_buf(), vec![p]);
                }
            },
        }
        Ok(())
    })?;
    // 2. The frames taken put back where their files do not hold them, a
    // file at a time, each opened once, its frames in their order in the
    // journal, each read back from its place, one record held at once:
    // skipped, a frame before a later `forget` of its path, or of a
    // directory it is in. A file written to is cut at the end of the last
    // frame taken of it.
    let segment_files = paths
        .iter()
        .map(|p| File::open(p).map_err(|e| named(p, e)))
        .collect::<io::Result<Vec<File>>>()?;
    let (mut body, mut have) = (Vec::new(), Vec::new());
    let mut named_paths = BTreeSet::new();
    for (path, places) in &places {
        let mut taken = places
            .iter()
            .filter(|p| !forgets.iter().any(|(m, f)| *m > p.n && path.starts_with(f)))
            .peekable();
        if taken.peek().is_none() {
            continue;
        }
        if kept.is_some() {
            named_paths.insert(path.clone());
        }
        let full = root.join(path);
        let file = match OpenOptions::new().read(true).write(true).open(&full) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
            Err(e) => return Err(named(&full, e)),
        };
        let mut size = file.metadata().map_err(|e| named(&full, e))?.len();
        let (mut wrote, mut last) = (false, 0);
        for p in taken {
            let segment = &paths[p.segment as usize];
            body.clear();
            body.resize(p.len as usize, 0);
            held(body.capacity());
            segment_files[p.segment as usize]
                .read_exact_at(&mut body, p.at)
                .map_err(|e| named(segment, e))?;
            let Some((_, Record::Frame { offset, bytes, .. })) = decode(&body) else {
                return Err(invalid(format!(
                    "{}: a record changed while the start read it",
                    segment.display()
                )));
            };
            if size < offset {
                return Err(invalid(format!(
                    "{}: {size} bytes long, and the journal holds a frame of it at {offset}: a frame before that is missing",
                    full.display()
                )));
            }
            let end = offset + bytes.len() as u64;
            let there = size.min(end) - offset;
            have.clear();
            have.resize(there as usize, 0);
            held(have.capacity());
            file.read_exact_at(&mut have, offset)
                .map_err(|e| named(&full, e))?;
            if there < bytes.len() as u64 || have[..] != bytes[..] {
                file.write_all_at(bytes, offset)
                    .map_err(|e| named(&full, e))?;
                size = size.max(end);
                wrote = true;
                done.written += 1;
            }
            last = end;
        }
        // A file written to holds nothing after the last record taken of
        // it: what follows is what a frame an append wrote and cut back,
        // the cut never synced, left after a shorter one's place, which is
        // never read as frames.
        if wrote && size > last {
            file.set_len(last).map_err(|e| named(&full, e))?;
        }
        // Adopting, the journal's first checkpoint makes it durable.
        if kept.is_some() {
            continue;
        }
        // Handed to the drive, whether written to or not: what the journal
        // holds of it may be in the system's memory alone. One sync that
        // reaches the disk follows, before the journal goes. On Linux one
        // sync of the data directory's file system does all of it, below.
        #[cfg(not(target_os = "linux"))]
        {
            crate::flush_file(&file).map_err(|e| named(&full, e))?;
            started(Started::Synced);
        }
        done.files += 1;
    }
    // 3. Adopted, the segments stay as they are, for the journal's first
    // checkpoint to make durable and let go.
    if let Some(kept) = kept {
        done.adopted = Some(Adopted {
            last: kept.last().map_or(0, |k| k.upto),
            bytes: kept.iter().map(|k| k.end - MAGIC_LEN).sum(),
            segments: numbers
                .iter()
                .zip(kept)
                .map(|(&number, k)| Kept { number, ..k })
                .collect(),
            paths: named_paths,
        });
        return Ok(done);
    }
    #[cfg(target_os = "linux")]
    {
        File::open(root)
            .and_then(|r| crate::sync_filesystem(&r))
            .map_err(|e| named(root, e))?;
        started(Started::Synced);
    }
    #[cfg(not(target_os = "linux"))]
    {
        sync_dir(&dir).map_err(|e| named(&dir, e))?;
        started(Started::Synced);
    }
    // Lowest first, the directory synced after each, as a checkpoint
    // deletes them: no segment is left without those after it.
    for path in &paths {
        match std::fs::remove_file(path) {
            Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(named(path, e)),
            _ => {}
        }
        started(Started::Unlinked);
        sync_dir(&dir).map_err(|e| named(&dir, e))?;
        started(Started::Synced);
    }
    Ok(done)
}

/// Where a record a start took is in the segments, with its number: a few
/// bytes, its path held apart, once for all its records (`redo`).
#[derive(Clone, Copy, Debug)]
struct Place {
    /// Its number.
    n: u64,
    /// Its segment, by its index among those read, and its body's length.
    segment: u32,
    len: u32,
    /// Where its body is in its segment.
    at: u64,
}

/// Give `f` each record a start takes of the segments at `paths`, in
/// order, with its place, one at a time: up to the first not whole, or
/// not the one after the record before it. What follows a segment's last
/// whole record, zeros or a record torn, ends nothing by itself: the next
/// segment's records are taken if their numbers follow on, a torn
/// record's number never having been used. With `whole`, answers too
/// where every record in the segments was taken, each of whole magic and
/// holding nothing after its last record taken but zeros: of each, lowest
/// first, the number of its last record and where its records end
/// (`Kept`, its own number left 0). None where not, and without `whole`.
fn each_taken(
    paths: &[PathBuf],
    whole: bool,
    mut f: impl FnMut(Place, Record<'_>) -> io::Result<()>,
) -> io::Result<Option<Vec<Kept>>> {
    let mut last: Option<u64> = None;
    let mut kept = whole.then(Vec::new);
    for (i, path) in paths.iter().enumerate() {
        let Some(mut r) = Reader::open(path).map_err(|e| named(path, e))? else {
            kept = None;
            continue;
        };
        while let Some((mut p, rec)) = r.next().map_err(|e| named(path, e))? {
            if last.is_some_and(|l| p.n != l + 1) {
                return Ok(None);
            }
            last = Some(p.n);
            p.segment = i as u32;
            f(p, rec)?;
        }
        if kept.is_some() {
            match r.zeros_after().map_err(|e| named(path, e))? {
                true => kept.as_mut().unwrap().push(Kept {
                    number: 0,
                    upto: last.unwrap_or(0),
                    end: r.end,
                }),
                false => kept = None,
            }
        }
    }
    Ok(kept)
}

/// A segment read a record at a time, with one record's bytes held.
struct Reader {
    file: io::BufReader<File>,
    /// The bytes not yet read.
    left: u64,
    /// Where its last whole record read ends, magic and all, and its size.
    end: u64,
    size: u64,
    /// The last record's body.
    body: Vec<u8>,
}

impl Reader {
    /// The segment at `path`, read past its magic: none where it holds no
    /// record, its making cut short by a power cut (part of its magic, or
    /// zeros); `InvalidData` where it is of another format.
    fn open(path: &Path) -> io::Result<Option<Reader>> {
        use std::io::Read;
        let file = File::open(path)?;
        let size = file.metadata()?.len();
        let mut file = io::BufReader::with_capacity(1 << 16, file);
        let mut head = [0u8; MAGIC.len()];
        let n = (size as usize).min(MAGIC.len());
        file.read_exact(&mut head[..n])?;
        let head = &head[..n];
        if head.iter().all(|&b| b == 0) || (n < MAGIC.len() && MAGIC.starts_with(head)) {
            return Ok(None);
        }
        if head != MAGIC {
            return Err(invalid(format!(
                "{}: not a segment of a journal this server reads",
                path.display()
            )));
        }
        Ok(Some(Reader {
            file,
            left: size - MAGIC_LEN,
            end: MAGIC_LEN,
            size,
            body: Vec::new(),
        }))
    }

    /// Whether the segment holds nothing but zeros after its last whole
    /// record read (`end`): room, and no record, whole or torn.
    fn zeros_after(&self) -> io::Result<bool> {
        let file = self.file.get_ref();
        let mut buf = vec![0u8; (self.size - self.end).min(1 << 16) as usize];
        let mut at = self.end;
        while at < self.size {
            let n = ((self.size - at) as usize).min(buf.len());
            file.read_exact_at(&mut buf[..n], at)?;
            if buf[..n].iter().any(|&b| b != 0) {
                return Ok(false);
            }
            at += n as u64;
        }
        Ok(true)
    }

    /// The next whole record, with its place in the segment (`segment`
    /// left 0); none at the first place that holds none. A length past the
    /// segment's end is none, with nothing allocated for it.
    fn next(&mut self) -> io::Result<Option<(Place, Record<'_>)>> {
        use std::io::Read;
        if self.left < HEADER as u64 {
            return Ok(None);
        }
        let mut head = [0u8; HEADER];
        self.file.read_exact(&mut head)?;
        self.left -= HEADER as u64;
        let len = u32::from_le_bytes(head[..4].try_into().unwrap());
        let c = u64::from_le_bytes(head[4..].try_into().unwrap());
        if len == 0 || u64::from(len) > self.left {
            self.left = 0;
            return Ok(None);
        }
        self.body.clear();
        self.body.resize(len as usize, 0);
        held(self.body.capacity());
        self.file.read_exact(&mut self.body)?;
        self.left -= u64::from(len);
        if check(len, &self.body) != c {
            self.left = 0;
            return Ok(None);
        }
        let Some((n, r)) = decode(&self.body) else {
            self.left = 0;
            return Ok(None);
        };
        let at = self.end + HEADER as u64;
        self.end = at + u64::from(len);
        let place = Place {
            n,
            segment: 0,
            len,
            at,
        };
        Ok(Some((place, r)))
    }
}

/// What a start (`redo`) does to the disk that a test counts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Started {
    /// A sync: of a file, the file system, or the journal's directory.
    Synced,
    /// A segment deleted.
    Unlinked,
}

// The syncs and deletions `redo` made on this thread, for a test.
#[cfg(test)]
thread_local!(static STARTED: std::cell::RefCell<Vec<Started>> = const { std::cell::RefCell::new(Vec::new()) });

/// Note that `redo` did `s`: for a test, nothing else.
fn started(s: Started) {
    #[cfg(test)]
    STARTED.with_borrow_mut(|v| v.push(s));
    let _ = s;
}

// The most bytes a buffer of `redo` held on this thread, for a test.
#[cfg(test)]
thread_local!(static HELD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });

/// Note that a buffer of `redo` holds `n` bytes: for a test, nothing else.
fn held(n: usize) {
    #[cfg(test)]
    HELD.set(HELD.get().max(n));
    let _ = n;
}

fn named(path: &Path, e: io::Error) -> io::Error {
    io::Error::new(e.kind(), format!("{}: {e}", path.display()))
}

/// The error of a failure a journal noted (`State::failed`, `State::stuck`).
fn failure(noted: &Option<(io::ErrorKind, String)>) -> io::Error {
    match noted {
        Some((kind, why)) => io::Error::new(*kind, why.clone()),
        None => io::Error::other("the journal failed"),
    }
}

/// What appends change, under the journal's lock.
struct State {
    /// The current segment, open; none once the journal is closed or let go.
    file: Option<Arc<File>>,
    /// Its number, and the lowest of the segments there.
    number: u64,
    first: u64,
    /// Where its records end, magic and all, and its size, room and all.
    len: u64,
    size: u64,
    /// Whether an append failed and the segment may hold part of it.
    torn: bool,
    /// The records appended so far: the number of the last.
    written: u64,
    /// Earlier segments whose records may not be durable: a sync takes
    /// them in first, and a checkpoint before it counts them durable.
    older: Vec<Older>,
    /// The bytes of records in the earlier segments still there, and of
    /// each, by its number: a segment's bytes leave `kept` as its file is
    /// deleted, under this lock, so that `bytes` never counts a segment
    /// gone, nor misses one there (`spec/OPERATIONS.md`, `pds_log_bytes`).
    kept: u64,
    kept_by: std::collections::BTreeMap<u64, u64>,
    /// The logs appended to since the checkpoint before began, by path
    /// relative to the data directory.
    touched: BTreeSet<PathBuf>,
    /// How many of them appends named since the checkpoint before: those a
    /// start adopted not among them.
    appended: usize,
    /// Whether it takes no more records.
    closed: bool,
    /// Why a sync of a segment failed, if one did: from then on no wait is
    /// answered and no record taken, for the run.
    failed: Option<(io::ErrorKind, String)>,
    /// Why a checkpoint's flush of a log or sync of the directory failed,
    /// if one did: from then on no checkpoint runs, for the run.
    stuck: Option<(io::ErrorKind, String)>,
    /// A record, made here before it is written, so that none allocates.
    buf: Vec<u8>,
}

/// A segment before the current one whose records may not be durable.
#[derive(Clone)]
struct Older {
    /// The number of its last record.
    upto: u64,
    /// Its own number, and where its records end.
    number: u64,
    len: u64,
    file: Arc<File>,
}

/// What the checkpoint thread is told, apart from the journal, which it
/// holds only while it makes one.
#[derive(Default)]
struct Quiet {
    /// When the last record was appended, if one has been since the
    /// checkpoint before began.
    last: Option<Instant>,
    /// Whether the segment holds more than `SEGMENT`, or one is asked for.
    due: bool,
    stop: bool,
}

#[derive(Default)]
struct Signal {
    quiet: Mutex<Quiet>,
    changed: Condvar,
}

/// The journal of a data directory's logs: see the module.
pub struct Journal {
    root: PathBuf,
    dir: PathBuf,
    state: Mutex<State>,
    synced: Mutex<Syncs>,
    sync_ended: Condvar,
    /// Records known to be on disk: the number of the last.
    durable: AtomicU64,
    /// Held through a checkpoint, one at a time.
    checkpointing: Mutex<()>,
    signal: Arc<Signal>,
    thread: Mutex<Option<JoinHandle<()>>>,
    #[cfg(test)]
    pub(crate) test: Test,
}

/// What the tests see of a journal, and how they make its syncs fail.
#[cfg(test)]
#[derive(Default)]
pub(crate) struct Test {
    /// The syncs of its segments made by waits.
    pub syncs: AtomicU64,
    /// Called before each such sync: it may hold it, or fail it.
    pub hook: Mutex<Option<Hook>>,
    /// Each file a sync made durable, segment or log, and its length then:
    /// what a power cut leaves of it.
    pub synced: Mutex<std::collections::BTreeMap<PathBuf, u64>>,
    /// A checkpoint's deletions of segments and syncs of the directory,
    /// in order: what a power cut may undo of them.
    pub dir: Mutex<Vec<DirOp>>,
    /// Called at each place a write, cut or sync of the journal's may fail
    /// (`Fault`): it may fail it, having done part of it.
    pub fault: Mutex<Option<FaultHook>>,
    /// In place of `FILES` where not 0.
    pub files: std::sync::atomic::AtomicUsize,
}

/// A change to the journal's directory a checkpoint made.
#[cfg(test)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DirOp {
    Unlinked(PathBuf),
    Synced,
}

/// What a test has a sync do first.
#[cfg(test)]
pub(crate) type Hook = Arc<dyn Fn() -> io::Result<()> + Send + Sync>;

/// What a test has a write, cut or sync of the journal's answer first.
#[cfg(test)]
pub(crate) type FaultHook = Arc<dyn Fn(&Fault<'_>) -> io::Result<()> + Send + Sync>;

/// A place where a write, cut or sync of the journal's may fail, as a test
/// is told of it (`Test::fault`).
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) enum Fault<'a> {
    /// A record written to the current segment, at `at`.
    Write {
        file: &'a File,
        at: u64,
        record: &'a [u8],
    },
    /// The current segment cut back to its records.
    Cut,
    /// A checkpoint making a log durable: each by itself, or on Linux all
    /// of them by one sync of the file system.
    Flush,
    /// A segment made, its magic written.
    Make,
    /// An earlier segment synced, by a wait or a checkpoint, before the
    /// records after it are counted durable.
    Older,
}

impl Drop for Journal {
    /// A journal dropped stops its thread, which then makes no checkpoint,
    /// and leaves its segments as a kill would.
    fn drop(&mut self) {
        self.stop();
    }
}

impl Journal {
    /// Open the journal of the data directory `root`, `redo` having emptied
    /// it or adopted its segments (`adopted`): its next segment made,
    /// durably, and its checkpoint thread started. `journal/` is made if it
    /// is not there. Segments found that are not those adopted are an
    /// error: a start redoes them first. So is a journal another handle
    /// holds open.
    ///
    /// Adopted segments are its earlier segments, held as a checkpoint
    /// holds those it swapped out: what of them is on disk is not known, so
    /// the first wait's sync takes them in first, and a checkpoint is due
    /// at once, which makes them and the logs they name durable and
    /// deletes them. Records are numbered on from the last adopted; none is
    /// counted durable before a sync.
    pub fn open(root: &Path, adopted: Option<Adopted>) -> io::Result<Arc<Journal>> {
        Journal::open_with(root, adopted, true)
    }

    pub(crate) fn open_with(
        root: &Path,
        adopted: Option<Adopted>,
        background: bool,
    ) -> io::Result<Arc<Journal>> {
        let dir = root.join(DIR);
        let made = make_dirs(&dir).map_err(|e| named(&dir, e))?;
        let adopted = adopted.unwrap_or_default();
        let found = segments(&dir)?;
        if let Some(&n) = found
            .iter()
            .find(|&&n| !adopted.segments.iter().any(|k| k.number == n))
        {
            return Err(invalid(format!(
                "{}: a segment no start has redone",
                segment_path(&dir, n).display()
            )));
        }
        if let Some(k) = adopted.segments.iter().find(|k| !found.contains(&k.number)) {
            return Err(invalid(format!(
                "{}: a segment adopted is not there",
                segment_path(&dir, k.number).display()
            )));
        }
        let mut older = Vec::with_capacity(adopted.segments.len());
        for k in &adopted.segments {
            let path = segment_path(&dir, k.number);
            let file = open_locked(&path, OpenOptions::new().read(true).write(true))
                .map_err(|e| named(&path, e))?;
            older.push(Older {
                upto: k.upto,
                number: k.number,
                len: k.end,
                file: Arc::new(file),
            });
        }
        let number = adopted.segments.last().map_or(1, |k| k.number + 1);
        let first = adopted.segments.first().map_or(number, |k| k.number);
        let file = Journal::make_segment(&dir, number, || Ok(()))?;
        for x in &made {
            if let Some(parent) = x.parent().filter(|p| !p.as_os_str().is_empty()) {
                sync_dir(parent).map_err(|e| named(parent, e))?;
            }
        }
        // Adopted segments are let go by a checkpoint as any are: due
        // `QUIET` after the open where nothing is appended, so that they are
        // not kept for ever, and not at once, beside the start's own work.
        let signal = Signal::default();
        if !older.is_empty() {
            lock(&signal.quiet).last = Some(Instant::now());
        }
        let j = Arc::new(Journal {
            root: root.to_path_buf(),
            dir,
            state: Mutex::new(State {
                file: Some(Arc::new(file)),
                number,
                first,
                len: MAGIC_LEN,
                size: MAGIC_LEN,
                torn: false,
                written: adopted.last,
                older,
                kept: adopted.bytes,
                kept_by: adopted
                    .segments
                    .iter()
                    .map(|k| (k.number, k.end - MAGIC_LEN))
                    .collect(),
                touched: adopted.paths,
                appended: 0,
                closed: false,
                failed: None,
                stuck: None,
                buf: Vec::new(),
            }),
            synced: Mutex::new(Syncs::default()),
            sync_ended: Condvar::new(),
            durable: AtomicU64::new(0),
            checkpointing: Mutex::new(()),
            signal: Arc::new(signal),
            thread: Mutex::new(None),
            #[cfg(test)]
            test: Test::default(),
        });
        if background {
            let (weak, signal) = (Arc::downgrade(&j), j.signal.clone());
            let spawned = std::thread::Builder::new()
                .name("pds-journal".into())
                .spawn(move || checkpoints(weak, signal))
                .map_err(|e| named(&j.dir, e))?;
            *lock(&j.thread) = Some(spawned);
        }
        Ok(j)
    }

    /// Segment `n`, made with its magic, locked, and durable with the
    /// directory before a record is written to it; `made` is told once its
    /// magic is written. One of its number there already is made anew: a
    /// stray of a making that failed, its number above every live
    /// segment's. One whose making fails is removed, so that the next
    /// checkpoint can make it.
    fn make_segment(dir: &Path, n: u64, made: impl FnOnce() -> io::Result<()>) -> io::Result<File> {
        let path = segment_path(dir, n);
        let f = open_locked(
            &path,
            OpenOptions::new().create(true).write(true).read(true),
        )
        .map_err(|e| named(&path, e))?;
        let ready = (|| {
            f.set_len(0)?;
            f.write_all_at(&MAGIC, 0)?;
            made()?;
            sync_data(&f)
        })()
        .map_err(|e| named(&path, e))
        .and_then(|()| sync_dir(dir).map_err(|e| named(dir, e)));
        if let Err(e) = ready {
            drop(f);
            let _ = std::fs::remove_file(&path);
            return Err(e);
        }
        Ok(f)
    }

    /// The data directory it is of.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// The bytes of the records in its segments: those a checkpoint has not
    /// yet let go, without magic or room.
    pub fn bytes(&self) -> u64 {
        let st = lock(&self.state);
        st.kept + st.len - MAGIC_LEN
    }

    /// The path of the file at `path` relative to the data directory.
    fn relative<'a>(&self, path: &'a Path) -> io::Result<&'a Path> {
        path.strip_prefix(&self.root).map_err(|_| {
            invalid(format!(
                "{}: not in {}, whose journal this is",
                path.display(),
                self.root.display()
            ))
        })
    }

    /// Append the record of a frame of the log at `path`, written there at
    /// `offset`: answers its number, to `wait` for. Refused once the journal
    /// is closed. A record that cannot be written whole is cut back off the
    /// segment, before the next is written.
    pub(crate) fn append(&self, path: &Path, offset: u64, frame: &[u8]) -> io::Result<u64> {
        let rel = self.relative(path)?;
        self.put(FRAME, rel, offset, frame)
    }

    /// How many logs appended to since the checkpoint before make the next
    /// due: `FILES`, but where a test says otherwise.
    fn files_due(&self) -> usize {
        #[cfg(test)]
        match self.test.files.load(Ordering::SeqCst) {
            0 => {}
            n => return n,
        }
        FILES
    }

    fn put(&self, kind: u8, rel: &Path, offset: u64, frame: &[u8]) -> io::Result<u64> {
        let mut guard = lock(&self.state);
        let st = &mut *guard;
        let file = match (&st.file, st.closed) {
            (Some(_), false) if st.failed.is_some() => return Err(failure(&st.failed)),
            (Some(f), false) => f.clone(),
            _ => {
                return Err(io::Error::other(format!(
                    "{}: the journal is closed",
                    self.dir.display()
                )));
            }
        };
        if st.torn {
            self.fault(Fault::Cut).and_then(|()| file.set_len(st.len))?;
            st.size = st.len;
            st.torn = false;
        }
        encode(&mut st.buf, kind, st.written + 1, rel, offset, frame)?;
        let at = st.len;
        let written = self
            .fault(Fault::Write {
                file: &file,
                at,
                record: &st.buf,
            })
            .and_then(|()| file.write_all_at(&st.buf, at));
        if let Err(e) = written {
            st.torn = true;
            if self
                .fault(Fault::Cut)
                .and_then(|()| file.set_len(at))
                .is_ok()
            {
                st.size = st.len;
                st.torn = false;
            }
            return Err(e);
        }
        let n = st.buf.len() as u64;
        st.len += n;
        if st.len > st.size {
            let ahead = (st.len - MAGIC_LEN).clamp(ROOM_LEAST, ROOM_MOST);
            st.size = st.len + room(&file, st.len, ahead);
        }
        st.written += 1;
        if kind == FRAME && !st.touched.contains(rel) {
            st.touched.insert(rel.to_path_buf());
            st.appended += 1;
        }
        let full =
            (st.len - MAGIC_LEN > SEGMENT || st.appended >= self.files_due()) && st.stuck.is_none();
        let mut q = lock(&self.signal.quiet);
        // The thread waits with no end while nothing is appended: woken by
        // the first record, and by a segment full.
        let first = q.last.replace(Instant::now()).is_none();
        if full && !q.due {
            q.due = true;
        }
        if first || q.due {
            self.signal.changed.notify_all();
        }
        Ok(st.written)
    }

    /// Return once record `n` is on disk, with every record before it.
    /// Waiters at once share a sync, as a log's do (`Wal::wait`): one sync
    /// covers every record appended when it began, and one that fails is
    /// the answer to each it would have covered.
    pub fn wait(&self, n: u64) -> io::Result<()> {
        if let Some(failed) = &lock(&self.state).failed {
            return Err(failure(&Some(failed.clone())));
        }
        wait_shared(
            &self.synced,
            &self.sync_ended,
            &self.durable,
            n,
            |covered| self.sync(covered),
        )
    }

    fn sync(&self, covered: &mut u64) -> io::Result<()> {
        let (file, number, len, older) = {
            let st = lock(&self.state);
            if st.failed.is_some() {
                return Err(failure(&st.failed));
            }
            *covered = st.written;
            (st.file.clone(), st.number, st.len, st.older.clone())
        };
        let target = *covered;
        let Some(file) = file else {
            return Err(io::Error::other(format!(
                "{}: the journal is closed",
                self.dir.display()
            )));
        };
        let synced = (|| {
            #[cfg(test)]
            {
                let hook = lock(&self.test.hook).clone();
                if let Some(hook) = hook {
                    hook()?;
                }
                self.test.syncs.fetch_add(1, Ordering::SeqCst);
            }
            for o in &older {
                self.fault(Fault::Older).and_then(|()| sync_data(&o.file))?;
                self.note_synced(&segment_path(&self.dir, o.number), o.len);
            }
            sync_data(&file)
        })();
        if let Err(e) = synced {
            self.fail(&e);
            return Err(e);
        }
        self.note_synced(&segment_path(&self.dir, number), len);
        self.durable.fetch_max(target, Ordering::SeqCst);
        if !older.is_empty() {
            lock(&self.state).older.retain(|o| o.upto > target);
        }
        Ok(())
    }

    /// Note, for a test's model of a power cut, that the file at `path` was
    /// synced holding `len` bytes.
    fn note_synced(&self, path: &Path, len: u64) {
        #[cfg(test)]
        lock(&self.test.synced).insert(path.to_path_buf(), len);
        let _ = (path, len);
    }

    /// Fail the journal for the run, a sync of a segment having failed
    /// with `e` (the module's "A sync that failed"); said once.
    fn fail(&self, e: &io::Error) {
        let first = {
            let mut st = lock(&self.state);
            let first = st.failed.is_none();
            if first {
                st.failed = Some((e.kind(), e.to_string()));
            }
            first
        };
        if first {
            report(&format!(
                "the journal: {e}: no write is answered from now on; the next start redoes its segments"
            ));
        }
    }

    /// End the checkpoints for the run, a checkpoint's flush of a log or
    /// sync of the directory having failed with `e`; said once.
    fn stick(&self, e: &io::Error) {
        let first = {
            let mut st = lock(&self.state);
            let first = st.stuck.is_none();
            if first {
                st.stuck = Some((e.kind(), e.to_string()));
            }
            first
        };
        if first {
            report(&format!(
                "the journal: {e}: no segment is deleted from now on; the next start redoes them"
            ));
        }
    }

    /// Whether no checkpoint runs from now on, a sync having failed.
    fn stopped(&self) -> bool {
        let st = lock(&self.state);
        st.failed.is_some() || st.stuck.is_some()
    }

    /// What a test has the write, cut or sync `f` answer first: nothing,
    /// but in a test.
    fn fault(&self, f: Fault<'_>) -> io::Result<()> {
        #[cfg(test)]
        {
            let hook = lock(&self.test.fault).clone();
            if let Some(hook) = hook {
                return hook(&f);
            }
        }
        let _ = f;
        Ok(())
    }

    /// Note, for a test's model of a power cut, a segment deleted, or with
    /// none, the directory synced.
    fn note_dir(&self, unlinked: Option<&Path>) {
        #[cfg(test)]
        lock(&self.test.dir).push(match unlinked {
            Some(p) => DirOp::Unlinked(p.to_path_buf()),
            None => DirOp::Synced,
        });
        let _ = unlinked;
    }

    /// Whether record `n` is known to be on disk.
    pub fn is_durable(&self, n: u64) -> bool {
        self.durable.load(Ordering::SeqCst) >= n
    }

    /// Put a record in the journal that the file or directory at `path`
    /// is to be replaced or removed, and return once it is on disk: from
    /// then on a start writes nothing the journal held of it before into
    /// what is there. Before anything replaces or removes it.
    pub fn forget(&self, path: &Path) -> io::Result<()> {
        let rel = self.relative(path)?;
        let n = self.put(FORGET, rel, 0, &[])?;
        self.wait(n)
    }

    /// A checkpoint now, on this thread (see the module).
    pub fn checkpoint(&self) -> io::Result<()> {
        self.checkpoint_until(3, false)
    }

    /// A checkpoint stopping after step `last`, as if killed then: 1 the
    /// next segment, 2 the logs durable, 3 the segments before deleted. The
    /// last (`close`) makes no next segment, and deletes the current.
    fn checkpoint_until(&self, last: u8, closing: bool) -> io::Result<()> {
        let _one = lock(&self.checkpointing);
        {
            let mut st = lock(&self.state);
            if st.failed.is_some() || st.stuck.is_some() {
                if closing {
                    st.closed = true;
                }
                return Err(failure(if st.failed.is_some() {
                    &st.failed
                } else {
                    &st.stuck
                }));
            }
        }
        // 1. The next segment, durable before a record goes in it.
        let (number, idle) = {
            let st = lock(&self.state);
            (
                st.number,
                st.len == MAGIC_LEN && st.touched.is_empty() && st.first == st.number,
            )
        };
        if idle && !closing {
            return Ok(());
        }
        let next = match closing {
            true => None,
            false => Some(Arc::new(Journal::make_segment(
                &self.dir,
                number + 1,
                || self.fault(Fault::Make),
            )?)),
        };
        let (paths, upto, first) = {
            let mut st = lock(&self.state);
            if closing {
                st.closed = true;
            }
            // A segment swapped out holds nothing after its records: one
            // that holds part of a record is cut back first, or not swapped
            // out, the next segment going.
            if st.torn {
                let len = st.len;
                let cut = match &st.file {
                    Some(f) => self.fault(Fault::Cut).and_then(|()| f.set_len(len)),
                    None => Ok(()),
                };
                if let Err(e) = cut {
                    drop(st);
                    if next.is_some() {
                        drop(next);
                        let _ = std::fs::remove_file(segment_path(&self.dir, number + 1));
                    }
                    return Err(named(&segment_path(&self.dir, number), e));
                }
                st.size = len;
                st.torn = false;
            }
            let old = match next {
                Some(f) => st.file.replace(f),
                None => st.file.take(),
            };
            if let Some(file) = old
                && st.written > self.durable.load(Ordering::SeqCst)
            {
                let o = Older {
                    upto: st.written,
                    number,
                    len: st.len,
                    file,
                };
                st.older.push(o);
            }
            let held = st.len - MAGIC_LEN;
            st.kept += held;
            st.kept_by.insert(number, held);
            st.number = number + 1;
            st.len = MAGIC_LEN;
            st.size = MAGIC_LEN;
            st.torn = false;
            lock(&self.signal.quiet).last = None;
            st.appended = 0;
            (std::mem::take(&mut st.touched), st.written, st.first)
        };
        if last < 2 {
            return Ok(());
        }
        // 2. The segments before the next made durable first, every record
        // of them on disk in the journal; then each log appended to before
        // it, durable in its own file. A record is counted durable only once
        // it is on disk in the journal with every record before it: a
        // record of the next segment is answered only so, and a `forget`
        // only so goes before what it is for.
        let older = lock(&self.state).older.clone();
        for o in older.iter().filter(|o| o.upto <= upto) {
            let path = segment_path(&self.dir, o.number);
            if let Err(e) = self.fault(Fault::Older).and_then(|()| sync_data(&o.file)) {
                let e = named(&path, e);
                self.fail(&e);
                return Err(e);
            }
            self.note_synced(&path, o.len);
        }
        // On Linux, one sync of the data directory's file system makes every
        // log durable, the journal's directory with them: no fsync of each
        // log, every one its own commit of the file system's journal, that
        // the journal's own syncs wait behind. Elsewhere each log is handed
        // to the drive, then one sync of the directory reaches the disk.
        #[cfg(target_os = "linux")]
        {
            let root = match File::open(&self.root) {
                Ok(f) => f,
                // No sync tried: the next checkpoint tries again.
                Err(e) => {
                    lock(&self.state).touched.extend(paths.iter().cloned());
                    return Err(named(&self.root, e));
                }
            };
            if let Err(e) = self
                .fault(Fault::Flush)
                .and_then(|()| crate::sync_filesystem(&root))
            {
                let e = named(&self.root, e);
                self.stick(&e);
                return Err(e);
            }
            #[cfg(test)]
            for p in &paths {
                let full = self.root.join(p);
                self.note_synced(&full, std::fs::metadata(&full).map_or(0, |m| m.len()));
            }
        }
        #[cfg(not(target_os = "linux"))]
        {
            for p in &paths {
                let full = self.root.join(p);
                let f = match File::open(&full) {
                    Ok(f) => f,
                    Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
                    // No flush of it tried: the next checkpoint tries again.
                    Err(e) => {
                        lock(&self.state).touched.extend(paths.iter().cloned());
                        return Err(named(&full, e));
                    }
                };
                if let Err(e) = self
                    .fault(Fault::Flush)
                    .and_then(|()| crate::flush_file(&f))
                {
                    let e = named(&full, e);
                    self.stick(&e);
                    return Err(e);
                }
                self.note_synced(&full, f.metadata().map_or(0, |m| m.len()));
            }
            if let Err(e) = sync_dir(&self.dir) {
                let e = named(&self.dir, e);
                self.stick(&e);
                return Err(e);
            }
        }
        self.durable.fetch_max(upto, Ordering::SeqCst);
        lock(&self.state).older.retain(|o| o.upto > upto);
        self.sync_ended.notify_all();
        if last < 3 {
            return Ok(());
        }
        // 3. The segments before the next deleted, all of them closing:
        // lowest first, the directory synced after each, so that what a
        // power cut leaves of them is those from some number on, with no
        // gap, which hold every `forget` their records need.
        for n in first..=number {
            let path = segment_path(&self.dir, n);
            {
                let mut st = lock(&self.state);
                match std::fs::remove_file(&path) {
                    Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(named(&path, e)),
                    _ => {}
                }
                let held = st.kept_by.remove(&n).unwrap_or(0);
                st.kept -= held;
            }
            self.note_dir(Some(&path));
            if let Err(e) = sync_dir(&self.dir) {
                let e = named(&self.dir, e);
                self.stick(&e);
                return Err(e);
            }
            self.note_dir(None);
            lock(&self.state).first = n + 1;
        }
        Ok(())
    }

    /// Stop the checkpoint thread, and wait for it to end, unless this is
    /// it.
    fn stop(&self) {
        let mut q = lock(&self.signal.quiet);
        q.stop = true;
        drop(q);
        self.signal.changed.notify_all();
        let handle = lock(&self.thread).take();
        if let Some(h) = handle
            && h.thread().id() != std::thread::current().id()
        {
            let _ = h.join();
        }
    }

    /// Close the journal, every log given it closed first: it takes no
    /// record from then on, an append is refused as one to a closed log
    /// is, its last checkpoint makes every log appended to durable in its
    /// own file, and no segment is left. Answers why not, its segments then
    /// left for the next start to redo.
    pub fn close(&self) -> io::Result<()> {
        self.stop();
        self.checkpoint_until(3, true)
    }

    /// Let the journal go as a kill would: it takes no record, makes no
    /// sync and no checkpoint from then on, holds no file open, and leaves
    /// its segments for the next start to redo.
    pub fn let_go(&self) {
        self.stop();
        let mut st = lock(&self.state);
        st.closed = true;
        st.file = None;
        st.older.clear();
    }
}

/// The checkpoint thread: one when due, until the journal is closed or
/// dropped.
fn checkpoints(journal: Weak<Journal>, signal: Arc<Signal>) {
    let mut q = lock(&signal.quiet);
    loop {
        if q.stop {
            return;
        }
        let quiet = q.last.map(|t| t.elapsed());
        if !q.due && quiet.is_none_or(|t| t < QUIET) {
            q = match quiet {
                Some(t) => {
                    signal
                        .changed
                        .wait_timeout(q, QUIET - t)
                        .unwrap_or_else(PoisonError::into_inner)
                        .0
                }
                None => signal
                    .changed
                    .wait(q)
                    .unwrap_or_else(PoisonError::into_inner),
            };
            continue;
        }
        q.due = false;
        drop(q);
        let Some(j) = journal.upgrade() else { return };
        if let Err(e) = j.checkpoint()
            && !j.stopped()
        {
            report(&format!("the journal: {e}"));
            // Tried again once as long has gone by.
            lock(&signal.quiet).last.get_or_insert_with(Instant::now);
        }
        drop(j);
        q = lock(&signal.quiet);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Files, Wal, frame, scan};
    use serde_json::{Value as Json, json};
    use std::sync::atomic::AtomicBool;
    use std::sync::mpsc;

    fn scratch(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("pds-journal-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    /// A journal with no checkpoint thread, and a pool of logs written to it.
    fn journaled(root: &Path) -> (Arc<Journal>, Arc<Files>) {
        let j = Journal::open_with(root, None, false).unwrap();
        let pool = Files::with_journal(16, j.clone());
        (j, pool)
    }

    fn log(root: &Path, name: &str, pool: &Arc<Files>) -> Wal {
        Wal::open(&root.join(name).join("x.log"), Some(pool.clone()))
            .unwrap()
            .0
    }

    fn frames(path: &Path) -> Vec<Vec<Json>> {
        scan(&std::fs::read(path).unwrap()).unwrap().0
    }

    /// The bytes of a segment holding these records, numbered from `first`.
    fn segment(first: u64, records: &[(u8, &str, u64, &[u8])]) -> Vec<u8> {
        let mut out = MAGIC.to_vec();
        let mut buf = Vec::new();
        for (i, (kind, path, offset, bytes)) in records.iter().enumerate() {
            encode(
                &mut buf,
                *kind,
                first + i as u64,
                Path::new(path),
                *offset,
                bytes,
            )
            .unwrap();
            out.extend_from_slice(&buf);
        }
        out
    }

    fn put_segment(root: &Path, n: u64, bytes: &[u8]) {
        let dir = root.join(DIR);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(segment_path(&dir, n), bytes).unwrap();
    }

    #[test]
    fn records_read_back_as_written() {
        let data = segment(
            7,
            &[
                (FRAME, "repos/a/repo.0.log", 12, b"frame"),
                (FORGET, "repos/a", 0, b""),
            ],
        );
        let (rs, end) = records(&data[8..]);
        assert_eq!(end, data.len() - 8);
        assert_eq!(
            rs,
            vec![
                (
                    7,
                    Record::Frame {
                        path: Path::new("repos/a/repo.0.log"),
                        offset: 12,
                        bytes: b"frame"
                    }
                ),
                (
                    8,
                    Record::Forget {
                        path: Path::new("repos/a")
                    }
                )
            ]
        );
        // Zeros after them are the end, as room is.
        let mut roomy = data.clone();
        roomy.extend_from_slice(&[0; 100]);
        assert_eq!(records(&roomy[8..]).0.len(), 2);
    }

    /// Records of several logs made durable by one sync, and a wait on a
    /// log whose record an earlier sync covered makes none.
    #[test]
    fn logs_share_the_journals_syncs() {
        let root = scratch("share");
        let (j, pool) = journaled(&root);
        let wals: Vec<Wal> = (0..8)
            .map(|i| log(&root, &format!("l{i}"), &pool))
            .collect();
        let ns: Vec<u64> = wals
            .iter()
            .enumerate()
            .map(|(i, w)| w.append(&[json!(i)]).unwrap())
            .collect();
        wals[0].wait(ns[0]).unwrap();
        assert_eq!(j.test.syncs.load(Ordering::SeqCst), 1);
        for (w, n) in wals.iter().zip(&ns) {
            w.wait(*n).unwrap();
            assert!(w.is_durable(*n));
        }
        assert_eq!(j.test.syncs.load(Ordering::SeqCst), 1, "one sync for all");
        assert!(
            lock(&wals[3].0.trace)
                .iter()
                .all(|t| t.starts_with("journal"))
        );
        // Writers at once, each to its own log.
        std::thread::scope(|s| {
            for w in &wals {
                s.spawn(move || {
                    for i in 0..20 {
                        let n = w.append(&[json!(i)]).unwrap();
                        w.wait(n).unwrap();
                    }
                });
            }
        });
        let syncs = j.test.syncs.load(Ordering::SeqCst);
        assert!(syncs <= 161, "{syncs} syncs of 160 frames");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A waiter is answered only by a sync begun after its record was
    /// appended: one appended while a sync runs makes a sync of its own.
    #[test]
    fn a_sync_answers_only_the_records_before_it() {
        let root = scratch("before");
        let (j, pool) = journaled(&root);
        let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
        // Each sync is held until told.
        let (began, held) = (mpsc::channel::<()>(), mpsc::channel::<()>());
        let (tell_began, go) = (Mutex::new(began.0), Mutex::new(held.1));
        *lock(&j.test.hook) = Some(Arc::new(move || {
            let _ = lock(&tell_began).send(());
            let _ = lock(&go).recv();
            Ok(())
        }));
        std::thread::scope(|s| {
            let na = a.append(&[json!("a")]).unwrap();
            let first = {
                let a = &a;
                s.spawn(move || a.wait(na))
            };
            began.1.recv().unwrap();
            // Appended while the first sync runs: not covered by it.
            let nb = b.append(&[json!("b")]).unwrap();
            let second = {
                let b = &b;
                s.spawn(move || b.wait(nb))
            };
            held.0.send(()).unwrap();
            first.join().unwrap().unwrap();
            assert!(!b.is_durable(nb));
            // The second makes a sync of its own.
            began.1.recv().unwrap();
            held.0.send(()).unwrap();
            second.join().unwrap().unwrap();
            assert!(b.is_durable(nb));
        });
        assert_eq!(j.test.syncs.load(Ordering::SeqCst), 2);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A sync that failed is never taken back, though a later one succeeds,
    /// as one may after a failed one, what that was to write lost: the
    /// waiter of the failed sync and every one after fail, appends are
    /// refused, no checkpoint deletes a segment, and a power cut then
    /// loses no answered frame.
    #[test]
    fn a_failed_sync_is_never_taken_back() {
        let root = scratch("never-back");
        let (j, pool) = journaled(&root);
        let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
        let paths: Vec<PathBuf> = ["a", "b"]
            .iter()
            .map(|n| root.join(n).join("x.log"))
            .collect();
        a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
        let failed = AtomicBool::new(false);
        *lock(&j.test.hook) = Some(Arc::new(move || {
            match failed.swap(true, Ordering::SeqCst) {
                false => Err(io::Error::other("a sync failed")),
                true => Ok(()),
            }
        }));
        let na = a.append(&[json!("a1")]).unwrap();
        assert!(a.wait(na).is_err());
        let later = b.append(&[json!("b0")]).and_then(|n| b.wait(n));
        assert!(later.is_err(), "a wait after a failed sync answered");
        assert!(a.wait(na).is_err());
        let first = the_segment(&root);
        assert!(j.checkpoint().is_err());
        assert!(first.exists(), "a segment deleted after a failed sync");
        j.let_go();
        drop((a, b));
        power_cut(&j, &paths, &[]);
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(frames(&paths[0]), vec![vec![json!("a0")]]);
        assert!(frames(&paths[1]).is_empty());
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A checkpoint's flush of a log that failed ends the checkpoints for
    /// the run: the journal goes on taking records and answering them, and
    /// no checkpoint asked for after deletes a segment. A power cut that
    /// loses what the failed flush was to write, though a later flush of
    /// the log may succeed, loses no answered frame.
    #[test]
    fn a_failed_flush_deletes_no_segment() {
        let root = scratch("flush-failed");
        let (j, pool) = journaled(&root);
        let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
        let paths: Vec<PathBuf> = ["a", "b"]
            .iter()
            .map(|n| root.join(n).join("x.log"))
            .collect();
        a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
        b.wait(b.append(&[json!("b0")]).unwrap()).unwrap();
        let first = the_segment(&root);
        // The first flush fails: of `a`, or on Linux of the file system.
        let flushes = AtomicU64::new(0);
        *lock(&j.test.fault) = Some(Arc::new(move |f: &Fault<'_>| match f {
            Fault::Flush if flushes.fetch_add(1, Ordering::SeqCst) == 0 => {
                Err(io::Error::other("a flush failed"))
            }
            _ => Ok(()),
        }));
        assert!(j.checkpoint().is_err());
        a.wait(a.append(&[json!("a1")]).unwrap()).unwrap();
        for _ in 0..2 {
            let _ = j.checkpoint();
        }
        assert!(first.exists(), "a segment deleted after a failed flush");
        j.let_go();
        drop((a, b));
        lock(&j.test.synced).remove(&paths[0]);
        power_cut(&j, &paths, &[]);
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(
            frames(&paths[0]),
            vec![vec![json!("a0")], vec![json!("a1")]]
        );
        assert_eq!(frames(&paths[1]), vec![vec![json!("b0")]]);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Every log of `root` as a power cut leaves it, synced by itself at
    /// none of its frames since it was made: empty.
    fn cut_logs(root: &Path, names: &[&str]) {
        for n in names {
            std::fs::write(root.join(n).join("x.log"), b"").unwrap();
        }
    }

    fn the_segment(root: &Path) -> PathBuf {
        let dir = root.join(DIR);
        let n = *segments(&dir).unwrap().last().unwrap();
        segment_path(&dir, n)
    }

    /// A power cut with frames journaled and durable, every log's own
    /// unsynced tail lost: a start puts back every answered frame, byte for
    /// byte, in order. With the last record cut at every byte too, of a
    /// frame not answered, each log holds a prefix of its frames that has
    /// every answered one.
    #[test]
    fn a_power_cut_loses_no_answered_frame() {
        let root = scratch("power");
        let (j, pool) = journaled(&root);
        let names = ["a", "b", "c"];
        let wals: Vec<Wal> = names.iter().map(|n| log(&root, n, &pool)).collect();
        let mut want: Vec<Vec<Vec<Json>>> = vec![Vec::new(); 3];
        for i in 0..10 {
            let k = i % 3;
            let entries = vec![json!({ "i": i, "pad": "x".repeat(i * 7) })];
            let n = wals[k].append(&entries).unwrap();
            wals[k].wait(n).unwrap();
            want[k].push(entries);
        }
        let logs: Vec<Vec<u8>> = names
            .iter()
            .map(|n| std::fs::read(root.join(n).join("x.log")).unwrap())
            .collect();
        let durable = std::fs::read(the_segment(&root)).unwrap();
        // One more, never waited for.
        wals[1].append(&[json!("last")]).unwrap();
        let whole = std::fs::read(the_segment(&root)).unwrap();
        let (to, from) = (records(&whole[8..]).1 + 8, records(&durable[8..]).1 + 8);
        j.let_go();
        drop(wals);
        let work = scratch("power-work");
        for cut in from..=to {
            for (n, bytes) in names.iter().zip(&logs) {
                std::fs::create_dir_all(work.join(n)).unwrap();
                std::fs::write(work.join(n).join("x.log"), bytes).unwrap();
            }
            cut_logs(&work, &names);
            put_segment(&work, 1, &whole[..cut]);
            let done = redo(&work, Redo::Eager).unwrap();
            assert_eq!(done.files, 3, "cut at {cut}");
            assert!(segments(&work.join(DIR)).unwrap().is_empty());
            for (k, n) in names.iter().enumerate() {
                let got = frames(&work.join(n).join("x.log"));
                let mut w = want[k].clone();
                if k == 1 && cut == to {
                    w.push(vec![json!("last")]);
                }
                assert_eq!(got, w, "{n} with the journal cut at {cut} of {from}..{to}");
            }
        }
        let _ = std::fs::remove_dir_all(&root);
        let _ = std::fs::remove_dir_all(&work);
    }

    /// The torn tail of the last segment is dropped at every byte; a record
    /// whose file is gone is skipped; a record already in its file changes
    /// nothing.
    #[test]
    fn a_start_takes_whole_records_of_files_there() {
        let root = scratch("whole");
        let one = frame(&[json!(1)]);
        let two = frame(&[json!(2)]);
        let data = segment(
            1,
            &[
                (FRAME, "a.log", 0, &one),
                (FRAME, "gone.log", 0, &one),
                (FRAME, "a.log", one.len() as u64, &two),
            ],
        );
        let last = records(&data[8..]).1 + 8 - (HEADER + 1 + 8 + 2 + 5 + 8 + two.len());
        for cut in last..=data.len() {
            std::fs::write(root.join("a.log"), &one).unwrap();
            put_segment(&root, 1, &data[..cut]);
            let done = redo(&root, Redo::Eager).unwrap();
            let got = frames(&root.join("a.log"));
            if cut == data.len() {
                assert_eq!(got, vec![vec![json!(1)], vec![json!(2)]]);
                assert_eq!((done.records, done.written, done.files), (3, 1, 1));
            } else {
                assert_eq!(got, vec![vec![json!(1)]], "cut at {cut}");
                assert_eq!((done.records, done.written), (2, 0), "cut at {cut}");
            }
            assert!(!root.join("gone.log").exists());
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Records after a gap in their numbers, as a later segment's that
    /// reached the disk without an earlier one's, are not taken.
    #[test]
    fn nothing_after_a_gap_is_taken() {
        let root = scratch("gap");
        let one = frame(&[json!(1)]);
        let two = frame(&[json!(2)]);
        std::fs::write(root.join("a.log"), b"").unwrap();
        put_segment(&root, 1, &segment(1, &[(FRAME, "a.log", 0, &one)]));
        put_segment(&root, 2, &segment(3, &[(FRAME, "a.log", 99, &two)]));
        assert_eq!(redo(&root, Redo::Eager).unwrap().records, 1);
        assert_eq!(frames(&root.join("a.log")), vec![vec![json!(1)]]);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A file shorter than a record's offset cannot be recovered; a segment
    /// of another format refuses the start, and is left as it is.
    #[test]
    fn what_cannot_be_redone_refuses_the_start() {
        let root = scratch("refuse");
        let one = frame(&[json!(1)]);
        std::fs::write(root.join("a.log"), b"").unwrap();
        put_segment(&root, 1, &segment(1, &[(FRAME, "a.log", 5, &one)]));
        let e = redo(&root, Redo::Eager).unwrap_err();
        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
        assert!(
            e.to_string().contains("a frame before that is missing"),
            "{e}"
        );
        assert_eq!(std::fs::read(root.join("a.log")).unwrap(), b"");
        let other = [b"PDSJNL02".to_vec(), vec![1, 2, 3]].concat();
        put_segment(&root, 1, &other);
        let e = redo(&root, Redo::Eager).unwrap_err();
        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
        assert_eq!(
            std::fs::read(segment_path(&root.join(DIR), 1)).unwrap(),
            other
        );
        // A segment whose making was cut short holds no record.
        put_segment(&root, 1, b"PDSJ");
        assert_eq!(redo(&root, Redo::Eager).unwrap().records, 0);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A record of a path before a `forget` of it, or of a directory it is
    /// in, is not written into the file there now; one after it is.
    #[test]
    fn a_forgotten_path_is_not_written_over() {
        let root = scratch("forget");
        let (old, new, more) = (
            frame(&[json!("old")]),
            frame(&[json!("new")]),
            frame(&[json!("more")]),
        );
        std::fs::create_dir_all(root.join("d")).unwrap();
        for (forgot, path) in [("a.log", "a.log"), ("d", "d/a.log")] {
            std::fs::write(root.join(path), &new).unwrap();
            put_segment(
                &root,
                1,
                &segment(
                    1,
                    &[
                        (FRAME, path, 0, &old),
                        (FORGET, forgot, 0, b""),
                        (FRAME, path, new.len() as u64, &more),
                    ],
                ),
            );
            let done = redo(&root, Redo::Eager).unwrap();
            assert_eq!(done.written, 1, "{forgot}");
            assert_eq!(
                frames(&root.join(path)),
                vec![vec![json!("new")], vec![json!("more")]],
                "{forgot}"
            );
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A log rewritten after records of it were journaled is not written
    /// over by them at the next start, killed just before its `forget` is
    /// durable, or just after.
    #[test]
    fn a_rewrite_forgets_what_the_journal_held() {
        let root = scratch("rewrite");
        let (j, pool) = journaled(&root);
        let wal = log(&root, "a", &pool);
        for i in 0..5 {
            wal.wait(wal.append(&[json!(i)]).unwrap()).unwrap();
        }
        let path = root.join("a").join("x.log");
        let before = std::fs::read(&path).unwrap();
        let journal_before = std::fs::read(the_segment(&root)).unwrap();
        wal.rewrite(|_| Ok(vec![vec![json!("folded")]])).unwrap();
        let after = std::fs::read(&path).unwrap();
        let journal_after = std::fs::read(the_segment(&root)).unwrap();
        j.let_go();
        drop(wal);
        // Killed before the forget: the file not yet replaced.
        put_segment(&root, 1, &journal_before);
        std::fs::write(&path, &before).unwrap();
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), before);
        // After it: the new file, never written over.
        put_segment(&root, 1, &journal_after);
        std::fs::write(&path, &after).unwrap();
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(frames(&path), vec![vec![json!("folded")]]);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Killed at each step of a checkpoint, a start recovers every frame;
    /// redoing records already in their files writes nothing.
    #[test]
    fn a_checkpoint_killed_at_each_step_loses_nothing() {
        for step in 1..=3u8 {
            let root = scratch(&format!("killed-{step}"));
            let (j, pool) = journaled(&root);
            let wals: Vec<Wal> = ["a", "b"].iter().map(|n| log(&root, n, &pool)).collect();
            for i in 0..6 {
                let w = &wals[i % 2];
                w.wait(w.append(&[json!(i)]).unwrap()).unwrap();
            }
            j.checkpoint_until(step, false).unwrap();
            // Written after the next segment began, and waited for.
            wals[0]
                .wait(wals[0].append(&[json!("after")]).unwrap())
                .unwrap();
            j.let_go();
            drop(wals);
            let done = redo(&root, Redo::Eager).unwrap();
            assert_eq!(done.written, 0, "step {step}");
            assert!(segments(&root.join(DIR)).unwrap().is_empty());
            let a = frames(&root.join("a").join("x.log"));
            assert_eq!(a.len(), 4, "step {step}");
            assert_eq!(a[3], vec![json!("after")]);
            assert_eq!(frames(&root.join("b").join("x.log")).len(), 3);
            let _ = std::fs::remove_dir_all(&root);
        }
    }

    /// A journal little written to keeps little room; a checkpoint lets go
    /// of the segments before; closed, it leaves no segment, and takes no
    /// more records.
    #[test]
    fn a_journal_keeps_little() {
        let root = scratch("little");
        let (j, pool) = journaled(&root);
        let first = the_segment(&root);
        assert_eq!(std::fs::metadata(&first).unwrap().len(), 8, "magic alone");
        let wal = log(&root, "a", &pool);
        for i in 0..20 {
            wal.wait(wal.append(&[json!(i)]).unwrap()).unwrap();
        }
        let size = std::fs::metadata(&first).unwrap().len();
        assert!(size < 128 << 10, "{size}");
        assert!(j.bytes() > 0);
        j.checkpoint().unwrap();
        assert!(!first.exists());
        assert_eq!(std::fs::metadata(the_segment(&root)).unwrap().len(), 8);
        assert_eq!(j.bytes(), 0);
        wal.wait(wal.append(&[json!("x")]).unwrap()).unwrap();
        wal.close().unwrap();
        j.close().unwrap();
        assert!(segments(&root.join(DIR)).unwrap().is_empty());
        assert_eq!(frames(&root.join("a").join("x.log")).len(), 21);
        let wal = log(&root, "b", &pool);
        assert!(wal.append(&[json!("y")]).is_err(), "the journal is closed");
        assert!(frames(&root.join("b").join("x.log")).is_empty());
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The journal and `logs` as a power cut leaves them: each file as long
    /// as when a sync last made it durable (`Test::synced`), a segment no
    /// sync has taken since it was made its magic alone, and a log none has
    /// taken empty, as each was made. `gone` are segments deleted since,
    /// by path, as they were before: a deletion no sync of the directory
    /// made durable undone.
    fn power_cut(j: &Journal, logs: &[PathBuf], gone: &[(PathBuf, Vec<u8>)]) {
        let synced = lock(&j.test.synced).clone();
        for (path, bytes) in gone {
            std::fs::write(path, bytes).unwrap();
        }
        let dir = j.root.join(DIR);
        for n in segments(&dir).unwrap() {
            let path = segment_path(&dir, n);
            let keep = synced.get(&path).copied().unwrap_or(MAGIC_LEN) as usize;
            let bytes = std::fs::read(&path).unwrap();
            std::fs::write(&path, &bytes[..keep.min(bytes.len())]).unwrap();
        }
        for path in logs {
            // Synced with room after its frames, which it gave back since.
            let keep = synced.get(path).copied().unwrap_or(0) as usize;
            let bytes = std::fs::read(path).unwrap();
            std::fs::write(path, &bytes[..keep.min(bytes.len())]).unwrap();
        }
    }

    /// The segments there, by path, and their bytes.
    fn the_segments(root: &Path) -> Vec<(PathBuf, Vec<u8>)> {
        let dir = root.join(DIR);
        segments(&dir)
            .unwrap()
            .into_iter()
            .map(|n| {
                let p = segment_path(&dir, n);
                let b = std::fs::read(&p).unwrap();
                (p, b)
            })
            .collect()
    }

    /// A checkpoint counts no record durable before its segment is: records
    /// appended and not waited for, a checkpoint stopped after its first
    /// step and after its second, then records in the next segment waited
    /// for and answered; a power cut, every file as it was last synced, the
    /// logs and the segments: a start puts back every answered frame. And a
    /// `forget` whose wait has returned is on disk: the start writes
    /// nothing of the path's records before it into what replaced it.
    #[test]
    fn a_checkpoint_counts_no_record_durable_before_its_segment_is() {
        for step in [1u8, 2] {
            let root = scratch(&format!("counts-{step}"));
            let (j, pool) = journaled(&root);
            let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
            let p = log(&root, "p", &pool);
            let paths: Vec<PathBuf> = ["a", "b", "p"]
                .iter()
                .map(|n| root.join(n).join("x.log"))
                .collect();
            a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
            p.wait(p.append(&[json!("p0")]).unwrap()).unwrap();
            for i in 1..4 {
                a.append(&[json!(format!("a{i}"))]).unwrap();
            }
            // A forget as a rewrite or a removal makes one, its wait apart.
            let forget = j.put(FORGET, Path::new("p"), 0, &[]).unwrap();
            j.checkpoint_until(step, false).unwrap();
            j.wait(forget).unwrap();
            drop(p);
            let replaced = frame(&[json!("another")]);
            std::fs::write(&paths[2], &replaced).unwrap();
            lock(&j.test.synced).insert(paths[2].clone(), replaced.len() as u64);
            b.wait(b.append(&[json!("b0")]).unwrap()).unwrap();
            j.let_go();
            drop((a, b));
            power_cut(&j, &paths, &[]);
            redo(&root, Redo::Eager).unwrap();
            assert_eq!(frames(&paths[1]), vec![vec![json!("b0")]], "step {step}");
            assert_eq!(frames(&paths[0])[0], vec![json!("a0")], "step {step}");
            assert_eq!(std::fs::read(&paths[2]).unwrap(), replaced, "step {step}");
            let _ = std::fs::remove_dir_all(&root);
        }
    }

    /// A checkpoint's deletions of three segments, each subset of them
    /// undone by a power cut, the segments back as they were synced, the
    /// middle one holding a `forget` of a path replaced since. A subset is
    /// tried where what the checkpoint did, its deletions and its syncs of
    /// the directory in order (`Test::dir`), can leave it: a deletion a
    /// sync of the directory followed is not undone, and one not yet made
    /// is. Deleted lowest first with a sync after each, no subset with a
    /// gap, or with a segment back and one after it gone, can be left:
    /// those are not tried. Of those that can, a start recovers every
    /// answered frame, and writes nothing over the path replaced.
    #[test]
    fn a_checkpoints_deletions_undone() {
        let root = scratch("undone");
        let (j, pool) = journaled(&root);
        let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
        let paths: Vec<PathBuf> = ["a", "b", "p"]
            .iter()
            .map(|n| root.join(n).join("x.log"))
            .collect();
        let p = log(&root, "p", &pool);
        p.wait(p.append(&[json!("p0")]).unwrap()).unwrap();
        a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
        // Checkpoints that failed after their second step left their
        // segments: three before the next.
        j.checkpoint_until(2, false).unwrap();
        a.wait(a.append(&[json!("a1")]).unwrap()).unwrap();
        j.forget(&root.join("p")).unwrap();
        drop(p);
        let replaced = frame(&[json!("another")]);
        std::fs::write(&paths[2], &replaced).unwrap();
        lock(&j.test.synced).insert(paths[2].clone(), replaced.len() as u64);
        j.checkpoint_until(2, false).unwrap();
        a.wait(a.append(&[json!("a2")]).unwrap()).unwrap();
        let before = the_segments(&root);
        assert_eq!(before.len(), 3);
        lock(&j.test.dir).clear();
        j.checkpoint_until(3, false).unwrap();
        assert_eq!(the_segments(&root).len(), 1);
        b.wait(b.append(&[json!("b0")]).unwrap()).unwrap();
        j.let_go();
        drop((a, b));
        let ops = lock(&j.test.dir).clone();
        let logs: Vec<Vec<u8>> = paths.iter().map(|p| std::fs::read(p).unwrap()).collect();
        let after = the_segments(&root);
        // Whether the segments `back` can be all that a power cut brings
        // back, cut after some prefix of `ops`.
        let can = |back: &[bool]| {
            (0..=ops.len()).any(|t| {
                before.iter().zip(back).all(|((path, _), &back)| {
                    let at = ops[..t]
                        .iter()
                        .position(|o| matches!(o, DirOp::Unlinked(p) if p == path));
                    match at {
                        None => back,
                        Some(i) if ops[i..t].contains(&DirOp::Synced) => !back,
                        Some(_) => true,
                    }
                })
            })
        };
        let mut tried = Vec::new();
        for subset in 0..8u8 {
            let back: Vec<bool> = (0..3).map(|i| subset & (1 << i) != 0).collect();
            if !can(&back) {
                continue;
            }
            tried.push(back.clone());
            for (p, bytes) in paths.iter().zip(&logs) {
                std::fs::write(p, bytes).unwrap();
            }
            for (p, _) in the_segments(&root) {
                std::fs::remove_file(p).unwrap();
            }
            for (p, bytes) in &after {
                std::fs::write(p, bytes).unwrap();
            }
            let gone: Vec<(PathBuf, Vec<u8>)> = before
                .iter()
                .zip(&back)
                .filter(|(_, b)| **b)
                .map(|(s, _)| s.clone())
                .collect();
            power_cut(&j, &paths, &gone);
            redo(&root, Redo::Eager).unwrap();
            assert_eq!(frames(&paths[1]), vec![vec![json!("b0")]], "{back:?}");
            assert_eq!(
                frames(&paths[0]),
                vec![vec![json!("a0")], vec![json!("a1")], vec![json!("a2")]],
                "{back:?}"
            );
            assert_eq!(std::fs::read(&paths[2]).unwrap(), replaced, "{back:?}");
        }
        // Those back are the highest, with no gap.
        let suffixes: Vec<Vec<bool>> = (0..=3)
            .rev()
            .map(|k| (0..3).map(|i| i >= k).collect())
            .collect();
        tried.sort();
        let mut want = suffixes;
        want.sort();
        assert_eq!(tried, want);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Two journals on one data directory are an error, as is opening one
    /// over segments no start has redone.
    #[test]
    fn one_journal_to_a_directory() {
        let root = scratch("one");
        let j = Journal::open_with(&root, None, false).unwrap();
        assert!(Journal::open_with(&root, None, false).is_err());
        j.let_go();
        assert!(
            Journal::open_with(&root, None, false).is_err(),
            "a segment left"
        );
        redo(&root, Redo::Eager).unwrap();
        Journal::open_with(&root, None, false)
            .unwrap()
            .close()
            .unwrap();
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The checkpoint thread runs once appends have been quiet a while, and
    /// stops with the journal.
    #[test]
    fn a_quiet_journal_is_checkpointed() {
        let root = scratch("quiet");
        let j = Journal::open(&root, None).unwrap();
        let pool = Files::with_journal(4, j.clone());
        let wal = log(&root, "a", &pool);
        wal.wait(wal.append(&[json!(1)]).unwrap()).unwrap();
        let first = the_segment(&root);
        let t = Instant::now();
        while first.exists() && t.elapsed() < QUIET * 5 {
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(!first.exists(), "checkpointed");
        assert!(t.elapsed() >= QUIET - Duration::from_millis(100));
        drop(wal);
        let weak = Arc::downgrade(&j);
        drop((j, pool));
        // Freed once the thread's checkpoint, which deleted the segment,
        // has ended.
        let t = Instant::now();
        while weak.upgrade().is_some() && t.elapsed() < QUIET {
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(weak.upgrade().is_none());
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A log with generations writes its seal to the journal once the next
    /// log is made, and a start puts it back.
    #[test]
    fn a_seal_is_journaled() {
        use crate::{Fold, Layout, Policy};
        struct Keep;
        impl Fold for Keep {
            fn fold(
                &self,
                _: Option<Vec<u8>>,
                _: Vec<Vec<Json>>,
                _: u64,
            ) -> Result<Vec<u8>, String> {
                Ok(b"[]".to_vec())
            }
        }
        let root = scratch("seal");
        let (j, pool) = journaled(&root);
        let layout = Layout::new(root.join("r"), "repo");
        let never = Policy {
            floor: u64::MAX,
            cap: None,
            max_age: None,
        };
        let (wal, _) = Wal::open_log(&layout, 0, 0, Some(pool.clone()), never).unwrap();
        wal.set_fold(Arc::new(Keep));
        wal.wait(wal.append(&[json!(1)]).unwrap()).unwrap();
        let log0 = std::fs::read(layout.log(0)).unwrap();
        wal.compact_until(1).unwrap();
        wal.wait(wal.written()).unwrap();
        let sealed = std::fs::read(layout.log(0)).unwrap();
        assert!(sealed.len() > log0.len());
        j.let_go();
        drop(wal);
        std::fs::write(layout.log(0), &log0).unwrap();
        assert_eq!(redo(&root, Redo::Eager).unwrap().written, 1);
        assert_eq!(std::fs::read(layout.log(0)).unwrap(), sealed);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A frame is never on disk before a file it rests on: a blob's sync
    /// held while its commit is appended and waited for on a thread of its
    /// own, and another log's wait syncing the journal meanwhile. A power
    /// cut then, the blob never synced, finds no record of the commit on
    /// disk.
    #[test]
    fn no_frame_is_on_disk_before_a_file_it_rests_on() {
        let root = scratch("first");
        let (j, pool) = journaled(&root);
        let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
        let blob = root.join("blob");
        std::fs::write(&blob, b"bytes").unwrap();
        let (began, held) = (mpsc::channel::<()>(), mpsc::channel::<()>());
        let (tell, go) = (Mutex::new(began.0), Mutex::new(held.1));
        *lock(&a.0.files_first) = Some(Arc::new(move || {
            let _ = lock(&tell).send(());
            let _ = lock(&go).recv();
            Ok(())
        }));
        a.sync_first([blob]);
        let on_disk = std::thread::scope(|s| {
            let a = &a;
            let commit = s.spawn(move || {
                let n = a.append(&[json!("commit")])?;
                a.wait(n)
            });
            began.1.recv().unwrap();
            b.wait(b.append(&[json!("other")]).unwrap()).unwrap();
            // The power cut, now: of the segment, what a sync made durable.
            let segment = the_segment(&root);
            let len = lock(&j.test.synced)[&segment] as usize;
            let on_disk = std::fs::read(&segment).unwrap()[..len].to_vec();
            held.0.send(()).unwrap();
            commit.join().unwrap().unwrap();
            on_disk
        });
        let paths: Vec<&Path> = records(&on_disk[MAGIC.len()..])
            .0
            .into_iter()
            .filter_map(|(_, r)| match r {
                Record::Frame { path, .. } => Some(path),
                Record::Forget { .. } => None,
            })
            .collect();
        assert_eq!(paths, [Path::new("b/x.log")], "the commit's record on disk");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Have each write of a record fail having written half of it while
    /// `tear` says so, and each cut of a segment fail while `cut` does.
    fn tearing(j: &Journal, tear: Arc<AtomicBool>, cut: Arc<AtomicBool>) {
        *lock(&j.test.fault) = Some(Arc::new(move |f: &Fault<'_>| match f {
            Fault::Write { file, at, record } if tear.load(Ordering::SeqCst) => {
                file.write_all_at(&record[..record.len() / 2], *at)?;
                Err(io::Error::other("a write torn"))
            }
            Fault::Cut if cut.load(Ordering::SeqCst) => Err(io::Error::other("a cut failed")),
            _ => Ok(()),
        }));
    }

    /// A segment holding part of a record whose write failed, which could
    /// not be cut back then, is cut back before a checkpoint swaps it out:
    /// while it cannot be, the checkpoint fails, the segment stays the
    /// current one and no next one is left.
    #[test]
    fn a_torn_segment_is_cut_before_it_is_swapped_out() {
        let root = scratch("torn-swap");
        let (j, pool) = journaled(&root);
        let a = log(&root, "a", &pool);
        a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
        let (tear, cut) = (
            Arc::new(AtomicBool::new(true)),
            Arc::new(AtomicBool::new(true)),
        );
        tearing(&j, tear.clone(), cut.clone());
        assert!(a.append(&[json!("a1")]).is_err());
        tear.store(false, Ordering::SeqCst);
        let first = the_segment(&root);
        assert!(j.checkpoint().is_err(), "swapped out torn");
        assert_eq!(the_segments(&root).len(), 1, "a next segment left");
        assert_eq!(the_segment(&root), first);
        cut.store(false, Ordering::SeqCst);
        j.checkpoint_until(2, false).unwrap();
        let old = std::fs::read(&first).unwrap();
        assert_eq!(MAGIC.len() + records(&old[MAGIC.len()..]).1, old.len());
        a.wait(a.append(&[json!("a2")]).unwrap()).unwrap();
        j.let_go();
        drop(a);
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(
            frames(&root.join("a").join("x.log")),
            vec![vec![json!("a0")], vec![json!("a2")]]
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Part of a record after a segment's last whole one ends nothing by
    /// itself: the next segment's records are taken where their numbers
    /// follow on, and not where they do not.
    #[test]
    fn a_torn_tail_ends_nothing_where_the_next_segment_follows_on() {
        let root = scratch("torn-tail");
        let f: Vec<Vec<u8>> = (0..4).map(|i| frame(&[json!(i)])).collect();
        let at = |i: usize| f[..i].iter().map(Vec::len).sum::<usize>() as u64;
        for (second, want) in [(3, 4), (4, 2)] {
            std::fs::write(root.join("a.log"), b"").unwrap();
            let mut one = segment(
                1,
                &[
                    (FRAME, "a.log", at(0), &f[0]),
                    (FRAME, "a.log", at(1), &f[1]),
                ],
            );
            let torn = segment(3, &[(FRAME, "a.log", at(2), &f[2])]);
            one.extend_from_slice(&torn[MAGIC.len()..MAGIC.len() + 10]);
            put_segment(&root, 1, &one);
            put_segment(
                &root,
                2,
                &segment(
                    second,
                    &[
                        (FRAME, "a.log", at(2), &f[2]),
                        (FRAME, "a.log", at(3), &f[3]),
                    ],
                ),
            );
            assert_eq!(
                redo(&root, Redo::Eager).unwrap().records,
                want,
                "numbered from {second}"
            );
            assert_eq!(
                frames(&root.join("a.log")),
                f[..want as usize]
                    .iter()
                    .map(|b| scan(b).unwrap().0[0].clone())
                    .collect::<Vec<_>>()
            );
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A segment whose making failed is removed, and the next checkpoint
    /// makes it; one found there all the same, a stray, is made anew.
    #[test]
    fn a_segment_whose_making_failed_is_made_again() {
        let root = scratch("stray");
        let (j, pool) = journaled(&root);
        let a = log(&root, "a", &pool);
        a.wait(a.append(&[json!(0)]).unwrap()).unwrap();
        let fail = Arc::new(AtomicBool::new(true));
        let failing = fail.clone();
        *lock(&j.test.fault) = Some(Arc::new(move |f: &Fault<'_>| match f {
            Fault::Make if failing.load(Ordering::SeqCst) => {
                Err(io::Error::other("a segment's making failed"))
            }
            _ => Ok(()),
        }));
        let dir = root.join(DIR);
        assert!(j.checkpoint().is_err());
        assert!(!segment_path(&dir, 2).exists(), "a stray left");
        fail.store(false, Ordering::SeqCst);
        j.checkpoint().unwrap();
        a.wait(a.append(&[json!(1)]).unwrap()).unwrap();
        std::fs::write(segment_path(&dir, 3), b"a stray").unwrap();
        j.checkpoint().unwrap();
        assert_eq!(std::fs::read(segment_path(&dir, 3)).unwrap(), MAGIC);
        a.wait(a.append(&[json!(2)]).unwrap()).unwrap();
        j.let_go();
        drop(a);
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(
            frames(&root.join("a").join("x.log")),
            vec![vec![json!(0)], vec![json!(1)], vec![json!(2)]]
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A frame whose append failed, cut back with the cut never synced, a
    /// shorter frame journaled in its place: a power cut can leave the
    /// longer one's bytes after the shorter's, a whole frame among them.
    /// The start cuts the file at the end of the last record it took, and
    /// the log opened then holds the journaled frames alone.
    #[test]
    fn what_a_longer_frame_left_after_the_last_record_is_cut() {
        let root = scratch("left");
        let (a, c) = (frame(&[json!("a")]), frame(&[json!("c")]));
        let mut file = a.clone();
        file.extend(vec![b'x'; c.len()]);
        file.extend(frame(&[json!("never taken")]));
        std::fs::write(root.join("a.log"), &file).unwrap();
        put_segment(
            &root,
            1,
            &segment(
                1,
                &[
                    (FRAME, "a.log", 0, &a),
                    (FRAME, "a.log", a.len() as u64, &c),
                ],
            ),
        );
        redo(&root, Redo::Eager).unwrap();
        let (_, got) = Wal::open(&root.join("a.log"), None).unwrap();
        assert_eq!(got, vec![vec![json!("a")], vec![json!("c")]]);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A segment of 16 MiB of records round-robin over a few hundred files
    /// is redone a record at a time: no buffer holds more than a record's
    /// bytes, let alone the segment. Every frame is put back, each file
    /// byte for byte its frames in order; adopting or not, the same. Of a
    /// file whose records run on both sides of a `forget` of its directory,
    /// only those after it; of one whose records are all before it, none.
    #[test]
    fn a_large_segment_is_redone_a_record_at_a_time() {
        let root = scratch("large");
        let files = 300;
        let names: Vec<String> = (0..files).map(|i| format!("f{i}.log")).collect();
        let mut frames: Vec<Vec<u8>> = Vec::new();
        let mut at = vec![0u64; files];
        let mut want = vec![Vec::new(); files];
        let mut placed = Vec::new();
        let mut i = 0;
        while frames.iter().map(Vec::len).sum::<usize>() < 16 << 20 {
            let k = i % files;
            let f = frame(&[json!({ "i": i, "pad": "x".repeat(2000 + i % 97) })]);
            placed.push((k, at[k]));
            at[k] += f.len() as u64;
            want[k].extend_from_slice(&f);
            frames.push(f);
            i += 1;
        }
        let mut records: Vec<(u8, &str, u64, &[u8])> = placed
            .iter()
            .zip(&frames)
            .map(|(&(k, offset), f)| (FRAME, names[k].as_str(), offset, &f[..]))
            .collect();
        // In the middle, `d/g.log` and `d/h.log` written, `d` forgotten,
        // and `d/g.log` written again from its start, its first run longer.
        let old: Vec<Vec<u8>> = (0..3)
            .map(|i| frame(&[json!({ "old": i, "pad": "o".repeat(500) })]))
            .collect();
        let new: Vec<Vec<u8>> = (0..2).map(|i| frame(&[json!({ "new": i })])).collect();
        let runs = |fs: &[Vec<u8>]| {
            let mut at = 0;
            fs.iter()
                .map(|f| {
                    at += f.len() as u64;
                    at - f.len() as u64
                })
                .collect::<Vec<u64>>()
        };
        let (old_at, new_at) = (runs(&old), runs(&new));
        let mut middle: Vec<(u8, &str, u64, &[u8])> = Vec::new();
        for (f, &o) in old.iter().zip(&old_at) {
            middle.push((FRAME, "d/g.log", o, f));
            middle.push((FRAME, "d/h.log", o, f));
        }
        middle.push((FORGET, "d", 0, b""));
        for (f, &o) in new.iter().zip(&new_at) {
            middle.push((FRAME, "d/g.log", o, f));
        }
        let half = records.len() / 2;
        records.splice(half..half, middle.iter().copied());
        let data = segment(1, &records);
        assert!(data.len() > 16 << 20);
        let start = |way: Redo| {
            put_segment(&root, 1, &data);
            std::fs::create_dir_all(root.join("d")).unwrap();
            for n in names
                .iter()
                .map(String::as_str)
                .chain(["d/g.log", "d/h.log"])
            {
                std::fs::write(root.join(n), b"").unwrap();
            }
            HELD.set(0);
            let done = redo(&root, way).unwrap();
            (done, HELD.get())
        };
        let records = records.len() as u64;
        for way in [Redo::Eager, Redo::Adopting] {
            let (mut done, most) = start(way);
            assert_eq!(done.adopted.take().is_some(), way == Redo::Adopting);
            assert_eq!(
                done,
                Redone {
                    segments: 1,
                    records,
                    written: (frames.len() + new.len()) as u64,
                    files: match way {
                        Redo::Eager => files + 1,
                        Redo::Adopting => 0,
                    },
                    adopted: None,
                },
                "{way:?}"
            );
            let largest = frames.iter().map(Vec::len).max().unwrap();
            assert!(
                most < 4 * largest,
                "{most} bytes held, the largest record {largest}"
            );
            for (n, w) in names.iter().zip(&want) {
                assert!(std::fs::read(root.join(n)).unwrap() == *w, "{n}");
            }
            assert_eq!(std::fs::read(root.join("d/g.log")).unwrap(), new.concat());
            assert_eq!(std::fs::read(root.join("d/h.log")).unwrap(), b"");
            assert_eq!(the_segments(&root).is_empty(), way == Redo::Eager);
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A start as the server's: `redo` adopting where it can, and the
    /// journal opened with what it adopted, with no checkpoint thread, and
    /// a pool of logs written to it. Answers what `redo` did, its
    /// adoption taken.
    fn adopting(root: &Path) -> (Redone, Arc<Journal>, Arc<Files>) {
        let mut done = redo(root, Redo::Adopting).unwrap();
        let j = Journal::open_with(root, done.adopted.take(), false).unwrap();
        let pool = Files::with_journal(16, j.clone());
        (done, j, pool)
    }

    /// What a power cut leaves of the files the journal `from` synced,
    /// carried to `to`, opened by a start after it was let go: the start
    /// syncs none of them, so a power cut now leaves them as `from`'s syncs
    /// did, until `to` syncs them again.
    fn carry(from: &Journal, to: &Journal) {
        let synced = lock(&from.test.synced).clone();
        lock(&to.test.synced).extend(synced);
    }

    fn logs_of(root: &Path, names: &[&str]) -> Vec<PathBuf> {
        names.iter().map(|n| root.join(n).join("x.log")).collect()
    }

    fn read_all(paths: &[PathBuf]) -> Vec<Vec<u8>> {
        paths.iter().map(|p| std::fs::read(p).unwrap()).collect()
    }

    /// A run killed with two segments, `a` and `b` written to and waited
    /// for in each, `c` only in the first, and one record of `a` never
    /// waited for: the journal, let go, and its logs' paths `a`, `b`, `c`.
    fn killed_with_two_segments(root: &Path) -> (Arc<Journal>, Vec<PathBuf>) {
        let (j, pool) = journaled(root);
        let names = ["a", "b", "c"];
        let wals: Vec<Wal> = names.iter().map(|n| log(root, n, &pool)).collect();
        for i in 0..6 {
            let w = &wals[i % 3];
            w.wait(w.append(&[json!(i)]).unwrap()).unwrap();
        }
        // A checkpoint killed after its first step: two segments.
        j.checkpoint_until(1, false).unwrap();
        for i in 6..10 {
            let w = &wals[i % 2];
            w.wait(w.append(&[json!(i)]).unwrap()).unwrap();
        }
        wals[0].append(&[json!("never waited for")]).unwrap();
        j.let_go();
        drop(wals);
        assert_eq!(the_segments(root).len(), 2);
        (j, logs_of(root, &names))
    }

    /// Which sets of the segments `before` a power cut can bring back after
    /// a checkpoint's deletions and syncs of the directory, `ops` in order:
    /// one a sync followed is not undone, one not yet made is, and one in
    /// between may be. Each as whether each segment is back.
    fn leavable(before: &[(PathBuf, Vec<u8>)], ops: &[DirOp]) -> Vec<Vec<bool>> {
        let can = |back: &[bool]| {
            (0..=ops.len()).any(|t| {
                before.iter().zip(back).all(|((path, _), &back)| {
                    let at = ops[..t]
                        .iter()
                        .position(|o| matches!(o, DirOp::Unlinked(p) if p == path));
                    match at {
                        None => back,
                        Some(i) if ops[i..t].contains(&DirOp::Synced) => !back,
                        Some(_) => true,
                    }
                })
            })
        };
        (0..1u32 << before.len())
            .map(|s| (0..before.len()).map(|i| s & (1 << i) != 0).collect())
            .filter(|back: &Vec<bool>| can(back))
            .collect()
    }

    /// Killed with two segments, every record whole; a start adopts them,
    /// syncing nothing; new records are appended to it and waited for; a
    /// power cut before its first checkpoint, every file as it was last
    /// synced: the next start recovers every record answered, those before
    /// the kill and after, in order, byte for byte.
    #[test]
    fn an_adopting_start_then_a_power_cut_loses_nothing() {
        let root = scratch("adopt-cut");
        let (old, paths) = killed_with_two_segments(&root);
        let (done, j, pool) = adopting(&root);
        assert_eq!((done.segments, done.files), (2, 0));
        carry(&old, &j);
        let wals: Vec<Wal> = ["a", "b"].iter().map(|n| log(&root, n, &pool)).collect();
        for (i, w) in wals.iter().enumerate() {
            w.wait(w.append(&[json!(format!("new {i}"))]).unwrap())
                .unwrap();
        }
        let want = read_all(&paths);
        j.let_go();
        drop(wals);
        power_cut(&j, &paths, &[]);
        redo(&root, Redo::Eager).unwrap();
        assert_eq!(read_all(&paths), want);
        assert_eq!(frames(&paths[0]).len(), 6);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// As before, the power cut after the first checkpoint synced the
    /// adopted segments and the logs they name, `c` among them though no
    /// record of it was appended since, and before its deletions are
    /// durable: of each set of segments that deleting them lowest first,
    /// the directory synced after each, can leave, a start recovers every
    /// answered record, byte for byte.
    #[test]
    fn an_adopting_starts_checkpoint_undone() {
        let root = scratch("adopt-undone");
        let (old, paths) = killed_with_two_segments(&root);
        let (_, j, pool) = adopting(&root);
        carry(&old, &j);
        let wals: Vec<Wal> = ["a", "b"].iter().map(|n| log(&root, n, &pool)).collect();
        wals[1]
            .wait(wals[1].append(&[json!("new")]).unwrap())
            .unwrap();
        let before = the_segments(&root);
        assert_eq!(before.len(), 3);
        lock(&j.test.dir).clear();
        j.checkpoint().unwrap();
        assert_eq!(the_segments(&root).len(), 1);
        wals[0]
            .wait(wals[0].append(&[json!("after")]).unwrap())
            .unwrap();
        let want = read_all(&paths);
        j.let_go();
        drop(wals);
        let ops = lock(&j.test.dir).clone();
        let after = the_segments(&root);
        let sets = leavable(&before, &ops);
        assert_eq!(sets.len(), 4, "{sets:?}");
        for back in sets {
            for (p, bytes) in paths.iter().zip(&want) {
                std::fs::write(p, bytes).unwrap();
            }
            for (p, _) in the_segments(&root) {
                std::fs::remove_file(p).unwrap();
            }
            for (p, bytes) in &after {
                std::fs::write(p, bytes).unwrap();
            }
            let gone: Vec<(PathBuf, Vec<u8>)> = before
                .iter()
                .zip(&back)
                .filter(|(_, b)| **b)
                .map(|(s, _)| s.clone())
                .collect();
            power_cut(&j, &paths, &gone);
            redo(&root, Redo::Eager).unwrap();
            assert_eq!(read_all(&paths), want, "{back:?}");
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Killed with a record waited for and one not, then a segment begun
    /// whose record, never waited for either, the system wrote out without
    /// the one before it; a start adopts, and a power cut comes at once,
    /// nothing synced since the kill: the next start recovers the record
    /// answered, takes nothing after the gap, and leaves no segment.
    #[test]
    fn a_power_cut_at_once_after_an_adopting_start() {
        let root = scratch("adopt-at-once");
        let (old, pool) = journaled(&root);
        let (a, b) = (log(&root, "a", &pool), log(&root, "b", &pool));
        a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
        a.append(&[json!("a1")]).unwrap();
        old.checkpoint_until(1, false).unwrap();
        b.append(&[json!("b0")]).unwrap();
        old.let_go();
        drop((a, b));
        let second = the_segment(&root);
        let (done, j, _pool) = adopting(&root);
        assert_eq!(done.records, 3);
        carry(&old, &j);
        let written = std::fs::read(&second).unwrap();
        j.let_go();
        let paths = logs_of(&root, &["a", "b"]);
        power_cut(&j, &paths, &[]);
        // Of the second segment, its record reached the disk all the same.
        std::fs::write(&second, &written).unwrap();
        let done = redo(&root, Redo::Adopting).unwrap();
        assert_eq!(done.records, 1);
        assert!(done.adopted.is_none(), "records after a gap adopted");
        assert!(the_segments(&root).is_empty());
        assert_eq!(frames(&paths[0]), vec![vec![json!("a0")]]);
        assert!(frames(&paths[1]).is_empty());
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A start that finds a torn record, or records after a gap, makes
    /// every file durable and leaves no segment; a run after it, killed,
    /// and a start adopting its segment recover it all.
    #[test]
    fn a_start_not_taking_every_record_adopts_nothing() {
        let f: Vec<Vec<u8>> = (0..4).map(|i| frame(&[json!(i)])).collect();
        let at = |i: usize| f[..i].iter().map(Vec::len).sum::<usize>() as u64;
        for torn in [true, false] {
            let root = scratch(&format!("adopt-none-{torn}"));
            std::fs::create_dir_all(root.join("a")).unwrap();
            std::fs::write(root.join("a").join("x.log"), b"").unwrap();
            let one = segment(
                1,
                &[
                    (FRAME, "a/x.log", at(0), &f[0]),
                    (FRAME, "a/x.log", at(1), &f[1]),
                ],
            );
            let next = segment(3, &[(FRAME, "a/x.log", at(2), &f[2])]);
            match torn {
                true => {
                    let mut one = one;
                    one.extend_from_slice(&next[MAGIC.len()..MAGIC.len() + 10]);
                    one.extend_from_slice(&[0; 100]);
                    put_segment(&root, 1, &one);
                }
                false => {
                    put_segment(&root, 1, &one);
                    put_segment(&root, 2, &segment(4, &[(FRAME, "a/x.log", 99, &f[3])]));
                }
            }
            STARTED.take();
            let done = redo(&root, Redo::Adopting).unwrap();
            assert!(done.adopted.is_none(), "torn {torn}");
            assert_eq!((done.records, done.files), (2, 1), "torn {torn}");
            assert!(STARTED.take().contains(&Started::Synced), "torn {torn}");
            assert!(the_segments(&root).is_empty(), "torn {torn}");
            let (j, pool) = journaled(&root);
            let a = log(&root, "a", &pool);
            a.wait(a.append(&[json!("after")]).unwrap()).unwrap();
            j.let_go();
            drop(a);
            let (done, j, _pool) = adopting(&root);
            assert_eq!(done.segments, 1, "torn {torn}");
            assert_eq!(lock(&j.state).first, 1, "torn {torn}");
            assert_eq!(
                frames(&root.join("a").join("x.log")),
                vec![vec![json!(0)], vec![json!(1)], vec![json!("after")]],
                "torn {torn}"
            );
            j.let_go();
            let _ = std::fs::remove_dir_all(&root);
        }
    }

    /// Two adoptions in a row, killed before any checkpoint: segment and
    /// record numbers go on in order, nothing is lost, and a `forget` in
    /// the first run's segment still keeps its path's earlier frames out
    /// of what replaced it at the third start.
    #[test]
    fn two_adoptions_in_a_row() {
        let root = scratch("adopt-twice");
        let (j1, pool) = journaled(&root);
        let (a, p) = (log(&root, "a", &pool), log(&root, "p", &pool));
        let paths = logs_of(&root, &["a", "p"]);
        a.wait(a.append(&[json!("a0")]).unwrap()).unwrap();
        p.wait(p.append(&[json!("p0")]).unwrap()).unwrap();
        j1.forget(&root.join("p")).unwrap();
        drop(p);
        let replaced = frame(&[json!("another")]);
        std::fs::write(&paths[1], &replaced).unwrap();
        a.wait(a.append(&[json!("a1")]).unwrap()).unwrap();
        let w1 = lock(&j1.state).written;
        j1.let_go();
        drop(a);
        let (_, j2, pool) = adopting(&root);
        {
            let st = lock(&j2.state);
            assert_eq!((st.first, st.number, st.written), (1, 2, w1));
        }
        let a = log(&root, "a", &pool);
        a.wait(a.append(&[json!("a2")]).unwrap()).unwrap();
        let w2 = lock(&j2.state).written;
        assert_eq!(w2, w1 + 1);
        j2.let_go();
        drop(a);
        let (done, j3, pool) = adopting(&root);
        assert_eq!(done.records, w2);
        assert_eq!(std::fs::read(&paths[1]).unwrap(), replaced);
        {
            let st = lock(&j3.state);
            assert_eq!((st.first, st.number, st.written), (1, 3, w2));
        }
        let a = log(&root, "a", &pool);
        a.wait(a.append(&[json!("a3")]).unwrap()).unwrap();
        j3.let_go();
        drop(a);
        assert_eq!(the_segments(&root).len(), 3);
        assert_eq!(redo(&root, Redo::Eager).unwrap().records, w2 + 1);
        assert_eq!(
            frames(&paths[0]),
            ["a0", "a1", "a2", "a3"]
                .iter()
                .map(|s| vec![json!(s)])
                .collect::<Vec<_>>()
        );
        assert_eq!(std::fs::read(&paths[1]).unwrap(), replaced);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// An adopting start makes no sync of any log's file and deletes no
    /// segment; the journal's first checkpoint, on its thread `QUIET` after
    /// the open with nothing appended, and not before, makes the logs
    /// durable and leaves the new segment alone.
    #[test]
    fn an_adopting_start_syncs_and_deletes_nothing() {
        let root = scratch("adopt-nothing");
        let (_, paths) = killed_with_two_segments(&root);
        let before = the_segments(&root);
        STARTED.take();
        let mut done = redo(&root, Redo::Adopting).unwrap();
        assert_eq!(STARTED.take(), vec![], "synced or deleted");
        assert_eq!(done.files, 0);
        assert_eq!(the_segments(&root), before);
        let t = Instant::now();
        let j = Journal::open(&root, done.adopted.take()).unwrap();
        // Listed by number alone: the thread deletes them meanwhile.
        let dir = root.join(DIR);
        while (segments(&dir).unwrap().len() > 1 || j.bytes() > 0) && t.elapsed() < QUIET * 3 {
            std::thread::sleep(Duration::from_millis(5));
        }
        // The one its checkpoint began, after the one it opened with (3).
        let left: Vec<u64> = segments(&dir).unwrap();
        assert_eq!(left, vec![4]);
        assert_eq!(lock(&j.state).number, 4);
        assert!(t.elapsed() >= QUIET, "not QUIET after: {:?}", t.elapsed());
        assert!(t.elapsed() < QUIET * 2, "{:?}", t.elapsed());
        let synced = lock(&j.test.synced).clone();
        for p in &paths {
            assert!(synced.contains_key(p), "{} not made durable", p.display());
        }
        assert_eq!(j.bytes(), 0);
        j.close().unwrap();
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Appends naming `FILES` logs since the checkpoint before make the
    /// next due, the segment far from full and no quiet passed; fewer do
    /// not, and those a start adopted are not counted.
    #[test]
    fn many_logs_make_a_checkpoint_due() {
        let root = scratch("files-due");
        killed_with_two_segments(&root);
        let (_, j, pool) = adopting(&root);
        j.test.files.store(3, Ordering::SeqCst);
        assert_eq!(lock(&j.state).touched.len(), 3, "adopted");
        let due = || lock(&j.signal.quiet).due;
        let wals: Vec<Wal> = ["x", "y", "z"]
            .iter()
            .map(|n| log(&root, n, &pool))
            .collect();
        for w in &wals[..2] {
            w.append(&[json!(1)]).unwrap();
            w.append(&[json!(2)]).unwrap();
        }
        assert!(!due(), "due with two logs appended to");
        wals[2].append(&[json!(1)]).unwrap();
        assert!(due(), "not due with three");
        // Counted from the swap: one log after it is not three.
        lock(&j.signal.quiet).due = false;
        j.checkpoint().unwrap();
        wals[0].append(&[json!(3)]).unwrap();
        assert!(!due());
        j.let_go();
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A wait on a record after an adopting start syncs the adopted
    /// segments first: their sync failing, the wait fails and no record is
    /// counted durable.
    #[test]
    fn a_wait_after_an_adopting_start_syncs_the_adopted_first() {
        let root = scratch("adopt-first");
        killed_with_two_segments(&root);
        let (_, j, pool) = adopting(&root);
        *lock(&j.test.fault) = Some(Arc::new(|f: &Fault<'_>| match f {
            Fault::Older => Err(io::Error::other("an adopted segment's sync failed")),
            _ => Ok(()),
        }));
        let a = log(&root, "a", &pool);
        let n = a.append(&[json!("new")]).unwrap();
        assert!(
            a.wait(n).is_err(),
            "answered before the adopted segments synced"
        );
        assert!(!a.is_durable(n));
        assert_eq!(j.durable.load(Ordering::SeqCst), 0);
        let _ = std::fs::remove_dir_all(&root);
    }
}