Skip to content

Commit 4e45924

Browse files
committed
feat: drop statement payloads past their retention
Payloads, such as CI logs, were kept for ever. The `[retention]` table of `policy.toml` keeps those of each kind for a period, counted from when this node stored the statement: `"ci.*" = "90d"`. The most specific rule wins, and the reserved `core.*` kinds, whose payloads core reads, always keep theirs: a rule naming them is refused. `origin gc` drops the payloads past their retention, then compacts the store. Statements stay, and so does a payload another statement still keeps, or that a revision or a tree refers to. Collection waits for the writers holding the store's objects, and reads the index again once they're done, so a writer never refers to a payload deleted under it.
1 parent e414669 commit 4e45924

10 files changed

Lines changed: 658 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ origin annotate @ review --withdraw -m "Spoke too soon" # take your statement
3232
origin annotate --on <id> flaky --neutral -m "Timeout on CI" # a statement about a statement
3333
origin statements [<rev>] # the statements about a revision, and those about them
3434
origin promote [<rev>] # carry results over from revisions with the same inputs
35+
origin gc # drop expired payloads (policy.toml) and pack objects
3536

3637
origin land [<change>] [--onto <target>] # land a change and the ones below it
3738
origin land --from <target> --onto <target> # land a target's tip on another

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
//! Statements: issuing them, reading them, and promoting them by input
2-
//! digest.
1+
//! Statements: issuing them, reading them, promoting them by input digest,
2+
//! and dropping their payloads once retention ends.
33
//!
44
//! Core interprets only the reserved kinds: [`Kind::ABANDON`],
55
//! [`Kind::CONFLICT`] and [`Kind::DIVERGENT`], and only from the issuers
@@ -9,6 +9,7 @@
99
//! names still stands.
1010
1111
mod promotion;
12+
mod retention;
1213

1314
use std::collections::HashSet;
1415

@@ -21,6 +22,7 @@ use crate::index::Index;
2122
use crate::store::{Store, StoreError};
2223

2324
pub use promotion::{Claim, InvalidPromotion};
25+
pub use retention::Dropped;
2426

2527
/// The statements of a store, through its index.
2628
#[derive(Debug)]
Lines changed: 293 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,293 @@
1+
//! Dropping the payloads of statements once their retention ends.
2+
3+
use std::collections::HashSet;
4+
use std::time::SystemTime;
5+
6+
use origin_platform::Platform;
7+
use origin_shared::{ObjectId, RecordId};
8+
9+
use super::Annotations;
10+
use crate::index::Index;
11+
use crate::policy::Retention;
12+
use crate::store::StoreError;
13+
14+
/// What garbage collection dropped.
15+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16+
pub struct Dropped {
17+
/// The payloads deleted.
18+
pub payloads: usize,
19+
/// The bytes that freed on disk.
20+
pub bytes: u64,
21+
}
22+
23+
impl<P: Platform> Annotations<'_, P> {
24+
/// Deletes the payloads whose retention ended by `now`, counted from
25+
/// when this node stored their statement. A payload stays while any
26+
/// statement still keeps it, or a revision or a tree refers to the same
27+
/// blob, such as an empty file and an empty payload. Statements stay.
28+
/// It waits for the writers [holding objects](crate::store::Store::hold_objects),
29+
/// which landings on `policy` are too, then reads the rules from
30+
/// `retention` and the index again, so a writer never refers to a
31+
/// payload deleted under it, and a policy landed meanwhile applies.
32+
/// Without rules, it neither waits nor reads anything: a policy landed
33+
/// meanwhile could only have dropped payloads that this run keeps.
34+
///
35+
/// # Errors
36+
///
37+
/// Fails if `retention` does, a record cannot be read or a payload
38+
/// deleted.
39+
pub fn drop_expired_payloads<E: From<StoreError>>(
40+
&mut self,
41+
retention: impl Fn() -> Result<Retention, E>,
42+
now: SystemTime,
43+
) -> Result<Dropped, E> {
44+
if retention()?.is_empty() {
45+
return Ok(Dropped::default());
46+
}
47+
let _collecting = self.store.lock_for_collection()?;
48+
let retention = retention()?;
49+
if retention.is_empty() {
50+
return Ok(Dropped::default());
51+
}
52+
self.index = Index::open(self.store)?;
53+
let mut expired = HashSet::new();
54+
let mut live: HashSet<ObjectId> = HashSet::new();
55+
let mut roots = Vec::new();
56+
for &record in self.index.arrivals() {
57+
match record {
58+
RecordId::Revision(id) => {
59+
let revision = self.store.get(id)?;
60+
roots.push(revision.snapshot);
61+
live.insert(revision.description.into());
62+
}
63+
RecordId::Acceptance(id) => roots.push(self.store.get(id)?.body().state),
64+
RecordId::Statement(id) => {
65+
let statement = self.store.get(id)?;
66+
if let RecordId::Snapshot(tree) = statement.subject {
67+
roots.push(tree);
68+
}
69+
let Some(payload) = statement.payload else {
70+
continue;
71+
};
72+
let ended = match retention.period(&statement.kind) {
73+
Some(period) => {
74+
let stored = self.store.stored_at(id.into())?;
75+
now.duration_since(stored).is_ok_and(|age| age >= period)
76+
}
77+
None => false,
78+
};
79+
if ended {
80+
expired.insert(payload.into());
81+
} else {
82+
live.insert(payload.into());
83+
}
84+
}
85+
RecordId::Snapshot(_) => {}
86+
}
87+
}
88+
if expired.is_empty() {
89+
return Ok(Dropped::default());
90+
}
91+
self.store.reach(roots, &mut live)?;
92+
let mut doomed = Vec::new();
93+
for &id in expired.difference(&live) {
94+
if self.store.contains(id)? {
95+
doomed.push(id);
96+
}
97+
}
98+
Ok(Dropped {
99+
payloads: doomed.len(),
100+
bytes: self.store.remove(&doomed)?,
101+
})
102+
}
103+
}
104+
105+
#[cfg(test)]
106+
mod tests {
107+
use std::thread;
108+
use std::time::Duration;
109+
110+
use origin_platform::Native;
111+
use origin_shared::{EncodedObject, Verdict};
112+
113+
use super::*;
114+
use crate::annotations::tests::{FILES, check, issue, revision, store};
115+
use crate::store::Store;
116+
117+
#[test]
118+
fn retention_drops_payloads_and_keeps_statements() {
119+
let (_dir, store) = store();
120+
let first = revision(&store, 1, &[], &[("empty", "")]);
121+
let with_payload = |kind: &str, payload: &[u8]| {
122+
let payload = EncodedObject::blob(payload);
123+
let mut statement = check(first, kind, Verdict::Pass, "node:ci", None);
124+
statement.payload = Some(payload.id().into());
125+
let annotations = Annotations::open(&store).unwrap();
126+
let id = annotations
127+
.issue(&statement, Some(payload.clone()))
128+
.unwrap();
129+
(id, payload.id())
130+
};
131+
let (log_statement, log) = with_payload("ci.test", b"a long log");
132+
// The same blob as the empty file, which must stay.
133+
let (_, empty) = with_payload("ci.lint", b"");
134+
let (_, review) = with_payload("review", b"looks good");
135+
let (_, shared) = with_payload("ci.bench", b"shared");
136+
// Also the payload of a statement whose retention hasn't ended.
137+
let mut kept = check(first, "keep", Verdict::Pass, "node:ci", None);
138+
kept.payload = Some(shared.into());
139+
issue(&store, &kept);
140+
141+
let retention: Retention = toml::from_str::<crate::policy::Policy>(
142+
"[retention]\n\"ci.*\" = \"1d\"\n\"keep\" = \"1000d\"\n",
143+
)
144+
.unwrap()
145+
.retention;
146+
let mut annotations = Annotations::open(&store).unwrap();
147+
let now = SystemTime::now();
148+
assert_eq!(
149+
annotations
150+
.drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), now)
151+
.unwrap(),
152+
Dropped::default(),
153+
"not a day old yet"
154+
);
155+
let later = now + Duration::from_hours(48);
156+
let dropped = annotations
157+
.drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), later)
158+
.unwrap();
159+
assert_eq!(dropped.payloads, 1);
160+
assert!(!store.contains(log).unwrap());
161+
for stays in [empty, review, shared] {
162+
assert!(store.contains(stays).unwrap(), "{stays}");
163+
}
164+
assert!(store.get(log_statement).is_ok(), "statements are permanent");
165+
}
166+
167+
#[test]
168+
fn without_rules_collection_waits_for_no_writer() {
169+
let (_dir, store) = store();
170+
let held = store.hold_objects().unwrap();
171+
let (done, collected) = std::sync::mpsc::channel();
172+
thread::scope(|scope| {
173+
scope.spawn(|| {
174+
let none = || Ok::<_, StoreError>(Retention::default());
175+
let dropped = Annotations::open(&store)
176+
.unwrap()
177+
.drop_expired_payloads(none, SystemTime::now())
178+
.unwrap();
179+
done.send(dropped).unwrap();
180+
});
181+
let finished = collected.recv_timeout(Duration::from_secs(2));
182+
drop(held);
183+
assert_eq!(finished, Ok(Dropped::default()), "it waited for the writer");
184+
});
185+
}
186+
187+
#[test]
188+
fn collection_waits_for_writers_holding_objects() {
189+
let (_dir, store) = store();
190+
let first = revision(&store, 1, &[], FILES);
191+
let payload = EncodedObject::blob(b"a log, and a file");
192+
let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None);
193+
statement.payload = Some(payload.id().into());
194+
Annotations::open(&store)
195+
.unwrap()
196+
.issue(&statement, Some(payload.clone()))
197+
.unwrap();
198+
let retention = toml::from_str::<crate::policy::Policy>("[retention]\n\"ci.*\" = \"1s\"\n")
199+
.unwrap()
200+
.retention;
201+
202+
// A writer finds the expired payload stored as a file it snapshots,
203+
// so it doesn't write it, then writes the revision referring to it.
204+
let held = store.hold_objects().unwrap();
205+
assert_eq!(store.write_all(std::slice::from_ref(&payload)).unwrap(), 0);
206+
let (done, collected) = std::sync::mpsc::channel();
207+
thread::scope(|scope| {
208+
scope.spawn(|| {
209+
let later = SystemTime::now() + Duration::from_hours(1);
210+
let dropped = Annotations::open(&store)
211+
.unwrap()
212+
.drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), later)
213+
.unwrap();
214+
done.send(dropped).unwrap();
215+
});
216+
thread::sleep(Duration::from_millis(100));
217+
assert!(collected.try_recv().is_err(), "collection waits");
218+
revision(&store, 2, &[], &[("log", "a log, and a file")]);
219+
drop(held);
220+
assert_eq!(collected.recv().unwrap(), Dropped::default());
221+
});
222+
assert!(store.contains(payload.id()).unwrap());
223+
}
224+
225+
#[test]
226+
fn promotions_and_collection_exclude_each_other() {
227+
let (_dir, store) = store();
228+
let first = revision(&store, 1, &[], FILES);
229+
let payload = EncodedObject::blob(b"a log to promote");
230+
let inputs = Some((&["src"][..], false));
231+
let mut result = check(first, "ci.test", Verdict::Pass, "node:ci", inputs);
232+
result.payload = Some(payload.id().into());
233+
Annotations::open(&store)
234+
.unwrap()
235+
.issue(&result, Some(payload.clone()))
236+
.unwrap();
237+
let second = RecordId::Revision(revision(&store, 2, &[], FILES));
238+
239+
// A promotion refers to the payload without writing it: it waits
240+
// for a collection under way, which then reads it.
241+
let collecting = store.lock_for_collection().unwrap();
242+
let (done, promoted) = std::sync::mpsc::channel();
243+
thread::scope(|scope| {
244+
scope.spawn(|| {
245+
let issuer = "node:queue".parse().unwrap();
246+
let promotions = Annotations::open(&store)
247+
.unwrap()
248+
.promote(second, &issuer)
249+
.unwrap();
250+
done.send(promotions.len()).unwrap();
251+
});
252+
thread::sleep(Duration::from_millis(100));
253+
assert!(promoted.try_recv().is_err(), "promotion waits");
254+
drop(collecting);
255+
assert_eq!(promoted.recv().unwrap(), 1);
256+
});
257+
assert!(store.contains(payload.id()).unwrap());
258+
}
259+
260+
#[test]
261+
fn writers_never_trust_a_pack_collection_rewrote() {
262+
let (dir, store) = store();
263+
let first = revision(&store, 1, &[], FILES);
264+
let payload = EncodedObject::blob(b"expired, then needed again");
265+
let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None);
266+
statement.payload = Some(payload.id().into());
267+
Annotations::open(&store)
268+
.unwrap()
269+
.issue(&statement, Some(payload.clone()))
270+
.unwrap();
271+
store.compact().unwrap();
272+
// Another process, which loaded the pack holding the payload.
273+
let writer = Store::new(dir.path().join(".origin"), Native::default());
274+
assert!(writer.contains(payload.id()).unwrap());
275+
276+
let retention = toml::from_str::<crate::policy::Policy>("[retention]\n\"ci.*\" = \"1s\"\n")
277+
.unwrap()
278+
.retention;
279+
let later = SystemTime::now() + Duration::from_hours(1);
280+
let dropped = Annotations::open(&store)
281+
.unwrap()
282+
.drop_expired_payloads(|| Ok::<_, StoreError>(retention.clone()), later)
283+
.unwrap();
284+
assert_eq!(dropped.payloads, 1, "its pack is rewritten without it");
285+
let _held = writer.hold_objects().unwrap();
286+
assert_eq!(
287+
writer.write_all(std::slice::from_ref(&payload)).unwrap(),
288+
1,
289+
"so the writer writes it again"
290+
);
291+
assert!(store.contains(payload.id()).unwrap());
292+
}
293+
}

‎apps/origin-src/src/cli.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ enum WorkspaceCommand {
128128
#[arg(default_value = "@")]
129129
rev: String,
130130
},
131+
/// Drop the payloads past the retention set in `policy.toml`, pack
132+
/// small objects, and remove the leftovers of crashed writes.
133+
Gc,
131134
/// Land a change on a target, with the changes below it the target
132135
/// doesn't have yet. The queue rebases it onto the target's tip, checks
133136
/// the evidence `policy.toml` requires, and if it's there, appends a
@@ -402,6 +405,7 @@ impl WorkspaceCommand {
402405
}
403406
Self::Statements { rev } => workspace.statements(&rev)?,
404407
Self::Promote { rev } => workspace.promote(&rev)?,
408+
Self::Gc => workspace.gc()?,
405409
Self::Land(args) => match (args.from, args.onto) {
406410
_ if args.status => workspace.land_status()?,
407411
(Some(from), Some(onto)) => workspace.land_target(&from, &onto)?,

‎apps/origin-src/src/conflict.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,8 +178,8 @@ impl Conflicts {
178178
}
179179

180180
/// The conflicts a `core.conflict` statement lists. Its payload is the
181-
/// list, which a repository always keeps, so one it lacks fails rather
182-
/// than reading as no conflicts.
181+
/// list, which retention keeps, as it does every reserved kind's, so
182+
/// one the repository lacks fails rather than reading as no conflicts.
183183
///
184184
/// # Errors
185185
///

0 commit comments

Comments
 (0)