Skip to content

Commit 2c63840

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 0ebf8db commit 2c63840

8 files changed

Lines changed: 484 additions & 10 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ origin annotate @ review --pass -m "Looks good" # with details: -m, o
3131
origin annotate @ review --withdraw -m "Spoke too soon" # take your statement of a kind back
3232
origin statements [<rev>] # the statements about a revision
3333
origin promote [<rev>] # carry results over from revisions with the same inputs
34+
origin gc # drop expired payloads (policy.toml) and pack objects
3435

3536
origin land [<change>] [--onto <target>] # land a change and the ones below it
3637
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: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
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), and
29+
/// reads the index again once they're done, so a writer never refers
30+
/// to a payload deleted under it.
31+
///
32+
/// # Errors
33+
///
34+
/// Fails if a record cannot be read or a payload deleted.
35+
pub fn drop_expired_payloads(
36+
&mut self,
37+
retention: &Retention,
38+
now: SystemTime,
39+
) -> Result<Dropped, StoreError> {
40+
if retention.is_empty() {
41+
return Ok(Dropped::default());
42+
}
43+
let _collecting = self.store.lock_for_collection()?;
44+
self.index = Index::open(self.store)?;
45+
let mut expired = HashSet::new();
46+
let mut live: HashSet<ObjectId> = HashSet::new();
47+
let mut roots = Vec::new();
48+
for &record in self.index.arrivals() {
49+
match record {
50+
RecordId::Revision(id) => {
51+
let revision = self.store.get(id)?;
52+
roots.push(revision.snapshot);
53+
live.insert(revision.description.into());
54+
}
55+
RecordId::Acceptance(id) => roots.push(self.store.get(id)?.body().state),
56+
RecordId::Statement(id) => {
57+
let statement = self.store.get(id)?;
58+
if let RecordId::Snapshot(tree) = statement.subject {
59+
roots.push(tree);
60+
}
61+
let Some(payload) = statement.payload else {
62+
continue;
63+
};
64+
let ended = match retention.period(&statement.kind) {
65+
Some(period) => {
66+
let stored = self.store.stored_at(id.into())?;
67+
now.duration_since(stored).is_ok_and(|age| age >= period)
68+
}
69+
None => false,
70+
};
71+
if ended {
72+
expired.insert(payload.into());
73+
} else {
74+
live.insert(payload.into());
75+
}
76+
}
77+
RecordId::Snapshot(_) => {}
78+
}
79+
}
80+
if expired.is_empty() {
81+
return Ok(Dropped::default());
82+
}
83+
self.store.reach(roots, &mut live)?;
84+
let mut doomed = Vec::new();
85+
for &id in expired.difference(&live) {
86+
if self.store.contains(id)? {
87+
doomed.push(id);
88+
}
89+
}
90+
Ok(Dropped {
91+
payloads: doomed.len(),
92+
bytes: self.store.remove(&doomed)?,
93+
})
94+
}
95+
}
96+
97+
#[cfg(test)]
98+
mod tests {
99+
use std::thread;
100+
use std::time::Duration;
101+
102+
use origin_platform::Native;
103+
use origin_shared::{EncodedObject, Verdict};
104+
105+
use super::*;
106+
use crate::annotations::tests::{FILES, check, issue, revision, store};
107+
use crate::store::Store;
108+
109+
#[test]
110+
fn retention_drops_payloads_and_keeps_statements() {
111+
let (_dir, store) = store();
112+
let first = revision(&store, 1, &[], &[("empty", "")]);
113+
let with_payload = |kind: &str, payload: &[u8]| {
114+
let payload = EncodedObject::blob(payload);
115+
let mut statement = check(first, kind, Verdict::Pass, "node:ci", None);
116+
statement.payload = Some(payload.id().into());
117+
let annotations = Annotations::open(&store).unwrap();
118+
let id = annotations
119+
.issue(&statement, Some(payload.clone()))
120+
.unwrap();
121+
(id, payload.id())
122+
};
123+
let (log_statement, log) = with_payload("ci.test", b"a long log");
124+
// The same blob as the empty file, which must stay.
125+
let (_, empty) = with_payload("ci.lint", b"");
126+
let (_, review) = with_payload("review", b"looks good");
127+
let (_, shared) = with_payload("ci.bench", b"shared");
128+
// Also the payload of a statement whose retention hasn't ended.
129+
let mut kept = check(first, "keep", Verdict::Pass, "node:ci", None);
130+
kept.payload = Some(shared.into());
131+
issue(&store, &kept);
132+
133+
let retention: Retention = toml::from_str::<crate::policy::Policy>(
134+
"[retention]\n\"ci.*\" = \"1d\"\n\"keep\" = \"1000d\"\n",
135+
)
136+
.unwrap()
137+
.retention;
138+
let mut annotations = Annotations::open(&store).unwrap();
139+
let now = SystemTime::now();
140+
assert_eq!(
141+
annotations.drop_expired_payloads(&retention, now).unwrap(),
142+
Dropped::default(),
143+
"not a day old yet"
144+
);
145+
let later = now + Duration::from_hours(48);
146+
let dropped = annotations
147+
.drop_expired_payloads(&retention, later)
148+
.unwrap();
149+
assert_eq!(dropped.payloads, 1);
150+
assert!(!store.contains(log).unwrap());
151+
for stays in [empty, review, shared] {
152+
assert!(store.contains(stays).unwrap(), "{stays}");
153+
}
154+
assert!(store.get(log_statement).is_ok(), "statements are permanent");
155+
}
156+
157+
#[test]
158+
fn collection_waits_for_writers_holding_objects() {
159+
let (_dir, store) = store();
160+
let first = revision(&store, 1, &[], FILES);
161+
let payload = EncodedObject::blob(b"a log, and a file");
162+
let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None);
163+
statement.payload = Some(payload.id().into());
164+
Annotations::open(&store)
165+
.unwrap()
166+
.issue(&statement, Some(payload.clone()))
167+
.unwrap();
168+
let retention = toml::from_str::<crate::policy::Policy>("[retention]\n\"ci.*\" = \"1s\"\n")
169+
.unwrap()
170+
.retention;
171+
172+
// A writer finds the expired payload stored as a file it snapshots,
173+
// so it doesn't write it, then writes the revision referring to it.
174+
let held = store.hold_objects().unwrap();
175+
assert_eq!(store.write_all(std::slice::from_ref(&payload)).unwrap(), 0);
176+
let (done, collected) = std::sync::mpsc::channel();
177+
thread::scope(|scope| {
178+
scope.spawn(|| {
179+
let later = SystemTime::now() + Duration::from_hours(1);
180+
let dropped = Annotations::open(&store)
181+
.unwrap()
182+
.drop_expired_payloads(&retention, later)
183+
.unwrap();
184+
done.send(dropped).unwrap();
185+
});
186+
thread::sleep(Duration::from_millis(100));
187+
assert!(collected.try_recv().is_err(), "collection waits");
188+
revision(&store, 2, &[], &[("log", "a log, and a file")]);
189+
drop(held);
190+
assert_eq!(collected.recv().unwrap(), Dropped::default());
191+
});
192+
assert!(store.contains(payload.id()).unwrap());
193+
}
194+
195+
#[test]
196+
fn writers_never_trust_a_pack_collection_rewrote() {
197+
let (dir, store) = store();
198+
let first = revision(&store, 1, &[], FILES);
199+
let payload = EncodedObject::blob(b"expired, then needed again");
200+
let mut statement = check(first, "ci.test", Verdict::Pass, "node:ci", None);
201+
statement.payload = Some(payload.id().into());
202+
Annotations::open(&store)
203+
.unwrap()
204+
.issue(&statement, Some(payload.clone()))
205+
.unwrap();
206+
store.compact().unwrap();
207+
// Another process, which loaded the pack holding the payload.
208+
let writer = Store::new(dir.path().join(".origin"), Native::default());
209+
assert!(writer.contains(payload.id()).unwrap());
210+
211+
let retention = toml::from_str::<crate::policy::Policy>("[retention]\n\"ci.*\" = \"1s\"\n")
212+
.unwrap()
213+
.retention;
214+
let later = SystemTime::now() + Duration::from_hours(1);
215+
let dropped = Annotations::open(&store)
216+
.unwrap()
217+
.drop_expired_payloads(&retention, later)
218+
.unwrap();
219+
assert_eq!(dropped.payloads, 1, "its pack is rewritten without it");
220+
let _held = writer.hold_objects().unwrap();
221+
assert_eq!(
222+
writer.write_all(std::slice::from_ref(&payload)).unwrap(),
223+
1,
224+
"so the writer writes it again"
225+
);
226+
assert!(store.contains(payload.id()).unwrap());
227+
}
228+
}

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ enum WorkspaceCommand {
120120
#[arg(default_value = "@")]
121121
rev: String,
122122
},
123+
/// Drop the payloads past the retention set in `policy.toml`, pack
124+
/// small objects, and remove the leftovers of crashed writes.
125+
Gc,
123126
/// Land a change on a target, with the changes below it the target
124127
/// doesn't have yet. The queue rebases it onto the target's tip, checks
125128
/// the evidence `policy.toml` requires, and if it's there, appends a
@@ -324,6 +327,7 @@ impl WorkspaceCommand {
324327
)?,
325328
Self::Statements { rev } => workspace.statements(&rev)?,
326329
Self::Promote { rev } => workspace.promote(&rev)?,
330+
Self::Gc => workspace.gc()?,
327331
Self::Land(args) => match (args.from, args.onto) {
328332
_ if args.status => workspace.land_status()?,
329333
(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)