Skip to main content

agentmux_srv_core/backend/
old_versions_service.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Runs the old-version cleanup (`old_versions.rs`) once a day.
5//!
6//! Every srv looks at its own channel's version folders and logs what it found. It removes them by
7//! default; a host whose settings say `oldversions:clean: false` only gets the plan as the report
8//! (the log line, and `GET /agentmux/old-versions`). Like the build-cache cleanup it runs only in
9//! an srv started by its launcher on the real home, never in a dev, headless or test instance.
10//! A pass removes nothing unless this version carried the previous one's data forward, so a start
11//! that lost its data keeps every older folder. A hosted workspace's srv runs it two minutes after
12//! start rather than twenty; the same rules apply.
13
14use std::sync::Arc;
15use std::time::{Duration, SystemTime};
16
17use crate::backend::old_versions::{self as ov, Policy};
18use crate::backend::wconfig::ConfigState;
19
20/// The first pass waits this long after start, so it never competes with startup.
21const FIRST_AFTER: Duration = Duration::from_secs(20 * 60);
22/// A hosted workspace runs for minutes, not days: its first pass comes sooner, once the start is long done.
23const HOSTED_FIRST_AFTER: Duration = Duration::from_secs(2 * 60);
24const EVERY: Duration = Duration::from_secs(24 * 3600);
25
26/// The policy the settings ask for. `hosted`: this srv serves a hosted workspace (the one host that vouches for the
27/// person's window is registered at boot), which removes by default.
28pub fn policy(config: &ConfigState, hosted: bool) -> Policy {
29    Policy::from_extra_for(&config.get_settings().extra, hosted)
30}
31
32/// A hosted pass is skipped when this version started without the data of the one before it, or carried forward a copy
33/// that was itself empty. Then the old folders may hold the only good copy of the person's data, so none of them is
34/// judged. A version that was carried forward records where from (`carried-from`), but a marker proves a copy happened,
35/// not that its source held good data: a copy of an empty fresh start has one too. So the chain is followed back from the
36/// running version, and every hop must hold data and lead, hop by hop, to the origin of the data (the pre-versioning copy,
37/// or a version with no older data). A version that started fresh after a failed copy has no marker and older data
38/// behind it, so any chain through it fails.
39fn start_is_confirmed(layout: &ov::Layout) -> bool {
40    use crate::migrations::carry_forward::{version_core, CARRIED_FROM_FILE, PRE_VERSIONING};
41    let db_of = |name: &str| layout.versions_root.join(name).join("data").join("db");
42    let has_older_data = |than: (u64, u64, u64)| {
43        std::fs::read_dir(&layout.versions_root).map(|d| {
44            d.filter_map(|e| e.ok()).any(|e| {
45                let name = e.file_name();
46                name.to_str().and_then(version_core).is_some_and(|v| v < than) && db_of(&name.to_string_lossy()).join("objects.db").is_file()
47            })
48        })
49    };
50    let Some(mut at) = version_core(&layout.running) else {
51        return false;
52    };
53    let mut marker = std::fs::read_to_string(db_of(&layout.running).join(CARRIED_FROM_FILE));
54    // Each hop goes to a strictly older version, so the walk ends; a marker naming anything else fails.
55    loop {
56        let Ok(text) = marker else {
57            return false;
58        };
59        let from = text.trim();
60        if from == PRE_VERSIONING {
61            return true;
62        }
63        let Some(from_core) = version_core(from).filter(|v| *v < at) else {
64            return false;
65        };
66        let source = db_of(from);
67        // A source an earlier pass already removed ends the chain, as an unmarked origin does: that pass was confirmed,
68        // and nothing older is left to lose. Older data still on disk behind a gone source cannot be vouched for.
69        if !source.join("objects.db").is_file() {
70            return has_older_data(from_core).is_ok_and(|older| !older);
71        }
72        marker = std::fs::read_to_string(source.join(CARRIED_FROM_FILE));
73        if marker.is_err() {
74            return has_older_data(from_core).is_ok_and(|older| !older);
75        }
76        at = from_core;
77    }
78}
79
80fn pass(config: &ConfigState, hosted: bool) {
81    let Some(layout) = ov::layout_from_env() else {
82        tracing::debug!("old versions: this srv has no per-version folders");
83        return;
84    };
85    let policy = policy(config, hosted);
86    if policy.clean && !start_is_confirmed(&layout) {
87        tracing::info!("old versions: this version did not carry its data forward; nothing is removed");
88        return;
89    }
90    let run = ov::run(&layout, &policy, !policy.clean, None, SystemTime::now());
91    if !run.scan_ok {
92        tracing::warn!("old versions: the running processes could not be read; nothing is removed");
93        return;
94    }
95    let plan = &run.plan;
96    match &run.report {
97        Some(report) => {
98            for (dir, bytes) in &report.removed {
99                tracing::info!(dir = %dir.display(), freed = %crate::backend::build_cache::human(*bytes), "old versions: removed");
100            }
101            for (dir, why) in &report.skipped {
102                tracing::info!(dir = %dir.display(), why = %why, "old versions: left alone");
103            }
104        }
105        None if !plan.removable.is_empty() => {
106            for c in &plan.removable {
107                tracing::info!(dir = %c.dir.display(), kind = ?c.kind, size = %crate::backend::build_cache::human(c.bytes), "old versions: could be removed");
108            }
109            tracing::info!(
110                folders = plan.removable.len(),
111                reclaimable = %crate::backend::build_cache::human(plan.reclaimable_bytes()),
112                "old versions: a dry run (set oldversions:clean to remove them)"
113            );
114        }
115        None => {}
116    }
117}
118
119/// Starts the schedule. Safe to call once at boot.
120pub fn install(config: Arc<ConfigState>, hosted: bool) {
121    // A hosted srv is headless, which `this_srv_may_clean` refuses: it has its own home, the person's volume.
122    if !hosted && !crate::backend::build_cache_service::this_srv_may_clean() {
123        tracing::debug!("old versions: not an srv that cleans");
124        return;
125    }
126    tokio::spawn(async move {
127        tokio::time::sleep(if hosted { HOSTED_FIRST_AFTER } else { FIRST_AFTER }).await;
128        let mut tick = tokio::time::interval(EVERY);
129        loop {
130            tick.tick().await;
131            let cfg = config.clone();
132            let _ = tokio::task::spawn_blocking(move || pass(&cfg, hosted)).await;
133        }
134    });
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    fn layout(root: &std::path::Path) -> ov::Layout {
142        ov::Layout { versions_root: root.join("versions"), running: "0.60.35".into(), channel: "chan".into(), portable_parents: Vec::new() }
143    }
144
145    fn db_dir(l: &ov::Layout) -> std::path::PathBuf {
146        let dir = l.versions_root.join(&l.running).join("data").join("db");
147        std::fs::create_dir_all(&dir).unwrap();
148        dir
149    }
150
151    /// A version folder named `name` with an `objects.db`, and `marker` as its `carried-from` when given.
152    fn version_with_data(l: &ov::Layout, name: &str, marker: Option<&str>) {
153        let dir = l.versions_root.join(name).join("data").join("db");
154        std::fs::create_dir_all(&dir).unwrap();
155        std::fs::write(dir.join("objects.db"), "").unwrap();
156        if let Some(m) = marker {
157            std::fs::write(dir.join(crate::migrations::carry_forward::CARRIED_FROM_FILE), m).unwrap();
158        }
159    }
160
161    fn carried_from_old(root: &std::path::Path) -> ov::Layout {
162        let l = layout(root);
163        std::fs::write(db_dir(&l).join(crate::migrations::carry_forward::CARRIED_FROM_FILE), "0.60.34\n").unwrap();
164        l
165    }
166
167    #[test]
168    fn a_start_that_carried_forward_the_origin_of_the_data_is_confirmed() {
169        let root = tempfile::tempdir().unwrap();
170        let l = carried_from_old(root.path());
171        version_with_data(&l, "0.60.34", None);
172        assert!(start_is_confirmed(&l), "the source is the oldest version with data");
173    }
174
175    #[test]
176    fn a_start_that_carried_forward_a_version_that_was_carried_itself_is_confirmed() {
177        let root = tempfile::tempdir().unwrap();
178        let l = carried_from_old(root.path());
179        version_with_data(&l, "0.60.33", None);
180        version_with_data(&l, "0.60.34", Some("0.60.33"));
181        assert!(start_is_confirmed(&l));
182    }
183
184    #[test]
185    fn a_start_from_the_pre_versioning_copy_is_confirmed() {
186        let root = tempfile::tempdir().unwrap();
187        let l = layout(root.path());
188        std::fs::write(db_dir(&l).join(crate::migrations::carry_forward::CARRIED_FROM_FILE), crate::migrations::carry_forward::PRE_VERSIONING).unwrap();
189        assert!(start_is_confirmed(&l));
190    }
191
192    /// A marker proves a copy, not good data: 0.60.35 copied the empty 0.60.34 and so has a marker, and 0.60.36 copied that.
193    /// The chain back from 36 passes 35 (marked) but ends at 34, which has no marker and older data behind it.
194    #[test]
195    fn a_chain_through_a_copy_of_an_empty_fresh_start_is_not_confirmed() {
196        let root = tempfile::tempdir().unwrap();
197        let l = layout(root.path());
198        version_with_data(&l, "0.60.33", None);
199        version_with_data(&l, "0.60.34", None);
200        version_with_data(&l, "0.60.35", Some("0.60.34"));
201        std::fs::write(db_dir(&l).join(crate::migrations::carry_forward::CARRIED_FROM_FILE), "0.60.35").unwrap();
202        assert!(!start_is_confirmed(&l));
203    }
204
205    #[test]
206    fn a_marker_that_does_not_name_an_older_version_is_not_confirmed() {
207        let root = tempfile::tempdir().unwrap();
208        let l = carried_from_old(root.path());
209        version_with_data(&l, "0.60.34", Some("0.60.34"));
210        assert!(!start_is_confirmed(&l), "a loop back to itself");
211    }
212
213    /// The data-loss case: 0.60.34 started fresh after a failed copy (empty databases, no record), and this version then
214    /// copied that empty copy. The pass would keep it and the running one and remove the only good copy, 0.60.33.
215    #[test]
216    fn a_start_that_copied_an_empty_fresh_start_is_not_confirmed() {
217        let root = tempfile::tempdir().unwrap();
218        let l = carried_from_old(root.path());
219        version_with_data(&l, "0.60.33", None);
220        version_with_data(&l, "0.60.34", None);
221        assert!(!start_is_confirmed(&l));
222    }
223
224    /// After a pass: 0.60.33 (the origin) was removed, 0.60.34 still names it, and the running 0.60.35 carried 0.60.34.
225    /// Every later start must still be confirmed, or the cleanup never runs twice.
226    #[test]
227    fn a_chain_whose_origin_an_earlier_pass_removed_is_still_confirmed() {
228        let root = tempfile::tempdir().unwrap();
229        let l = carried_from_old(root.path());
230        version_with_data(&l, "0.60.34", Some("0.60.33"));
231        assert!(start_is_confirmed(&l));
232    }
233
234    /// A source that is gone with older data still on disk behind it is not vouched for.
235    #[test]
236    fn a_source_folder_that_is_gone_with_older_data_behind_it_is_not_confirmed() {
237        let root = tempfile::tempdir().unwrap();
238        let l = carried_from_old(root.path());
239        version_with_data(&l, "0.60.33", None);
240        assert!(!start_is_confirmed(&l), "0.60.34 is gone, 0.60.33 is still there");
241    }
242
243    /// A failed copy leaves the new version to start with empty databases: the old folders may hold the only good copy.
244    #[test]
245    fn a_start_with_no_record_of_a_carry_forward_is_not_confirmed_so_nothing_is_judged() {
246        let root = tempfile::tempdir().unwrap();
247        let l = layout(root.path());
248        db_dir(&l);
249        assert!(!start_is_confirmed(&l), "a database folder, but no record of where its data came from");
250        assert!(!start_is_confirmed(&layout(&root.path().join("elsewhere"))), "no folder at all");
251    }
252}