Collect stale OSTree objects under explicit keep refs

This commit is contained in:
Archipelago 2026-11-16 21:43:51 +03:00
parent 715bbe18b5
commit 10bbfa7de9
3 changed files with 415 additions and 0 deletions

View file

@ -1,5 +1,42 @@
# archipelagod implementation checkpoint
## 2026-11-16 checkpoint: guarded OSTree object collection
Installed hosts accumulated image objects forever. `ostree prune` without
`--refs-only` traverses *every* commit in the repository, so it only removes objects
that were written but never committed; old image commits stay alive. `--refs-only`
does collect them, but then the deployed systems must be reachable from refs. The new
`system/src/gc.rs` makes that explicit:
- `archipelago cleanup plan [--json]` is a read-only inventory: deployments with
roles, protected commits (deployment checksums plus their `archipelago.base`,
`archipelago.layer-core` and `archipelago.layer-purpose` metadata), keep refs to
create, unreferenced `service/*` composition refs, repository size and the guard
result.
- `archipelago cleanup apply` takes the same host mutation lock as updates and
extensions, refuses to run in the live environment, without a booted deployment or
while a pending/staged deployment exists, runs `ostree admin cleanup`, mirrors every
retained deployment into `archipelago/keep/<checksum>` refs, drops `service/bases`,
`service/overlays` and `service/overlay-builds` refs that no retained deployment
names, verifies every protected commit resolves, then runs
`ostree prune --refs-only`. Each protected deployment is re-read afterwards; a
vanished commit is reported as a critical failure. The record (protected commits,
prune output, bytes before/after) is written to `/var/lib/archipelago/cleanup/`.
- The `archipelago-ostree-gc.timer` unit (30 minutes after boot, then weekly) runs the
guarded apply on installed hosts; the live ISO is excluded by condition.
Unit tests cover deployment parsing, the pending/unbooted guards, keep-ref mirroring
and stale composition refs. The engine compiles and those tests pass; actual pruning
on real hardware remains a user-verified scenario, and `cleanup plan` is the
read-only way to inspect a host before it runs.
## 2026-11-16 checkpoint: quoted release code name
`defaults/os-release` now writes `VERSION="Tesseract"`, `VERSION_ID="Tesseract"` and
`VERSION_CODENAME="tesseract"`, and the Core package build asserts those exact lines
so a Purpose cannot drift from an unquoted value. Container Runner keeps inheriting
the Core file, with only the edition name substituted.
## 2026-11-16 checkpoint: native artifact verification on the overlay path
Managed Overlay planning no longer shells out to `python3 artifact.py`. Every

377
src/gc.rs Normal file
View file

@ -0,0 +1,377 @@
//! Guarded OSTree object collection.
//!
//! `ostree prune` without `--refs-only` traverses *every* commit in the repository,
//! so it only removes objects that were written but never committed. Old image
//! commits therefore stay alive forever and the object store grows with each
//! update. `--refs-only` does collect those commits, but then the commits of the
//! deployed systems must be reachable from refs. This module makes that reachability
//! explicit with `archipelago/keep/<checksum>` refs before pruning, keeps the
//! service refs still referenced by a retained deployment, and refuses to run in
//! states where the protected set cannot be established. It never walks the object
//! store itself.
use serde_json::Value;
use std::{collections::BTreeSet, fs, io::Write, os::unix::fs::OpenOptionsExt, path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}};
const REPO: &str = "/sysroot/ostree/repo";
const STATE: &str = "/var/lib/archipelago/cleanup";
const LOCK: &str = "/run/archipelago-compose.lock";
const LIVE: &str = "/run/archipelago-live";
const BOOTED: &str = "/run/ostree-booted";
const KEEP: &str = "archipelago/keep";
const SERVICE_PREFIXES: [&str; 3] = ["service/bases/", "service/overlays/", "service/overlay-builds/"];
/// Commit metadata that names an input a retained deployment still needs.
const PROTECTED_KEYS: [&str; 3] = ["archipelago.base", "archipelago.layer-core", "archipelago.layer-purpose"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Deployment {
pub checksum: String,
pub serial: u64,
pub booted: bool,
pub pending: bool,
pub pinned: bool,
}
fn digest(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn command(program: &str, args: &[&str]) -> Result<String, String> {
let output = Command::new(program).args(args).env("LC_ALL", "C").output()
.map_err(|e| format!("{program}: {e}"))?;
if !output.status.success() {
return Err(format!("{program} {}: {}", args.join(" "), String::from_utf8_lossy(&output.stderr).trim()));
}
String::from_utf8(output.stdout).map_err(|e| e.to_string())
}
fn ostree(args: &[&str]) -> Result<String, String> { command("ostree", args) }
fn repository(args: &[&str]) -> Result<String, String> {
let repo = format!("--repo={REPO}");
let mut full: Vec<&str> = vec![&repo];
full.extend(args.iter().copied());
ostree(&full)
}
/// Read the deployment list. Every listed deployment is protected by this module,
/// regardless of stateroot: the object store is shared and a wrong root is not
/// recoverable from a pruned repository.
pub(crate) fn parse_deployments(status: &Value) -> Result<Vec<Deployment>, String> {
let entries = status["deployments"].as_array().ok_or("missing deployments")?;
let mut result = Vec::new();
for entry in entries {
let checksum = entry["checksum"].as_str().filter(|value| digest(value))
.ok_or("invalid deployment checksum")?;
let serial = entry["serial"].as_u64().ok_or("missing deployment serial")?;
result.push(Deployment {
checksum: checksum.to_owned(),
serial,
booted: entry["booted"] == true,
pending: entry["pending"] == true || entry["staged"] == true,
pinned: entry["pinned"] == true,
});
}
Ok(result)
}
/// Refuse to collect while the protected set is not stable. A pending or staged
/// deployment may still be finalized, and a repository without a booted
/// deployment is not a host we understand.
pub(crate) fn preconditions(deployments: &[Deployment]) -> Result<(), String> {
if deployments.is_empty() { return Err("no OSTree deployments; refusing to collect objects".into()); }
if !deployments.iter().any(|deployment| deployment.booted) {
return Err("no booted OSTree deployment; refusing to collect objects".into());
}
if let Some(deployment) = deployments.iter().find(|deployment| deployment.pending) {
return Err(format!("pending deployment {} is not activated yet; run cleanup after reboot",
deployment.checksum));
}
Ok(())
}
/// Keep refs mirror the current deployment set. Creates protect a commit before
/// pruning; removals only drop protection for deployments that no longer exist.
pub(crate) fn keep_ref_sync(existing: &[String], deployments: &[Deployment])
-> (Vec<(String, String)>, Vec<String>) {
let desired: BTreeSet<&str> = deployments.iter().map(|deployment| deployment.checksum.as_str()).collect();
let mut create = Vec::new();
for commit in &desired {
let name = format!("{KEEP}/{commit}");
if !existing.iter().any(|ref_name| ref_name == &name) {
create.push((name, (*commit).to_owned()));
}
}
let remove = existing.iter().filter(|ref_name| ref_name.starts_with(&format!("{KEEP}/")))
.filter(|ref_name| {
let commit = ref_name.rsplit('/').next().unwrap_or("");
!desired.contains(commit)
}).cloned().collect();
(create, remove)
}
/// Service refs built by planning belong to one composition. Anything not named by
/// a retained deployment is a build artifact and may be dropped.
pub(crate) fn stale_service_refs(refs: &[(String, String)], desired: &BTreeSet<String>) -> Vec<(String, String)> {
refs.iter().filter(|(name, _)| SERVICE_PREFIXES.iter().any(|prefix| name.starts_with(prefix)))
.filter(|(_, target)| !desired.contains(target))
.cloned().collect()
}
/// Human/JSON inventory. Read-only: it reports what apply would consider and
/// refuses to pretend it can predict the exact byte count without pruning.
pub fn plan(as_json: bool) -> Result<(), String> {
require_host()?;
let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?)
.map_err(|_| "invalid OSTree deployment status".to_string())?;
let deployments = parse_deployments(&status)?;
let guard = preconditions(&deployments);
let refs = list_refs()?;
let mut protected: BTreeSet<String> = deployments.iter().map(|deployment| deployment.checksum.clone()).collect();
for deployment in &deployments {
for key in PROTECTED_KEYS {
if let Some(commit) = metadata_commit(&deployment.checksum, key) { protected.insert(commit); }
}
}
let stale = stale_service_refs(&refs, &protected);
let (create, remove) = keep_ref_sync(&ref_names(&refs), &deployments);
if as_json {
println!("{}", serde_json::json!({
"deployments": deployments.iter().map(|deployment| serde_json::json!({
"checksum": deployment.checksum, "serial": deployment.serial,
"booted": deployment.booted, "pending": deployment.pending,
"pinned": deployment.pinned})).collect::<Vec<_>>(),
"protected_commits": protected,
"keep_refs_to_create": create.iter().map(|(name, _)| name).collect::<Vec<_>>(),
"keep_refs_to_remove": remove,
"stale_service_refs": stale.iter().map(|(name, target)| serde_json::json!({
"ref": name, "commit": target})).collect::<Vec<_>>(),
"repository_bytes": repository_bytes(),
"guard": match &guard { Err(error) => Some(error.clone()), Ok(_) => None },
}));
return guard;
}
println!("OSTree repository: {REPO}");
if let Some(bytes) = repository_bytes() { println!("Objects on disk: {bytes} bytes"); }
println!("Deployments:");
for deployment in &deployments {
let role = if deployment.booted { "booted" } else if deployment.pending { "pending" } else { "retained" };
println!(" {} serial {} {role}{}", deployment.checksum, deployment.serial,
if deployment.pinned { " pinned" } else { "" });
}
println!("Protected commits: {}", protected.len());
println!("Keep refs to create: {}", create.len());
if !remove.is_empty() { println!("Keep refs for removed deployments: {}", remove.len()); }
if !stale.is_empty() {
println!("Unreferenced composition refs:");
for (name, target) in &stale { println!(" {name} {target}"); }
}
if let Err(error) = guard {
println!("Collection currently unavailable: {error}");
return Err(error);
}
println!("Run `archipelago cleanup apply` to delete unreachable objects.");
Ok(())
}
/// Apply the guarded collection: OSTree deployment retention, explicit keep refs
/// for every retained deployment, removal of unreferenced composition refs, then
/// `ostree prune --refs-only`. Protected commits are re-resolved afterwards.
pub fn apply() -> Result<(), String> {
require_host()?;
let _lock = lock()?;
let before = repository_bytes();
let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?)
.map_err(|_| "invalid OSTree deployment status".to_string())?;
let mut deployments = parse_deployments(&status)?;
preconditions(&deployments)?;
// OSTree's own retention: booted, previous, pending and pinned deployments.
// Failure is not fatal for object collection, which protects what still exists.
let cleanup = ostree(&["admin", "cleanup"]);
let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?)
.map_err(|_| "invalid OSTree deployment status".to_string())?;
deployments = parse_deployments(&status)?;
preconditions(&deployments)?;
let mut protected: BTreeSet<String> = deployments.iter().map(|deployment| deployment.checksum.clone()).collect();
for deployment in &deployments {
for key in PROTECTED_KEYS {
if let Some(commit) = metadata_commit(&deployment.checksum, key) { protected.insert(commit); }
}
}
let refs = list_refs()?;
for (name, commit) in keep_ref_sync(&ref_names(&refs), &deployments).0 {
repository(&["refs", "--force", &format!("--create={name}"), &commit])?;
}
for (name, _) in stale_service_refs(&refs, &protected) {
repository(&["refs", "--delete", &name])?;
}
// Every protected commit must resolve through a ref before anything is deleted.
for commit in &protected {
repository(&["ls", commit, "/"])?;
}
let prune = repository(&["prune", "--refs-only"])?;
for deployment in &deployments {
repository(&["ls", &deployment.checksum, "/"])
.map_err(|error| format!("protected deployment became unreadable after prune: {error}"))?;
}
let after = repository_bytes();
let cleanup_status = match &cleanup {
Ok(_) => "ok".to_string(),
Err(error) => error.clone(),
};
let record = serde_json::json!({
"version": 1, "finished_unix": now()?, "deployments": deployments.len(),
"protected_commits": protected, "keep_refs_checked": true,
"admin_cleanup": cleanup_status,
"prune": prune.trim(), "bytes_before": before, "bytes_after": after,
});
record_journal(&record)?;
println!("Protected deployments: {}", deployments.len());
println!("{}", prune.trim());
if let (Some(before), Some(after)) = (before, after) {
println!("Repository bytes: {before} -> {after} ({} freed)", before.saturating_sub(after));
}
Ok(())
}
fn now() -> Result<String, String> {
let seconds = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_secs();
Ok(seconds.to_string())
}
fn require_host() -> Result<(), String> {
if !Path::new(BOOTED).exists() { return Err("OSTree object collection requires an installed, OSTree-booted host".into()); }
if Path::new(LIVE).exists() { return Err("OSTree object collection is disabled in the live environment".into()); }
if !Path::new(REPO).is_dir() { return Err(format!("missing OSTree repository {REPO}")); }
let uid = Command::new("id").arg("-u").output().map_err(|e| e.to_string())?;
if String::from_utf8_lossy(&uid.stdout).trim() != "0" { return Err("Run as root".into()); }
Ok(())
}
/// The same host mutation lock as updates and extensions: collection must not run
/// while a composition or staging operation owns the sysroot. The status observer
/// takes it briefly every few seconds, so wait through that transient instead of
/// failing the weekly timer spuriously.
fn lock() -> Result<fs::File, String> {
let file = fs::OpenOptions::new().create(true).truncate(false).read(true).write(true).mode(0o600)
.open(LOCK).map_err(|e| format!("{LOCK}: {e}"))?;
let deadline = SystemTime::now() + std::time::Duration::from_secs(120);
loop {
match file.try_lock() {
Ok(()) => return Ok(file),
Err(std::fs::TryLockError::WouldBlock) => {
if SystemTime::now() >= deadline { return Err("another composition or update is running".into()); }
std::thread::sleep(std::time::Duration::from_millis(500));
}
Err(std::fs::TryLockError::Error(error)) => return Err(format!("{LOCK}: {error}")),
}
}
}
fn list_refs() -> Result<Vec<(String, String)>, String> {
let output = repository(&["refs", "--list"])?;
let mut refs = Vec::new();
for name in output.lines().filter(|line| !line.trim().is_empty()) {
let name = name.trim();
let target = repository(&["rev-parse", name])?;
refs.push((name.to_owned(), target.trim().to_owned()));
}
Ok(refs)
}
fn ref_names(refs: &[(String, String)]) -> Vec<String> {
refs.iter().map(|(name, _)| name.clone()).collect()
}
fn metadata_commit(commit: &str, key: &str) -> Option<String> {
let raw = ostree(&["show", &format!("--print-metadata-key={key}"), commit]).ok()?;
let value = raw.trim().trim_matches('\'');
digest(value).then(|| value.to_owned())
}
fn repository_bytes() -> Option<u64> {
let output = Command::new("du").args(["-s", "--block-size=1", REPO]).env("LC_ALL", "C").output().ok()?;
if !output.status.success() { return None; }
String::from_utf8_lossy(&output.stdout).split_whitespace().next()?.parse().ok()
}
fn record_journal(record: &Value) -> Result<(), String> {
let directory = Path::new(STATE);
fs::create_dir_all(directory).map_err(|e| e.to_string())?;
let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos();
let path = directory.join(format!("cleanup-{stamp}.json"));
let mut file = fs::OpenOptions::new().create_new(true).write(true).mode(0o600).open(&path).map_err(|e| e.to_string())?;
file.write_all(serde_json::to_vec_pretty(record).map_err(|e| e.to_string())?.as_slice()).map_err(|e| e.to_string())?;
file.write_all(b"\n").map_err(|e| e.to_string())?;
file.sync_all().map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn status() -> Value {
json!({"deployments": [
{"stateroot":"archipelago","osname":"archipelago","checksum":"a".repeat(64),"serial":0,"booted":true,"pending":false,"staged":false,"pinned":false},
{"stateroot":"archipelago","osname":"archipelago","checksum":"b".repeat(64),"serial":1,"booted":false,"pending":false,"staged":false,"pinned":true}
]})
}
#[test]
fn deployments_and_guards_are_parsed() {
let deployments = parse_deployments(&status()).unwrap();
assert_eq!(deployments.len(), 2);
assert!(deployments[0].booted && !deployments[0].pending);
assert!(deployments[1].pinned);
assert!(preconditions(&deployments).is_ok());
let pending = json!({"deployments": [
{"checksum":"a".repeat(64),"serial":0,"booted":true,"pending":false},
{"checksum":"c".repeat(64),"serial":1,"booted":false,"pending":true}]});
let deployments = parse_deployments(&pending).unwrap();
assert!(preconditions(&deployments).unwrap_err().contains("not activated"));
let staged = json!({"deployments": [
{"checksum":"a".repeat(64),"serial":0,"booted":true,"staged":true}]});
assert!(preconditions(&parse_deployments(&staged).unwrap()).unwrap_err().contains("not activated"));
let unbooted = json!({"deployments": [{"checksum":"a".repeat(64),"serial":0,"booted":false}]});
assert!(preconditions(&parse_deployments(&unbooted).unwrap()).unwrap_err().contains("no booted"));
assert!(parse_deployments(&json!({"deployments": [{"checksum":"../../etc","serial":0}]})).is_err());
assert!(preconditions(&[]).is_err());
}
#[test]
fn keep_refs_track_exactly_the_current_deployments() {
let deployments = parse_deployments(&status()).unwrap();
let existing = vec![
format!("{KEEP}/{}", "a".repeat(64)),
format!("{KEEP}/{}", "c".repeat(64)),
"stable/core".to_string(),
];
let (create, remove) = keep_ref_sync(&existing, &deployments);
assert_eq!(create, vec![(format!("{KEEP}/{}", "b".repeat(64)), "b".repeat(64))]);
assert_eq!(remove, vec![format!("{KEEP}/{}", "c".repeat(64))]);
// A second run is a no-op for protection.
let created = keep_ref_sync(&[format!("{KEEP}/{}", "a".repeat(64)), format!("{KEEP}/{}", "b".repeat(64))], &deployments);
assert!(created.0.is_empty() && created.1.is_empty());
}
#[test]
fn only_unreferenced_composition_refs_are_stale() {
let target = "d".repeat(64);
let refs = vec![
("service/bases/".to_owned() + &target, target.clone()),
("service/overlays/old".to_owned(), "e".repeat(64)),
("service/overlay-builds/old".to_owned(), "f".repeat(64)),
("stable/core".to_owned(), "a".repeat(64)),
(format!("{KEEP}/{}", "a".repeat(64)), "a".repeat(64)),
];
let desired: BTreeSet<String> = [target.clone(), "a".repeat(64)].into_iter().collect();
let stale = stale_service_refs(&refs, &desired);
assert_eq!(stale.len(), 2);
assert!(stale.iter().all(|(name, _)| name != "stable/core"));
assert!(stale.iter().all(|(name, _)| !name.starts_with(&format!("{KEEP}/"))));
}
}

View file

@ -1,6 +1,7 @@
//! Installed-host lifecycle engine and service integration.
pub mod onboarding;
pub mod power;
pub mod gc;
pub mod extensions;
pub mod desktop;
pub mod updates;