Skip to main content

agentmux_srv_core/migrations/
carry_forward.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A new version starts with the data of the version before it
5//! (`docs/specs/SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` ยง6).
6//!
7//! Installed and portable builds keep their databases per version
8//! (`channels/<ch>/versions/<v>/data/db/`), so without this an upgrade
9//! starts with an empty `objects.db`: no windows, no layouts, and no pane's
10//! `agent:sessionid` to resume. On the first start of a version, before its
11//! pre-migration snapshot and migrations, each database is copied from the
12//! newest older version in the same channel; migrations then bring it up to
13//! date as they would after an in-place upgrade.
14//!
15//! Each copy is `VACUUM INTO` a temporary file, renamed into place: a
16//! consistent snapshot even if the older version is still running (two
17//! portable folders side by side), and never a half-written file. Any failure
18//! leaves the new version to start fresh, as it did before. Dev builds keep
19//! their data per branch, and local `task package` builds get a channel of
20//! their own, so neither has an older version to copy from.
21//!
22//! This is the only thing that seeds a version's databases. A channel whose
23//! install predates per-version data still has its old `channels/<ch>/data/db/`;
24//! it is copied only while no version has data yet. The launcher used to copy
25//! that folder into every new version before srv started, so srv found an
26//! `objects.db` in place and carried nothing forward: each upgrade started from
27//! that old data, without the layout the previous version's quit had saved
28//! (`docs/incident/RCA_UPGRADE_LOSES_LAYOUT_2026_10_22.md`). Each copy
29//! records where it came from ([`CARRIED_FROM_FILE`]), and the first start
30//! after an upgrade checks it ([`continuity_problem`]).
31
32use std::path::{Path, PathBuf};
33
34use crate::backend::storage::db_copy::copy_database;
35
36/// The databases copied, `objects.db` last: its presence is what marks a
37/// version as started, so a copy cut short is tried again on the next start.
38const DATABASES: [&str; 3] = ["filestore.db", "sagas.db", "objects.db"];
39
40/// In a version's `data/db/`: the version folder its databases were copied
41/// from, or [`PRE_VERSIONING`].
42pub(crate) const CARRIED_FROM_FILE: &str = "carried-from";
43
44/// What [`CARRIED_FROM_FILE`] says for a copy of the channel's pre-versioning
45/// `data/db/`.
46pub(crate) const PRE_VERSIONING: &str = "pre-versioning data";
47
48/// `major.minor.patch` of a version or version directory name.
49pub(crate) fn version_core(v: &str) -> Option<(u64, u64, u64)> {
50    let core = v.trim().trim_start_matches('v').split(['+', '-']).next()?;
51    let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
52    let version = (parts.next()??, parts.next()??, parts.next()??);
53    parts.next().is_none().then_some(version)
54}
55
56/// The `data/db/` of the newest version in `versions_dir` older than
57/// `current` that has an `objects.db`.
58fn previous_db_dir(versions_dir: &Path, current: (u64, u64, u64)) -> Option<PathBuf> {
59    std::fs::read_dir(versions_dir)
60        .ok()?
61        .filter_map(|e| e.ok())
62        .filter_map(|e| {
63            let v = version_core(e.file_name().to_str()?)?;
64            let db = e.path().join("data").join("db");
65            (v < current && db.join("objects.db").is_file()).then_some((v, db))
66        })
67        .max_by_key(|(v, _)| *v)
68        .map(|(_, db)| db)
69}
70
71/// The channel's pre-versioning `data/db/` (`channels/<ch>/data/db/`, beside
72/// `versions_dir`), while no version in `versions_dir` has an `objects.db`:
73/// an install from before data was kept per version, on its first versioned
74/// start. Never once a version has data: that folder stopped changing when
75/// its install moved to per-version data, so it is older than all of it.
76fn pre_versioning_db_dir(versions_dir: &Path) -> Option<PathBuf> {
77    let a_version_has_data = std::fs::read_dir(versions_dir)
78        .map(|d| d.filter_map(|e| e.ok()).any(|e| e.path().join("data").join("db").join("objects.db").is_file()))
79        .unwrap_or(false);
80    if a_version_has_data {
81        return None;
82    }
83    let db = versions_dir.parent()?.join("data").join("db");
84    db.join("objects.db").is_file().then_some(db)
85}
86
87/// What [`CARRIED_FROM_FILE`] says for a copy from `source` (a `data/db/`).
88fn carried_from_name(source: &Path) -> String {
89    let owner = source.parent().and_then(Path::parent);
90    match owner {
91        Some(dir) if dir.parent().and_then(Path::file_name).is_some_and(|n| n == "versions") => {
92            dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
93        }
94        _ => PRE_VERSIONING.to_string(),
95    }
96}
97
98/// Where the databases in `db_dir` were copied from, if a copy-forward seeded them.
99fn carried_from(db_dir: &Path) -> Option<String> {
100    let text = std::fs::read_to_string(db_dir.join(CARRIED_FROM_FILE)).ok()?;
101    Some(text.trim().to_string()).filter(|s| !s.is_empty())
102}
103
104/// The check on the first start after an upgrade from version `from`: when
105/// `from`'s data is in this channel (`versions/<from>/data/db/objects.db`
106/// beside this version's), this version's databases (`db_dir`) must have been
107/// copied from it, or the windows, tabs and panes `from` saved at its quit
108/// are not here. `None` when they were, or when `from` has no data to compare.
109pub(crate) fn continuity_problem(db_dir: &Path, from: &str) -> Option<String> {
110    let versions_dir = db_dir.parent()?.parent()?.parent()?;
111    if versions_dir.file_name()? != "versions" {
112        return None;
113    }
114    let from_db = versions_dir.join(from).join("data").join("db");
115    if !from_db.join("objects.db").is_file() {
116        return None;
117    }
118    // Either way the layout `from` quit with isn't here. Which cause it is
119    // can't be told from here: this version may have run before (a rollback,
120    // then this upgrade again), or something else put its databases in place.
121    match carried_from(db_dir) {
122        Some(source) if source == from => None,
123        Some(source) => Some(format!(
124            "this version's data was copied from {source}, not from {from}, the version this upgrade was from \
125             (it has run before, or was copied from another version)"
126        )),
127        None => Some(format!(
128            "this version's data wasn't copied from {from}, the version this upgrade was from: \
129             its databases were already in {} (it has run before, or something other than srv's \
130             copy-forward put them there)",
131            db_dir.display()
132        )),
133    }
134}
135
136/// On the first start of `version` (no `objects.db` in `db_dir` yet), copy
137/// the databases of the newest older version in the same channel (or the
138/// channel's pre-versioning ones, [`source_for`]), and record where they came
139/// from ([`CARRIED_FROM_FILE`]). Returns
140/// the version directory copied from, or `None` when there was nothing to do
141/// or the copy failed (logged; the version then starts fresh).
142pub fn from_previous_version(db_dir: &Path, version: &str) -> Option<PathBuf> {
143    match try_from_previous_version(db_dir, version) {
144        Ok(from) => from,
145        Err(e) => {
146            tracing::warn!("carry-forward: {e}; starting fresh");
147            None
148        }
149    }
150}
151
152/// What a failed copy-forward is, in plain words: the cause a person can act on.
153fn plain_cause(error: &str) -> &'static str {
154    let e = error.to_ascii_lowercase();
155    let full = ["no space left", "disk is full", "disk full", "not enough space", "os error 28", "os error 112", "quota"];
156    let unreadable = ["not a database", "malformed", "corrupt", "unable to open", "permission denied", "locked", "busy"];
157    if full.iter().any(|m| e.contains(m)) {
158        "there is not enough free space on the disk"
159    } else if unreadable.iter().any(|m| e.contains(m)) {
160        "a database of the previous version could not be read"
161    } else {
162        "the previous version's data could not be copied"
163    }
164}
165
166/// The message a start that cannot carry the previous version's data forward stops with: the cause in plain words, that the
167/// previous version's data was not touched, and that this version did not start empty. `error` is what
168/// [`try_from_previous_version`] returned; it goes last, for the log.
169pub fn stop_message(error: &str) -> String {
170    format!(
171        "this version could not start with the previous version's data: {}. The previous version's data is untouched and this version \
172         did not start with empty data instead. Fix that and start again ({error})",
173        plain_cause(error)
174    )
175}
176
177/// [`from_previous_version`], telling "nothing to copy" (`Ok(None)`) apart
178/// from "there was data to copy and copying it failed" (`Err`), which
179/// `migrate --prepare` must not treat as a fresh start: that would relaunch
180/// the new version without the user's data (`migrations/prepare.rs`). Copies
181/// that failed are removed again, so a retry starts clean.
182pub fn try_from_previous_version(db_dir: &Path, version: &str) -> Result<Option<PathBuf>, String> {
183    let Some(source) = source_for(db_dir, version) else {
184        return Ok(None);
185    };
186    let from = source.parent().and_then(Path::parent).map(Path::to_path_buf).unwrap_or_else(|| source.clone());
187    let from_name = carried_from_name(&source);
188    std::fs::create_dir_all(db_dir).map_err(|e| format!("can't create {}: {e}", db_dir.display()))?;
189    // A large filestore.db takes a while to copy: the same line migrations
190    // print moves the launcher's ESTART deadline from 30 s to 30 minutes.
191    eprintln!("{}", agentmux_common::srv_stderr::migrating_line("copying-previous-version", &from_name));
192    crate::boot_timing::step("copy_previous_version", &format!("Copying from {from_name}"), || {
193        let mut copied = Vec::new();
194        for name in DATABASES {
195            let src = source.join(name);
196            let dst = db_dir.join(name);
197            // Already here: copied by a start that was cut short before objects.db.
198            if !src.is_file() || dst.exists() {
199                continue;
200            }
201            if let Err(e) = copy_database(&src, &dst) {
202                for dst in copied {
203                    let _ = std::fs::remove_file(dst);
204                }
205                return Err(format!("copying {name} from {}: {e}", from.display()));
206            }
207            copied.push(dst);
208        }
209        Ok(())
210    })?;
211    // Best-effort: without it the first start after this upgrade reports that
212    // the data didn't come from the previous version (`continuity_problem`),
213    // which is wrong but harmless; failing the copy over it would not be.
214    if let Err(e) = std::fs::write(db_dir.join(CARRIED_FROM_FILE), &from_name) {
215        tracing::warn!(error = %e, "carry-forward: couldn't record where the data came from");
216    }
217    CARRIED_FORWARD.store(true, std::sync::atomic::Ordering::Relaxed);
218    tracing::info!(from = %from.display(), "carry-forward: started from the previous version's data");
219    Ok(Some(from))
220}
221
222/// The `data/db` of the newest older version in the same channel to copy
223/// from on the first start of `version`, else the channel's pre-versioning
224/// one while no version has data ([`pre_versioning_db_dir`]); `None` once
225/// `db_dir` has an `objects.db`, outside a `versions/<v>/data/db` layout, or
226/// with nothing to copy.
227pub(crate) fn source_for(db_dir: &Path, version: &str) -> Option<PathBuf> {
228    if db_dir.join("objects.db").exists() {
229        return None;
230    }
231    let current = version_core(version)?;
232    // db_dir is channels/<ch>/versions/<v>/data/db.
233    let version_dir = db_dir.parent()?.parent()?;
234    let versions_dir = version_dir.parent()?;
235    if versions_dir.file_name()? != "versions" {
236        return None;
237    }
238    previous_db_dir(versions_dir, current).or_else(|| pre_versioning_db_dir(versions_dir))
239}
240
241static CARRIED_FORWARD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
242
243/// Whether this process copied a previous version's data forward. The
244/// previous version's folder then still holds that data untouched, so the
245/// pre-migration snapshot and the backup of `objects.db` would only copy the
246/// same data again (`bootstrap/stores.rs`, `migrations/backup.rs`).
247pub(crate) fn carried_forward_this_run() -> bool {
248    CARRIED_FORWARD.load(std::sync::atomic::Ordering::Relaxed)
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use rusqlite::Connection;
255
256    fn db_dir(root: &Path, v: &str) -> PathBuf {
257        root.join("channels/stable/versions").join(v).join("data/db")
258    }
259
260    /// An `objects.db` in WAL mode holding `marker`, left open so its last
261    /// write is still only in the WAL.
262    fn seed(root: &Path, v: &str, marker: &str) -> Connection {
263        seed_dir(&db_dir(root, v), marker)
264    }
265
266    /// [`seed`] at any `data/db/`.
267    fn seed_dir(dir: &Path, marker: &str) -> Connection {
268        std::fs::create_dir_all(dir).unwrap();
269        let conn = Connection::open(dir.join("objects.db")).unwrap();
270        conn.pragma_update(None, "journal_mode", "WAL").unwrap();
271        conn.pragma_update(None, "wal_autocheckpoint", 0).unwrap();
272        conn.execute_batch("CREATE TABLE t (v TEXT)").unwrap();
273        conn.execute("INSERT INTO t VALUES (?1)", [marker]).unwrap();
274        conn
275    }
276
277    fn marker(dir: &Path) -> String {
278        Connection::open(dir.join("objects.db")).unwrap().query_row("SELECT v FROM t", [], |r| r.get(0)).unwrap()
279    }
280
281    #[test]
282    fn a_new_version_starts_from_the_newest_older_one_even_while_it_runs() {
283        let root = tempfile::tempdir().unwrap();
284        let _old = seed(root.path(), "0.59.9", "old");
285        let _prev = seed(root.path(), "0.59.26", "previous");
286        let _newer = seed(root.path(), "0.60.0", "newer");
287        let new = db_dir(root.path(), "0.59.27");
288        let from = from_previous_version(&new, "0.59.27").unwrap();
289        assert!(from.ends_with("versions/0.59.26"));
290        assert_eq!(marker(&new), "previous");
291        assert!(!new.join("objects.db.copying").exists());
292    }
293
294    #[test]
295    fn a_version_that_has_started_before_is_left_alone() {
296        let root = tempfile::tempdir().unwrap();
297        let _prev = seed(root.path(), "0.59.26", "previous");
298        let _mine = seed(root.path(), "0.59.27", "mine");
299        assert!(from_previous_version(&db_dir(root.path(), "0.59.27"), "0.59.27").is_none());
300        assert_eq!(marker(&db_dir(root.path(), "0.59.27")), "mine");
301    }
302
303    #[test]
304    fn nothing_older_or_not_a_versioned_layout_means_a_fresh_start() {
305        let root = tempfile::tempdir().unwrap();
306        let _newer = seed(root.path(), "0.60.0", "newer");
307        let first = db_dir(root.path(), "0.59.27");
308        assert!(from_previous_version(&first, "0.59.27").is_none());
309        assert!(!first.join("objects.db").exists());
310        // A dev build's data dir isn't under versions/.
311        let dev = root.path().join("dev/main/data/db");
312        assert!(from_previous_version(&dev, "0.59.27").is_none());
313        assert!(from_previous_version(&first, "not-a-version").is_none());
314    }
315
316    #[test]
317    fn a_failed_copy_stops_the_start_and_leaves_the_previous_versions_data_as_it_was() {
318        let root = tempfile::tempdir().unwrap();
319        let prev = seed(root.path(), "0.59.26", "previous");
320        let old = db_dir(root.path(), "0.59.26");
321        Connection::open(old.join("filestore.db")).unwrap().execute_batch("CREATE TABLE f (v)").unwrap();
322        std::fs::write(old.join("sagas.db"), b"not a database").unwrap();
323        drop(prev);
324        let bytes = |dir: &Path| {
325            let mut files: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()).collect();
326            files.sort();
327            files.into_iter().map(|f| (f.file_name().unwrap().to_owned(), std::fs::read(&f).unwrap())).collect::<Vec<_>>()
328        };
329        let before = bytes(&old);
330        let new = db_dir(root.path(), "0.59.27");
331
332        let err = try_from_previous_version(&new, "0.59.27").expect_err("a copy that failed is an error, not a fresh start");
333        assert_eq!(bytes(&old), before, "the previous version's files are byte-identical");
334        let left: Vec<_> = std::fs::read_dir(&new).map(|d| d.map(|e| e.unwrap().file_name()).collect()).unwrap_or_default();
335        assert!(left.is_empty(), "nothing half-written is left in the new version's folder: {left:?}");
336        assert!(!new.join("objects.db").exists());
337
338        let say = stop_message(&err);
339        assert!(say.contains("a database of the previous version could not be read"), "{say}");
340        assert!(say.contains("untouched") && say.contains("did not start with empty data"), "{say}");
341    }
342
343    #[test]
344    fn the_stop_names_the_cause_in_plain_words() {
345        for full in ["copy x: database or disk is full", "rename into y: No space left on device (os error 28)", "There is not enough space on the disk. (os error 112)"] {
346            assert!(stop_message(full).contains("not enough free space on the disk"), "{full}");
347        }
348        assert!(stop_message("open x: file is not a database").contains("could not be read"));
349        assert!(stop_message("something else").contains("the previous version's data could not be copied"));
350        assert!(stop_message("copy x: database or disk is full").contains("(copy x: database or disk is full)"), "the detail is kept for the log");
351    }
352
353    #[test]
354    fn a_first_start_with_no_older_version_still_starts_fresh_on_purpose() {
355        let root = tempfile::tempdir().unwrap();
356        let first = db_dir(root.path(), "0.59.27");
357        assert_eq!(try_from_previous_version(&first, "0.59.27"), Ok(None));
358        let _prev = seed(root.path(), "0.59.30", "newer");
359        assert_eq!(try_from_previous_version(&db_dir(root.path(), "0.59.20"), "0.59.20"), Ok(None), "only an OLDER version is copied from");
360    }
361
362    #[test]
363    fn a_failed_copy_removes_only_what_it_copied() {
364        let root = tempfile::tempdir().unwrap();
365        let _prev = seed(root.path(), "0.59.26", "previous");
366        let old = db_dir(root.path(), "0.59.26");
367        Connection::open(old.join("filestore.db")).unwrap().execute_batch("CREATE TABLE f (v)").unwrap();
368        // A file that isn't SQLite fails its copy, after filestore.db was copied.
369        std::fs::write(old.join("sagas.db"), b"not a database").unwrap();
370        let new = db_dir(root.path(), "0.59.27");
371        assert!(from_previous_version(&new, "0.59.27").is_none());
372        for name in DATABASES {
373            assert!(!new.join(name).exists(), "{name} left behind");
374        }
375
376        // One already in the new version's folder is never removed or replaced.
377        std::fs::write(new.join("filestore.db"), b"already here").unwrap();
378        assert!(from_previous_version(&new, "0.59.27").is_none());
379        assert_eq!(std::fs::read(new.join("filestore.db")).unwrap(), b"already here");
380        assert!(!new.join("objects.db").exists());
381    }
382
383    /// The channel's `data/db/` from before data was kept per version.
384    fn pre_versioning(root: &Path) -> PathBuf {
385        root.join("channels/stable/data/db")
386    }
387
388    #[test]
389    fn pre_versioning_data_never_shadows_the_previous_version() {
390        let root = tempfile::tempdir().unwrap();
391        let _legacy = seed_dir(&pre_versioning(root.path()), "legacy");
392        let _prev = seed(root.path(), "0.59.38", "previous");
393        let new = db_dir(root.path(), "0.59.39");
394        assert!(from_previous_version(&new, "0.59.39").unwrap().ends_with("versions/0.59.38"));
395        assert_eq!(marker(&new), "previous");
396        assert_eq!(carried_from(&new).as_deref(), Some("0.59.38"));
397    }
398
399    #[test]
400    fn pre_versioning_data_seeds_only_a_channel_without_versioned_data() {
401        let root = tempfile::tempdir().unwrap();
402        let _legacy = seed_dir(&pre_versioning(root.path()), "legacy");
403        let first = db_dir(root.path(), "0.59.39");
404        assert!(from_previous_version(&first, "0.59.39").is_some());
405        assert_eq!(marker(&first), "legacy");
406        assert_eq!(carried_from(&first).as_deref(), Some(PRE_VERSIONING));
407
408        // An older build started after a newer one has data: not that old folder.
409        let older = db_dir(root.path(), "0.59.30");
410        assert!(from_previous_version(&older, "0.59.30").is_none());
411        assert!(!older.join("objects.db").exists());
412    }
413
414    /// The layout a quit saved (`session:last_topology` in the client's meta,
415    /// `server/service/session_restore.rs`) is in the new version's data, so
416    /// its first window restores every window, tab and pane.
417    #[test]
418    fn the_layout_a_quit_saved_crosses_the_upgrade() {
419        use crate::backend::obj::Client;
420        use crate::backend::storage::store::Store;
421        use crate::backend::session_snapshot::{load_last_session_snapshot, save_last_session_snapshot};
422
423        let root = tempfile::tempdir().unwrap();
424        let _legacy = seed_dir(&pre_versioning(root.path()), "legacy");
425        let old = db_dir(root.path(), "0.59.38");
426        std::fs::create_dir_all(&old).unwrap();
427        let store = Store::open(&old.join("objects.db")).unwrap();
428        store.insert(&mut Client { oid: "client-1".to_string(), ..Default::default() }).unwrap();
429        let record = serde_json::json!({
430            "saved_for": "quit",
431            "windows": [{"name": "Main", "tabs": [{"name": "Tab 1", "blocks": [
432                {"meta": {"view": "agent", "agent:sessionid": "session-1"}},
433                {"meta": {"view": "agent", "agent:sessionid": "session-2"}},
434                {"meta": {"view": "swarm"}}
435            ]}]}]
436        });
437        assert!(save_last_session_snapshot(&store, record.clone()));
438
439        // The old version still holds its store open: the record may be only in its WAL.
440        let new = db_dir(root.path(), "0.59.39");
441        assert!(from_previous_version(&new, "0.59.39").is_some());
442        let carried = Store::open(&new.join("objects.db")).unwrap();
443        assert_eq!(load_last_session_snapshot(&carried), Some(record));
444        assert_eq!(continuity_problem(&new, "0.59.38"), None);
445    }
446
447    #[test]
448    fn an_upgrade_whose_data_isnt_the_previous_versions_is_reported() {
449        let root = tempfile::tempdir().unwrap();
450        let _prev = seed(root.path(), "0.59.38", "previous");
451
452        // Databases put in place before srv's copy-forward: what the launcher did.
453        let _put = seed(root.path(), "0.59.39", "legacy");
454        let new = db_dir(root.path(), "0.59.39");
455        assert!(from_previous_version(&new, "0.59.39").is_none());
456        let problem = continuity_problem(&new, "0.59.38").expect("reported");
457        assert!(problem.contains("wasn't copied from 0.59.38"), "{problem}");
458
459        // Copied from another version than the one this upgrade was from.
460        std::fs::write(new.join(CARRIED_FROM_FILE), "0.59.36").unwrap();
461        let problem = continuity_problem(&new, "0.59.38").expect("reported");
462        assert!(problem.contains("copied from 0.59.36, not from 0.59.38"), "{problem}");
463
464        std::fs::write(new.join(CARRIED_FROM_FILE), "0.59.38\n").unwrap();
465        assert_eq!(continuity_problem(&new, "0.59.38"), None);
466
467        // Nothing to compare with: the version upgraded from has no data here.
468        assert_eq!(continuity_problem(&new, "0.59.37"), None);
469    }
470
471    #[test]
472    fn versions_compare_as_numbers() {
473        assert_eq!(version_core("0.59.100"), Some((0, 59, 100)));
474        assert!(version_core("0.59.100") > version_core("0.59.27"));
475        assert_eq!(version_core("v1.2.3+g1a2b"), Some((1, 2, 3)));
476        assert_eq!(version_core("1.2"), None);
477        assert_eq!(version_core("1.2.3.4"), None);
478    }
479}