Skip to content

Commit ae1ba2c

Browse files
committed
feat(queue): keep waiting landings, and list them
A landing that conflicted or lacked evidence only said so to whoever ran it. Nothing remembered it, so nobody else could see what waited on a target, or why. Each landing that waits is now kept durably in its target's queue directory, `queue/<target id>/change-<id>` or `target-<target id>`, replacing the last attempt's, and forgotten once it lands or the target turns out to have it already. The file holds what lands, what the evidence must be about, and either the requirements missing or the `core.conflict` statement, whose payload lists the paths. A stack that waits is kept whole, as the landing of the change it was asked for, so retrying it lands the rest once the change it waits on can. `Queue::pending` lists every landing that waits, on every target, reading without the locks: a landing that ends while it reads is skipped.
1 parent ed569b6 commit ae1ba2c

7 files changed

Lines changed: 258 additions & 11 deletions

File tree

‎apps/origin-src/src/queue/mod.rs‎

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
//! isn't on the target yet, from the bottom, with an acceptance each. A
66
//! change that diverged, that its creator abandoned, or whose head has
77
//! unresolved conflicts (see [`conflict`](crate::conflict)) is refused. A
8-
//! stack stops at the first change that waits. For each revision:
8+
//! stack that waits is kept whole, so retrying it lands the rest once the
9+
//! change it waits on can. For each revision:
910
//!
1011
//! 1. **Rebase.** The changes it made to its base are merged onto the
1112
//! target's tip, file by file ([`Store::merge`]). A revision made on the
@@ -36,22 +37,27 @@
3637
//! and later merges start from it.
3738
//!
3839
//! The queue of each target lives in `queue/<target id>/`: a `lock` held
39-
//! while landing, so landings on one target never race.
40+
//! while landing, so landings on one target never race, and a file for each
41+
//! landing that waits, `change-<id>` or `target-<target id>`, so waiting
42+
//! landings can be listed and retried.
4043
44+
mod pending;
4145
mod session;
4246

4347
use std::fmt;
4448
use std::fs;
49+
use std::io;
4550
use std::path::PathBuf;
4651

47-
use origin_platform::{LockMode, LockedFile, Native, Platform};
52+
use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform};
4853
use origin_shared::{
4954
AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, NodeKey, Principal, PrincipalName,
5055
Record, RecordId, RepoPath, RevisionId, Source, StatementId, TargetId, TargetName, Tree,
5156
TreeId,
5257
};
5358

5459
use crate::annotations::{AnnotateError, Annotations};
60+
use crate::conflict::Conflicts;
5561
use crate::policy::{Policy, PolicyError, Requirement};
5662
use crate::store::{Store, StoreError};
5763
use crate::targets::Head;
@@ -89,11 +95,11 @@ pub enum Landing {
8995
},
9096
/// The target already has it, so nothing landed.
9197
Unchanged(Proposal),
92-
/// It waits.
98+
/// It waits, and the queue keeps it.
9399
Pending(Pending),
94100
}
95101

96-
/// A landing that waits.
102+
/// A landing that waits, kept in the queue to be listed and retried.
97103
#[derive(Clone, Debug, PartialEq, Eq)]
98104
pub struct Pending {
99105
/// The target it lands on.
@@ -176,7 +182,9 @@ impl<'a, P: Platform> Queue<'a, P> {
176182
}
177183

178184
/// Lands `change`, and the changes below it that `onto` doesn't have
179-
/// yet, from the bottom of the stack. Stops at the first that waits.
185+
/// yet, from the bottom of the stack. Stops at the first that waits,
186+
/// which the queue keeps as a landing of `change`: retrying it lands
187+
/// the rest of the stack once that one can.
180188
///
181189
/// # Errors
182190
///
@@ -191,6 +199,7 @@ impl<'a, P: Platform> Queue<'a, P> {
191199
let mut session = self.session(onto)?;
192200
let stack = session.stack(change)?;
193201
if stack.is_empty() {
202+
session.forget(&Proposal::Change(change))?;
194203
return Ok(vec![Landing::Unchanged(Proposal::Change(change))]);
195204
}
196205
let proposal = Proposal::Change(change);
@@ -242,6 +251,7 @@ impl<'a, P: Platform> Queue<'a, P> {
242251
let [ours, theirs] = tips;
243252
let either = history.descends(ours, theirs) || history.descends(theirs, ours);
244253
if merge.tree == session.state && either {
254+
session.forget(&proposal)?;
245255
return Ok(Landing::Unchanged(proposal));
246256
}
247257
// Even a merge that changes nothing lands, so that the tip is in
@@ -289,6 +299,47 @@ impl<'a, P: Platform> Queue<'a, P> {
289299
Ok(Head { seq: 0, acceptance })
290300
}
291301

302+
/// Every landing that waits, on every target, sorted by target.
303+
///
304+
/// # Errors
305+
///
306+
/// Fails if the queues cannot be listed, or a landing cannot be read or
307+
/// is malformed.
308+
pub fn pending(store: &Store<P>) -> Result<Vec<Pending>, StoreError> {
309+
let root = store.queue_dir();
310+
let list = |dir: &PathBuf| match fs::read_dir(dir) {
311+
Ok(entries) => entries
312+
.map(|entry| entry.map(|entry| entry.path()))
313+
.collect::<io::Result<Vec<_>>>()
314+
.map_err(|source| StoreError::io(dir, source)),
315+
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
316+
Err(source) => Err(StoreError::io(dir, source)),
317+
};
318+
let mut pending = Vec::new();
319+
for dir in list(&root)? {
320+
for path in list(&dir)? {
321+
let name = path.file_name().unwrap_or_default();
322+
if name == Self::LOCK || DurableWrite::<P>::is_temporary(name) {
323+
continue;
324+
}
325+
// Read without the lock: a landing that just ended forgot it.
326+
let text = match fs::read_to_string(&path) {
327+
Ok(text) => text,
328+
Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
329+
Err(source) => return Err(StoreError::io(&path, source)),
330+
};
331+
let mut landing =
332+
Pending::decode(&text).ok_or_else(|| StoreError::Malformed(path.clone()))?;
333+
if let Blocked::Conflict { statement, paths } = &mut landing.blocked {
334+
*paths = Conflicts::listed(store, &store.get(*statement)?)?.paths();
335+
}
336+
pending.push(landing);
337+
}
338+
}
339+
pending.sort_by(|a, b| a.onto.cmp(&b.onto));
340+
Ok(pending)
341+
}
342+
292343
/// The policy in `state`, about to become the policy in force, if it's
293344
/// a valid one that names an authority for `policy`, so the target
294345
/// never locks up.
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
//! The file a landing that waits is kept in, in the queue's directory,
2+
//! until it can continue.
3+
4+
use origin_shared::RecordId;
5+
6+
use crate::policy::Requirement;
7+
8+
use super::{Blocked, Pending, Proposal};
9+
10+
impl Pending {
11+
/// The first line of every file keeping a waiting landing.
12+
const HEADER: &str = "origin pending 1";
13+
14+
/// Encodes the landing as lines: the header, `onto <target>`, `change
15+
/// <id>` or `target <name>`, `subject <kind> <id>`, then a `missing
16+
/// <kind> <verdict> <issuer>` line for each requirement it lacks, or
17+
/// `conflict <statement>`, whose payload lists the paths.
18+
pub(super) fn encode(&self) -> String {
19+
let mut lines = vec![Self::HEADER.to_owned(), format!("onto {}", self.onto)];
20+
lines.push(match &self.proposal {
21+
Proposal::Change(change) => format!("change {change}"),
22+
Proposal::Target(target) => format!("target {target}"),
23+
});
24+
let (kind, id) = match self.subject {
25+
RecordId::Snapshot(id) => ("snapshot", id.to_hex()),
26+
RecordId::Revision(id) => ("revision", id.to_hex()),
27+
RecordId::Statement(id) => ("statement", id.to_hex()),
28+
RecordId::Acceptance(id) => ("acceptance", id.to_hex()),
29+
};
30+
lines.push(format!("subject {kind} {id}"));
31+
match &self.blocked {
32+
Blocked::Evidence(missing) => lines.extend(missing.iter().map(|requirement| {
33+
format!(
34+
"missing {} {} {}",
35+
requirement.kind, requirement.verdict, requirement.issuer
36+
)
37+
})),
38+
Blocked::Conflict { statement, .. } => lines.push(format!("conflict {statement}")),
39+
}
40+
lines.join("\n") + "\n"
41+
}
42+
43+
/// Decodes what [`Pending::encode`] wrote, without the conflicting
44+
/// paths, or `None` if it's malformed.
45+
pub(super) fn decode(text: &str) -> Option<Self> {
46+
let mut lines = text.lines();
47+
if lines.next()? != Self::HEADER {
48+
return None;
49+
}
50+
let onto = lines.next()?.strip_prefix("onto ")?.parse().ok()?;
51+
let proposal = match lines.next()?.split_once(' ')? {
52+
("change", id) => Proposal::Change(id.parse().ok()?),
53+
("target", name) => Proposal::Target(name.parse().ok()?),
54+
_ => return None,
55+
};
56+
let subject = match lines.next()?.strip_prefix("subject ")?.split_once(' ')? {
57+
("snapshot", id) => RecordId::Snapshot(id.parse().ok()?),
58+
("revision", id) => RecordId::Revision(id.parse().ok()?),
59+
("statement", id) => RecordId::Statement(id.parse().ok()?),
60+
("acceptance", id) => RecordId::Acceptance(id.parse().ok()?),
61+
_ => return None,
62+
};
63+
let mut missing = Vec::new();
64+
let mut conflict = None;
65+
for line in lines {
66+
match line.split_once(' ')? {
67+
("missing", requirement) => {
68+
let mut fields = requirement.split(' ');
69+
missing.push(Requirement {
70+
kind: fields.next()?.parse().ok()?,
71+
verdict: fields.next()?.parse().ok()?,
72+
issuer: fields.next()?.parse().ok()?,
73+
});
74+
}
75+
("conflict", id) => conflict = Some(id.parse().ok()?),
76+
_ => return None,
77+
}
78+
}
79+
let blocked = match conflict {
80+
Some(statement) => Blocked::Conflict {
81+
statement,
82+
paths: Vec::new(),
83+
},
84+
None => Blocked::Evidence(missing),
85+
};
86+
Some(Self {
87+
onto,
88+
proposal,
89+
subject,
90+
blocked,
91+
})
92+
}
93+
}

‎apps/origin-src/src/queue/session.rs‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
//! keeping it to wait.
44
55
use std::collections::HashSet;
6+
use std::fs;
7+
use std::io;
8+
use std::path::PathBuf;
69

710
use origin_platform::{LockedFile, Platform};
811
use origin_shared::{
@@ -37,7 +40,7 @@ pub(super) struct Session<'q, 'a, P> {
3740
pub(super) struct Candidate {
3841
/// What lands.
3942
pub(super) proposal: Proposal,
40-
/// What waits, if it waits: the landing of the stack it's in.
43+
/// What the queue keeps if it waits: the landing of the stack it's in.
4144
pub(super) kept_as: Proposal,
4245
pub(super) source: Source,
4346
/// What the evidence must be about.
@@ -148,6 +151,7 @@ impl<P: Platform> Session<'_, '_, P> {
148151
return self.block(stack.clone(), RecordId::Revision(id), &merge.conflicts);
149152
}
150153
if merge.tree == self.state {
154+
self.forget(&proposal)?;
151155
return Ok(Landing::Unchanged(proposal));
152156
}
153157
let tip = Base::Acceptance(self.tip.acceptance);
@@ -239,6 +243,7 @@ impl<P: Platform> Session<'_, '_, P> {
239243
subject: candidate.subject,
240244
blocked: Blocked::Evidence(missing),
241245
};
246+
self.keep(&pending)?;
242247
return Ok(Landing::Pending(pending));
243248
}
244249

@@ -268,6 +273,7 @@ impl<P: Platform> Session<'_, '_, P> {
268273
self.policy = policy;
269274
self.policy_head = id;
270275
}
276+
self.forget(&candidate.proposal)?;
271277
Ok(Landing::Landed {
272278
proposal: candidate.proposal,
273279
source: candidate.source,
@@ -321,9 +327,39 @@ impl<P: Platform> Session<'_, '_, P> {
321327
paths: conflicts.paths(),
322328
},
323329
};
330+
self.keep(&pending)?;
324331
Ok(Landing::Pending(pending))
325332
}
326333

334+
/// The file keeping a waiting landing of `proposal`.
335+
fn pending_path(&self, proposal: &Proposal) -> Result<PathBuf, StoreError> {
336+
let name = match proposal {
337+
Proposal::Change(change) => format!("change-{change}"),
338+
Proposal::Target(target) => format!("target-{}", target.id()),
339+
};
340+
Ok(self.queue.queue_dir(self.onto.id())?.join(name))
341+
}
342+
343+
/// Durably keeps a waiting landing, replacing the last attempt's.
344+
fn keep(&self, pending: &Pending) -> Result<(), StoreError> {
345+
let write = self.store().durable_write();
346+
write.stage(
347+
self.pending_path(&pending.proposal)?,
348+
pending.encode().as_bytes(),
349+
)?;
350+
Ok(write.commit()?)
351+
}
352+
353+
/// Durably forgets a landing that waited, if one did.
354+
pub(super) fn forget(&self, proposal: &Proposal) -> Result<(), StoreError> {
355+
let path = self.pending_path(proposal)?;
356+
match fs::remove_file(&path) {
357+
Ok(()) => self.store().sync_dir(path.parent().unwrap_or(&path)),
358+
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
359+
Err(source) => Err(StoreError::io(&path, source)),
360+
}
361+
}
362+
327363
/// The history of `tips`, the target's and another target's, to merge
328364
/// that one from: the state of the newest acceptance both histories
329365
/// share, or the [merge](Ancestry::merge_base) of several, if each

‎apps/origin-src/src/queue/tests/changes.rs‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
//! Landing changes: rebasing, stacks, and who may land.
1+
//! Landing changes: rebasing, stacks, who may land, and keeping a
2+
//! landing that waits.
23
34
use std::sync::Mutex;
45
use std::thread;
56

6-
use origin_shared::Statement;
7+
use origin_shared::{Statement, Verdict};
78

89
use super::*;
910

@@ -146,6 +147,31 @@ fn concurrent_landings_serialize() {
146147
assert_eq!(repo.main_files().len(), changes.len(), "every file landed");
147148
}
148149

150+
#[test]
151+
fn pending_landings_round_trip() {
152+
let pending = Pending {
153+
onto: TargetName::new("release/v3").unwrap(),
154+
proposal: Proposal::Target(TargetName::MAIN),
155+
subject: RecordId::Snapshot(Tree::default().encode().id().into()),
156+
blocked: Blocked::Evidence(vec![Requirement {
157+
kind: Kind::new("ci.test").unwrap(),
158+
verdict: Verdict::Pass,
159+
issuer: "group:runners".parse().unwrap(),
160+
}]),
161+
};
162+
assert_eq!(Pending::decode(&pending.encode()), Some(pending.clone()));
163+
let conflict = Pending {
164+
proposal: change(9),
165+
blocked: Blocked::Conflict {
166+
statement: EncodedObject::blob(b"conflict").id().into(),
167+
paths: Vec::new(),
168+
},
169+
..pending
170+
};
171+
assert_eq!(Pending::decode(&conflict.encode()), Some(conflict));
172+
assert_eq!(Pending::decode("origin pending 2\n"), None);
173+
}
174+
149175
#[test]
150176
fn only_the_creator_of_a_change_abandons_it() {
151177
let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n");
@@ -165,3 +191,34 @@ fn only_the_creator_of_a_change_abandons_it() {
165191
.unwrap();
166192
assert!(matches!(repo.land(1)[..], [Landing::Landed { .. }]));
167193
}
194+
195+
#[test]
196+
fn a_waiting_stack_lands_whole_once_it_can() {
197+
let repo = requiring_ci();
198+
let lower = repo.change_on_main(1, &[("a", "a")]);
199+
repo.revision(2, &[], Base::Revision(lower), &[("a", "a"), ("b", "b")]);
200+
let [Landing::Pending(pending)] = &repo.land(2)[..] else {
201+
panic!("the lower change waits")
202+
};
203+
assert_eq!(pending.subject, RecordId::Revision(lower));
204+
assert_eq!(
205+
Queue::pending(&repo.store).unwrap(),
206+
[Pending {
207+
proposal: change(2),
208+
..pending.clone()
209+
}],
210+
"kept as the landing of the whole stack"
211+
);
212+
213+
// Retrying it, as once the evidence arrives, lands both: the result
214+
// is promoted to the upper change, which doesn't change `src`.
215+
let annotations = Annotations::open(&repo.store).unwrap();
216+
annotations.issue(&ci_test(lower, "user:ci"), None).unwrap();
217+
let landings = repo.land(2);
218+
assert_eq!(landed(&landings[0]), lower);
219+
assert!(
220+
matches!(landings[1], Landing::Landed { proposal: ref p, .. } if *p == change(2)),
221+
"{landings:?}"
222+
);
223+
assert_eq!(Queue::pending(&repo.store).unwrap(), []);
224+
}

0 commit comments

Comments
 (0)