diff --git a/apps/origin-src/benches/annotations.rs b/apps/origin-src/benches/annotations.rs index 16eb2ef1..a15505d8 100644 --- a/apps/origin-src/benches/annotations.rs +++ b/apps/origin-src/benches/annotations.rs @@ -180,12 +180,22 @@ fn promotions_cached(bencher: Bencher<'_, '_>) { let (_dir, store, target) = promotion_store(); let issuer: Principal = "node:queue".parse().unwrap(); let mut annotations = Annotations::open(&store).unwrap(); - assert_eq!(annotations.promotions(target, &issuer).unwrap().len(), 9); + assert_eq!( + annotations + .promotions(RecordId::Revision(target), &issuer) + .unwrap() + .len(), + 9 + ); let index = Index::open(&store).unwrap(); bencher .counter(ItemsCount::new(STATEMENTS)) .with_inputs(|| Annotations::new(&store, index.clone())) - .bench_local_refs(|annotations| annotations.promotions(target, &issuer).unwrap()); + .bench_local_refs(|annotations| { + annotations + .promotions(RecordId::Revision(target), &issuer) + .unwrap() + }); } /// The first search, which computes and remembers the digest of each of @@ -202,5 +212,9 @@ fn promotions_uncached(bencher: Bencher<'_, '_>) { fs::remove_file(&log).unwrap(); Annotations::open(&store).unwrap() }) - .bench_local_refs(|annotations| annotations.promotions(target, &issuer).unwrap()); + .bench_local_refs(|annotations| { + annotations + .promotions(RecordId::Revision(target), &issuer) + .unwrap() + }); } diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index 2359acae..2d38a539 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -358,7 +358,9 @@ mod tests { use std::sync::Barrier; use std::thread; - use origin_shared::{Base, BlobId, Digest, Inputs, ObjectId, RepoPath, Revision, Verdict}; + use origin_shared::{ + Base, BlobId, Digest, Inputs, ObjectId, RepoPath, Revision, RevisionId, Verdict, + }; use super::*; use crate::tree::tests::build; @@ -440,7 +442,7 @@ mod tests { let promoter = principal("node:queue"); Annotations::open(store) .unwrap() - .promote(revision, &promoter) + .promote(RecordId::Revision(revision), &promoter) .unwrap() .into_iter() .map(|(_, statement)| { diff --git a/apps/origin-src/src/annotations/promotion.rs b/apps/origin-src/src/annotations/promotion.rs index abef909a..b9bf1620 100644 --- a/apps/origin-src/src/annotations/promotion.rs +++ b/apps/origin-src/src/annotations/promotion.rs @@ -17,7 +17,7 @@ use std::collections::HashSet; use origin_platform::Platform; -use origin_shared::{Principal, Record, RecordId, RevisionId, Statement, StatementId, TreeId}; +use origin_shared::{Principal, Record, RecordId, Statement, StatementId, TreeId}; use super::Annotations; use crate::store::{Store, StoreError}; @@ -140,25 +140,27 @@ impl Annotations<'_, P> { self.index.remember_digests(self.store, &digests.concat()) } - /// The statements promoting results to `revision`, as `issuer` would - /// issue them, without writing them, sorted by kind: for each - /// [promotion group](Statement::promotion_group), the latest statement - /// about another record with the same input digest as the revision, - /// unless its issuer superseded it. Groups whose kind and issuer the - /// revision already has a result of, directly or promoted, are skipped: - /// a result that ran there wins. + /// Returns the statements that would promote results to `subject`, as + /// `issuer` would issue them, without writing them, sorted by kind. For + /// each [promotion group](Statement::promotion_group), it picks the latest + /// statement about another record whose input digest equals the subject's, + /// unless its issuer superseded it. It skips a group if the subject already + /// has a result of that kind from that issuer, direct or promoted: a result + /// that ran on the subject wins. A statement has no snapshot, so nothing is + /// promoted to one. /// /// # Errors /// - /// Fails if a record or tree cannot be read, or computed digests cannot - /// be remembered. + /// Fails if a record or tree cannot be read, or the computed digests cannot + /// be saved to the index. pub fn promotions( &mut self, - revision: RevisionId, + subject: RecordId, issuer: &Principal, ) -> Result, StoreError> { - let subject = RecordId::Revision(revision); - let snapshot = self.store.get(revision)?.snapshot; + let Some(snapshot) = self.store.snapshot_of(subject)? else { + return Ok(Vec::new()); + }; self.compute_digests()?; // The results the revision has that hold, by kind and original @@ -203,19 +205,19 @@ impl Annotations<'_, P> { Ok(promotions) } - /// Issues the [`promotions`](Self::promotions) to `revision` as - /// `issuer`, returning them. + /// Issues the [`promotions`](Self::promotions) to `subject` as `issuer` and + /// returns them. /// /// # Errors /// - /// Fails like [`Annotations::promotions`], or if the statements cannot - /// be written. + /// Fails like [`Annotations::promotions`], or if the statements cannot be + /// written. pub fn promote( &mut self, - revision: RevisionId, + subject: RecordId, issuer: &Principal, ) -> Result, StoreError> { - let promotions = self.promotions(revision, issuer)?; + let promotions = self.promotions(subject, issuer)?; let encoded: Vec<_> = promotions.iter().map(Statement::encode).collect(); self.store.write_all(&encoded)?; Ok(encoded diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index 18b17f5b..cc7ecf04 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -17,9 +17,15 @@ //! statement about the revision lists the paths, and the change waits //! until a new revision of it merges. //! 3. **Policy.** The policy in force must name this node as the target's -//! authority. -//! 4. **Otherwise** this node signs an acceptance naming what landed and -//! the policy, and appends it to the target's chain. +//! authority. Each of the target's requirements needs a +//! [claim](crate::annotations::Claim) about the revision that lands. +//! Results about other records with the same input digest are promoted +//! to it first, and a valid promotion claims what its original does, as +//! the original's issuer. +//! 4. **Missing evidence.** The landing waits until the statements are +//! issued and the landing is retried. +//! 5. **Otherwise** this node signs an acceptance naming what landed, the +//! evidence and the policy, and appends it to the target's chain. //! //! Each target's queue lives in `queue//`. It holds a `lock`, //! taken while landing so landings on one target never race. @@ -38,7 +44,7 @@ use origin_shared::{ }; use crate::annotations::{AnnotateError, Annotations}; -use crate::policy::{Policy, PolicyError}; +use crate::policy::{Policy, PolicyError, Requirement}; use crate::store::{Store, StoreError}; use crate::targets::Head; @@ -84,7 +90,8 @@ pub struct Pending { pub onto: TargetName, /// What lands. pub proposal: Proposal, - /// The revision that didn't merge. + /// What the evidence must be about: the revision that would land. For a + /// conflict, the revision that did not merge. pub subject: RecordId, /// Why it waits. pub blocked: Blocked, @@ -93,6 +100,8 @@ pub struct Pending { /// Why a landing waits. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Blocked { + /// The subject lacks these statements, which the target requires. + Evidence(Vec), /// Both sides changed these paths. The `core.conflict` statement lists /// them too. Conflict { @@ -260,6 +269,7 @@ impl<'a, P: Platform> Queue<'a, P> { Ok(Session { queue: self, onto: onto.clone(), + policy, policy_head, state: self.store.get(tip.acceptance)?.body().state, tip, diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 4e20ffdf..7949b833 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -1,16 +1,18 @@ -//! Landing one candidate: rebasing it onto the target's tip, then appending -//! its acceptance, or keeping it waiting on a conflict. +//! Landing one candidate: rebasing it onto the target's tip, checking the +//! evidence the policy requires, then appending its acceptance, or keeping +//! it waiting. use std::collections::HashSet; use origin_platform::{LockedFile, Platform}; use origin_shared::{ AcceptanceBody, AcceptanceId, Base, ChangeId, EncodedObject, Kind, Record, RecordId, Revision, - RevisionId, Source, TargetName, TreeId, + RevisionId, Source, StatementId, TargetName, TreeId, }; -use crate::annotations::Annotations; +use crate::annotations::{AnnotateError, Annotations, Claim}; use crate::conflict::Conflicts; +use crate::policy::{Policy, Requirement}; use crate::store::{Store, StoreError}; use crate::targets::Head; @@ -20,7 +22,8 @@ use super::{Blocked, LandError, Landing, Pending, Proposal, Queue}; pub(super) struct Session<'q, 'a, P> { pub(super) queue: &'q Queue<'a, P>, pub(super) onto: TargetName, - /// The acceptance of `policy` holding the policy in force. + pub(super) policy: Policy, + /// The acceptance of `policy` that holds `policy`. pub(super) policy_head: AcceptanceId, /// The target's latest acceptance, and its snapshot. pub(super) tip: Head, @@ -33,7 +36,12 @@ pub(super) struct Session<'q, 'a, P> { pub(super) struct Candidate { /// What lands. pub(super) proposal: Proposal, + /// What the queue keeps waiting, if the candidate waits: the landing of the + /// stack it is in. + pub(super) kept_as: Proposal, pub(super) source: Source, + /// What the evidence must be about. + pub(super) subject: RecordId, /// The target's snapshot once it lands. pub(super) state: TreeId, /// The trees the merge made, to write first. @@ -146,7 +154,9 @@ impl Session<'_, '_, P> { if revision.base == tip { return self.submit(Candidate { proposal, + kept_as: stack.clone(), source: Source::Revision(id), + subject: RecordId::Revision(id), state: merge.tree, trees: merge.trees, revision: None, @@ -163,29 +173,68 @@ impl Session<'_, '_, P> { let rebased_id = RevisionId::from(rebased.id()); self.submit(Candidate { proposal, + kept_as: stack.clone(), source: Source::Revision(rebased_id), + subject: RecordId::Revision(rebased_id), state: merge.tree, trees: merge.trees, revision: Some(rebased), }) } - /// Lands `candidate`. Writes the records in layers, each durable before the - /// next refers to it: first the trees, then the rebased revision and the - /// acceptance. + /// Checks the policy for `candidate`, and lands it if its evidence is there + /// or else keeps it waiting. Writes the records in layers, each durable + /// before the next refers to it: the trees, then the rebased revision, then + /// the promoted statements and the acceptance. pub(super) fn submit(&mut self, candidate: Candidate) -> Result { let store = self.queue.store; if !candidate.trees.is_empty() { store.write_all(&candidate.trees)?; } let mut records: Vec = candidate.revision.into_iter().collect(); + let requirements = self.policy.requirements(&self.onto).to_vec(); + let mut evidence = Vec::new(); + let mut missing = Vec::new(); + if !requirements.is_empty() { + // Promotion reads the revision. + store.write_all(&records)?; + records.clear(); + let promotions = self + .annotations + .promotions(candidate.subject, &self.queue.principal())?; + let mut claims = self.annotations.claims(candidate.subject)?; + for promotion in promotions { + let encoded = promotion.encode(); + let claim = store.claim(encoded.id().into(), promotion)?; + claims.push(claim.map_err(AnnotateError::from)?); + records.push(encoded); + } + for requirement in requirements { + match self.evidence(&claims, &requirement) { + Some(id) if !evidence.contains(&id) => evidence.push(id), + Some(_) => {} + None => missing.push(requirement), + } + } + } + if !missing.is_empty() { + store.write_all(&records)?; + let pending = Pending { + onto: self.onto.clone(), + proposal: candidate.kept_as, + subject: candidate.subject, + blocked: Blocked::Evidence(missing), + }; + return Ok(Landing::Pending(pending)); + } + let acceptance = AcceptanceBody { target: self.onto.id(), seq: self.tip.seq + 1, prev: Some(self.tip.acceptance), state: candidate.state, landed: vec![candidate.source], - evidence: Vec::new(), + evidence, policy: Some(self.policy_head), } .sign(self.queue.key); @@ -204,6 +253,21 @@ impl Session<'_, '_, P> { }) } + /// Returns the first of `claims` that meets `requirement`: of the required + /// kind and verdict, from an issuer the policy admits. For a promotion, the + /// original's issuer counts. + fn evidence(&self, claims: &[Claim], requirement: &Requirement) -> Option { + claims + .iter() + .find(|claim| { + let claimed = claim.claimed(); + claimed.kind == requirement.kind + && claimed.verdict == Some(requirement.verdict) + && self.policy.admits(&requirement.issuer, &claimed.issuer) + }) + .map(Claim::id) + } + /// Blocks a landing on `conflicts` and keeps it waiting. Issues a /// `core.conflict` statement about `subject` listing them, unless this /// node's latest one already lists the same. diff --git a/apps/origin-src/src/queue/tests/conflicts.rs b/apps/origin-src/src/queue/tests/conflicts.rs index 9cd1f989..585eba56 100644 --- a/apps/origin-src/src/queue/tests/conflicts.rs +++ b/apps/origin-src/src/queue/tests/conflicts.rs @@ -15,7 +15,9 @@ fn conflicts_block_until_a_revision_merges() { panic!("{blocked:?}") }; assert_eq!(pending.subject, RecordId::Revision(two)); - let Blocked::Conflict { statement, paths } = &pending.blocked; + let Blocked::Conflict { statement, paths } = &pending.blocked else { + panic!("{pending:?}") + }; assert_eq!(paths, &[RepoPath::new("shared").unwrap()]); let conflict = repo.store.get(*statement).unwrap(); assert_eq!(conflict.kind, Kind::CONFLICT); diff --git a/apps/origin-src/src/queue/tests/evidence.rs b/apps/origin-src/src/queue/tests/evidence.rs new file mode 100644 index 00000000..57a2aa53 --- /dev/null +++ b/apps/origin-src/src/queue/tests/evidence.rs @@ -0,0 +1,118 @@ +//! Tests for the evidence a policy requires: results, promoted or not. + +use origin_shared::{Statement, Verdict}; + +use super::*; + +#[test] +fn missing_evidence_waits_and_promoted_results_count() { + let repo = Repo::new( + "[groups]\nrunners = [\"node:ci\"]\n[targets.main]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"group:runners\" }]\n", + ); + let code = repo.change_on_main(1, &[("src/lib.rs", "fn a() {}")]); + let docs = repo.change_on_main(2, &[("docs/guide.md", "# Guide")]); + let waiting = repo.land(1); + let [Landing::Pending(pending)] = &waiting[..] else { + panic!("{waiting:?}") + }; + assert!(matches!(&pending.blocked, Blocked::Evidence(missing) if missing.len() == 1)); + + // A user outside the group doesn't count; the runner does. + let annotations = Annotations::open(&repo.store).unwrap(); + annotations + .issue(&ci_test(code, "user:mallory"), None) + .unwrap(); + assert_eq!(repo.land(1), waiting); + let result = annotations.issue(&ci_test(code, "node:ci"), None).unwrap(); + let [landing] = &repo.land(1)[..] else { + panic!() + }; + let acceptance = repo + .store + .get(repo.tip(&TargetName::MAIN).acceptance) + .unwrap(); + assert_eq!(landed(landing), code); + assert_eq!(acceptance.body().evidence, [result]); + + // The docs change is rebased onto `src` as tested, so the result is + // promoted to it, and counts as the runner's. + let [landing] = &repo.land(2)[..] else { + panic!() + }; + let rebased = landed(landing); + assert_ne!(rebased, docs); + let acceptance = repo + .store + .get(repo.tip(&TargetName::MAIN).acceptance) + .unwrap(); + let [evidence] = acceptance.body().evidence[..] else { + panic!() + }; + let promoted = repo.store.get(evidence).unwrap(); + assert_eq!(promoted.subject, RecordId::Revision(rebased)); + assert_eq!(promoted.promoted_from, Some(result)); + assert_eq!(promoted.issuer, "node:queue".parse().unwrap()); +} + +#[test] +fn forged_promotions_are_no_evidence() { + let repo = requiring_ci(); + let failed = repo.change_on_main(1, &[("src/lib.rs", "bad")]); + let mut original = ci_test(failed, "user:ci"); + original.verdict = Some(Verdict::Fail); + let id = Annotations::open(&repo.store) + .unwrap() + .issue(&original, None) + .unwrap(); + // Eve wraps the trusted failure as a pass, written as a fetch would. + let forged = Statement { + verdict: Some(Verdict::Pass), + issuer: "user:eve".parse().unwrap(), + promoted_from: Some(id), + ..original.clone() + }; + // And carries a result that read the network to another change. + let old = repo.change_on_main(3, &[("src/lib.rs", "bad")]); + let docs = repo.change_on_main(2, &[("src/lib.rs", "bad"), ("docs", "d")]); + let mut external = ci_test(old, "user:ci"); + external.inputs.as_mut().unwrap().external = true; + let external_id: StatementId = external.encode().id().into(); + let reused = Statement { + subject: RecordId::Revision(docs), + issuer: "user:eve".parse().unwrap(), + promoted_from: Some(external_id), + ..external.clone() + }; + repo.store.write_all(&[external.encode()]).unwrap(); + repo.store + .write_all(&[forged.encode(), reused.encode()]) + .unwrap(); + assert!(matches!(repo.land(1)[..], [Landing::Pending(_)])); + assert!(matches!(repo.land(2)[..], [Landing::Pending(_)])); +} + +#[test] +fn replaced_results_are_promoted_again() { + let repo = requiring_ci(); + let old = repo.change_on_main(1, &[("src/lib.rs", "code")]); + let new = repo.change_on_main(2, &[("src/lib.rs", "code"), ("docs", "new")]); + let original = ci_test(old, "user:ci"); + let annotations = Annotations::open(&repo.store).unwrap(); + let id = annotations.issue(&original, None).unwrap(); + Annotations::open(&repo.store) + .unwrap() + .promote(RecordId::Revision(new), &"node:queue".parse().unwrap()) + .unwrap(); + // The same passing result runs again, replacing the one promoted. + let rerun = Statement { + supersedes: Some(id), + ..original + }; + annotations.issue(&rerun, None).unwrap(); + let landings = repo.land(2); + assert!( + matches!(landings[..], [Landing::Landed { .. }]), + "{landings:?}" + ); +} diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 4a0e0970..1c7745a7 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -2,12 +2,13 @@ mod changes; mod conflicts; +mod evidence; use origin_platform::Native; -use origin_shared::BlobId; use origin_shared::{ - Base, ChangeId, EncodedObject, Kind, NodeKey, PrincipalName, Record, RecordId, RepoPath, - Revision, RevisionId, Source, TargetName, TreeId, + Base, BlobId, ChangeId, Digest, EncodedObject, Inputs, Kind, NodeKey, PrincipalName, Record, + RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetName, TreeId, + Verdict, }; use super::*; @@ -155,3 +156,32 @@ fn landed(landing: &Landing) -> RevisionId { other => panic!("expected a landed revision, got {other:?}"), } } + +/// Returns a passing `ci.test` result about `subject` from `issuer`, whose +/// inputs are `src`. +fn ci_test(subject: RevisionId, issuer: &str) -> Statement { + Statement { + subject: RecordId::Revision(subject), + kind: Kind::new("ci.test").unwrap(), + verdict: Some(Verdict::Pass), + issuer: issuer.parse().unwrap(), + inputs: Some(Inputs { + paths: vec![RepoPath::new("src").unwrap()], + definition: Digest::of(b"cargo test"), + toolchain: Digest::of(b"rustc"), + external: false, + }), + payload: None, + supersedes: None, + promoted_from: None, + } +} + +/// Returns a repository whose `main` requires a passing `ci.test` from +/// `user:ci`. +fn requiring_ci() -> Repo { + Repo::new( + "[targets.main]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }]\n", + ) +} diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 9ef171dc..4f0f19e3 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -93,7 +93,7 @@ impl Payload { impl Workspace { /// This node, which issues the statements core makes. - fn node_principal(&self) -> Principal { + pub(super) fn node_principal(&self) -> Principal { Principal::Node(self.config.node().clone()) } @@ -325,7 +325,7 @@ impl Workspace { let working_copy = self.refresh()?; let mut annotations = Annotations::open(&self.store)?; let revision = working_copy.find_revision(annotations.index(), rev)?; - let promoted = annotations.promote(revision, &self.node_principal())?; + let promoted = annotations.promote(RecordId::Revision(revision), &self.node_principal())?; if promoted.is_empty() { println!("Nothing to promote to revision {}", revision.short()); }