diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index df84d1f9..de6fcb2e 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -1,5 +1,5 @@ -//! The landing queue: how a target's authority lands changes on it, one -//! acceptance at a time. +//! The landing queue: how a target's authority lands changes and other +//! targets on it, one acceptance at a time. //! //! Landing a change lands its stack: the head of each change below it that //! isn't on the target yet, from the bottom, with an acceptance each. A @@ -27,6 +27,14 @@ //! 5. **Otherwise** this node signs an acceptance naming what landed, the //! evidence and the policy, and appends it to the target's chain. //! +//! Landing another target works the same way: its tip is merged from the +//! newest acceptances both targets' histories share, and the requirements +//! apply to the merged snapshot. A merge that changes nothing lands +//! nothing if either tip is in the other's history: the target has the +//! source's already, or the source has nothing more. Otherwise it lands, +//! with no evidence then, so the target's history records the source's tip +//! and later merges start from it. +//! //! The queue of each target lives in `queue//`: a `lock` held //! while landing, so landings on one target never race. @@ -48,7 +56,7 @@ use crate::policy::{Policy, PolicyError, Requirement}; use crate::store::{Store, StoreError}; use crate::targets::Head; -use session::Session; +use session::{Candidate, Session}; /// The landing queues of a store's targets, as run by one node. #[derive(Debug)] @@ -63,6 +71,8 @@ pub struct Queue<'a, P = Native> { pub enum Proposal { /// A change, as of its head. Change(ChangeId), + /// Another target, as of its tip. + Target(TargetName), } /// How a landing went. @@ -72,7 +82,7 @@ pub enum Landing { Landed { /// What landed. proposal: Proposal, - /// The revision the acceptance names. + /// The revision or acceptance the acceptance names. source: Source, /// The acceptance. acceptance: Head, @@ -90,8 +100,9 @@ pub struct Pending { pub onto: TargetName, /// What lands. pub proposal: Proposal, - /// What the evidence must be about: the revision that would land. A - /// conflict is about the revision that didn't merge. + /// What the evidence must be about: the revision that would land, or + /// the merged snapshot of a target. A conflict is about the revision, + /// or the acceptance, that didn't merge. pub subject: RecordId, /// Why it waits. pub blocked: Blocked, @@ -195,6 +206,89 @@ impl<'a, P: Platform> Queue<'a, P> { Ok(landings) } + /// Lands the tip of `source` on `onto`. + /// + /// # Errors + /// + /// Fails if either target doesn't exist or they're the same, this node + /// isn't the authority of `onto`, or the records cannot be read or + /// written. + pub fn land_target( + &self, + source: &TargetName, + onto: &TargetName, + ) -> Result { + if source == onto { + return Err(LandError::SameTarget(onto.clone())); + } + let mut session = self.session(onto)?; + let tip = self + .store + .head(source)? + .ok_or_else(|| LandError::UnknownTarget(source.clone()))?; + let state = self.store.get(tip.acceptance)?.body().state; + let tips = [session.tip.acceptance, tip.acceptance]; + let history = session.history(&tips)?; + let base = history.merge_base(self.store, &tips)?; + let merge = self.store.merge(base, state, session.state)?; + let proposal = Proposal::Target(source.clone()); + if !merge.conflicts.is_empty() { + let subject = RecordId::Acceptance(tip.acceptance); + return session.block(proposal, subject, &merge.conflicts); + } + // A merge that changes nothing has nothing to record either when + // one tip is in the other's history: the target has the source's + // already, or the source has nothing the target lacks. + let [ours, theirs] = tips; + let either = history.descends(ours, theirs) || history.descends(theirs, ours); + if merge.tree == session.state && either { + return Ok(Landing::Unchanged(proposal)); + } + // Even a merge that changes nothing lands, so that the tip is in + // the target's history, and later merges start from it. + session.submit(Candidate { + kept_as: proposal.clone(), + proposal, + source: Source::Target(tip.acceptance), + subject: RecordId::Snapshot(merge.tree), + state: merge.tree, + trees: merge.trees, + revision: None, + }) + } + + /// Creates the target `name` at the tip of `from`, with a first + /// acceptance landing it. + /// + /// # Errors + /// + /// Fails if `name` exists, `from` doesn't, this node wouldn't be the new + /// target's authority, or the records cannot be read or written. + pub fn create_target(&self, name: &TargetName, from: &TargetName) -> Result { + let _lock = self.lock(name)?; + if self.store.head(name)?.is_some() { + return Err(LandError::TargetExists(name.clone())); + } + let (policy_head, policy) = Policy::in_force(self.store)?; + self.authorize(&policy, name)?; + let from = self + .store + .head(from)? + .ok_or_else(|| LandError::UnknownTarget(from.clone()))?; + let acceptance = AcceptanceBody { + target: name.id(), + seq: 0, + prev: None, + state: self.store.get(from.acceptance)?.body().state, + landed: vec![Source::Target(from.acceptance)], + evidence: Vec::new(), + policy: Some(policy_head), + } + .sign(self.key); + let acceptance = self.store.append(name, &acceptance)?; + Ok(Head { seq: 0, acceptance }) + } + /// The policy in `state`, about to become the policy in force, if it's /// a valid one that names an authority for `policy`, so the target /// never locks up. @@ -287,6 +381,7 @@ impl fmt::Display for Proposal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Change(change) => write!(f, "change {}", change.short()), + Self::Target(target) => write!(f, "`{target}`"), } } } @@ -297,6 +392,12 @@ pub enum LandError { /// No target has this name. #[error("no target is named `{0}`")] UnknownTarget(TargetName), + /// `target new` was given a name already taken. + #[error("a target is already named `{0}`")] + TargetExists(TargetName), + /// A target was landed on itself. + #[error("cannot land `{0}` on itself")] + SameTarget(TargetName), /// The policy names no authority for the target. #[error("policy.toml names no authority for `{0}`: give it, or `policy`, a [targets] table")] NoAuthority(TargetName), diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 1bf71cb6..dd8fe04b 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -10,6 +10,7 @@ use origin_shared::{ RevisionId, Source, StatementId, TargetName, TreeId, }; +use crate::ancestry::Ancestry; use crate::annotations::{AnnotateError, Annotations, Claim}; use crate::conflict::Conflicts; use crate::policy::{Policy, PolicyError, Requirement}; @@ -199,7 +200,13 @@ impl Session<'_, '_, P> { None }; let mut records: Vec = candidate.revision.into_iter().collect(); - let requirements = self.policy.requirements(&self.onto).to_vec(); + // A landing that changes nothing, which only records another + // target's tip, needs no evidence. + let requirements = if candidate.state == self.state { + Vec::new() + } else { + self.policy.requirements(&self.onto).to_vec() + }; let mut evidence = Vec::new(); let mut missing = Vec::new(); if !requirements.is_empty() { @@ -316,4 +323,30 @@ impl Session<'_, '_, P> { }; Ok(Landing::Pending(pending)) } + + /// The history of `tips`, the target's and another target's, to merge + /// that one from: the state of the newest acceptance both histories + /// share, or the [merge](Ancestry::merge_base) of several, if each + /// lacks another, as after targets landed each other. An acceptance's + /// history is the one before it, and the acceptances of other targets + /// it landed: a target's first lands the one it was created from, so + /// targets created from the same one share it. + /// + /// The nearest shared acceptance can be an older one, through a target + /// that forked early and landed recently, so both histories are read + /// whole, each acceptance once. + pub(super) fn history( + &self, + tips: &[AcceptanceId], + ) -> Result, StoreError> { + Ancestry::walk(tips, |id| { + let acceptance = self.store().get(id)?; + let body = acceptance.body(); + let landed = body.landed.iter().filter_map(|source| match *source { + Source::Target(landed) => Some(landed), + Source::Revision(_) => None, + }); + Ok::<_, StoreError>((landed.chain(body.prev).collect(), body.state)) + }) + } } diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 5da053ef..13fef032 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -4,12 +4,13 @@ mod changes; mod conflicts; mod evidence; mod policy; +mod targets; use origin_platform::Native; use origin_shared::{ - Base, BlobId, ChangeId, Digest, EncodedObject, Inputs, Kind, NodeKey, PrincipalName, Record, - RecordId, RepoPath, Revision, RevisionId, Source, Statement, StatementId, TargetName, TreeId, - Verdict, + AcceptanceBody, Base, BlobId, ChangeId, Digest, EncodedObject, Inputs, Kind, NodeKey, + PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, + StatementId, TargetName, TreeId, Verdict, }; use super::*; diff --git a/apps/origin-src/src/queue/tests/targets.rs b/apps/origin-src/src/queue/tests/targets.rs new file mode 100644 index 00000000..80458c85 --- /dev/null +++ b/apps/origin-src/src/queue/tests/targets.rs @@ -0,0 +1,309 @@ +//! Landing targets on each other, and the merges that takes. + +use origin_shared::Statement; + +use super::*; + +#[test] +fn targets_land_on_each_other() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let (main, overhaul) = (TargetName::MAIN, TargetName::new("overhaul").unwrap()); + repo.change_on_main(1, &[("shared", "v1")]); + repo.land(1); + let queue = repo.queue(); + queue.create_target(&overhaul, &main).unwrap(); + assert!(matches!( + queue.create_target(&overhaul, &main), + Err(LandError::TargetExists(_)) + )); + assert_eq!(repo.state(&overhaul), repo.state(&main)); + + // Work lands on the overhaul while `main` moves on elsewhere. + let on_overhaul = Base::Acceptance(repo.tip(&overhaul).acceptance); + repo.revision(2, &[], on_overhaul, &[("shared", "v2"), ("new", "n")]); + queue + .land_change(ChangeId::from_bytes([2; 16]), &overhaul) + .unwrap(); + repo.change_on_main(3, &[("other", "o")]); + repo.land(3); + + // Catching up merges `main`'s change since the fork; finishing + // lands the overhaul on `main`. + assert!(matches!( + queue.land_target(&main, &overhaul).unwrap(), + Landing::Landed { .. } + )); + let landing = queue.land_target(&overhaul, &main).unwrap(); + assert!(matches!( + landing, + Landing::Landed { + source: Source::Target(_), + .. + } + )); + let expected = repo.files(&[("shared", "v2"), ("new", "n"), ("other", "o")]); + assert_eq!(repo.state(&main), expected); + assert_eq!(repo.state(&overhaul), expected); + assert_eq!( + queue.land_target(&overhaul, &main).unwrap(), + Landing::Unchanged(Proposal::Target(overhaul.clone())) + ); + assert!(matches!( + queue.land_target(&main, &main), + Err(LandError::SameTarget(_)) + )); +} + +#[test] +fn sibling_targets_merge_from_where_they_forked() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + repo.change_on_main(1, &[("keep", "k"), ("delete", "d")]); + repo.land(1); + let (a, b) = (TargetName::new("a").unwrap(), TargetName::new("b").unwrap()); + let queue = repo.queue(); + queue.create_target(&a, &TargetName::MAIN).unwrap(); + queue.create_target(&b, &TargetName::MAIN).unwrap(); + // `a` deletes a file, `b` adds one: neither ever landed the other. + let on = |target| Base::Acceptance(repo.tip(target).acceptance); + repo.revision(2, &[], on(&a), &[("keep", "k")]); + queue + .land_change(ChangeId::from_bytes([2; 16]), &a) + .unwrap(); + repo.revision( + 3, + &[], + on(&b), + &[("keep", "k"), ("delete", "d"), ("other", "o")], + ); + queue + .land_change(ChangeId::from_bytes([3; 16]), &b) + .unwrap(); + assert!(matches!( + queue.land_target(&a, &b).unwrap(), + Landing::Landed { .. } + )); + assert_eq!(repo.state(&b), repo.files(&[("keep", "k"), ("other", "o")])); +} + +#[test] +fn a_merge_that_changes_nothing_still_records_the_tip() { + // `b` requires tests, which a landing changing nothing doesn't. + let repo = Repo::new( + "[targets.b]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }]\n", + ); + let queue = repo.queue(); + let annotations = Annotations::open(&repo.store).unwrap(); + // Results without inputs, which are never promoted to a merge. + let pass = |subject| { + let statement = Statement { + subject, + inputs: None, + ..ci_test(RevisionId::from(EncodedObject::blob(b"").id()), "user:ci") + }; + annotations.issue(&statement, None).unwrap(); + }; + let (a, b) = (TargetName::new("a").unwrap(), TargetName::new("b").unwrap()); + let land = |change: u8, target: &TargetName, files: &[(&str, &str)]| { + let on = Base::Acceptance(repo.tip(target).acceptance); + pass(RecordId::Revision(repo.revision(change, &[], on, files))); + queue + .land_change(ChangeId::from_bytes([change; 16]), target) + .unwrap(); + }; + queue.create_target(&a, &TargetName::MAIN).unwrap(); + queue.create_target(&b, &TargetName::MAIN).unwrap(); + // Both add the same file: `a`'s tip lands on `b`, changing nothing. + land(1, &a, &[("f", "f")]); + land(2, &b, &[("f", "f")]); + let state = repo.state(&b); + assert!(matches!( + queue.land_target(&a, &b).unwrap(), + Landing::Landed { .. } + )); + assert_eq!(repo.state(&b), state); + assert_eq!( + queue.land_target(&a, &b).unwrap(), + Landing::Unchanged(Proposal::Target(a.clone())) + ); + + // So once `a` deletes the file, landing it on `b` deletes it there. + land(3, &a, &[]); + let landing = queue.land_target(&a, &b).unwrap(); + let Landing::Pending(pending) = landing else { + panic!("a deletion waits for its evidence: {landing:?}") + }; + pass(pending.subject); + assert!(matches!( + queue.land_target(&a, &b).unwrap(), + Landing::Landed { .. } + )); + assert_eq!(repo.state(&b), repo.files(&[])); + + // A target and the one it was made from, neither changing: landing + // either on the other records nothing, however often. + let c = TargetName::new("c").unwrap(); + queue.create_target(&c, &TargetName::MAIN).unwrap(); + for _ in 0..2 { + for (from, onto) in [(&c, &TargetName::MAIN), (&TargetName::MAIN, &c)] { + assert_eq!( + queue.land_target(from, onto).unwrap(), + Landing::Unchanged(Proposal::Target(from.clone())) + ); + } + } +} + +#[test] +fn targets_merge_from_their_newest_shared_acceptance() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let queue = repo.queue(); + let [a, b, c, d] = ["a", "b", "c", "d"].map(|name| TargetName::new(name).unwrap()); + let land = |change: u8, target: &TargetName, files: &[(&str, &str)]| { + let on = Base::Acceptance(repo.tip(target).acceptance); + repo.revision(change, &[], on, files); + queue + .land_change(ChangeId::from_bytes([change; 16]), target) + .unwrap(); + }; + // `c` and `d` fork from an empty `main`, `a` and `b` from the next + // `main`, which adds a file. + queue.create_target(&c, &TargetName::MAIN).unwrap(); + queue.create_target(&d, &TargetName::MAIN).unwrap(); + repo.change_on_main(1, &[("delete", "d")]); + repo.land(1); + queue.create_target(&a, &TargetName::MAIN).unwrap(); + queue.create_target(&b, &TargetName::MAIN).unwrap(); + // `a` deletes it, `b` keeps it, and both move on. + for n in 0..4 { + let counter = n.to_string(); + land(10 + n, &a, &[("a", &counter)]); + land(20 + n, &b, &[("delete", "d"), ("b", &counter)]); + } + // Then each lands a side line: the empty `main` is nearer. + land(30, &c, &[("c", "c")]); + land(31, &d, &[("d", "d")]); + assert!(matches!( + queue.land_target(&c, &a).unwrap(), + Landing::Landed { .. } + )); + assert!(matches!( + queue.land_target(&d, &b).unwrap(), + Landing::Landed { .. } + )); + + assert!(matches!( + queue.land_target(&a, &b).unwrap(), + Landing::Landed { .. } + )); + assert_eq!( + repo.state(&b), + repo.files(&[("a", "3"), ("b", "3"), ("c", "c"), ("d", "d")]), + "the deletion stands" + ); +} + +#[test] +fn criss_crossed_targets_merge_what_their_bases_agree_on() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let queue = repo.queue(); + let [a, b] = ["a", "b"].map(|name| TargetName::new(name).unwrap()); + let land = |change: u8, target: &TargetName, files: &[(&str, &str)]| { + let on = Base::Acceptance(repo.tip(target).acceptance); + repo.revision(change, &[], on, files); + queue + .land_change(ChangeId::from_bytes([change; 16]), target) + .unwrap(); + }; + queue.create_target(&a, &TargetName::MAIN).unwrap(); + queue.create_target(&b, &TargetName::MAIN).unwrap(); + land(1, &a, &[("a", "0"), ("shared", "a")]); + land(2, &b, &[("b", "0"), ("shared", "b")]); + // Each lands the other's tip at once, resolving `shared` its own + // way: two merge bases, which disagree on it. + let tips = [repo.tip(&a), repo.tip(&b)]; + let policy = Some(repo.tip(&TargetName::POLICY).acceptance); + for (target, prev, other, shared) in [(&a, tips[0], tips[1], "a"), (&b, tips[1], tips[0], "b")] + { + let merged = AcceptanceBody { + target: target.id(), + seq: prev.seq + 1, + prev: Some(prev.acceptance), + state: repo.files(&[("a", "0"), ("b", "0"), ("shared", shared)]), + landed: vec![Source::Target(other.acceptance)], + evidence: vec![], + policy, + } + .sign(&repo.key); + repo.store.append(target, &merged).unwrap(); + } + // Then each changes another file. + land(3, &a, &[("a", "1"), ("b", "0"), ("shared", "a")]); + land(4, &b, &[("a", "0"), ("b", "1"), ("shared", "b")]); + + let Landing::Pending(pending) = queue.land_target(&a, &b).unwrap() else { + panic!("the bases disagree on `shared`, so it can't be merged blindly"); + }; + assert!( + matches!(&pending.blocked, Blocked::Conflict { paths, .. } if paths.iter().map(RepoPath::as_str).eq(["shared"])), + "{pending:?}" + ); + // Once `a` takes `b`'s side, the disjoint edits merge. + land(5, &a, &[("a", "1"), ("b", "0"), ("shared", "b")]); + assert!(matches!( + queue.land_target(&a, &b).unwrap(), + Landing::Landed { .. } + )); + assert_eq!( + repo.state(&b), + repo.files(&[("a", "1"), ("b", "1"), ("shared", "b")]) + ); +} + +#[test] +fn bases_that_disagree_on_a_kind_conflict_on_any_change_under_it() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let queue = repo.queue(); + let land = |change: u8, target: &TargetName, files: &[(&str, &str)]| { + let on = Base::Acceptance(repo.tip(target).acceptance); + repo.revision(change, &[], on, files); + queue + .land_change(ChangeId::from_bytes([change; 16]), target) + .unwrap(); + }; + let [a, b] = ["a", "b"].map(|name| TargetName::new(name).unwrap()); + queue.create_target(&a, &TargetName::MAIN).unwrap(); + queue.create_target(&b, &TargetName::MAIN).unwrap(); + land(1, &a, &[("p", "file")]); + land(2, &b, &[("p/delete", "original")]); + // Each lands the other's tip at once, both choosing the directory: + // two merge bases, one with a file at `p`, the other a directory. + let tips = [repo.tip(&a), repo.tip(&b)]; + let policy = Some(repo.tip(&TargetName::POLICY).acceptance); + for (target, prev, other) in [(&a, tips[0], tips[1]), (&b, tips[1], tips[0])] { + let merged = AcceptanceBody { + target: target.id(), + seq: prev.seq + 1, + prev: Some(prev.acceptance), + state: repo.files(&[("p/delete", "original")]), + landed: vec![Source::Target(other.acceptance)], + evidence: vec![], + policy, + } + .sign(&repo.key); + repo.store.append(target, &merged).unwrap(); + } + // `a` deletes `p/delete`, `b` keeps it and adds beside it. + land(3, &a, &[("a", "new")]); + land(4, &b, &[("p/delete", "original"), ("p/new", "new")]); + + // What `p` was is unknown, so the deletion can't be told from an + // addition: it conflicts, rather than bring `p/delete` back. + let Landing::Pending(pending) = queue.land_target(&a, &b).unwrap() else { + panic!("the bases disagree on `p`, so it can't be merged blindly"); + }; + assert!( + matches!(&pending.blocked, Blocked::Conflict { paths, .. } if paths.iter().map(RepoPath::as_str).eq(["p"])), + "{pending:?}" + ); +} diff --git a/docs/design.md b/docs/design.md index efedfbde..28ef1f85 100644 --- a/docs/design.md +++ b/docs/design.md @@ -384,7 +384,11 @@ and stops at the first one that waits. several, as git's recursive strategy does. The merge is checked as a revision on the tip, authored by the queue's node, so results about the same merge on another target never count. - - A landing that changes nothing is skipped. + - A landing that changes nothing is skipped: the target already has it. + But a merge of another target's tip that changes nothing still lands, + as an acceptance of the same state that needs no evidence, so later + merges start from it, unless either tip is already in the other's + history: then neither has anything the other lacks. 3. **On conflict,** issue a `core.conflict` statement and keep the landing blocked. Nothing fails, and landing again retries it. 4. **Check the policy** in force *now*: