From 7b8dc0308e80db0008a45b2d865ddb9cb69abbe7 Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 23 Nov 2026 21:18:58 +0100 Subject: [PATCH] docs(statements): say plainly what each item does Rewrites the doc comments of these files so each says plainly what its item does, without design asides. Code and code examples are unchanged. --- apps/origin-src/benches/annotations.rs | 31 +++-- apps/origin-src/src/ancestry.rs | 46 +++---- apps/origin-src/src/annotations/mod.rs | 132 ++++++++++--------- apps/origin-src/src/annotations/promotion.rs | 102 +++++++------- apps/origin-src/src/conflict.rs | 19 +-- apps/origin-src/src/policy.rs | 66 +++++----- apps/origin-src/src/targets.rs | 64 ++++----- apps/origin-src/src/tree.rs | 95 ++++++------- 8 files changed, 291 insertions(+), 264 deletions(-) diff --git a/apps/origin-src/benches/annotations.rs b/apps/origin-src/benches/annotations.rs index a15505d8..a4bfe3ff 100644 --- a/apps/origin-src/benches/annotations.rs +++ b/apps/origin-src/benches/annotations.rs @@ -1,6 +1,6 @@ -//! Statements: input digests over a large snapshot, and the promotion -//! search over many statements, with their digests cached by the index and -//! without. +//! Benchmarks for statements: the input digest of a large snapshot, and +//! the promotion search over many statements, with and without their +//! digests cached in the index. use std::fs; @@ -42,8 +42,9 @@ fn inputs(paths: &[&str], definition: &str) -> Inputs { } } -/// The input digest of the 20k-file fixture, for inputs naming two -/// directories, a file and a missing path. Each run reads the trees anew. +/// Benchmarks the input digest of the 20k-file fixture, for inputs naming +/// two directories, a file and a missing path. Each run reads the trees +/// anew. #[divan::bench(sample_count = 50)] fn input_digest(bencher: Bencher<'_, '_>) { let dir = tempfile::tempdir().unwrap(); @@ -81,8 +82,9 @@ const CHECKS: [(&str, &[&str]); 10] = [ ("ci.unit", &["src"]), ]; -/// A snapshot of a small crate, at version `version` of its sources and -/// `docs` of its documentation. +/// Builds the objects of a small crate's snapshot, with version `version` +/// of its sources and version `docs` of its documentation. The root tree +/// comes last. fn snapshot(version: usize, docs: usize) -> Vec { let file = |content: String| { let blob = EncodedObject::blob(content.as_bytes()); @@ -123,9 +125,9 @@ fn snapshot(version: usize, docs: usize) -> Vec { objects } -/// A store with a revision of its own change for each version, each with a -/// result of every check, 20k statements in all, and a revision whose -/// sources match one of them. +/// Builds a store with one revision per version, each of its own change +/// and with a passing result of every check: 20k statements in all. Returns +/// it with one more revision, whose sources match one of the others. fn promotion_store() -> (tempfile::TempDir, Store, RevisionId) { let (dir, store) = store(); let revision = |store: &Store, change: usize, version: usize, docs: usize| { @@ -173,8 +175,9 @@ fn promotion_store() -> (tempfile::TempDir, Store, RevisionId) { (dir, store, target) } -/// Searching 20k statements for those to promote to a revision, with every -/// digest cached: the cost of each search after the first. +/// Benchmarks searching 20k statements for those to promote to a +/// revision, with every digest already cached: the cost of every search +/// after the first. #[divan::bench(sample_count = 20)] fn promotions_cached(bencher: Bencher<'_, '_>) { let (_dir, store, target) = promotion_store(); @@ -198,8 +201,8 @@ fn promotions_cached(bencher: Bencher<'_, '_>) { }); } -/// The first search, which computes and remembers the digest of each of -/// the 20k statements, reading its subject's trees. +/// Benchmarks the first search, which computes the digest of each of the +/// 20k statements from its subject's trees and stores it in the index. #[divan::bench(sample_count = 10, sample_size = 1)] fn promotions_uncached(bencher: Bencher<'_, '_>) { let (dir, store, target) = promotion_store(); diff --git a/apps/origin-src/src/ancestry.rs b/apps/origin-src/src/ancestry.rs index 8278e72f..42b8e5f8 100644 --- a/apps/origin-src/src/ancestry.rs +++ b/apps/origin-src/src/ancestry.rs @@ -1,7 +1,7 @@ -//! Merge bases in a history of immutable records with snapshots: the -//! acceptances of targets, each after the one before it and the -//! acceptances it landed, or the revisions of a change, each after its -//! predecessors. +//! Finds merge bases in a history of records that each have parents and a +//! snapshot. The records are either the acceptances of a target, whose +//! parents are the acceptance before and the acceptances it landed, or the +//! revisions of a change, whose parents are their predecessors. use std::collections::{HashMap, HashSet}; use std::hash::Hash; @@ -19,12 +19,12 @@ pub struct Ancestry { } impl Ancestry { - /// Walks everything `tips` descend from, asking `read` for the parents - /// and the snapshot of each record, once. + /// Walks every record `tips` descend from, `tips` included, calling + /// `read` once per record for its parents and snapshot. /// /// # Errors /// - /// Fails as `read` does. + /// Fails if `read` fails. pub fn walk( tips: &[I], mut read: impl FnMut(I) -> Result<(Vec, TreeId), E>, @@ -42,13 +42,13 @@ impl Ancestry { Ok(Self { records }) } - /// The snapshot to merge `tips` from, `None` if they share no ancestor: - /// that of their best common ancestor. Several, as histories that - /// merged each other criss-cross have, merge into one first, as git's - /// recursive strategy does: each from their own merge base, with what - /// [`Store::merge_bases`] leaves where they conflict, so a merge from - /// the result conflicts there, and under it, unless both sides agree. Writes the trees - /// that makes, which merging reads. + /// Returns the snapshot to merge `tips` from: that of their best common + /// ancestor, or `None` if they have no common ancestor. When there are + /// several best common ancestors, as after criss-cross merges, it first + /// merges them into one with [`Store::merge_bases`], like git's recursive + /// strategy. A merge from the result then conflicts at or under every path + /// where those ancestors conflicted, unless both sides agree. Writes the + /// trees this makes to the store. /// /// # Errors /// @@ -62,7 +62,8 @@ impl Ancestry { self.merge_base_of(store, &groups) } - /// The snapshot to merge `groups` from, each standing for all it holds. + /// Like [`Self::merge_base`], but for groups of records: each group stands + /// for a merge of all its records. fn merge_base_of( &self, store: &Store

, @@ -84,10 +85,9 @@ impl Ancestry { Ok(Some(tree)) } - /// The best common ancestors of `groups`: the records that every group - /// has one that is or descends from, but that none of the others - /// descends from, sorted. Each record is visited a bounded number of - /// times. + /// Returns the best common ancestors of `groups`, sorted: the records + /// that are, or are ancestors of, a record in every group, and that no + /// other such record descends from. fn best_common(&self, groups: &[&[I]]) -> Vec { let Some((first, others)) = groups.split_first() else { return Vec::new(); @@ -104,7 +104,7 @@ impl Ancestry { bases } - /// The records `from` are or descend from. + /// Returns the records in `from` and every record they descend from. fn reachable(&self, from: impl IntoIterator) -> HashSet { let mut reached = HashSet::new(); let mut next: Vec<_> = from.into_iter().collect(); @@ -116,8 +116,8 @@ impl Ancestry { reached } - /// Whether `id` is or descends from `ancestor`, as far as the walk - /// read. + /// Whether `id` is `ancestor` or descends from it, within the records the + /// walk read. #[must_use] pub fn descends(&self, id: I, ancestor: I) -> bool { self.reachable([id]).contains(&ancestor) @@ -138,7 +138,7 @@ mod tests { use super::*; - /// The history of `edges`, each a record and its parents. + /// Builds the history of `edges`, each a record and its parents. fn ancestry(edges: &[(u8, &[u8])]) -> Ancestry { let tips: Vec<_> = edges.iter().map(|&(id, _)| id).collect(); let empty = Tree::default().encode().id().into(); diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index 2d38a539..56a38b1e 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -1,14 +1,13 @@ -//! Statements: issuing them, reading them, and promoting them by input -//! digest. +//! Issuing statements, reading them, and promoting them by input digest. //! -//! Core interprets only the reserved kinds: [`Kind::ABANDON`], +//! Core acts only on the reserved kinds, [`Kind::ABANDON`], //! [`Kind::CONFLICT`] and [`Kind::DIVERGENT`], and only from the issuers -//! [`Store::authorizes`] names. Every other kind belongs to whoever issues -//! it. Supersession counts only within one issuer: a statement claiming to -//! supersede another issuer's is issued like any other, and the one it -//! names still stands. [`Annotations::supersede`] supersedes an issuer's -//! current statement atomically, so two statements issued through it at -//! once in one store never supersede the same one. +//! [`Store::authorizes`] allows. Every other kind means whatever its issuer +//! means by it. A statement only supersedes one from its own issuer: one +//! that names another issuer's statement leaves that statement standing. +//! [`Annotations::supersede`] picks the statement to supersede under a +//! lock, so two statements issued through it at once in one store never +//! supersede the same one. mod promotion; @@ -24,53 +23,56 @@ use crate::store::{Store, StoreError}; pub use promotion::{Claim, InvalidPromotion}; -/// The statements of a store, through its index. +/// The statements in a store, found through its index. #[derive(Debug)] pub struct Annotations<'a, P = Native> { store: &'a Store

, index: Index, } -/// A statement, and whether its issuer superseded it. +/// A statement, and the statement from its issuer that superseded it, if +/// any. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Annotation { /// The statement's id. pub id: StatementId, /// The statement. pub statement: Statement, - /// The first statement from the same issuer that supersedes it. + /// The first statement from the same issuer that supersedes this one, if + /// any. pub superseded_by: Option, } impl<'a, P: Platform> Annotations<'a, P> { - /// The statements of `store`, as `index` knows them. + /// Reads the statements of `store` through `index`. pub fn new(store: &'a Store

, index: Index) -> Self { Self { store, index } } - /// The statements of `store`, opening its index. + /// Reads the statements of `store`, opening its index. /// /// # Errors /// - /// Fails like [`Index::open`]. + /// Fails if the index cannot be opened, like [`Index::open`]. pub fn open(store: &'a Store

) -> Result { Ok(Self::new(store, Index::open(store)?)) } - /// The index the statements are found through. + /// Returns the index the statements are found through. #[must_use] pub fn index(&self) -> &Index { &self.index } - /// Writes a statement and its payload. Issuing a statement the store - /// has is a no-op. + /// Checks and writes a statement and its payload, returning the + /// statement's id. Issuing a statement the store already has writes + /// nothing new. /// /// # Errors /// /// Fails if the statement supersedes one from another issuer, is a - /// promotion that [`Store::claim`] refuses, is of a reserved kind its - /// issuer may not issue, or the records cannot be read or written. + /// promotion that [`Store::claim`] refuses, or is of a reserved kind its + /// issuer may not issue, or if records cannot be read or written. pub fn issue( &self, statement: &Statement, @@ -99,22 +101,22 @@ impl<'a, P: Platform> Annotations<'a, P> { Ok(self.write(statement, payload)?) } - /// Issues `statement` as its issuer's latest of its kind about its - /// subject, superseding the [current](Self::current) one, and returns - /// it with its id. One without a verdict, of a kind that isn't - /// reserved, withdraws the current one. It reads the current one and - /// issues under a lock, from the index read again, so two statements - /// issued at once in this store never supersede the same one: the - /// second supersedes the first. Statements issued in other stores and - /// put here chose what they supersede there, so two of one issuer's can - /// still both supersede the same one. Afterwards these annotations hold - /// the index as read before the issue, without the new statement. + /// Issues `statement` so that it supersedes its issuer's + /// [current](Self::current) statement of the same kind about the same + /// subject, and returns it with its id. A statement without a verdict, of a + /// kind that isn't reserved, withdraws the current one. + /// + /// It rereads the index, finds the current statement and issues under a + /// lock, so two statements issued at once in this store never supersede the + /// same one: the second supersedes the first. Statements issued in other + /// stores and synced here may still both supersede the same one. Afterwards, + /// the index these annotations hold doesn't include the new statement. /// /// # Errors /// /// Fails like [`Annotations::issue`], or with - /// [`AnnotateError::NothingToWithdraw`] if a withdrawal finds no - /// current statement with a verdict. + /// [`AnnotateError::NothingToWithdraw`] if a withdrawal finds no current + /// statement with a verdict. pub fn supersede( &mut self, mut statement: Statement, @@ -141,8 +143,8 @@ impl<'a, P: Platform> Annotations<'a, P> { Ok((id, statement)) } - /// Writes a statement after its payload, which is durable before - /// anything refers to it. + /// Writes the payload, if any, then the statement, so the payload is + /// durable before anything refers to it. Returns the statement's id. fn write( &self, statement: &Statement, @@ -156,8 +158,8 @@ impl<'a, P: Platform> Annotations<'a, P> { Ok(encoded.id().into()) } - /// The first statement superseding `statement`, `id`, that its issuer - /// issued. + /// Returns the first statement that supersedes `statement`, whose id is + /// `id`, and comes from the same issuer. fn superseded_by( &self, id: StatementId, @@ -171,7 +173,7 @@ impl<'a, P: Platform> Annotations<'a, P> { Ok(None) } - /// The statements about `subject`, in arrival order. + /// Returns the statements about `subject`, in the order they arrived. /// /// # Errors /// @@ -191,8 +193,9 @@ impl<'a, P: Platform> Annotations<'a, P> { .collect() } - /// The latest statement of `kind` from `issuer` about `subject` that - /// nothing superseded: the one a new such statement supersedes. + /// Returns the latest statement of `kind` from `issuer` about `subject` + /// that nothing superseded. A new statement of that kind from that issuer + /// supersedes this one. /// /// # Errors /// @@ -215,11 +218,11 @@ impl<'a, P: Platform> Annotations<'a, P> { .map(|annotation| annotation.id)) } - /// Issues a `core.divergent` statement as `issuer` if `change` has more - /// than one head, returning it. It is about the head with the smallest - /// id, and its payload lists every head, one id per line, so the same - /// heads always make the same statement: flagging them again writes - /// nothing. + /// If `change` has more than one head, issues a `core.divergent` + /// statement as `issuer` and returns its id; otherwise returns `None`. The + /// statement is about the head with the smallest id, and its payload lists + /// every head, one id per line. The same heads always make the same + /// statement, so flagging them again writes nothing new. /// /// # Errors /// @@ -254,19 +257,18 @@ impl<'a, P: Platform> Annotations<'a, P> { } impl Store

{ - /// Whether `statement`'s issuer may issue a statement of its kind, if - /// that kind is reserved: + /// Whether `statement`'s issuer may issue a statement of its kind. Anyone + /// may issue a kind that isn't reserved. The reserved kinds may be issued + /// by: /// - /// - `core.abandon`, about a revision, only the change's creator: the - /// author of its first revision, so no one who took it over, or - /// rebased it, gives it up for them; - /// - `core.conflict`, a node, as a landing queue that could not rebase - /// the record, or the author of the revision it's about, listing - /// the conflicts its files still have; - /// - `core.divergent`, a node. + /// - `core.abandon`, about a revision: only the creator of its change, the + /// author of its first revision, not someone who took it over or rebased it; + /// - `core.conflict`: a node, such as a landing queue that could not rebase + /// the record, or, about a revision, its author, listing the conflicts its + /// files still have; + /// - `core.divergent`, about a revision: a node. /// - /// Reserved kinds are never promoted. Other kinds are anyone's, as far - /// as core is concerned. + /// No one may promote a statement of a reserved kind. /// /// # Errors /// @@ -293,9 +295,8 @@ impl Store

{ }) } - /// Whether `author` created the change of `revision`: made each - /// revision it evolves from that evolves from none. Records being - /// immutable, there is always one, and no one adds another later. + /// Whether `author` created the change of `revision`, that is, authored + /// every revision in its history that has no predecessors. fn created(&self, revision: RevisionId, author: &Principal) -> Result { let mut seen = HashSet::new(); let mut next = vec![revision]; @@ -321,15 +322,15 @@ pub enum AnnotateError { ForeignSupersession { /// The statement it supersedes. superseded: StatementId, - /// Who issued that one. + /// Who issued the superseded statement. issuer: Principal, - /// Who issues the new one. + /// Who issues the new statement. by: Principal, }, /// A promotion doesn't match its original. #[error("invalid promotion")] InvalidPromotion(#[from] InvalidPromotion), - /// A reserved kind from an issuer that may not issue it. + /// The statement is of a reserved kind that its issuer may not issue. #[error("{issuer} may not issue `{kind}` statements about this record")] Reserved { /// The kind. @@ -337,7 +338,7 @@ pub enum AnnotateError { /// Who issued it. issuer: Principal, }, - /// A withdrawal found no statement of its issuer's to take back. + /// A withdrawal found no statement from its issuer to take back. #[error( "you have no `{kind}` statement about {} to withdraw", subject.describe() @@ -345,7 +346,7 @@ pub enum AnnotateError { NothingToWithdraw { /// The kind. kind: Kind, - /// What it would be about: a revision or a statement. + /// The record the withdrawn statement would be about. subject: RecordId, }, /// Records cannot be read or written. @@ -398,7 +399,7 @@ mod tests { encoded.id().into() } - /// A check result about `revision` from `issuer`. + /// Builds a check result of `kind` about `revision` from `issuer`. pub(super) fn check( revision: RevisionId, kind: &str, @@ -434,7 +435,8 @@ mod tests { .unwrap() } - /// The kinds and originals of what `promote` issues to `revision`. + /// Promotes results to `revision` as `node:queue`, and returns the kind + /// and original of each promotion issued. pub(super) fn promote( store: &Store, revision: RevisionId, diff --git a/apps/origin-src/src/annotations/promotion.rs b/apps/origin-src/src/annotations/promotion.rs index b9bf1620..1bbd1414 100644 --- a/apps/origin-src/src/annotations/promotion.rs +++ b/apps/origin-src/src/annotations/promotion.rs @@ -1,18 +1,16 @@ -//! Promotion: carrying results over to the records with the same input +//! Promotion: carrying check results over to records with the same input //! digest. //! -//! A promotion claims what its original does, so it counts only once -//! checked against it: [`Store::claim`] checks it, and only that makes a -//! [`Claim`]. Whatever reads results, such as the landing queue, reads -//! claims, through [`Annotations::claims`]. +//! A promotion is a statement that repeats an original statement, about +//! another record with the same inputs. It counts only once +//! [`Store::claim`] has checked it against its original, which makes a +//! [`Claim`]. Code that reads results, such as the landing queue, reads +//! claims through [`Annotations::claims`]. //! -//! Promotion runs on demand, never as a side effect of reading: `origin -//! promote`, and the landing queue when it checks evidence, call -//! [`Annotations::promote`]. The index groups promotable statements by -//! kind, issuer and declared inputs, so the search costs one lookup per -//! input path for each group, then a comparison per statement against -//! digests the index caches. A statement's digest is computed from its -//! subject's trees the first time a search meets it. +//! Promotion happens only when asked for, through [`Annotations::promote`], +//! which `origin promote` and the landing queue call. Reading never +//! promotes. The index caches each statement's input digest, computed from +//! its subject's trees the first time a search meets it. use std::collections::HashSet; @@ -23,33 +21,34 @@ use super::Annotations; use crate::store::{Store, StoreError}; use crate::tree::Snapshots; -/// The claim a statement makes, checked: only [`Store::claim`] makes one. -/// A statement claims for itself, unless it promotes another. Then it makes -/// its original's claim, kind, verdict and issuer included, which holds -/// because their subjects' input digests are equal. +/// A statement's claim, checked by [`Store::claim`], the only way to make +/// one. A statement that isn't a promotion claims for itself. A promotion +/// makes its original's claim, with the original's kind, verdict and +/// issuer, since both subjects have the same input digest. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Claim { id: StatementId, statement: Statement, - /// The original a promotion carries, checked. + /// For a promotion, the original's id and the original. original: Option<(StatementId, Statement)>, } impl Claim { - /// The statement making the claim, which evidence cites. + /// Returns the id of the statement making the claim, which evidence + /// cites. #[must_use] pub fn id(&self) -> StatementId { self.id } - /// The statement making the claim. + /// Returns the statement making the claim. #[must_use] pub fn statement(&self) -> &Statement { &self.statement } - /// What is claimed: the statement, or for a promotion its original, - /// whose kind, verdict and issuer count. + /// Returns what is claimed: the statement itself, or for a promotion, its + /// original. Its kind, verdict and issuer are the ones that count. #[must_use] pub fn claimed(&self) -> &Statement { self.original @@ -57,7 +56,8 @@ impl Claim { .map_or(&self.statement, |(_, original)| original) } - /// The original the statement promotes, if it's a promotion. + /// Returns the id of the original the statement promotes, if it is a + /// promotion. #[must_use] pub fn original(&self) -> Option { self.original.as_ref().map(|&(id, _)| id) @@ -65,13 +65,16 @@ impl Claim { } impl Annotations<'_, P> { - /// The claims about `subject` that hold, in arrival order: those of - /// the statements nothing superseded, that [`Store::claim`] accepts with - /// the records this node has, and for a promotion, whose original - /// nothing superseded either, and that no statement about `subject` - /// of the kind from the original's issuer replaces, whatever came - /// first: a result that ran there wins, and so does one taken back - /// there (see [`Statement::drop_replaced_promotions`]). + /// Returns the claims about `subject` that hold, in arrival order. A + /// claim holds if: + /// + /// - nothing superseded its statement; + /// - [`Store::claim`] accepts it with the records this node has; + /// - for a promotion, nothing superseded its original either, and no other + /// statement about `subject` of the same kind from the original's issuer + /// replaces it, whichever came first (see + /// [`Statement::drop_replaced_promotions`]). A result run on `subject` + /// itself wins, and so does a withdrawal of one. /// /// # Errors /// @@ -101,9 +104,10 @@ impl Annotations<'_, P> { Ok(claims) } - /// Computes and remembers the input digest of every promotable - /// statement the index has none for, from every core. Those whose - /// subject or trees aren't in the store yet are left for a later search. + /// Computes the input digest of every promotable statement the index has + /// no digest for, on every core, and stores them in the index. It skips + /// statements whose subject or trees the store doesn't have yet, for a + /// later search to retry. fn compute_digests(&mut self) -> Result<(), StoreError> { let missing: Vec = self .index @@ -229,8 +233,10 @@ impl Annotations<'_, P> { } impl Store

{ - /// The snapshot of a record a statement is about, which its input - /// digest is taken from. Statements have none. + /// Returns the snapshot of `subject`, the record a statement is about, + /// which the statement's input digest is taken from: the snapshot itself, a + /// revision's snapshot, or an acceptance's state. Returns `None` for a + /// statement, which has no snapshot. /// /// # Errors /// @@ -244,14 +250,13 @@ impl Store

{ }) } - /// Checks the claim `statement`, `id`, makes. A statement that promotes - /// none makes its own. A promotion must name an original the store has - /// that is [promotable](Statement::is_promotable), match its kind, - /// verdict, inputs and payload, and be about a record whose input - /// digest equals the original's subject's: then it makes the - /// original's claim, or else the claim is invalid, which is the inner - /// error. Whether anyone superseded either is left to the reader, see - /// [`Annotations::claims`]. + /// Checks the claim that `statement`, whose id is `id`, makes. A statement + /// that isn't a promotion makes its own claim. A promotion makes its + /// original's claim if the store has the original, the original is + /// [promotable](Statement::is_promotable), they match in kind, verdict, + /// inputs and payload, and their subjects have the same input digest. + /// Otherwise it returns the reason as the inner error. It doesn't check + /// whether either statement was superseded: [`Annotations::claims`] does. /// /// # Errors /// @@ -312,17 +317,20 @@ pub enum InvalidPromotion { /// The store doesn't have the original. #[error("it promotes statement {}, which this repository doesn't have", .0.short())] UnknownOriginal(StatementId), - /// The original declares no inputs, depends on external ones, is - /// reserved, about a statement, or a promotion itself. + /// The original isn't promotable: it declares no inputs, depends on + /// external inputs, is of a reserved kind, is about a statement, or is + /// itself a promotion. #[error("it promotes statement {}, which isn't promotable", .0.short())] NotPromotable(StatementId), - /// A field differs from the original's. + /// A field differs from the original's. Holds the field's name. #[error("its {0} differs from its original's")] Differs(&'static str), - /// Its subject is a statement, which has no snapshot. + /// The promotion or its original is about a statement, which has no + /// snapshot. #[error("it is about a statement, which has no inputs")] NoSnapshot, - /// Its subject's input digest differs from the original's subject's. + /// The promotion's subject has a different input digest from the + /// original's subject. #[error("its subject's inputs differ from its original's")] InputsDiffer, } diff --git a/apps/origin-src/src/conflict.rs b/apps/origin-src/src/conflict.rs index 929e1896..722c5847 100644 --- a/apps/origin-src/src/conflict.rs +++ b/apps/origin-src/src/conflict.rs @@ -56,11 +56,11 @@ pub struct Conflicted { pub struct Conflicts(Vec); impl Conflicts { - /// The line starting our side, then its label. + /// The marker that starts our side, followed by its label. const OURS: &str = "<<<<<<< "; - /// The line between the sides. + /// The marker between the two sides. const BETWEEN: &str = "======="; - /// The line ending their side, then its label. + /// The marker that ends their side, followed by its label. const THEIRS: &str = ">>>>>>> "; /// Builds the conflicts from `conflicted`, sorted by path. When a path @@ -75,13 +75,14 @@ impl Conflicts { Self(conflicted) } - /// Adds `conflicted`, which must come after every path listed. + /// Adds `conflicted`, whose path must sort after every path already + /// listed. pub(crate) fn push(&mut self, conflicted: Conflicted) { debug_assert!(self.0.last().is_none_or(|last| last.path < conflicted.path)); self.0.push(conflicted); } - /// Whether there are none. + /// Whether there are no conflicts. #[must_use] pub fn is_empty(&self) -> bool { self.0.is_empty() @@ -118,10 +119,10 @@ impl Conflicts { resolved } - /// The content of a file both sides changed: `ours`, then `theirs`, - /// between markers naming them with `labels`. A side that removed the - /// file is empty. `None` if either side is binary, holding a NUL byte: - /// markers would only corrupt it. + /// Returns the content of a file both sides changed: `ours`, then + /// `theirs`, between conflict markers labeled with `labels`. A side that + /// removed the file counts as empty. Returns `None` if either side is + /// binary, holding a NUL byte, since markers would corrupt it. #[must_use] pub fn mark(ours: &[u8], theirs: &[u8], labels: [&str; 2]) -> Option> { if ours.contains(&0) || theirs.contains(&0) { diff --git a/apps/origin-src/src/policy.rs b/apps/origin-src/src/policy.rs index 6c2cc9e8..ad84eecc 100644 --- a/apps/origin-src/src/policy.rs +++ b/apps/origin-src/src/policy.rs @@ -1,6 +1,7 @@ -//! `policy.toml`, in the snapshot of the `policy` target: the nodes and -//! groups of a repository, and who orders each target and what landing on -//! it requires. The policy in force is the one at the target's head. +//! Reads `policy.toml`, the repository's policy, from the snapshot of the +//! `policy` target. It lists the repository's nodes and groups, the node +//! that orders each target, and what landing on each target requires. The +//! policy in force is the one at the head of the `policy` target. //! //! ```toml //! [nodes] # each node's ed25519 public key, in hex @@ -22,10 +23,10 @@ //! grants = { all = "none", "group:maintainers" = "write" } //! ``` //! -//! A target without a table of its own has the authority of `policy`, and -//! requires nothing. Every name a policy refers to must be defined in it, -//! and unknown keys are errors, so a typo never drops a requirement. Path -//! rules are parsed and checked, but not enforced yet. +//! A target without a table of its own uses the authority of `policy` and +//! requires nothing. Every name a policy uses must be defined in it, and +//! unknown keys are errors, so a typo never drops a requirement. Path rules +//! are parsed and checked, but not enforced yet. use std::collections::BTreeMap; use std::fmt; @@ -50,7 +51,7 @@ pub struct Policy { paths: Vec, } -/// Who orders a target, and what landing on it requires. +/// The node that orders a target, and what landing on it requires. #[derive(Clone, Debug, PartialEq, Eq)] struct TargetRules { authority: PrincipalName, @@ -75,7 +76,7 @@ pub struct Requirement { pub enum Principals { /// A user or a node. One(Principal), - /// The members of a group of the policy. + /// The members of a group the policy defines. Group(PrincipalName), } @@ -100,7 +101,7 @@ pub enum Grantee { /// What a path rule grants. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Access { - /// Nothing, not even the content. + /// No access, not even reading the content. None, /// Reading the content. Read, @@ -140,13 +141,13 @@ impl Policy { } } - /// The policy in force, at the head of the `policy` target, and the - /// acceptance holding it. + /// Returns the policy in force, from the head of the `policy` target, + /// with the acceptance that holds it. /// /// # Errors /// - /// Fails if the repository has no policy, its records cannot be read, - /// or it is invalid. + /// Fails if the repository has no policy, its records cannot be read, or + /// the policy is invalid. pub fn in_force(store: &Store

) -> Result<(AcceptanceId, Self), PolicyError> { let head = store .head(&TargetName::POLICY)? @@ -156,11 +157,12 @@ impl Policy { Ok((head.acceptance, policy)) } - /// The policy in force, or the default if the repository has none. + /// Returns the policy in force, or the default policy if the repository + /// has none. /// /// # Errors /// - /// Fails like [`Policy::in_force`], but for a missing policy. + /// Fails like [`Policy::in_force`], except when the policy is missing. pub fn load(store: &Store

) -> Result { match Self::in_force(store) { Ok((_, policy)) => Ok(policy), @@ -169,12 +171,12 @@ impl Policy { } } - /// The policy in `snapshot`, or `None` if it has no `policy.toml`. + /// Reads the policy in `snapshot`, or returns `None` if it has no + /// `policy.toml`. /// /// # Errors /// - /// Fails if the snapshot cannot be read, or its `policy.toml` is - /// invalid. + /// Fails if the snapshot cannot be read, or its `policy.toml` is invalid. pub fn of_snapshot( store: &Store

, snapshot: TreeId, @@ -207,8 +209,9 @@ impl Policy { (file, tree.encode()) } - /// The node that orders `target`: the one its table names, or else the - /// authority of `policy`. `None` if neither has a table. + /// Returns the node that orders `target`: the authority its table names, + /// or else the authority of the `policy` target. `None` if neither has a + /// table. #[must_use] pub fn authority(&self, target: &TargetName) -> Option<&PrincipalName> { self.targets @@ -217,7 +220,8 @@ impl Policy { .map(|rules| &rules.authority) } - /// What landing on `target` requires: nothing, if it has no table. + /// Returns what landing on `target` requires: nothing if it has no + /// table. #[must_use] pub fn requirements(&self, target: &TargetName) -> &[Requirement] { self.targets @@ -225,7 +229,7 @@ impl Policy { .map_or(&[], |rules| rules.require.as_slice()) } - /// The public key of `node`, if the policy lists it. + /// Returns the public key of `node`, if the policy lists it. #[must_use] pub fn node_key(&self, node: &PrincipalName) -> Option<&NodePublicKey> { self.nodes.get(node) @@ -243,7 +247,7 @@ impl Policy { } } - /// The `[[paths]]` rules, in order. + /// Returns the `[[paths]]` rules, in file order. #[must_use] pub fn paths(&self) -> &[PathRule] { &self.paths @@ -288,7 +292,8 @@ struct PathRuleFile { } impl PolicyFile { - /// Parses `value`, which is a `what`. + /// Parses `value` as a `T`. If it doesn't parse, the error says the value + /// was meant to be a `what`. fn parse(what: &'static str, value: String) -> Result where T: FromStr, @@ -384,7 +389,8 @@ impl TryFrom for Policy { } impl Policy { - /// Checks that the group `principals` names, if any, is defined. + /// Checks that the group `principals` names, if any, is defined, and + /// returns `principals`. fn check(&self, principals: Principals) -> Result { match &principals { Principals::Group(group) if !self.groups.contains_key(group) => { @@ -458,7 +464,7 @@ pub enum RuleError { /// A value doesn't parse. #[error("{what}: {reason}")] Invalid { - /// What the value is. + /// What the value should be, such as `node key`. what: &'static str, /// The value. value: String, @@ -503,7 +509,7 @@ pub enum PolicyError { Invalid { /// The snapshot holding it. snapshot: TreeId, - /// What is wrong, boxed: it's large, and rare. + /// What is wrong. Boxed because the error is large and rare. source: Box, }, /// An acceptance of `policy`, at this sequence number, names a policy other @@ -520,8 +526,8 @@ pub enum PolicyError { mod tests { use super::*; - /// A policy with every table, whose node `hosted` has the key of the - /// secret `[42; 32]`. + /// Builds a policy with every table, where node `hosted` has the public + /// key of the secret key `[42; 32]`. fn full_policy() -> String { let key = origin_shared::NodeKey::from_bytes(&[42; 32]).public(); format!( diff --git a/apps/origin-src/src/targets.rs b/apps/origin-src/src/targets.rs index 3b912d8b..996f5e2a 100644 --- a/apps/origin-src/src/targets.rs +++ b/apps/origin-src/src/targets.rs @@ -1,21 +1,20 @@ //! Target chains: the acceptances of each target, in order. //! -//! A target lives in `targets//`, where the [`TargetId`] is the hash of -//! its name, so names never become file names: +//! A target is stored in `targets//`, where the [`TargetId`] is the hash +//! of its name, so names never become file names: //! //! - `name`: the target's name. -//! - `log`: the id of each acceptance in hex, one line each, append-only. -//! Appenders hold an exclusive lock on it, which the kernel releases if -//! the process dies, and it is never replaced, so the lock always -//! protects it. +//! - `log`: the id of each acceptance in hex, one per line, append-only. +//! Appenders hold an exclusive lock on it, which the kernel releases if the +//! process dies. The file is never replaced, so the lock always protects it. //! - `head`: ` `, the latest published acceptance, replaced //! atomically. //! -//! Appending writes the acceptance durably, then appends its id to the log -//! and syncs it, and only then publishes the new head. Readers go by the -//! head, so they only ever see durable acceptances. If a crash leaves the -//! log ahead of the head, or a partial line at its end, the next append -//! repairs it first, syncing the log before publishing what it holds. +//! An append writes the acceptance durably, appends its id to the log and +//! syncs the log, and only then publishes the new head. Readers go by the +//! head, so they only see durable acceptances. If a crash leaves the log +//! ahead of the head, or a partial line at its end, the next append repairs +//! it first: it syncs the log, then publishes what it holds. use std::fmt; use std::fs::{self, File}; @@ -32,14 +31,15 @@ use crate::store::{Store, StoreError}; /// The latest acceptance of a target. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Head { - /// Its position in the log, from 0. + /// Its position in the log, counting from 0. pub seq: u64, /// The acceptance. pub acceptance: AcceptanceId, } impl Head { - /// Describes where a target is, for error messages. + /// Describes a target's head for error messages, or `nothing` if it has + /// none. pub(crate) fn describe(head: Option) -> String { head.map_or_else(|| "nothing".to_owned(), |head| head.to_string()) } @@ -89,7 +89,7 @@ impl TargetFiles { } } - /// The published head. + /// Reads the published head, or `None` if the target has none. fn read_head(&self) -> Result, StoreError> { let path = self.head(); let Some(bytes) = Self::read(&path)? else { @@ -102,7 +102,8 @@ impl TargetFiles { .ok_or(StoreError::Malformed(path)) } - /// Parses the complete lines of a log, ignoring a partial last one. + /// Parses the complete lines of a log into acceptance ids, ignoring a + /// partial last line. fn parse_log(&self, bytes: &[u8]) -> Result, StoreError> { bytes .as_chunks::<{ Self::LINE }>() @@ -117,8 +118,8 @@ impl TargetFiles { .collect() } - /// The last complete entry of a locked log, after cutting off a partial - /// line left by a crash. + /// Returns the last complete entry of a locked log, first cutting off a + /// partial last line left by a crash. fn last_entry(&self, log: &File) -> Result, StoreError> { let io_error = |source| StoreError::io(&self.log(), source); let len = log.metadata().map_err(io_error)?.len(); @@ -148,7 +149,8 @@ impl Store

{ } } - /// The latest acceptance of `target`, or `None` if it doesn't exist. + /// Returns the latest acceptance of `target`, or `None` if it doesn't + /// exist. /// /// # Errors /// @@ -157,7 +159,7 @@ impl Store

{ self.target_files(target.id()).read_head() } - /// The acceptances of `target`, oldest first. + /// Returns the published acceptances of `target`, oldest first. /// /// # Errors /// @@ -204,7 +206,7 @@ impl Store

{ Ok(files.parse_log(&line)?.first().copied()) } - /// The names of every target, in no particular order. + /// Returns the names of every target, in no particular order. /// /// # Errors /// @@ -232,19 +234,19 @@ impl Store

{ Ok(names) } - /// Appends `acceptance` to the chain of `target`, creating the target - /// with its first acceptance. + /// Appends `acceptance` to the chain of `target`, and returns its id. The + /// first acceptance creates the target. /// /// This is a compare-and-swap: the acceptance must follow the target's - /// latest one, with the next sequence number and naming it as `prev`. - /// Concurrent appends are serialized, and all but one of those following - /// the same acceptance fail. Verifying the signature is the caller's job, + /// latest one, with the next sequence number and that one as its `prev`. + /// Concurrent appends are serialized, and of several that follow the same + /// acceptance, only one succeeds. The caller must verify the signature, /// since only it knows the target's authority. /// /// # Errors /// - /// Fails with [`StoreError::Conflict`] if the acceptance doesn't follow - /// the latest one, [`StoreError::WrongTarget`] if it belongs to another + /// Fails with [`StoreError::Conflict`] if the acceptance doesn't follow the + /// latest one, with [`StoreError::WrongTarget`] if it belongs to another /// target, or if the target's files cannot be locked, read or written. pub fn append( &self, @@ -304,9 +306,9 @@ impl Store

{ Ok(id) } - /// Durably replaces the head of a target. Publishing the first - /// acceptance creates the target: its name is written too, and its - /// directory made durable. + /// Durably replaces the head of a target with `head`. Publishing the + /// first acceptance creates the target: it also writes the target's name + /// and makes the targets directory durable. fn publish( &self, files: &TargetFiles, @@ -350,7 +352,7 @@ mod tests { NodeKey::from_bytes(&[42; 32]) } - /// An acceptance of `target` following `prev`. + /// Builds an acceptance of `target` that follows `prev`. fn acceptance(target: &TargetName, prev: Option) -> Acceptance { AcceptanceBody { target: target.id(), diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index cc59b90d..5b7c91e0 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -26,7 +26,7 @@ pub struct FileChange { impl Store

{ /// Lists the files that differ between two trees, sorted by path. /// Subtrees with equal ids are skipped without being read, so the cost - /// follows the size of the change. + /// grows with the size of the change, not of the trees. /// /// # Errors /// @@ -37,7 +37,8 @@ impl Store

{ Ok(changes) } - /// Diffs two directories, `None` standing for one that doesn't exist. + /// Diffs the directory `dir` between two trees, adding each changed file + /// to `changes`. `None` stands for a directory that doesn't exist. fn diff_dir( &self, dir: &RepoPath, @@ -86,41 +87,43 @@ impl Store

{ } } -/// Two trees merged with the changes each made to a common one. +/// The result of merging two trees that each changed a common base. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Merge { - /// The merged tree: both sides' changes, and `ours` where they conflict. + /// The merged tree, holding both sides' changes. Where they conflict, it + /// holds what the kind of merge leaves there. pub tree: TreeId, /// The trees the merge made, which the store may not have yet. pub trees: Vec, - /// The files with conflict markers a [marked](Store::merge_marked) - /// merge made, which the store may not have yet either. + /// The files with conflict markers that a + /// [marked](Store::merge_marked) merge made, which the store may not have + /// yet either. pub files: Vec, - /// The paths both sides changed, each its own way, with what the merge - /// left there. + /// The paths both sides changed in different ways, with what the merge + /// left at each. pub conflicts: Conflicts, } -/// What a merge leaves where both sides changed a path, each its own way. +/// What a merge leaves at a path both sides changed in different ways. #[derive(Clone, Copy, Debug)] enum OnConflict<'l> { - /// `ours`. + /// Our version. KeepOurs, - /// Both versions between conflict markers naming the sides with these - /// labels, see [`Conflicts::mark`]. + /// Both versions between conflict markers labeled with these labels; see + /// [`Conflicts::mark`]. Mark([&'l str; 2]), - /// [`Store::UNKNOWN`], a version neither side can have. + /// [`Store::UNKNOWN`], an entry neither side can have. Unknown, } impl Store

{ - /// Merges `ours` and `theirs`, two trees made from `base`, file by file: - /// a path one side changed takes that side's version, and a path both - /// changed, each its own way, is a conflict, where the merge keeps - /// `ours`. A path is a file, so two sides that changed different files - /// of a directory merge cleanly. Without a base, every path either side - /// has counts as changed. Subtrees with equal ids are never read, so the - /// cost follows the size of the changes. + /// Merges `ours` and `theirs`, two trees made from `base`, file by file. + /// A path only one side changed takes that side's version. A path both + /// sides changed in different ways is a conflict, where the merge keeps + /// `ours`. Two sides that changed different files of a directory merge + /// cleanly. Without a base, every path either side has counts as changed. + /// Subtrees with equal ids are never read, so the cost grows with the size + /// of the changes. /// /// # Errors /// @@ -135,14 +138,13 @@ impl Store

{ } /// Merges like [`Store::merge`], but where both sides changed a text - /// file, the merged one holds both versions between conflict markers - /// naming the sides with `labels`, see [`Conflicts::mark`]. Binary files, - /// and paths a directory is on either side of, keep `ours`. + /// file, the merged file holds both versions between conflict markers + /// labeled with `labels` (see [`Conflicts::mark`]). Binary files, and paths + /// that are a directory on either side, keep `ours`. /// /// # Errors /// - /// Fails if a tree that differs, or a file that conflicts, cannot be - /// read. + /// Fails if a tree that differs, or a file that conflicts, cannot be read. pub fn merge_marked( &self, base: Option, @@ -153,18 +155,18 @@ impl Store

{ self.merge_with(base, ours, theirs, OnConflict::Mark(labels)) } - /// The entry a merge of merge bases has where they conflict: an id no - /// object has, so it equals neither side of a merge from it. A merge - /// never reads under it either: the bases may have had a directory - /// there, so any change at or under its path conflicts. + /// The entry a merge of merge bases leaves where they conflict. Its id + /// belongs to no object, so it equals neither side of a later merge from + /// it. That merge never reads under it either: any change at or under its + /// path conflicts, since the bases may have had a directory there. const UNKNOWN: TreeEntry = TreeEntry { kind: EntryKind::File, id: ObjectId::from_bytes([0; ObjectId::LEN]), }; - /// Merges like [`Store::merge`], but where both sides changed a path, - /// the merged tree has [`Store::UNKNOWN`]: how merge bases are merged - /// into one, so a merge from it conflicts there unless both sides + /// Merges like [`Store::merge`], but puts [`Store::UNKNOWN`] where both + /// sides changed a path. This is how several merge bases become one, so + /// that a merge from the result conflicts at those paths unless both sides /// agree. /// /// # Errors @@ -215,9 +217,10 @@ impl Store

{ Ok(merge) } - /// Merges three versions of the directory `dir`, `None` standing for one - /// that doesn't exist, returning the merged one, or `None` if it's - /// empty. + /// Merges three versions of the directory `dir`, base, ours and theirs, + /// `None` standing for one that doesn't exist. Resolves conflicts as + /// `on_conflict` says and records the trees it makes and the conflicts in + /// `merge`. Returns the merged directory, or `None` if it's empty. fn merge_dir( &self, dir: &RepoPath, @@ -300,10 +303,11 @@ impl Store

{ Ok(Some(id)) } - /// The entry of a file both sides changed, `ours` and `theirs`, that - /// holds both versions between conflict markers: a file on the side - /// that removed it is empty. Keeps `ours` if either side isn't a - /// regular file, or is binary or missing from the store. + /// Returns the entry of a file both sides changed, `ours` and `theirs`, + /// that holds both versions between conflict markers, and adds the new + /// file to `merge`. A side that removed the file counts as empty. Keeps + /// `ours` if either side isn't a regular file, or is binary or missing from + /// the store. fn mark( &self, ours: Option, @@ -335,8 +339,8 @@ impl Store

{ } } -/// Looks up the entries of snapshots by path, reading each tree once, -/// however many snapshots share it. +/// Looks up the entries of snapshots by path, caching each tree it reads, +/// so a tree shared by several snapshots is read once. #[derive(Debug)] pub struct Snapshots<'a, P> { store: &'a Store

, @@ -344,7 +348,7 @@ pub struct Snapshots<'a, P> { } impl<'a, P: Platform> Snapshots<'a, P> { - /// Looks up snapshots in `store`. + /// Creates a lookup over the snapshots in `store`. pub fn new(store: &'a Store

) -> Self { Self { store, @@ -352,8 +356,8 @@ impl<'a, P: Platform> Snapshots<'a, P> { } } - /// What `snapshot` stores at `path`, or `None` if nothing is there. At - /// the root, that's the snapshot's own tree. + /// Returns what `snapshot` holds at `path`, or `None` if nothing is + /// there. At the root, that's the snapshot's own tree. /// /// # Errors /// @@ -383,7 +387,8 @@ impl<'a, P: Platform> Snapshots<'a, P> { Ok(Some(entry)) } - /// The input digest of `snapshot`: one lookup per path of `inputs`. + /// Computes the input digest of `snapshot` for `inputs`, with one lookup + /// per path of `inputs`. /// /// # Errors ///