diff --git a/apps/origin-src/benches/packs.rs b/apps/origin-src/benches/packs.rs index c0e15789..4dc11328 100644 --- a/apps/origin-src/benches/packs.rs +++ b/apps/origin-src/benches/packs.rs @@ -1,6 +1,6 @@ -//! Packs: writing and reading a million statements loose and packed, -//! compacting them, and looking objects up across several packs. Run on a -//! real disk: syncs cost nothing on a RAM-backed file system. +//! Benchmarks for packs: writing and reading a million statements loose and +//! packed, compacting them, and finding objects across several packs. Run +//! on a real disk: syncs cost nothing on a RAM-backed file system. use std::path::PathBuf; use std::sync::{LazyLock, OnceLock}; @@ -25,7 +25,8 @@ static ROOT: OnceLock = OnceLock::new(); /// How many statements the large stores hold. const STATEMENTS: usize = 1_000_000; -/// `count` distinct statements, like a CI runner issues, from `seed` on. +/// Returns `count` distinct statements, like those a CI runner issues, +/// numbered from `seed`. fn statements(seed: usize, count: usize) -> Vec { (seed..seed + count) .map(|seed| { @@ -57,17 +58,16 @@ fn store() -> Fixture { (dir, store) } -/// A store of the million statements, loose. +/// A store holding the million statements as loose objects. fn loose() -> Fixture { let (dir, store) = store(); store.write_all(&STATEMENTS_1M).unwrap(); (dir, store) } -/// A store of the million statements in `packs` packs, halving in size so -/// compaction keeps them apart. The first pack takes the remainder: each -/// later one is then at most half the one before, which compaction never -/// merges into it. +/// A store holding the million statements in `packs` packs. Each pack after +/// the first is at most half the size of the one before, so compaction never +/// merges them. The first pack takes the remainder. fn packed(packs: u32) -> Fixture { let (dir, store) = store(); let later: usize = (1..packs).map(|pack| STATEMENTS >> (pack + 1)).sum(); @@ -103,7 +103,7 @@ static PACKED: [LazyLock Fixture>; 3] = [ LazyLock::new(|| packed(16)), ]; -/// The large packed store with `packs` packs. +/// The packed store with `packs` packs: 1, 4 or 16. fn packed_store(packs: u32) -> &'static Store { let index = match packs { 1 => 0, @@ -125,8 +125,7 @@ fn write_loose(bencher: Bencher<'_, '_>) { .bench_local_refs(|(_, store)| store.write_all(&STATEMENTS_1M).unwrap()); } -/// Compacting a million loose statements into one pack: what packing costs -/// on top of writing them loose. +/// Compacting a million loose statements into one pack. #[divan::bench(sample_count = 3, sample_size = 1)] fn compact(bencher: Bencher<'_, '_>) { bencher @@ -135,8 +134,8 @@ fn compact(bencher: Bencher<'_, '_>) { .bench_local_refs(|(_, store)| store.compact().unwrap()); } -/// Reading back every statement of a million, in id order, from one -/// thread. +/// Reading every statement of a million back, in id order, from one thread, +/// loose or packed. #[divan::bench(args = ["loose", "packed"], sample_count = 3, sample_size = 1)] fn read_all(bencher: Bencher<'_, '_>, layout: &str) { let store = match layout { @@ -152,7 +151,7 @@ fn read_all(bencher: Bencher<'_, '_>, layout: &str) { }); } -/// Reading one statement of a million, loose or in the smallest of +/// Reading one statement of a million, loose or from the smallest of /// `packs` packs, which is searched last. #[divan::bench(args = [0, 1, 4, 16])] fn read_one(bencher: Bencher<'_, '_>, packs: u32) { @@ -167,8 +166,8 @@ fn read_one(bencher: Bencher<'_, '_>, packs: u32) { } /// Looking up an object the store doesn't have, among a million statements -/// loose or in `packs` packs: every pack is searched and the manifest -/// reread. +/// loose or in `packs` packs. Every pack is searched and the manifest is +/// read again. #[divan::bench(args = [0, 1, 4, 16])] fn contains_absent(bencher: Bencher<'_, '_>, packs: u32) { let store = if packs == 0 { diff --git a/apps/origin-src/benches/snapshot.rs b/apps/origin-src/benches/snapshot.rs index 3a19b625..48958aa4 100644 --- a/apps/origin-src/benches/snapshot.rs +++ b/apps/origin-src/benches/snapshot.rs @@ -1,5 +1,6 @@ -//! Snapshotting a working copy: the cost behind every command that reads it. -//! Objects are written durably, as the commands write them. +//! Benchmarks for snapshotting a working copy, which every command that +//! reads the working copy does. Objects are written durably, as the commands +//! write them. use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/apps/origin-src/benches/store.rs b/apps/origin-src/benches/store.rs index 5792f0b5..75eeb7c6 100644 --- a/apps/origin-src/benches/store.rs +++ b/apps/origin-src/benches/store.rs @@ -1,6 +1,6 @@ -//! Store throughput: durable writes with and without batching, verified -//! reads, target appends, and the record index. Run on a real disk: syncs -//! cost nothing on a RAM-backed file system. +//! Benchmarks for the store: durable writes with and without batching, +//! verified reads, target appends, and the record index. Run on a real disk: +//! syncs cost nothing on a RAM-backed file system. use std::fs::File; use std::io; @@ -23,7 +23,8 @@ fn main() { divan::main(); } -/// Source-code-like content, which compresses like real files do. +/// Returns `len` bytes of source-code-like content, distinct for each +/// `seed`, which compresses like real files do. fn content(len: usize, seed: usize) -> Vec { format!("fn item_{seed}() -> usize {{ {seed} }}\n") .into_bytes() @@ -46,8 +47,8 @@ fn store_on(platform: P) -> (tempfile::TempDir, Store

) { (dir, store) } -/// Writing new objects one batch each: a file and a directory sync per -/// object. +/// Writing new objects one batch each, which costs a file sync and a +/// directory sync per object. #[divan::bench(args = [4 * 1024, 1024 * 1024], sample_count = 20)] fn write_unbatched(bencher: Bencher<'_, '_>, len: usize) { let (_dir, store) = store(); @@ -61,8 +62,8 @@ fn write_unbatched(bencher: Bencher<'_, '_>, len: usize) { .bench_local_refs(|object| store.write_all(slice::from_ref(object)).unwrap()); } -/// Writing new 4 KiB objects in one batch, staged from every core: the -/// first snapshot of a tree of that many files. +/// Writing `count` new 4 KiB objects in one batch, staged from every core, +/// like the first snapshot of a tree of that many files. #[divan::bench(args = [1_000, 20_000], sample_count = 5, sample_size = 1)] fn write_batch(bencher: Bencher<'_, '_>, count: usize) { let objects: Vec<_> = (0..count) @@ -75,7 +76,7 @@ fn write_batch(bencher: Bencher<'_, '_>, count: usize) { } /// Walking a store of 20k objects for the temporary files crashed writes -/// left: what garbage collection pays. +/// left behind, as garbage collection does. #[divan::bench(sample_count = 20)] fn remove_stale_temps(bencher: Bencher<'_, '_>) { let (_dir, store) = store(); @@ -86,9 +87,9 @@ fn remove_stale_temps(bencher: Bencher<'_, '_>) { bencher.bench(|| store.remove_stale_temps().unwrap()); } -/// Writing objects the store already has: the common case when -/// snapshotting. The batch syncs the directory of each, for the writer that -/// renamed it there may not have yet. +/// Writing objects the store already has, the common case when +/// snapshotting. The batch still syncs each object's directory, since the +/// writer that put the object there may not have synced it yet. #[divan::bench(args = [1, 1_000, 20_000])] fn write_existing(bencher: Bencher<'_, '_>, count: usize) { let (_dir, store) = store(); @@ -101,7 +102,7 @@ fn write_existing(bencher: Bencher<'_, '_>, count: usize) { .bench(|| store.write_all(black_box(&objects)).unwrap()); } -/// Reading, decompressing, and verifying objects: the cost of checkouts. +/// Reading, decompressing and verifying an object, as checkouts do. #[divan::bench(args = [4 * 1024, 1024 * 1024])] fn read(bencher: Bencher<'_, '_>, len: usize) { let (_dir, store) = store(); @@ -112,7 +113,7 @@ fn read(bencher: Bencher<'_, '_>, len: usize) { .bench(|| store.read(black_box(object.id())).unwrap()); } -/// Appending an acceptance to a target: the durable part of every landing. +/// Appending an acceptance to a target, the durable step of every landing. #[divan::bench(sample_count = 20)] fn append(bencher: Bencher<'_, '_>) { let (_dir, store) = store(); @@ -135,9 +136,10 @@ fn append(bencher: Bencher<'_, '_>) { }); } -/// `count` records, as a busy repository receives them: a revision of one -/// of a hundred changes, evolving from that change's previous one, then nine -/// statements about it. +/// Returns `count` records like a busy repository receives them: every +/// tenth is a revision of one of a hundred changes, in turn, evolving from +/// that change's previous revision, and the nine after it are statements +/// about it. fn records(count: usize) -> Vec { let snapshot = TreeId::from(Tree::default().encode().id()); let mut heads = vec![None; 100]; @@ -176,7 +178,7 @@ fn records(count: usize) -> Vec { .collect() } -/// The native platform without syncs, to measure what syncs hide. +/// The native platform with every sync skipped, to measure what syncs cost. #[derive(Clone, Copy, Debug, Default)] struct NoSync; @@ -211,9 +213,9 @@ impl FileSystem for NoSync { } /// Writing new records in one batch, which indexes them, against blobs of -/// the same content, which aren't indexed: the difference is what indexing -/// costs, which [`NoSync`] shows apart from the syncs. One record is what -/// issuing a statement costs. +/// the same bytes, which aren't indexed. The difference is what indexing +/// costs; [`NoSync`] shows it without the syncs. A batch of one, a +/// revision, is the cost of writing a single record. #[divan::bench( types = [Native, NoSync], consts = [true, false], diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index 9927bf3d..14e86a59 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -1,43 +1,23 @@ -//! The record index: what reading every record would tell, without reading -//! them. It knows each change's revisions and heads (more than one head is -//! divergence), the statements about each record and those they claim to -//! supersede, the promotable statements by kind, issuer and declared -//! inputs, and the order this node received its records in. It also caches the input -//! digests of promotable statements, which take reading their subjects' -//! trees to compute. +//! The record index: lookups over a store's records without reading them. +//! It holds each change's revisions and heads, the statements about each +//! record and the statements claiming to supersede them, the promotable +//! statements by promotion group, and the order this node received its +//! records in. It also caches the input digests of promotable statements. //! -//! The index is derived from the store, so it is never trusted over it: a -//! missing or corrupt index is rebuilt from the store's records -//! ([`Index::rebuild`]), never fatal. A rebuild skips the objects that are -//! corrupt or don't decode, which readers can't use either, and reports -//! them ([`Skipped`]). +//! The index is a cache derived from the store. When it is missing or +//! corrupt, [`Index::open`] rebuilds it from the store's records. //! -//! On disk it is one append-only file, `index/log`: a header, then frames. -//! A frame is its payload's `u32` length, the payload, the first 8 bytes of -//! the payload's BLAKE3 hash, and the length again, so the last frame can be -//! checked from the end. A payload is what the index keeps of each record -//! of a batch, the mark that the batch at some offset was published, or -//! input digests computed since. +//! It is stored in one append-only file, `index/log`: a header, then +//! frames. [`Batch::commit`](crate::store::Batch::commit) appends a frame +//! with the batch's entries before it publishes the records, and a frame +//! marking them published after. Opening the index keeps the entries of +//! published batches, and of other batches only those whose records are in +//! the store. Batches append under a shared lock on `index/lock`, and a +//! rebuild takes it exclusively. //! -//! [`Batch::commit`](crate::store::Batch::commit) appends a batch's entries -//! before publishing its records, and the batch sync makes them durable -//! with the records, so indexing costs no sync of its own. Once the records -//! are published, it marks the batch, without syncing. Opening the index -//! trusts the marked batches, and checks that the records of the others are -//! in the store: those belong to batches that crashed, failed, or are being -//! published. A partial last frame is an append in progress, or one a crash -//! cut short, and is skipped. Any other damage rebuilds the index. -//! -//! Batches append under a shared lock on `index/lock`, held from appending -//! their entries to marking them, and appends serialize on an exclusive -//! lock of the log itself. A rebuild holds `index/lock` exclusively, so it -//! never misses a batch: it sees every batch's records published, or none -//! of them appended yet. Rebuilding keeps the arrival order the old log -//! still knows, and puts the records it didn't after them. -//! -//! The directory also holds `index/supersession`, which isn't an index -//! lock: [`Annotations::supersede`](crate::annotations::Annotations::supersede) -//! holds it to read an issuer's current statement and issue the next. +//! The directory also holds `index/supersession`, a separate lock that +//! [`Annotations::supersede`](crate::annotations::Annotations::supersede) +//! takes. use std::borrow::Cow; use std::collections::{HashMap, HashSet}; @@ -66,8 +46,9 @@ pub struct Index { changes: HashMap, /// The statements about each record, in arrival order. statements: HashMap>, - /// The statements claiming to supersede each statement. Only those from - /// the same issuer do, which reading them tells. + /// The statements claiming to supersede each statement. Only claims from + /// the statement's own issuer count, which the index doesn't check: it + /// doesn't keep issuers. superseders: HashMap>, /// The promotable statements, by their /// [promotion group](Statement::promotion_group), in arrival order. @@ -80,10 +61,10 @@ pub struct Index { /// The revisions of one change. #[derive(Clone, Debug, Default, PartialEq, Eq)] struct Change { - /// In arrival order. + /// The change's revisions, in arrival order. revisions: Vec, - /// The revisions another revision of the change evolves from: all but - /// the heads. + /// The revisions that another revision of the change evolves from: every + /// revision but the heads. superseded: HashSet, } @@ -92,11 +73,11 @@ struct Change { pub struct Rebuilt { /// The index. pub index: Index, - /// The objects skipped, also reported on stderr. + /// The objects skipped, which the rebuild also reports on stderr. pub skipped: Vec, } -/// An object a rebuild skips, since readers can't use it either. +/// An object a rebuild skips because it is unusable. #[derive(Debug, thiserror::Error)] pub enum Skipped { /// Its content doesn't hash to its id. @@ -110,7 +91,7 @@ pub enum Skipped { /// Why decompressing failed. error: io::Error, }, - /// It's a record that doesn't decode. + /// A record that doesn't decode. #[error("the index skips record {id}, which doesn't decode: {error}")] Undecodable { /// The record. @@ -142,10 +123,9 @@ impl Index { Ok(Self::rebuild_locked(store, &index)?.index) } - /// Reconstructs the index of `store` from its records, and replaces the - /// one on disk. Records the old index knew keep their arrival order. - /// Objects that are corrupt or don't decode are skipped, and reported on - /// stderr. + /// Rebuilds the index of `store` from its records and replaces the one on + /// disk. Records the old index knew keep their arrival order. Objects that + /// are corrupt or don't decode are skipped and reported on stderr. /// /// # Errors /// @@ -156,8 +136,8 @@ impl Index { Self::rebuild_locked(store, &old) } - /// Rebuilds the index while holding its lock exclusively, keeping the - /// arrival order of `old`. + /// Rebuilds the index, keeping the arrival order of `old`. The caller must + /// hold the index lock exclusively. fn rebuild_locked(store: &Store

, old: &Self) -> Result { let order: HashMap = old .arrivals @@ -190,8 +170,8 @@ impl Index { Ok(Rebuilt { index, skipped }) } - /// Reads as much of the index as is intact, returning whether all of it - /// was. A missing index is empty and not intact. + /// Reads as much of the index as is intact, and returns whether all of it + /// was. A missing index reads as empty and not intact. fn read(store: &Store

) -> Result<(Self, bool), StoreError> { let path = store.index_log(); let bytes = match fs::read(&path) { @@ -227,7 +207,7 @@ impl Index { Ok((index, tail != Tail::Damaged)) } - /// Adds a record, unless it's already indexed. + /// Adds the record of `entry`, unless it is already indexed. fn insert(&mut self, entry: Entry) { if !self.known.insert(entry.record()) { return; @@ -261,8 +241,8 @@ impl Index { } } - /// Every record indexed, in the order this node received them. A - /// position in it is a cursor: records received later come after it. + /// Every record indexed, in the order this node received them. A position + /// in this list works as a cursor: records received later come after it. #[must_use] pub fn arrivals(&self) -> &[RecordId] { &self.arrivals @@ -303,7 +283,7 @@ impl Index { } /// The statements claiming to supersede `statement`, in arrival order. - /// Only those from its issuer do. + /// Only claims from its issuer count, which the caller must check. #[must_use] pub fn superseders(&self, statement: StatementId) -> &[StatementId] { self.superseders.get(&statement).map_or(&[], Vec::as_slice) @@ -325,9 +305,9 @@ impl Index { self.digests.get(&statement).copied() } - /// Remembers the input digests of promotable statements, so they're - /// computed once. Since the index is a cache, they aren't synced: a - /// crash only costs computing them again. + /// Saves the input digests of promotable statements, so they are only + /// computed once. They are appended without a sync: after a crash they are + /// just computed again. /// /// # Errors /// @@ -346,33 +326,33 @@ impl Index { Ok(()) } - /// The one change whose id starts with `prefix`, a few hex digits. + /// Returns the one change whose id starts with `prefix`, a few hex digits. /// /// # Errors /// - /// Fails if no change, or more than one, has an id starting with - /// `prefix`. + /// Fails if `prefix` isn't hex digits, or if no change or more than one has + /// an id starting with it. pub fn find_change(&self, prefix: &str) -> Result { ChangeId::find(prefix, self.changes.keys().copied()) } - /// The one revision whose id starts with `prefix`, a few hex digits. + /// Returns the one revision whose id starts with `prefix`, a few hex digits. /// /// # Errors /// - /// Fails if no revision, or more than one, has an id starting with - /// `prefix`. + /// Fails if `prefix` isn't hex digits, or if no revision or more than one has + /// an id starting with it. pub fn find_revision(&self, prefix: &str) -> Result> { let revisions = self.changes.values().flat_map(|change| &change.revisions); RevisionId::find(prefix, revisions.copied()) } - /// The one statement whose id starts with `prefix`, a few hex digits. + /// Returns the one statement whose id starts with `prefix`, a few hex digits. /// /// # Errors /// - /// Fails if no statement, or more than one, has an id starting with - /// `prefix`. + /// Fails if `prefix` isn't hex digits, or if no statement or more than one has + /// an id starting with it. pub fn find_statement(&self, prefix: &str) -> Result> { StatementId::find(prefix, self.statements.values().flatten().copied()) } @@ -380,15 +360,15 @@ impl Index { /// Ids that can be named by a unique prefix of their hex digits. pub trait Prefixed: Copy + Ord + fmt::Display { - /// What the ids identify, for errors. + /// What the ids identify, such as `change`, for error messages. const WHAT: &str; - /// The one id of `ids` starting with `prefix`. + /// Returns the one id of `ids` that starts with `prefix`, ignoring case. /// /// # Errors /// - /// Fails if `prefix` isn't hex digits, or no id or more than one starts - /// with it. + /// Fails if `prefix` is empty or isn't hex digits, or if no id or more than + /// one starts with it. fn find(prefix: &str, ids: impl Iterator) -> Result> { let prefix = prefix.to_ascii_lowercase(); if prefix.is_empty() || !prefix.bytes().all(|byte| byte.is_ascii_hexdigit()) { @@ -426,13 +406,13 @@ pub type FindChangeError = FindError; /// An id prefix that doesn't name exactly one id. #[derive(Debug, PartialEq, Eq, thiserror::Error)] pub enum FindError { - /// It isn't hex digits. + /// The prefix isn't hex digits. #[error("`{0}` is not a {what} id", what = I::WHAT)] Invalid(String), - /// No id starts with it. + /// No id starts with the prefix. #[error("no {what} has an id starting with `{0}`", what = I::WHAT)] NotFound(String), - /// Several do. + /// More than one id starts with the prefix. #[error( "`{prefix}` could be any of the {what}s {}", matches.iter().map(ToString::to_string).collect::>().join(", "), @@ -446,7 +426,7 @@ pub enum FindError { }, } -/// What the index keeps of one record: its id, and the fields it's looked +/// What the index keeps of one record: its id and the fields it is looked /// up by. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Entry { @@ -466,8 +446,8 @@ pub(crate) enum Entry { } impl Entry { - /// The entry of `object`, or `None` if it isn't indexed: blobs and - /// trees. + /// Returns the entry of `object`, or `None` for the objects the index + /// doesn't keep: blobs and trees. /// /// # Errors /// @@ -513,10 +493,14 @@ impl Entry { Log::split(self.record()).1 } - /// Appends the entry: its record's kind and id, then for a revision its - /// change and a `u32` count of predecessors and their ids, and for a - /// statement its subject's kind and id, and the statement it supersedes - /// and its promotion group, each a 0 byte, or a 1 byte and the id. + /// Appends the entry's encoding to `out`: its record's kind and id, then + /// + /// - for a revision, its change, a `u32` count of predecessors, and their + /// ids; + /// - for a statement, its subject's kind and id, then the statement it + /// supersedes and its promotion group, each a 0 byte for none, or a 1 byte + /// and the id; + /// - for an acceptance, nothing more. fn write(&self, out: &mut Vec) { Log::write_record(self.record(), out); match self { @@ -579,14 +563,15 @@ impl Entry { } } -/// A frame of the log. +/// A frame of `index/log`. #[derive(Debug)] enum Frame<'a> { - /// The entries of a batch, appended before its records are published. + /// The entries of a batch's records, appended before the records are + /// published. Records(Cow<'a, [Entry]>), - /// The records of the batch at this offset are published. + /// Marks the batch whose frame starts at this offset as published. Published(u64), - /// Input digests of promotable statements, computed from the store. + /// Input digests of promotable statements. Digests(Cow<'a, [(StatementId, Digest)]>), } @@ -595,9 +580,9 @@ impl Frame<'_> { const PUBLISHED: u8 = 2; const DIGESTS: u8 = 3; - /// Encodes the frame: its payload's length, the payload (a tag and the - /// contents), a check, and the length again, so the last frame of a log - /// can be read backwards. + /// Encodes the frame: the payload's `u32` length, the payload (a tag and + /// the contents), a check, and the length again. The trailing length lets + /// the last frame of a log be read backwards. fn encode(&self) -> Vec { let mut out = vec![0; 4]; match self { @@ -660,14 +645,15 @@ impl Frame<'_> { } } -/// The format of `index/log`. +/// The format of `index/log`: a header, then frames. struct Log; impl Log { /// The start of every log, with the format's version. const HEADER: &[u8] = b"origin index 2\n"; - /// The length of a frame's check. + /// The length of a frame's check: the first bytes of its payload's BLAKE3 + /// hash. const CHECK: usize = 8; /// The bytes a frame adds to its payload: two lengths and a check. @@ -679,7 +665,7 @@ impl Log { .expect("a digest is longer than a check") } - /// Encodes a log holding `entries`, all published, and `digests`. + /// Encodes a log holding `entries`, marked published, and `digests`. fn encode(entries: &[Entry], digests: &[(StatementId, Digest)]) -> Vec { let mut log = Self::HEADER.to_vec(); let offset = log.len() as u64; @@ -691,8 +677,8 @@ impl Log { log } - /// The frames of a log and their offsets, up to the first broken one, - /// and how it ends after them. + /// Parses a log: returns its frames with their offsets, up to the first + /// broken one, and how the log ends after them. fn parse(bytes: &[u8]) -> (Vec<(u64, Frame<'static>)>, Tail) { let mut frames = Vec::new(); let Some(mut rest) = bytes.strip_prefix(Self::HEADER) else { @@ -716,8 +702,8 @@ impl Log { (frames, Tail::Clean) } - /// Checks the frame `bytes` start with, returning its payload and its - /// length. + /// Checks the frame at the start of `bytes`, and returns its payload and + /// the frame's length. fn payload(bytes: &[u8]) -> Result<(&[u8], usize), Broken> { let (len, rest) = bytes.split_first_chunk::<4>().ok_or(Broken::Partial)?; let (payload, rest) = rest @@ -733,8 +719,8 @@ impl Log { Ok((payload, payload.len() + Self::FRAMING)) } - /// Whether the locked `log` ends with an intact frame, or the header. - /// Reads only the last frame, backwards from its trailing length. + /// Whether the locked `log` ends with an intact frame, or with just the + /// header. Only reads the last frame, found from its trailing length. fn ends_cleanly(mut log: &File) -> io::Result { let len = log.metadata()?.len(); let header = Self::HEADER.len() as u64; @@ -789,7 +775,7 @@ impl Log { }) } - /// A record's kind and id. + /// Returns a record's kind and id. fn split(record: RecordId) -> (ObjectKind, ObjectId) { match record { RecordId::Snapshot(id) => (ObjectKind::Tree, id.into()), @@ -803,24 +789,22 @@ impl Log { /// How a log ends after its last intact frame. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Tail { - /// It ends there. + /// Nothing follows. Clean, - /// With part of a frame, at this offset: an append in progress, or one a - /// crash cut short. Appenders cut such a leftover off before appending, - /// so it is always last. + /// Part of a frame follows, at this offset: an append in progress, or one a + /// crash cut short. Appenders cut it off before appending, so it is always + /// last. Partial(u64), - /// With damage, or a header from another version: the index must be - /// rebuilt. + /// Damaged bytes follow, or the header is from another version. The index + /// must be rebuilt. Damaged, } /// Why a frame cannot be decoded. enum Broken { - /// The bytes end before it does. + /// The bytes end before the frame does. Partial, - /// It is not what was appended: it fails its check, or its payload - /// doesn't decode. Either way the index is rebuilt, so why doesn't - /// matter. + /// The frame fails its check, or its payload doesn't decode. Damaged, } @@ -829,15 +813,16 @@ impl Store

{ self.index_dir().join("log") } - /// Locks the index: shared by batches being indexed, exclusive for a + /// Locks `index/lock`: shared while a batch is indexed, exclusive for a /// rebuild. fn lock_index(&self, mode: LockMode) -> Result { self.lock_in_index("lock", mode) } - /// Locks supersession, exclusively: see [`Annotations::supersede`]. - /// It's a lock of its own, since issuing takes the index's, on another - /// handle, which `flock` conflicts with even within one process. + /// Locks `index/supersession` exclusively, for [`Annotations::supersede`]. + /// It is separate from the index lock because issuing a statement takes + /// that lock on another handle, and `flock` locks conflict even within one + /// process. /// /// [`Annotations::supersede`]: crate::annotations::Annotations::supersede pub(crate) fn lock_supersession(&self) -> Result { @@ -864,8 +849,8 @@ impl Store

{ } /// Commits `write`, which stages the records `entries` describe, and - /// indexes them: their entries are durable with the records, and marked - /// published after them. + /// indexes them. The entries are appended to the log before the records are + /// published, and synced with them. A frame marking them published follows. /// /// # Errors /// @@ -890,9 +875,9 @@ impl Store

{ Ok(()) } - /// Appends `frame` to the log, without syncing it, returning its offset, - /// or `None` if there's no log: opening the index will rebuild it from - /// the store. + /// Appends `frame` to the log without syncing it, and returns its offset. + /// Returns `None` if there is no log, which the next `Index::open` rebuilds + /// from the store. fn append_to_index(&self, frame: &Frame<'_>) -> Result, StoreError> { let path = self.index_log(); let io_error = |source| StoreError::io(&path, source); @@ -917,9 +902,9 @@ impl Store

{ Ok(Some(offset)) } - /// Cuts off the partial frame a crash left at the end of the locked - /// `log`, durably, so appends never follow one. Damage is left for - /// readers to find, so they rebuild the index. + /// Cuts off a partial frame a crash left at the end of the locked `log`, + /// and syncs it, so appends never follow a partial frame. Other damage is + /// left for readers, who rebuild the index. fn cut_partial_frame(&self, mut log: &File) -> io::Result<()> { let mut bytes = Vec::new(); log.seek(SeekFrom::Start(0))?; @@ -931,8 +916,8 @@ impl Store

{ Ok(()) } - /// The entry of every record in the store, read from every core, and - /// the objects skipped because they are corrupt or don't decode. + /// Reads the entry of every record in the store, from every core. Also + /// returns the objects skipped because they are corrupt or don't decode. fn entries(&self) -> Result<(Vec, Vec), StoreError> { let ids = self.ids()?; let chunks = Self::on_every_core(&ids, |ids| { @@ -981,7 +966,8 @@ mod tests { ChangeId::from_bytes([seed; 16]) } - /// A revision of `change` evolving from `predecessors`. + /// A revision of `change` evolving from `predecessors`, made distinct by + /// `seed`. fn revision(change: ChangeId, predecessors: &[&EncodedObject], seed: &str) -> EncodedObject { Revision { change, @@ -995,7 +981,7 @@ mod tests { .encode() } - /// A statement about `subject`. + /// A passing statement of `kind` about `subject`. fn statement(subject: RecordId, kind: &str) -> EncodedObject { Statement { subject, @@ -1077,7 +1063,7 @@ mod tests { } } - /// Records arriving in several batches, out of order and some twice. + /// Writes records in several batches, out of order and some twice. fn write_history(store: &Store) { let (a, b) = (change(1), change(2)); let a1 = revision(a, &[], "a1"); @@ -1138,7 +1124,8 @@ mod tests { assert_eq!(sorted(Index::open(&store).unwrap()), sorted(updated)); } - /// The index with every list sorted: what's left without arrival order. + /// Returns the index with every list sorted, to compare indexes regardless + /// of arrival order. fn sorted(mut index: Index) -> Index { index.arrivals.sort(); for change in index.changes.values_mut() { diff --git a/apps/origin-src/src/store/mod.rs b/apps/origin-src/src/store/mod.rs index 1318e04e..6caafab0 100644 --- a/apps/origin-src/src/store/mod.rs +++ b/apps/origin-src/src/store/mod.rs @@ -49,17 +49,16 @@ pub struct Store

{ } impl Store

{ - /// Favors speed: higher levels shrink source code little and cost a lot - /// on every snapshot. + /// The zstd compression level. It is low because higher levels shrink + /// source code little and slow down every snapshot. const COMPRESSION_LEVEL: i32 = 1; - /// How old a temporary file must be for [`Store::remove_stale_temps`] - /// to remove it. A write publishes or removes its own files long before: - /// even a million-object batch stages in under a minute. + /// How old a temporary file must be before [`Store::remove_stale_temps`] + /// removes it. Writes finish with their own files long before that. const STALE_TEMP: Duration = Duration::from_hours(1); - /// Opens the storage in `root`, the `.origin` directory, on `platform`, - /// for reading. + /// Opens the store in `root`, the `.origin` directory, on `platform`, for + /// reading. pub fn new(root: impl Into, platform: P) -> Self { Self { root: root.into(), @@ -83,7 +82,7 @@ impl Store

{ /// Collects garbage: compacts the store, unless another compaction is /// running, then removes the temporary files crashed writes left behind. - /// Returns what the compaction did. + /// Returns what the compaction did, or `None` if it was skipped. /// /// # Errors /// @@ -94,11 +93,9 @@ impl Store

{ Ok(compaction) } - /// Removes the temporary files that crashed writes left behind: those - /// older than an hour. It walks every loose object, so only garbage - /// collection calls it. It leaves the packs directory to the compactor, - /// which removes what crashed compactions left there under its lock, so - /// a long compaction never loses its pack. + /// Removes the temporary files crashed writes left behind, those older than + /// an hour. It walks every loose object, so only garbage collection should + /// call it. It skips the packs directory, which the compactor cleans itself. /// /// # Errors /// @@ -135,15 +132,14 @@ impl Store

{ Ok(()) } - /// Creates the directories of an empty store and its empty index, - /// durably, refusing a network file system. Creating every object shard - /// up front means batches only ever sync the shards they write to, never - /// a directory they had to create. + /// Creates an empty store and its empty index, durably, refusing a network + /// file system. It creates all 256 object shard directories up front, so + /// batches never have to create and sync a new directory. /// /// # Errors /// - /// Fails if the store would be on a network file system, or if a - /// directory cannot be created or synced. + /// Fails if the store would be on a network file system, or if a directory + /// or the index cannot be created or synced. pub fn init(&self) -> Result<(), StoreError> { fs::create_dir_all(&self.root).map_err(|source| StoreError::io(&self.root, source))?; self.platform.check_writable(&self.root)?; @@ -207,14 +203,13 @@ impl Store

{ DurableWrite::new(&self.platform) } - /// Writes `objects` in one batch, staged from every core, returning how - /// many were new. Staging compresses and writes without syncing, so it - /// scales with the cores. + /// Writes `objects` in one batch, staging them from every core, and returns + /// how many were new. /// /// # Errors /// - /// Fails if an object cannot be written. Objects written before the - /// failure may not be durable. + /// Fails if an object cannot be written. Objects written before the failure + /// may not be durable. pub fn write_all(&self, objects: &[EncodedObject]) -> Result { let batch = self.batch(); let written = Self::on_every_core(objects, |chunk| batch.write_all(chunk)) @@ -224,8 +219,8 @@ impl Store

{ Ok(written) } - /// Splits `items` into a chunk per core, and maps each on its own - /// thread, returning each chunk's result in order. + /// Splits `items` into one chunk per core, maps each chunk on its own + /// thread, and returns the results in chunk order. pub(crate) fn on_every_core( items: &[T], map: impl Fn(&[T]) -> R + Sync, @@ -323,14 +318,15 @@ impl Store

{ Ok(Some(EncodedObject::verify(id, bytes)?)) } - /// The largest size recorded in a frame that is decompressed in one - /// shot. A corrupt frame can claim any size, which a single allocation - /// of it would abort on. + /// The largest size, as recorded in a zstd frame, that is decompressed in + /// one allocation. Larger frames stream, since a corrupt frame can claim + /// any size. const ONE_SHOT_MAX: u64 = 64 << 20; - /// Decompresses in one shot using the size recorded in the frame, which - /// is much faster for small objects than a streaming decoder. Larger - /// frames stream, so the buffer only grows with what they really hold. + /// Decompresses a zstd frame. Frames up to `ONE_SHOT_MAX` are decompressed + /// in one shot, into a buffer of the size the frame records, which is much + /// faster for small objects. Larger ones stream. Fails if the frame doesn't + /// record its size. fn decompress(compressed: &[u8]) -> io::Result> { let corrupt = || io::Error::new(io::ErrorKind::InvalidData, "missing zstd frame size"); let size = zstd::zstd_safe::get_frame_content_size(compressed) @@ -381,30 +377,30 @@ impl Store

{ } } -/// Objects written durably as a group. None is durable until -/// [`Batch::commit`] returns, so nothing may refer to them before. Dropping -/// the batch abandons them. +/// A group of objects written durably together. None of them is durable +/// until [`Batch::commit`] returns, so nothing may refer to them before. +/// Dropping the batch abandons them. /// -/// Objects can be written from several threads at once, and should be: each -/// write compresses its object (see [`Store::write_all`]). +/// Objects can be written from several threads at once, and should be, +/// since each write compresses its object (see [`Store::write_all`]). #[derive(Debug)] pub struct Batch<'a, P> { store: &'a Store

, write: DurableWrite<'a, P>, - /// What the index keeps of each new record staged. + /// The index entries of the new records staged. entries: Mutex>, } impl Batch<'_, P> { - /// Stages an object, unless the store already has it, returning whether - /// it was new. Either way, it is durable once the batch commits. Packs - /// are only checked as last loaded: an object packed since is staged + /// Stages `object` unless the store already has it, and returns whether it + /// was new. Either way, the object is durable once the batch commits. Only + /// the packs loaded last are checked, so an object packed since is staged /// again, and the next compaction removes the copy. /// /// # Errors /// - /// Fails if the object is a record that doesn't decode, or if it cannot - /// be compressed or written. + /// Fails if the object is a record that doesn't decode, or if it cannot be + /// compressed or written. pub fn write(&self, object: &EncodedObject) -> Result { let id = object.id(); let path = self.store.path(id); @@ -477,13 +473,14 @@ pub enum StoreError { /// A durable write failed. #[error(transparent)] Write(#[from] origin_platform::Error), - /// The store is somewhere origin refuses to write. + /// The store is somewhere origin refuses to write, such as a network file + /// system. #[error(transparent)] Unwritable(#[from] WritableError), /// An object's content does not match its id. #[error(transparent)] Corrupt(#[from] IdMismatch), - /// An object's file is not valid zstd: it is corrupt too. + /// An object's file is not valid zstd, so it is corrupt. #[error("cannot decompress object {id} from {}", path.display())] Decompress { /// The object. @@ -501,8 +498,8 @@ pub enum StoreError { /// Why decoding failed. source: DecodeError, }, - /// An acceptance doesn't follow the target's latest one: another landing - /// got there first. + /// An acceptance doesn't follow the target's latest one, because another + /// landing got there first. #[error( "target `{target}` moved: expected acceptance {expected} to follow {}", Head::describe(*actual) @@ -510,7 +507,7 @@ pub enum StoreError { Conflict { /// The target. target: TargetName, - /// The sequence number of the acceptance appended. + /// The sequence number of the acceptance being appended. expected: u64, /// The target's latest acceptance. actual: Option, @@ -552,7 +549,7 @@ pub(crate) mod tests { (dir, store) } - /// Records syncs, in order, and performs them. + /// A platform that records each sync, in order, then performs it. #[derive(Default)] pub(crate) struct Recorder(pub(crate) Mutex>); diff --git a/apps/origin-src/src/store/packs.rs b/apps/origin-src/src/store/packs.rs index fad279af..4cc652ed 100644 --- a/apps/origin-src/src/store/packs.rs +++ b/apps/origin-src/src/store/packs.rs @@ -1,40 +1,28 @@ -//! Pack files: small objects gathered into a few large files, so a store of -//! a million statements holds a handful of files rather than a million. +//! Pack files: many small objects stored in a few large files, so a store +//! of a million statements holds a handful of files rather than a million. //! //! `objects/packs/` holds: //! //! - `.pack`: [`Pack::MAGIC`], then each object as the `u32` length of -//! its compressed encoding and the encoding, compressed as in a loose -//! file. A pack can be read on its own, start to end. +//! its compressed encoding followed by that encoding, compressed as in a +//! loose file. //! - `.idx`: [`Pack::INDEX_MAGIC`], the ids of the pack's objects in -//! ascending order, then where each one's compressed encoding is in the -//! pack: a `u64` offset and a `u32` length. The pack's id is the hash of -//! its object ids, which opening the pack verifies. +//! ascending order, then each one's `u64` offset and `u32` length in the +//! pack. The pack's id is the hash of its object ids. //! - `manifest`: the ids of the packs in use, one per line in hex, largest -//! pack first. Replacing it publishes and retires packs at once. -//! - `lock`: held by the compactor, so only one ever runs. +//! pack first. +//! - `lock`: held by the compactor, so only one compaction runs at a time. //! //! Integers are little endian. //! //! [`Store::compact`] gathers the small loose objects into a new pack, and -//! merges into it every pack smaller than twice what it holds so far, so a -//! store keeps a logarithmic number of packs and an object is rewritten a -//! logarithmic number of times. It writes the pack and its index durably, -//! then the manifest, and only then removes the loose files and the packs -//! it merged. A crash loses nothing: until the manifest is published, every -//! object is still where it was, and the next compaction removes the files -//! the manifest doesn't name. +//! merges into it every pack smaller than twice the new pack's size so far, +//! which keeps the number of packs logarithmic. It writes the pack and its +//! index, then the manifest, and only then removes the loose files and the +//! merged packs, so a crash loses nothing. //! -//! [`Store::compact_if_due`] compacts once enough loose objects pile up, -//! for a long-running process to call as it writes. -//! -//! Readers look in the packs they loaded last, and reload the manifest when -//! an object isn't there. An object in neither the loose objects nor the -//! current manifest's packs is not in the store, since a pack is published -//! before what it replaces is removed. A pack stays readable once opened, -//! even after it's retired, because an open file outlives its name, so -//! readers also reload the manifest every few seconds, to let go of the -//! packs it no longer names. +//! Readers look in the packs they loaded last. They read the manifest again +//! when an object isn't there, and every few seconds. use std::fmt; use std::fs::{self, File}; @@ -48,7 +36,7 @@ use origin_shared::{Digest, ObjectId}; use super::{Store, StoreError}; -/// The packs a store loaded last, shared by its clones. +/// The packs a store loaded last, shared by the store's clones. #[derive(Default)] pub(super) struct Packs { manifest: RwLock, @@ -56,7 +44,7 @@ pub(super) struct Packs { read_at: Mutex>, } -/// A manifest and the packs it names, open. +/// A manifest and the open packs it names. #[derive(Default)] struct Manifest { /// The manifest's contents, or `None` until it's first read. @@ -65,12 +53,12 @@ struct Manifest { } impl Packs { - /// How long a store goes by the manifest it read before its next lookup - /// in the packs reads it again, so that a long-running process lets go - /// of the packs another process's compaction retired. + /// How long a store trusts the manifest it read. After that, its next + /// lookup in the packs reads the manifest again, so a long-running process + /// lets go of packs that another process's compaction retired. const RELOAD_AFTER: Duration = Duration::from_secs(10); - /// The pack holding `id` among those loaded, and where it is. + /// Returns the loaded pack holding `id`, and where in it the object is. pub(super) fn find(&self, id: ObjectId) -> Option<(Arc, Location)> { let manifest = self.manifest.read().unwrap_or_else(PoisonError::into_inner); manifest @@ -107,7 +95,8 @@ pub(super) struct Pack { index: Vec, } -/// Where a compressed encoding is in a pack. +/// Where an object's compressed encoding is in a pack: its offset and +/// length. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Location { offset: u64, @@ -115,7 +104,7 @@ pub(super) struct Location { } impl Location { - /// The length of an encoded location. + /// The length of an encoded location: a `u64` offset and a `u32` length. const LEN: usize = 8 + 4; fn encode(self, out: &mut Vec) { @@ -139,21 +128,21 @@ impl Pack { /// How an index file starts: its format and version. const INDEX_MAGIC: [u8; 8] = *b"oindex\0\x01"; - /// The bytes an object takes in an index. + /// The bytes each object takes in an index: its id and its location. const ENTRY: usize = ObjectId::LEN + Location::LEN; - /// The path of the pack `id`'s file with `extension`, `pack` or `idx`. + /// The path of pack `id`'s file with `extension`, `pack` or `idx`. fn file_path(dir: &Path, id: Digest, extension: &str) -> PathBuf { dir.join(format!("{id}.{extension}")) } - /// The id of a pack holding `ids`, which are sorted. + /// The id of a pack: the hash of `ids`, its object ids in ascending order. fn id_of(ids: &[u8]) -> Digest { Digest::of(ids) } - /// Opens the pack `id` in `dir`, or returns `None` if its files are - /// gone. + /// Opens pack `id` in `dir` and checks its files, or returns `None` if they + /// are gone. fn open(platform: &impl ReadAt, dir: &Path, id: Digest) -> Result, StoreError> { let index_path = Self::file_path(dir, id, "idx"); let path = Self::file_path(dir, id, "pack"); @@ -184,8 +173,8 @@ impl Pack { Ok(Some(pack)) } - /// Whether the index has the right shape, ascending ids, and the ids - /// the pack's id says. + /// Whether the index has the right header and size, ascending ids, and ids + /// that hash to the pack's id. fn index_is_valid(&self) -> bool { let Some(tables) = self.index.strip_prefix(&Self::INDEX_MAGIC) else { return false; @@ -218,7 +207,7 @@ impl Pack { Some(Location::decode(&self.locations()[index])) } - /// Every object of the pack, in ascending order. + /// Every object of the pack and its location, in ascending id order. fn entries(&self) -> impl Iterator { self.ids() .iter() @@ -259,36 +248,38 @@ impl fmt::Debug for Pack { enum Source { /// Its loose file. Loose, - /// The merged pack at this position, at a location. + /// A merged pack, by its position in the list of merged packs, and the + /// object's location in it. Packed(usize, Location), } /// What a compaction did. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Compaction { - /// Loose objects moved into the new pack. + /// How many loose objects were moved into the new pack. pub packed: usize, - /// Packs merged into it. + /// How many packs were merged into the new pack. pub merged: usize, - /// Loose objects removed because a pack already held them, left by a - /// writer that didn't know of the pack yet, or by a crash. + /// How many loose objects were removed because a pack already held them. A + /// crash, or a writer that didn't know of the pack yet, leaves such copies. pub duplicates: usize, } impl Store

{ - /// The largest loose file compaction packs. Larger objects are mostly - /// file contents, which a pack merge would copy over and over. + /// The largest loose file compaction packs. Larger objects are mostly file + /// contents, which merging packs would copy again and again. const PACKED_MAX: u64 = 16 * 1024; /// How many small loose objects make a compaction due, see - /// [`Store::compact_if_due`]: about as many as git lets pile up. + /// [`Store::compact_if_due`]. const COMPACT_AFTER: usize = 8 * 1024; /// How many objects a compaction reads at once, from every core, before /// appending them to the pack. const READ_CHUNK: usize = 16 * 1024; - /// The packs directory's files besides the packs. + /// The names of the packs directory's other files: the manifest and the + /// compactor's lock. const MANIFEST: &str = "manifest"; const LOCK: &str = "lock"; @@ -296,8 +287,8 @@ impl Store

{ self.root.join("objects/packs") } - /// The pack holding `id`, reloading the manifest if no pack loaded - /// holds it, or if it was read too long ago. + /// Returns the pack holding `id`, and where it is. Reads the manifest again + /// if no loaded pack holds it, or if it was read too long ago. pub(super) fn find_packed( &self, id: ObjectId, @@ -312,7 +303,7 @@ impl Store

{ Ok(self.packs.find(id)) } - /// The id of every packed object, as of the current manifest. + /// Returns the id of every packed object, as of the current manifest. pub(super) fn packed_ids(&self) -> Result, StoreError> { self.reload_packs()?; Ok(self @@ -323,7 +314,7 @@ impl Store

{ .collect()) } - /// Loads the manifest's packs, unless they're already loaded. + /// Reads the manifest and opens its packs, unless they are already loaded. fn reload_packs(&self) -> Result<(), StoreError> { let dir = self.packs_dir(); let path = dir.join(Self::MANIFEST); @@ -374,8 +365,8 @@ impl Store

{ } } - /// Opens the packs a manifest names, reusing those already open, or - /// returns `None` if one is gone. + /// Opens the packs `manifest` names, reusing those in `open`. Returns + /// `None` if one of them is gone. fn open_packs( &self, dir: &Path, @@ -398,18 +389,16 @@ impl Store

{ Ok(Some(packs)) } - /// Moves the small loose objects into a new pack, merging packs into it - /// as the [module documentation](self) describes. Readers and writers - /// may use the store meanwhile, from any process, so a compaction can - /// run in the background. + /// Moves the small loose objects into a new pack, merging smaller packs + /// into it as the [module documentation](self) describes. Other readers and + /// writers, in any process, may use the store meanwhile. /// - /// Returns `None` without doing anything if another compaction is - /// running. + /// Returns `None` without doing anything if another compaction is running. /// /// # Errors /// - /// Fails if the store's files cannot be read, written or removed, or a - /// pack is malformed. Whatever the failure, no object is lost. + /// Fails if the store's files cannot be read, written or removed, or a pack + /// is malformed. No object is lost on failure. pub fn compact(&self) -> Result, StoreError> { let Some(_lock) = self.lock_compactor()? else { return Ok(None); @@ -419,11 +408,11 @@ impl Store

{ } /// Compacts like [`Store::compact`] if the store holds more than - /// [`Store::COMPACT_AFTER`] small loose objects, estimated from one - /// shard of the 256, as git estimates its loose objects. Cheap enough to - /// call after every few writes: it lists that one shard. + /// [`Store::COMPACT_AFTER`] small loose objects. It estimates the count + /// from one of the 256 shards, so it is cheap enough to call after every + /// few writes. /// - /// Returns `None` if the compaction isn't due, or another is running. + /// Returns `None` if no compaction is due, or another one is running. /// /// # Errors /// @@ -451,7 +440,8 @@ impl Store

{ )?) } - /// [`Store::compact`], holding the lock, with the packs reloaded. + /// Does the work of [`Store::compact`]. The caller must hold the + /// compactor's lock and have reloaded the packs. fn compact_locked(&self) -> Result, StoreError> { let dir = self.packs_dir(); let packs = self.packs.loaded(); @@ -517,8 +507,8 @@ impl Store

{ Ok(Some(compaction)) } - /// Writes a pack of `sources`, sorted by id, and its index, durably, - /// returning its id. + /// Writes a pack of `sources`, which are sorted by id, and its index, + /// durably, and returns the pack's id. fn write_pack( &self, dir: &Path, @@ -560,7 +550,8 @@ impl Store

{ Ok(id) } - /// Reads the compressed encoding of `id` from `source`, and its length. + /// Reads the compressed encoding of `id` from `source`, and returns its + /// length and bytes. fn read_source( &self, id: ObjectId, @@ -581,10 +572,9 @@ impl Store

{ } } - /// Removes the files of the packs directory that no pack of `packs` - /// owns: those of compactions that crashed before publishing, and of - /// packs retired by compactions that crashed before removing them. Only - /// the compactor writes there, so it must hold the lock. + /// Removes the files in the packs directory that belong to none of `packs`: + /// leftovers of compactions that crashed. The caller must hold the + /// compactor's lock. fn remove_unlisted(dir: &Path, packs: &[Arc]) -> Result<(), StoreError> { let mut keep = vec![Self::MANIFEST.to_owned(), Self::LOCK.to_owned()]; for pack in packs { @@ -599,8 +589,9 @@ impl Store

{ Ok(()) } - /// The small loose objects of `shards` that no pack of `packs` holds, - /// and how many loose duplicates of packed objects it removed. + /// Returns the small loose objects in `shards` that no pack of `packs` + /// holds. Removes the loose copies of packed objects, and also returns how + /// many it removed. fn small_loose( &self, packs: &[Arc], @@ -874,13 +865,15 @@ mod tests { ); } - /// The native platform, failing one batch sync once armed with - /// [`Crashing::crash_after`], as if the process died there. + /// The native platform, except that once armed with + /// [`Crashing::crash_after`], one batch sync fails, as if the process died + /// there. #[derive(Default)] struct Crashing(Mutex>); impl Crashing { - /// Fails the batch sync after the next `batches`. + /// Arms the platform: after `batches` more batch syncs succeed, the next one + /// fails. fn crash_after(&self, batches: usize) { *self.0.lock().unwrap() = Some(batches); }