diff --git a/apps/origin-src/benches/annotations.rs b/apps/origin-src/benches/annotations.rs index 8bd6458e..d482b46c 100644 --- a/apps/origin-src/benches/annotations.rs +++ b/apps/origin-src/benches/annotations.rs @@ -37,18 +37,24 @@ fn inputs(paths: &[&str], definition: &str) -> Inputs { .iter() .map(|path| RepoPath::new(path).unwrap()) .collect(), + target_paths: Vec::new(), definition: Digest::of(definition.as_bytes()), toolchain: Digest::of(b"rustc 1.99.0"), external: false, } } -/// 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<'_, '_>) { +/// A store holding the snapshot of the 20k-file fixture, with a +/// `checks.toml`, and the inputs the digest benches declare: two +/// directories, a file and a missing path. +fn digest_store() -> (tempfile::TempDir, Store, TreeId, Inputs) { let dir = tempfile::tempdir().unwrap(); FixtureTree::LARGE.write(dir.path()).unwrap(); + fs::write( + dir.path().join("checks.toml"), + "[checks.test]\ncommand = \"true\"\n", + ) + .unwrap(); let store = Store::new(dir.path().join(".origin"), Native::default()); store.init().unwrap(); let (snapshot, _) = Worktree::new(dir.path(), &store) @@ -58,9 +64,68 @@ fn input_digest(bencher: Bencher<'_, '_>) { &["dir0", "dir5/sub3", "dir12/sub7/file7820.rs", "missing"], "cargo test", ); + (dir, store, snapshot, inputs) +} + +/// The input digest of the fixture's snapshot. Each run reads the trees +/// anew. +#[divan::bench(sample_count = 50)] +fn input_digest(bencher: Bencher<'_, '_>) { + let (_dir, store, snapshot, inputs) = digest_store(); + let trees = store.input_trees(RecordId::Snapshot(snapshot)).unwrap(); bencher.bench(|| { Snapshots::new(&store) - .input_digest(snapshot, &inputs) + .input_digest(&mut trees.unwrap(), &inputs) + .unwrap() + }); +} + +/// The input digest of a revision three deep in a stack on an acceptance +/// of the fixture, which also reads `checks.toml` from the target: each +/// run reads the revision, the stack down to the acceptance, its state +/// and the trees anew. +#[divan::bench(sample_count = 50)] +fn input_digest_on_target(bencher: Bencher<'_, '_>) { + let (_dir, store, snapshot, inputs) = digest_store(); + let inputs = Inputs { + target_paths: vec![RepoPath::new("checks.toml").unwrap()], + ..inputs + }; + let acceptance = AcceptanceBody { + target: TargetName::MAIN.id(), + seq: 0, + prev: None, + state: snapshot, + landed: Vec::new(), + evidence: Vec::new(), + policy: None, + } + .sign(&NodeKey::from_bytes(&[1; 32])) + .encode(); + store.write_all(std::slice::from_ref(&acceptance)).unwrap(); + let mut base = Base::Acceptance(acceptance.id().into()); + let mut top = None; + for change in 0..3 { + let revision = Revision { + change: ChangeId::from_bytes([change; 16]), + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot, + description: EncodedObject::blob(b"").id().into(), + author: "user:bench".parse().unwrap(), + } + .encode(); + store.write_all(std::slice::from_ref(&revision)).unwrap(); + let id = RevisionId::from(revision.id()); + (base, top) = (Base::Revision(id), Some(id)); + } + let subject = RecordId::Revision(top.unwrap()); + bencher.bench(|| { + let mut trees = store.input_trees(subject).unwrap().unwrap(); + Snapshots::new(&store) + .input_digest(&mut trees, &inputs) + .unwrap() .unwrap() }); } diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index d3712466..3db39198 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -452,12 +452,25 @@ mod tests { change: u8, predecessors: &[RevisionId], files: &[(&str, &str)], + ) -> RevisionId { + revision_on_state(store, target, &[], change, predecessors, files) + } + + /// Writes a revision like [`revision_on`], on a first acceptance whose + /// state holds `state`. + pub(super) fn revision_on_state( + store: &Store, + target: &TargetName, + state: &[(&str, &str)], + change: u8, + predecessors: &[RevisionId], + files: &[(&str, &str)], ) -> RevisionId { let acceptance = AcceptanceBody { target: target.id(), seq: 0, prev: None, - state: build(store, &[]), + state: build(store, state), landed: Vec::new(), evidence: Vec::new(), policy: None, @@ -496,6 +509,7 @@ mod tests { .iter() .map(|path| RepoPath::new(path).unwrap()) .collect(), + target_paths: Vec::new(), definition: Digest::of(kind.as_bytes()), toolchain: Digest::of(b"rustc 1.99.0"), external, diff --git a/apps/origin-src/src/annotations/promotion.rs b/apps/origin-src/src/annotations/promotion.rs index 25a9ae9c..8b4eae99 100644 --- a/apps/origin-src/src/annotations/promotion.rs +++ b/apps/origin-src/src/annotations/promotion.rs @@ -20,7 +20,7 @@ use std::collections::HashSet; use origin_platform::Platform; use origin_shared::api::Annotation; use origin_shared::{ - Acceptance, Base, Principal, Record, RecordId, Statement, StatementId, TargetId, + Acceptance, Base, Principal, Record, RecordId, Statement, StatementId, TargetId, TreeId, }; use super::Annotations; @@ -137,14 +137,11 @@ impl Annotations<'_, P> { let Some(inputs) = &statement.inputs else { continue; }; - let digest = self - .store - .snapshot_of(statement.subject) - .and_then(|snapshot| { - snapshot - .map(|snapshot| snapshots.input_digest(snapshot, inputs)) - .transpose() - }); + let digest = match self.store.input_trees(statement.subject) { + Ok(Some(mut trees)) => snapshots.input_digest(&mut trees, inputs), + Ok(None) => Ok(None), + Err(error) => Err(error), + }; match digest { Ok(Some(digest)) => digests.push((id, digest)), Ok(None) | Err(StoreError::NotFound(_)) => {} @@ -179,8 +176,8 @@ impl Annotations<'_, P> { issuer: &Principal, mut sees: impl FnMut(RecordId) -> Result, ) -> Result, StoreError> { - let (Some(snapshot), Some(target)) = ( - self.store.snapshot_of(subject)?, + let (Some(mut trees), Some(target)) = ( + self.store.input_trees(subject)?, self.store.target_of(subject)?, ) else { return Ok(Vec::new()); @@ -206,7 +203,9 @@ impl Annotations<'_, P> { if held.contains(&(first.kind.clone(), first.issuer.clone())) { continue; } - let digest = snapshots.input_digest(snapshot, inputs)?; + let Some(digest) = snapshots.input_digest(&mut trees, inputs)? else { + continue; + }; for &id in statements.iter().rev() { if self.index.digest(id) != Some(digest) { continue; @@ -308,15 +307,16 @@ impl Store

{ if target.is_none() || target != self.target_of(original.subject)? { return Ok(Err(InvalidPromotion::OtherTarget)); } - let (Some(here), Some(there), Some(inputs)) = ( - self.snapshot_of(statement.subject)?, - self.snapshot_of(original.subject)?, + let (Some(mut here), Some(mut there), Some(inputs)) = ( + self.input_trees(statement.subject)?, + self.input_trees(original.subject)?, &original.inputs, ) else { return Ok(Err(InvalidPromotion::NoSnapshot)); }; let mut snapshots = Snapshots::new(self); - if snapshots.input_digest(here, inputs)? != snapshots.input_digest(there, inputs)? { + let here = snapshots.input_digest(&mut here, inputs)?; + if here.is_none() || here != snapshots.input_digest(&mut there, inputs)? { return Ok(Err(InvalidPromotion::InputsDiffer)); } Ok(Ok(Claim { @@ -346,6 +346,19 @@ impl Store

{ .map(|acceptance| acceptance.body().target)) } + /// The state of the target a revision based on `base` is on: that of + /// the acceptance it leads to, as [`Store::target_of`] finds it, or + /// `None` if the store lacks a record on the way. + /// + /// # Errors + /// + /// Fails if a record cannot be read. + pub fn base_state(&self, base: Base) -> Result, StoreError> { + Ok(self + .base_acceptance(base)? + .map(|acceptance| acceptance.body().state)) + } + /// The acceptance `base` leads to, through the revisions below it, or /// `None` if the store lacks a record on the way. fn base_acceptance(&self, mut base: Base) -> Result, StoreError> { @@ -391,15 +404,77 @@ pub enum InvalidPromotion { #[cfg(test)] mod tests { - use origin_shared::{EncodedObject, Kind, TargetName, Verdict}; + use origin_shared::{ + AcceptanceId, AttachmentId, ChangeId, Digest, EncodedObject, Inputs, Kind, ObjectId, + RepoPath, Revision, RevisionId, TargetName, Verdict, + }; use super::*; use crate::annotations::AnnotateError; use crate::annotations::tests::{ - FILES, check, issue, principal, promote, revision, revision_on, store, + FILES, check, issue, principal, promote, revision, revision_on, revision_on_state, store, }; use crate::index::Index; + #[test] + fn target_paths_are_read_from_the_base() { + let (_dir, store) = store(); + let inputs = Inputs { + paths: vec![RepoPath::new("src").unwrap()], + target_paths: vec![RepoPath::new("checks.toml").unwrap()], + definition: Digest::of(b"cargo test"), + toolchain: Digest::of(b"rustc 1.99.0"), + external: false, + }; + let digest = |revision: RevisionId| { + let mut trees = store.input_trees(RecordId::Revision(revision)).unwrap(); + Snapshots::new(&store) + .input_digest(trees.as_mut().unwrap(), &inputs) + .unwrap() + }; + let files = [("src/lib.rs", "v1"), ("checks.toml", "its own")]; + let on = |state: &[(&str, &str)]| { + revision_on_state(&store, &TargetName::MAIN, state, 1, &[], &files) + }; + let below = on(&[("checks.toml", "old"), ("src/lib.rs", "v0")]); + let old = digest(below); + assert!(old.is_some()); + assert_ne!( + digest(on(&[("checks.toml", "new"), ("src/lib.rs", "v0")])), + old, + "the base's checks.toml is an input" + ); + assert_eq!( + digest(on(&[ + ("checks.toml", "old"), + ("src/lib.rs", "v2"), + ("docs", "x") + ])), + old, + "the rest of the base isn't" + ); + + // A stack is on its bottom's base, and a revision whose base the + // store lacks on none. + let based = |base, change| { + let revision = Revision { + change: ChangeId::from_bytes([change; 16]), + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot: store.get(below).unwrap().snapshot, + description: AttachmentId::from(EncodedObject::attachment(b"").id()), + author: principal("user:alice"), + } + .encode(); + store.write_all(std::slice::from_ref(&revision)).unwrap(); + RevisionId::from(revision.id()) + }; + assert_eq!(digest(based(Base::Revision(below), 2)), old); + let missing = AcceptanceId::from(ObjectId::from_bytes([7; 32])); + assert_eq!(digest(based(Base::Acceptance(missing), 3)), None); + } + #[test] fn results_promote_within_their_target_only() { let (_dir, store) = store(); diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index d90e2091..b54ee041 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -451,6 +451,7 @@ impl AnnotateArgs { let digest = |arg: &Option| arg.map_or_else(|| Digest::of(b""), |arg| arg.0); (!self.inputs.is_empty()).then(|| Inputs { paths: self.inputs.clone(), + target_paths: Vec::new(), definition: digest(&self.definition), toolchain: digest(&self.toolchain), external: self.external, diff --git a/apps/origin-src/src/index.rs b/apps/origin-src/src/index.rs index c2deccbe..174617aa 100644 --- a/apps/origin-src/src/index.rs +++ b/apps/origin-src/src/index.rs @@ -1065,6 +1065,7 @@ mod tests { .unwrap(); result.inputs = Some(Inputs { paths: Vec::new(), + target_paths: Vec::new(), definition: Digest::of(b"cargo test"), toolchain: Digest::of(b"rustc"), external: false, diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index 7979cf14..c96f93ba 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -1482,6 +1482,7 @@ grants = { all = "none", "user:ada" = "write" } verdict: Some(origin_shared::Verdict::Pass), inputs: Some(origin_shared::Inputs { paths: vec![path("README.md")], + target_paths: Vec::new(), definition: origin_shared::Digest::of(b"test"), toolchain: origin_shared::Digest::of(b""), external: false, diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 66512310..fff6d179 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -180,6 +180,7 @@ pub(crate) fn ci_test(subject: RevisionId, issuer: &str) -> Statement { issuer: issuer.parse().unwrap(), inputs: Some(Inputs { paths: vec![RepoPath::new("src").unwrap()], + target_paths: Vec::new(), definition: Digest::of(b"cargo test"), toolchain: Digest::of(b"rustc"), external: false, diff --git a/apps/origin-src/src/tree.rs b/apps/origin-src/src/tree.rs index 055cbf02..ac32d86c 100644 --- a/apps/origin-src/src/tree.rs +++ b/apps/origin-src/src/tree.rs @@ -14,8 +14,8 @@ use std::path::PathBuf; use origin_platform::Platform; use origin_shared::access::{Level, PathAccess}; use origin_shared::{ - Base, Digest, EncodedObject, EntryKind, EntryName, Inputs, ObjectId, Record, RecordId, - RepoPath, Tree, TreeEntry, TreeId, + Base, Digest, EncodedObject, EntryKind, EntryName, InputSource, Inputs, ObjectId, Record, + RecordId, RepoPath, Tree, TreeEntry, TreeId, }; use crate::conflict::{Conflicted, Conflicts}; @@ -522,17 +522,66 @@ impl<'a, P: Platform> Snapshots<'a, P> { Ok(Some(entry)) } - /// The input digest of `snapshot`: one lookup per path of `inputs`. + /// The input digest of the record whose trees are `trees`: one lookup + /// per path of `inputs`. `None` if `inputs` read the target, and the + /// record is on none, or the store lacks its base. /// /// # Errors /// - /// Fails if a tree on the way to a path cannot be read. + /// Fails if a record, or a tree on the way to a path, cannot be read. pub fn input_digest( &mut self, - snapshot: TreeId, + trees: &mut InputTrees, inputs: &Inputs, - ) -> Result { - inputs.digest(|path| self.entry_at(snapshot, path)) + ) -> Result, StoreError> { + let target = if inputs.target_paths.is_empty() { + None + } else { + let Some(state) = trees.target(self.store)? else { + return Ok(None); + }; + Some(state) + }; + let snapshot = trees.snapshot; + inputs + .digest(|source, path| match (source, target) { + (InputSource::Snapshot, _) => self.entry_at(snapshot, path), + (InputSource::Target, Some(state)) => self.entry_at(state, path), + // There's a state whenever there are target paths. + (InputSource::Target, None) => Ok(None), + }) + .map(Some) + } +} + +/// The trees the input digest of a record reads: its snapshot, and the +/// state of the target it's on, read when first needed, once. +#[derive(Clone, Copy, Debug)] +pub struct InputTrees { + snapshot: TreeId, + target: TargetState, +} + +/// The state of the target a record is on. +#[derive(Clone, Copy, Debug)] +enum TargetState { + /// Not read yet: that of the acceptance a revision's base leads to. + Unread(Base), + /// Read: `None` if the record is on no target, or the store lacks its + /// base. + Read(Option), +} + +impl InputTrees { + /// The state of the target the record is on, reading it from `store` + /// the first time. + fn target(&mut self, store: &Store

) -> Result, StoreError> { + let state = match self.target { + TargetState::Read(state) => state, + TargetState::Unread(base) => store.base_state(base)?, + }; + self.target = TargetState::Read(state); + Ok(state) } } @@ -550,6 +599,28 @@ impl Store

{ }) } + /// The trees the input digest of `record` reads: see [`InputTrees`]. + /// A statement has none, and a snapshot is on no target. + /// + /// # Errors + /// + /// Fails if the record cannot be read. + pub fn input_trees(&self, record: RecordId) -> Result, StoreError> { + let (snapshot, target) = match record { + RecordId::Snapshot(id) => (id, TargetState::Read(None)), + RecordId::Revision(id) => { + let revision = self.get(id)?; + (revision.snapshot, TargetState::Unread(revision.base)) + } + RecordId::Acceptance(id) => { + let state = self.get(id)?.body().state; + (state, TargetState::Read(Some(state))) + } + RecordId::Statement(_) => return Ok(None), + }; + Ok(Some(InputTrees { snapshot, target })) + } + /// The snapshot of a record: a revision's, an acceptance's state, or a /// snapshot itself. Statements have none. /// diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 1253e085..0791a57e 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -182,9 +182,10 @@ impl Workspace { subject.describe() ); } - if let (Some(inputs), RecordId::Revision(revision)) = (&statement.inputs, subject) { - let snapshot = self.store.get(revision)?.snapshot; - let digest = Snapshots::new(&self.store).input_digest(snapshot, inputs)?; + if let (Some(inputs), Some(mut trees)) = + (&statement.inputs, self.store.input_trees(subject)?) + && let Some(digest) = Snapshots::new(&self.store).input_digest(&mut trees, inputs)? + { println!("Input digest: {}", digest.short()); } Ok(()) @@ -293,7 +294,16 @@ impl Workspace { ); } if let Some(inputs) = &statement.inputs { - let paths: Vec<_> = inputs.paths.iter().map(ToString::to_string).collect(); + let on_target = inputs + .target_paths + .iter() + .map(|path| format!("{path} on the target")); + let paths: Vec<_> = inputs + .paths + .iter() + .map(ToString::to_string) + .chain(on_target) + .collect(); let external = if inputs.external { ", and external" } else { diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index e5efd7ea..71aff378 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -460,6 +460,7 @@ async fn promotions_must_match_their_original() { issuer: "user:ada".parse().unwrap(), inputs: Some(Inputs { paths: vec!["a.txt".parse().unwrap()], + target_paths: Vec::new(), definition: Digest::of(b"test"), toolchain: Digest::of(b"rustc"), external: false, @@ -777,6 +778,7 @@ async fn promotes_results_by_input_digest() { let statement = Statement { inputs: Some(Inputs { paths: vec![RepoPath::new("a.txt").unwrap()], + target_paths: Vec::new(), definition: Digest::of(b"test"), toolchain: Digest::of(b""), external: false, diff --git a/crates/origin-shared/benches/object.rs b/crates/origin-shared/benches/object.rs index c2a15e8d..70bf27f1 100644 --- a/crates/origin-shared/benches/object.rs +++ b/crates/origin-shared/benches/object.rs @@ -65,6 +65,7 @@ fn statement() -> Statement { paths: ["src", "Cargo.toml", "Cargo.lock"] .map(|path| RepoPath::new(path).unwrap()) .into(), + target_paths: Vec::new(), definition: Digest::of(b"cargo test"), toolchain: Digest::of(b"rustc 1.99.0"), external: false, diff --git a/crates/origin-shared/src/lib.rs b/crates/origin-shared/src/lib.rs index d4bbf22f..39e10932 100644 --- a/crates/origin-shared/src/lib.rs +++ b/crates/origin-shared/src/lib.rs @@ -21,9 +21,9 @@ pub use id::{ }; pub use name::InvalidName; pub use object::{ - Acceptance, AcceptanceBody, Base, EncodedObject, EntryKind, EntryName, Inputs, Kind, NodeKey, - NodePublicKey, Object, ObjectKind, Record, RecordId, Revision, Signature, Source, Statement, - Tree, TreeEntry, Verdict, + Acceptance, AcceptanceBody, Base, EncodedObject, EntryKind, EntryName, InputSource, Inputs, + Kind, NodeKey, NodePublicKey, Object, ObjectKind, Record, RecordId, Revision, Signature, + Source, Statement, Tree, TreeEntry, Verdict, }; pub use path::RepoPath; pub use principal::{Principal, PrincipalName}; diff --git a/crates/origin-shared/src/object/mod.rs b/crates/origin-shared/src/object/mod.rs index 10310c42..afe79b2e 100644 --- a/crates/origin-shared/src/object/mod.rs +++ b/crates/origin-shared/src/object/mod.rs @@ -29,7 +29,7 @@ pub use encoding::Reader; pub(crate) use encoding::{Field, fields, tagged}; pub use errors::{DecodeError, IdMismatch}; pub use revision::{Base, Revision}; -pub use statement::{Inputs, Kind, RecordId, Statement, Verdict}; +pub use statement::{InputSource, Inputs, Kind, RecordId, Statement, Verdict}; pub use tree::{EntryKind, EntryName, Tree, TreeEntry}; mod acceptance; @@ -370,6 +370,7 @@ pub(crate) mod tests { issuer: "node:ci-1".parse().unwrap(), inputs: Some(Inputs { paths: vec![RepoPath::new("src").unwrap(), RepoPath::root()], + target_paths: Vec::new(), definition: Digest::of(b"cargo test"), toolchain: Digest::of(b"rustc 1.99.0"), external: false, @@ -437,8 +438,8 @@ pub(crate) mod tests { "ab13bedf42e8", "d06087ffcfd2", "8783b1fca530", - "b4f235b57ce9", - "f0442b2f9f6c", + "deec8210f35c", + "cfdeda35b53c", ] ); } diff --git a/crates/origin-shared/src/object/statement.rs b/crates/origin-shared/src/object/statement.rs index 221200f2..b7fa745e 100644 --- a/crates/origin-shared/src/object/statement.rs +++ b/crates/origin-shared/src/object/statement.rs @@ -307,13 +307,22 @@ impl Field for Verdict { /// What a statement depended on. /// -/// The input digest of a snapshot hashes the ids it stores at `paths`, with -/// `definition` and `toolchain`. A statement that declares inputs and isn't -/// `external` is promoted to every revision with the same input digest. +/// The input digest of a record hashes the ids its snapshot stores at +/// `paths`, those the state of the target it's on stores at +/// `target_paths`, with `definition` and `toolchain`. A statement that +/// declares inputs and isn't `external` is promoted to every revision on +/// the same target with the same input digest. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct Inputs { /// The files and directories read, each covering everything under it. pub paths: Vec, + /// The files and directories read from the state of the target the + /// record is on rather than from its snapshot, such as the definition + /// of the checks in force there: a revision is on the target of the + /// acceptance it's based on, directly or through the revisions below + /// it, and an acceptance on its own. + #[serde(default)] + pub target_paths: Vec, /// The check's command and configuration. pub definition: Digest, /// The tools that ran it, such as the hash of `rustc -V`. @@ -325,6 +334,7 @@ pub struct Inputs { fields!(Inputs { paths, + target_paths, definition, toolchain, external, @@ -332,40 +342,54 @@ fields!(Inputs { impl Inputs { /// The BLAKE3 key derivation contexts, which keep these hashes apart - /// from every other. - const SPEC_CONTEXT: &str = "origin 2026-10 input spec"; - const DIGEST_CONTEXT: &str = "origin 2026-10 input digest"; - - /// The paths, sorted and without duplicates: the order they're declared - /// in doesn't matter. - fn sorted_paths(&self) -> Vec<&RepoPath> { - let mut paths: Vec<_> = self.paths.iter().collect(); + /// from every other. Their date versions what they hash: 2026-11 added + /// the target paths. + const SPEC_CONTEXT: &str = "origin 2026-11 input spec"; + const DIGEST_CONTEXT: &str = "origin 2026-11 input digest"; + + /// The paths read from each source, in this order, each sorted and + /// without duplicates: the order they're declared in doesn't matter. + fn sorted_paths(&self) -> [(InputSource, Vec<&RepoPath>); 2] { + [ + (InputSource::Snapshot, Self::sorted(&self.paths)), + (InputSource::Target, Self::sorted(&self.target_paths)), + ] + } + + /// `paths`, sorted and without duplicates. + fn sorted(paths: &[RepoPath]) -> Vec<&RepoPath> { + let mut paths: Vec<_> = paths.iter().collect(); paths.sort_unstable(); paths.dedup(); paths } /// Identifies what the inputs declare: equal for statements reading the - /// same paths with the same definition and toolchain, whatever their - /// order. It hashes the definition, the toolchain, and each path's - /// `u32` length and bytes. + /// same paths from the same sources with the same definition and + /// toolchain, whatever their order. It hashes the definition, the + /// toolchain, then the paths, then the target paths, each list as its + /// `u32` count and each path's `u32` length and bytes. #[must_use] pub fn spec(&self) -> Digest { let mut hasher = blake3::Hasher::new_derive_key(Self::SPEC_CONTEXT); hasher.update(self.definition.as_bytes()); hasher.update(self.toolchain.as_bytes()); - for path in self.sorted_paths() { + for (_, paths) in self.sorted_paths() { let mut encoded = Vec::new(); - Reader::write_str(path.as_str(), &mut encoded); + Reader::write_len(paths.len(), &mut encoded); + for path in paths { + Reader::write_str(path.as_str(), &mut encoded); + } hasher.update(&encoded); } Digest::from_bytes(*hasher.finalize().as_bytes()) } - /// The input digest of a snapshot: the [`Inputs::spec`], then for each - /// path, in its order, a 0 byte if the snapshot has nothing there, or a - /// 1 byte, the entry's kind and its id. `entry_at` looks up what the - /// snapshot stores at a path; at the root, that's the snapshot's tree. + /// The input digest of a record: the [`Inputs::spec`], then for each + /// path, then each target path, in their order, a 0 byte if nothing is + /// there, or a 1 byte, the entry's kind and its id. `entry_at` looks up + /// what the record's snapshot, or the state of its target, stores at a + /// path; at the root, that's the whole tree. /// /// Records with equal digests agree on everything the inputs cover, so /// a promotable statement about one holds for the other. @@ -375,22 +399,33 @@ impl Inputs { /// Fails if `entry_at` does. pub fn digest( &self, - mut entry_at: impl FnMut(&RepoPath) -> Result, E>, + mut entry_at: impl FnMut(InputSource, &RepoPath) -> Result, E>, ) -> Result { let mut hasher = blake3::Hasher::new_derive_key(Self::DIGEST_CONTEXT); hasher.update(self.spec().as_bytes()); - for path in self.sorted_paths() { - match entry_at(path)? { - None => hasher.update(&[0]), - Some(entry) => hasher - .update(&[1, entry.kind as u8]) - .update(entry.id.as_bytes()), - }; + for (source, paths) in self.sorted_paths() { + for path in paths { + match entry_at(source, path)? { + None => hasher.update(&[0]), + Some(entry) => hasher + .update(&[1, entry.kind as u8]) + .update(entry.id.as_bytes()), + }; + } } Ok(Digest::from_bytes(*hasher.finalize().as_bytes())) } } +/// Where the input digest reads a path of [`Inputs`] from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InputSource { + /// The record's snapshot: [`Inputs::paths`]. + Snapshot, + /// The state of the target the record is on: [`Inputs::target_paths`]. + Target, +} + #[cfg(test)] mod tests { use std::collections::HashMap; @@ -405,15 +440,16 @@ mod tests { .iter() .map(|path| RepoPath::new(path).unwrap()) .collect(), + target_paths: Vec::new(), definition: Digest::of(definition.as_bytes()), toolchain: Digest::of(b"rustc 1.99.0"), external: false, } } - /// The digest of `inputs` over a snapshot holding `files`. - fn digest(inputs: &Inputs, files: &[(&str, &str)]) -> Digest { - let files: HashMap<_, _> = files + /// The entries of `files`, by path. + fn entries(files: &[(&str, &str)]) -> HashMap { + files .iter() .map(|&(path, content)| { let entry = TreeEntry { @@ -422,12 +458,29 @@ mod tests { }; (RepoPath::new(path).unwrap(), entry) }) - .collect(); + .collect() + } + + /// The digest of `inputs` over a snapshot holding `files`, on a target + /// holding `target`. + fn digest_on(inputs: &Inputs, files: &[(&str, &str)], target: &[(&str, &str)]) -> Digest { + let (files, target) = (entries(files), entries(target)); inputs - .digest(|path| Ok::<_, Infallible>(files.get(path).copied())) + .digest(|source, path| { + let tree = match source { + InputSource::Snapshot => &files, + InputSource::Target => &target, + }; + Ok::<_, Infallible>(tree.get(path).copied()) + }) .unwrap() } + /// The digest of `inputs` over a snapshot holding `files`. + fn digest(inputs: &Inputs, files: &[(&str, &str)]) -> Digest { + digest_on(inputs, files, &[]) + } + #[test] fn digests_cover_exactly_the_inputs() { let lint = inputs(&["src", "Cargo.toml"], "cargo clippy"); @@ -463,6 +516,40 @@ mod tests { assert_ne!(digest(&test, &[("src", "v1"), ("Cargo.toml", "a")]), base); } + #[test] + fn target_paths_are_read_from_the_target() { + let checks = Inputs { + target_paths: vec![RepoPath::new("checks.toml").unwrap()], + ..inputs(&["src"], "cargo test") + }; + let files = [("src", "v1"), ("checks.toml", "old")]; + let base = digest_on(&checks, &files, &[("checks.toml", "new")]); + assert_ne!( + digest_on(&checks, &files, &[("checks.toml", "newer")]), + base, + "the target's checks are an input" + ); + assert_eq!( + digest_on(&checks, &[("src", "v1")], &[("checks.toml", "new")]), + base, + "the snapshot's aren't" + ); + assert_eq!( + digest_on(&checks, &files, &[("checks.toml", "new"), ("src", "v2")]), + base, + "nor is the rest of the target" + ); + let on_target = Inputs { + target_paths: vec![RepoPath::new("checks.toml").unwrap()], + ..inputs(&[], "cargo test") + }; + assert_ne!( + inputs(&["checks.toml"], "cargo test").spec(), + on_target.spec(), + "a path read from the target isn't one read from the snapshot" + ); + } + #[test] fn kinds_are_validated() { for valid in ["ci.test", "review", "semantic.diff", "a_b.c-d.e1"] { diff --git a/docs/design.md b/docs/design.md index 28ef1f85..a489b284 100644 --- a/docs/design.md +++ b/docs/design.md @@ -236,18 +236,28 @@ A statement can declare what it depended on: ```rust struct Inputs { - paths: Vec, // e.g. ["src", "Cargo.toml", "Cargo.lock"]; "" is the whole snapshot - definition: Digest, // the check's command and configuration - toolchain: Digest, // e.g. the hash of `rustc -V` output - external: bool, // also depended on things outside the snapshot + paths: Vec, // e.g. ["src", "Cargo.toml", "Cargo.lock"]; "" is the whole snapshot + target_paths: Vec, // read from the target the record is on, e.g. ["checks.toml"] + definition: Digest, // the check's command and configuration + toolchain: Digest, // e.g. the hash of `rustc -V` output + external: bool, // also depended on things outside the snapshot } ``` -Each path names a file or a directory and covers everything under it. The -input digest hashes what the snapshot stores at each path (absent, or the -entry's kind and id), plus `definition` and `toolchain`. Trees are already -content-addressed, so the digest costs one lookup per path, however large the -tree. +Each path names a file or a directory and covers everything under it. +`paths` are read from the record's snapshot, `target_paths` from the state +of the target the record is on: a revision's is that of the acceptance it's +based on, directly or through the revisions below it, and an acceptance's is +its own. Target paths hold what's in force on the target rather than what the +record changes, such as the checks a worker runs: a candidate that restores +an older `checks.toml` doesn't match the results of the older checks. + +The input digest hashes the spec, then what each path holds (absent, or the +entry's kind and id): the paths', then the target paths', each list sorted. +The spec hashes `definition`, `toolchain`, then each list as its count and its +paths, so a path read from the target never matches one read from the +snapshot. Trees are already content-addressed, so the digest costs one lookup +per path, however large the tree. A statement is **promotable** when it declares inputs, isn't `external`, isn't itself a promotion, isn't about another statement, and its kind isn't @@ -499,8 +509,10 @@ external = true # reads the network: never promoted ``` - Each check's kind is `ci.`. -- `checks.toml` itself is always one of a check's inputs, so editing a check - runs it again. +- `checks.toml` itself is always one of a check's inputs: of the revision, for + `origin ci run`, and for a worker, a target path, as the target holds it. So + a check runs again once an edit to it lands, and a candidate can't bring + back the results of checks the target no longer has by restoring them. - Protecting `checks.toml` with a `[[paths]]` rule, as in the example policy, keeps submitters from changing the checks at all. - A change in a toolchain's output only reaches the queue's promotions through diff --git a/docs/openapi.json b/docs/openapi.json index 35aab7c3..6f47cd52 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1641,7 +1641,7 @@ }, "Inputs": { "type": "object", - "description": "What a statement depended on.\n\nThe input digest of a snapshot hashes the ids it stores at `paths`, with\n`definition` and `toolchain`. A statement that declares inputs and isn't\n`external` is promoted to every revision with the same input digest.", + "description": "What a statement depended on.\n\nThe input digest of a record hashes the ids its snapshot stores at\n`paths`, those the state of the target it's on stores at\n`target_paths`, with `definition` and `toolchain`. A statement that\ndeclares inputs and isn't `external` is promoted to every revision on\nthe same target with the same input digest.", "required": [ "paths", "definition", @@ -1664,6 +1664,13 @@ }, "description": "The files and directories read, each covering everything under it." }, + "target_paths": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RepoPath" + }, + "description": "The files and directories read from the state of the target the\nrecord is on rather than from its snapshot, such as the definition\nof the checks in force there: a revision is on the target of the\nacceptance it's based on, directly or through the revisions below\nit, and an acceptance on its own." + }, "toolchain": { "$ref": "#/components/schemas/Digest", "description": "The tools that ran it, such as the hash of `rustc -V`."