Skip to main content

agentmux_srv_core/backend/storage/
snapshot.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pre-migration snapshots — Increment B.2 lean cut from
5//! `docs/specs/SPEC_DATA_CHANNELS_2026_05_24.md` §3.4.
6//!
7//! When a launch detects an existing `objects.db` whose `user_version` is
8//! behind the binary's `OBJECT_SCHEMA_VERSION`, copy the SQLite DBs into
9//! `<data>/snapshots/<channel>-pre-v<code-version>-<ISO8601>.bak/` (this version's data directory)
10//! BEFORE any migration mutates them, then prune to the newest
11//! [`MAX_SNAPSHOTS_PER_CHANNEL`] per channel.
12//!
13//! Lean-cut scope decisions (vs. the full spec):
14//!
15//! - SQLite files only — no copy of `agents/`, `config/`, `logs/`, or
16//!   `cef-cache/`. Most state worth recovering lives in the DBs; agent
17//!   workspaces are typically git-managed; logs and cache are regenerable.
18//!   Cuts snapshot size by ~10× vs. a full data-dir copy.
19//! - `VACUUM INTO` instead of file copy — produces an atomic, WAL-consistent
20//!   single-file snapshot regardless of journal state. No need to coordinate
21//!   `.db-wal` and `.db-shm` files separately.
22//! - No restore CLI — manual restore is `cp snapshot/*.db <db_dir>/`.
23//!   Documented in the spec for now; a CLI can come later if used.
24//! - Snapshot failure is logged + non-fatal — the safety lock already
25//!   prevents downgrade corruption, so a failed snapshot is a missing
26//!   rollback aid, not a data-loss event. Refusing to boot would be worse.
27
28use std::fs;
29use std::path::{Path, PathBuf};
30use std::time::SystemTime;
31
32use chrono::{DateTime, Utc};
33use rusqlite::Connection;
34use tracing::{info, warn};
35
36/// Token that separates `<channel>` from the version segment in snapshot
37/// dir names: `<channel>-pre-v<code_version>-<ts>.bak`. Used by the prune
38/// step to extract the timestamp from the filename (more robust than mtime,
39/// which can be rewritten by backup tools).
40const NAME_PRE_TOKEN: &str = "-pre-v";
41const NAME_SUFFIX: &str = ".bak";
42
43/// Maximum number of snapshots retained per channel. Older ones are pruned
44/// after each new snapshot. Spec §3.4 budgets ~2 GB per channel at this
45/// retention level; the lean SQLite-only cut runs well under that.
46pub const MAX_SNAPSHOTS_PER_CHANNEL: usize = 5;
47
48/// DBs included in a snapshot. Lean-cut: SQLite files only.
49const SNAPSHOT_DB_NAMES: &[&str] = &["objects.db", "sagas.db", "filestore.db"];
50
51/// The database whose transcript zones a snapshot leaves out.
52const FILESTORE_DB_NAME: &str = "filestore.db";
53
54/// Every transcript zone starts with this (`agent:<id>:current`, its
55/// archives, and the files kept beside them). A snapshot never holds a
56/// conversation: the one stored copy lives in the shared transcript store, and
57/// a snapshot of it would be a second copy of what that store keeps once.
58const TRANSCRIPT_ZONE_PREFIX: &str = "agent:";
59
60/// The filestore tables that carry a `zoneid`.
61const ZONE_TABLES: &[&str] = &["db_wave_file", "db_file_data", "db_file_frame"];
62
63#[derive(Debug, thiserror::Error)]
64pub enum SnapshotError {
65    #[error("io error during snapshot ({path}): {source}")]
66    Io {
67        path: PathBuf,
68        #[source]
69        source: std::io::Error,
70    },
71
72    #[error("sqlite error during snapshot: {0}")]
73    Sql(#[from] rusqlite::Error),
74
75    #[error("invalid channel name for snapshot: {0:?}")]
76    InvalidChannel(String),
77}
78
79impl SnapshotError {
80    fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
81        SnapshotError::Io {
82            path: path.into(),
83            source,
84        }
85    }
86}
87
88/// Inspect `objects.db` to decide whether a pre-migration snapshot is
89/// warranted. Returns `Some(found_version)` if an existing DB is behind
90/// `current`; `None` for fresh installs (no file) or same-version opens.
91/// A newer-than-current DB is left alone — the safety lock in `store.rs`
92/// will refuse to open it before any migration runs.
93pub fn needs_snapshot(
94    objects_db: &Path,
95    current_schema_version: i64,
96) -> Result<Option<i64>, SnapshotError> {
97    if !objects_db.exists() {
98        return Ok(None);
99    }
100    // Read-only peek. Open in read-only mode so a concurrent write can't
101    // be triggered by anything we do here (the connection is dropped
102    // before any real open happens).
103    let conn = Connection::open_with_flags(
104        objects_db,
105        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_URI,
106    )?;
107    let found: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
108    drop(conn);
109    if found < current_schema_version {
110        Ok(Some(found))
111    } else {
112        Ok(None)
113    }
114}
115
116/// Snapshot the SQLite DBs in `db_dir` to a new directory under
117/// `snapshots_dir`. The snapshot dir is named
118/// `<channel>-pre-v<code_version>-<ISO8601>.bak`. Uses `VACUUM INTO` for
119/// atomic, WAL-consistent copies. Returns the new snapshot dir.
120pub fn create_snapshot(
121    db_dir: &Path,
122    snapshots_dir: &Path,
123    channel: &str,
124    code_version: &str,
125) -> Result<PathBuf, SnapshotError> {
126    validate_channel(channel)?;
127    let snap_name = snapshot_dir_name(channel, code_version, SystemTime::now());
128    let snap_dir = snapshots_dir.join(&snap_name);
129    fs::create_dir_all(&snap_dir).map_err(|e| SnapshotError::io(&snap_dir, e))?;
130    for db_name in SNAPSHOT_DB_NAMES {
131        let src = db_dir.join(db_name);
132        if !src.exists() {
133            continue;
134        }
135        let dst = snap_dir.join(db_name);
136        // A consistent copy including committed WAL frames, read-only on the
137        // source (`db_copy`). The filestore's transcript zones are left out.
138        let copied = if *db_name == FILESTORE_DB_NAME {
139            crate::backend::storage::db_copy::copy_database_excluding_zones(&src, &dst, TRANSCRIPT_ZONE_PREFIX, ZONE_TABLES)
140        } else {
141            crate::backend::storage::db_copy::copy_database(&src, &dst)
142        };
143        copied.map_err(|e| SnapshotError::io(&dst, std::io::Error::other(e)))?;
144    }
145    info!(
146        snapshot = %snap_dir.display(),
147        channel,
148        code_version,
149        "created pre-migration snapshot",
150    );
151    Ok(snap_dir)
152}
153
154/// Delete oldest snapshots for `channel` until at most
155/// [`MAX_SNAPSHOTS_PER_CHANNEL`] remain. Returns the number pruned.
156/// Pruning errors on a specific entry are logged and skipped rather than
157/// aborting the whole sweep (one bad dir shouldn't keep storage growing).
158pub fn prune_snapshots(snapshots_dir: &Path, channel: &str) -> Result<usize, SnapshotError> {
159    if !snapshots_dir.exists() {
160        return Ok(0);
161    }
162    let prefix = format!("{channel}{NAME_PRE_TOKEN}");
163    // Sort by the filename's embedded ISO timestamp rather than filesystem
164    // mtime — mtime can be rewritten by backup tools, copies, or restores,
165    // and would mis-rank snapshots after a `cp -a`. The filename is what
166    // the snapshot creator stamped at the moment it was made.
167    let mut matches: Vec<(String, PathBuf)> = Vec::new();
168    let entries = fs::read_dir(snapshots_dir).map_err(|e| SnapshotError::io(snapshots_dir, e))?;
169    for entry in entries {
170        let entry = entry.map_err(|e| SnapshotError::io(snapshots_dir, e))?;
171        let path = entry.path();
172        if !path.is_dir() {
173            continue;
174        }
175        let fname = entry.file_name().to_string_lossy().into_owned();
176        if !fname.starts_with(&prefix) || !fname.ends_with(NAME_SUFFIX) {
177            continue;
178        }
179        let Some(ts) = parse_ts_from_name(&fname, &prefix) else {
180            // Malformed name — skip rather than guess at ordering.
181            warn!(snapshot = %fname, "snapshot name doesn't match expected layout — ignored for prune");
182            continue;
183        };
184        matches.push((ts, path));
185    }
186    if matches.len() <= MAX_SNAPSHOTS_PER_CHANNEL {
187        return Ok(0);
188    }
189    // ISO 8601 strings sort lexicographically in chronological order, so
190    // a plain string sort gives oldest-first.
191    matches.sort_by(|a, b| a.0.cmp(&b.0));
192    let to_remove = matches.len() - MAX_SNAPSHOTS_PER_CHANNEL;
193    let mut removed = 0;
194    for (_, path) in matches.into_iter().take(to_remove) {
195        match fs::remove_dir_all(&path) {
196            Ok(()) => removed += 1,
197            Err(e) => warn!(snapshot = %path.display(), err = %e, "failed to prune snapshot"),
198        }
199    }
200    Ok(removed)
201}
202
203/// Extract the timestamp segment from a snapshot dir name.
204/// Format: `<channel>-pre-v<code_version>-<ISO8601>.bak`. We already know
205/// the name starts with `<channel>-pre-v` (the caller checked); find the
206/// last `-` before `.bak` to split off the timestamp from `<code_version>`.
207fn parse_ts_from_name(fname: &str, channel_prefix: &str) -> Option<String> {
208    let rest = fname.strip_prefix(channel_prefix)?;
209    let rest = rest.strip_suffix(NAME_SUFFIX)?;
210    // `rest` is now `<code_version>-<ISO8601>`. The ISO timestamp is the
211    // last 20 chars (`YYYY-MM-DDTHH-MM-SSZ`); split on the last `-` that
212    // separates them. Code versions can contain digits, dots, and dashes
213    // (semver pre-release like `0.39.0-rc1`), but our ISO format is fixed
214    // width — find the last position where the tail matches the shape.
215    const ISO_LEN: usize = 20; // "YYYY-MM-DDTHH-MM-SSZ"
216    if rest.len() <= ISO_LEN + 1 {
217        return None;
218    }
219    let sep_idx = rest.len() - ISO_LEN - 1;
220    if rest.as_bytes().get(sep_idx) != Some(&b'-') {
221        return None;
222    }
223    Some(rest[sep_idx + 1..].to_string())
224}
225
226/// High-level entry: check, snapshot, prune. Returns the snapshot dir on
227/// success, or `None` if no snapshot was needed. Errors are surfaced to the
228/// caller; production call sites should log-and-continue rather than abort
229/// boot (see module docs).
230pub fn maybe_snapshot_pre_migration(
231    db_dir: &Path,
232    snapshots_dir: &Path,
233    channel: &str,
234    code_version: &str,
235    current_schema_version: i64,
236) -> Result<Option<PathBuf>, SnapshotError> {
237    let objects_db = db_dir.join("objects.db");
238    let Some(found_version) = needs_snapshot(&objects_db, current_schema_version)? else {
239        return Ok(None);
240    };
241    info!(
242        from_version = found_version,
243        to_version = current_schema_version,
244        channel,
245        "pre-migration snapshot needed",
246    );
247    fs::create_dir_all(snapshots_dir).map_err(|e| SnapshotError::io(snapshots_dir, e))?;
248    let snap = crate::boot_timing::step("snapshot", "Taking a snapshot of this version's data", || {
249        create_snapshot(db_dir, snapshots_dir, channel, code_version)
250    })?;
251    let pruned = prune_snapshots(snapshots_dir, channel)?;
252    if pruned > 0 {
253        info!(pruned, channel, "pruned old snapshots");
254    }
255    Ok(Some(snap))
256}
257
258// ── helpers ────────────────────────────────────────────────────────────
259
260/// Reject channel names that would break the filename layout or escape the
261/// snapshots dir. Mirrors the reserved-name set in `agentmux-common`'s
262/// `sanitize_channel_name`, but operates on the already-resolved channel
263/// string this module receives via env.
264fn validate_channel(channel: &str) -> Result<(), SnapshotError> {
265    if channel.is_empty()
266        || channel.contains('/')
267        || channel.contains('\\')
268        || channel.contains("..")
269        || channel.contains('\0')
270    {
271        return Err(SnapshotError::InvalidChannel(channel.to_string()));
272    }
273    Ok(())
274}
275
276fn snapshot_dir_name(channel: &str, code_version: &str, t: SystemTime) -> String {
277    let dt: DateTime<Utc> = t.into();
278    // Windows-safe ISO 8601: `:` is illegal in NTFS filenames, so use `-`.
279    // Spec §3.4 example uses this same form.
280    let ts = dt.format("%Y-%m-%dT%H-%M-%SZ").to_string();
281    format!("{channel}-pre-v{code_version}-{ts}.bak")
282}
283
284// ── tests ──────────────────────────────────────────────────────────────
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use std::time::{Duration, UNIX_EPOCH};
290
291    fn make_db_with_version(path: &Path, version: i64) {
292        let conn = Connection::open(path).unwrap();
293        conn.execute_batch(&format!(
294            "CREATE TABLE IF NOT EXISTS t (x INTEGER); INSERT INTO t VALUES (42); PRAGMA user_version = {version};"
295        )).unwrap();
296    }
297
298    #[test]
299    fn needs_snapshot_returns_none_for_fresh_install() {
300        let tmp = tempfile::tempdir().unwrap();
301        let missing = tmp.path().join("objects.db");
302        assert_eq!(needs_snapshot(&missing, 4).unwrap(), None);
303    }
304
305    #[test]
306    fn needs_snapshot_returns_none_when_same_version() {
307        let tmp = tempfile::tempdir().unwrap();
308        let p = tmp.path().join("objects.db");
309        make_db_with_version(&p, 4);
310        assert_eq!(needs_snapshot(&p, 4).unwrap(), None);
311    }
312
313    #[test]
314    fn needs_snapshot_returns_some_when_db_is_behind() {
315        let tmp = tempfile::tempdir().unwrap();
316        let p = tmp.path().join("objects.db");
317        make_db_with_version(&p, 2);
318        assert_eq!(needs_snapshot(&p, 4).unwrap(), Some(2));
319    }
320
321    #[test]
322    fn needs_snapshot_returns_some_for_legacy_db_at_v0() {
323        // Pre-flatten DBs never set user_version, so they read 0 even
324        // though they contain real data. We snapshot those before the
325        // flat schema runs (it's idempotent but still touches state).
326        let tmp = tempfile::tempdir().unwrap();
327        let p = tmp.path().join("objects.db");
328        let conn = Connection::open(&p).unwrap();
329        conn.execute_batch("CREATE TABLE t (x INTEGER); INSERT INTO t VALUES (1);")
330            .unwrap();
331        assert_eq!(needs_snapshot(&p, 4).unwrap(), Some(0));
332    }
333
334    #[test]
335    fn a_snapshot_of_the_filestore_holds_no_transcript_zone() {
336        let tmp = tempfile::tempdir().unwrap();
337        let db_dir = tmp.path().join("db");
338        let snaps_dir = tmp.path().join("snapshots");
339        fs::create_dir_all(&db_dir).unwrap();
340        let conn = Connection::open(db_dir.join("filestore.db")).unwrap();
341        crate::backend::storage::migrations::run_filestore_migrations(&conn).unwrap();
342        conn.execute_batch(
343            "INSERT INTO db_wave_file (zoneid, name, size) VALUES ('agent:a:current', 'output', 24);
344             INSERT INTO db_file_data VALUES ('agent:a:current', 'output', 0, 'SNAPSHOT-MARKER-TRANSCRIPT');
345             INSERT INTO db_wave_file (zoneid, name, size) VALUES ('agent:a:archive:9', 'output', 24);
346             INSERT INTO db_file_data VALUES ('agent:a:archive:9', 'output', 0, 'SNAPSHOT-MARKER-ARCHIVE');
347             INSERT INTO db_wave_file (zoneid, name, size) VALUES ('block-1', 'term', 13);
348             INSERT INTO db_file_data VALUES ('block-1', 'term', 0, 'terminal text');",
349        )
350        .unwrap();
351
352        let snap = create_snapshot(&db_dir, &snaps_dir, "stable", "0.60.46").unwrap();
353        let copy = Connection::open(snap.join("filestore.db")).unwrap();
354        let zones: Vec<String> = copy
355            .prepare("SELECT zoneid FROM db_wave_file")
356            .unwrap()
357            .query_map([], |r| r.get(0))
358            .unwrap()
359            .collect::<Result<_, _>>()
360            .unwrap();
361        assert_eq!(zones, vec!["block-1"]);
362        let parts: i64 = copy.query_row("SELECT COUNT(*) FROM db_file_data", [], |r| r.get(0)).unwrap();
363        assert_eq!(parts, 1);
364        drop(copy);
365        for entry in fs::read_dir(&snap).unwrap().flatten() {
366            let bytes = fs::read(entry.path()).unwrap();
367            assert!(!bytes.windows(15).any(|w| w == b"SNAPSHOT-MARKER"), "{:?} holds a transcript", entry.path());
368        }
369    }
370
371    #[test]
372    fn create_snapshot_copies_existing_dbs_only() {
373        let tmp = tempfile::tempdir().unwrap();
374        let db_dir = tmp.path().join("db");
375        let snaps_dir = tmp.path().join("snapshots");
376        fs::create_dir_all(&db_dir).unwrap();
377        make_db_with_version(&db_dir.join("objects.db"), 2);
378        // filestore.db intentionally absent — should be skipped without error.
379        make_db_with_version(&db_dir.join("sagas.db"), 1);
380
381        let snap = create_snapshot(&db_dir, &snaps_dir, "stable", "0.39.0").unwrap();
382        assert!(snap.is_dir());
383        assert!(snap.join("objects.db").exists());
384        assert!(snap.join("sagas.db").exists());
385        assert!(!snap.join("filestore.db").exists());
386
387        // VACUUM INTO preserves user_version.
388        let conn = Connection::open(snap.join("objects.db")).unwrap();
389        let v: i64 = conn
390            .query_row("PRAGMA user_version", [], |r| r.get(0))
391            .unwrap();
392        assert_eq!(v, 2);
393        // And data.
394        let x: i64 = conn.query_row("SELECT x FROM t LIMIT 1", [], |r| r.get(0)).unwrap();
395        assert_eq!(x, 42);
396    }
397
398    #[test]
399    fn snapshot_dir_name_uses_filename_safe_iso8601() {
400        let t = UNIX_EPOCH + Duration::from_secs(1_716_634_800); // 2024-05-25T11:00:00Z
401        let name = snapshot_dir_name("stable", "0.39.0", t);
402        assert_eq!(name, "stable-pre-v0.39.0-2024-05-25T11-00-00Z.bak");
403        // Critical for Windows: no colons.
404        assert!(!name.contains(':'));
405    }
406
407    #[test]
408    fn validate_channel_rejects_traversal() {
409        assert!(validate_channel("").is_err());
410        assert!(validate_channel("..").is_err());
411        assert!(validate_channel("a/b").is_err());
412        assert!(validate_channel("a\\b").is_err());
413        assert!(validate_channel("ok").is_ok());
414        assert!(validate_channel("stable").is_ok());
415    }
416
417    #[test]
418    fn prune_keeps_newest_n_per_channel() {
419        let tmp = tempfile::tempdir().unwrap();
420        let snaps = tmp.path();
421        // Create MAX+3 snapshot dirs with synthetic, spaced-out timestamps
422        // in the filename. Prune sorts by the filename's ISO segment, not
423        // mtime — so we don't need any sleeps or filetime tweaks.
424        let extras = 3;
425        let mut created = Vec::new();
426        for i in 0..(MAX_SNAPSHOTS_PER_CHANNEL + extras) {
427            let t = UNIX_EPOCH + Duration::from_secs(1_700_000_000 + i as u64 * 60);
428            let name = snapshot_dir_name("stable", "0.39.0", t);
429            let p = snaps.join(&name);
430            fs::create_dir_all(&p).unwrap();
431            created.push((i, p));
432        }
433        // Other-channel dir must NOT be pruned even if older.
434        let other = snaps.join("beta-pre-v0.39.0-2020-01-01T00-00-00Z.bak");
435        fs::create_dir_all(&other).unwrap();
436
437        let pruned = prune_snapshots(snaps, "stable").unwrap();
438        assert_eq!(pruned, extras);
439        // The MAX_SNAPSHOTS_PER_CHANNEL newest (highest indices) survive.
440        for (i, p) in &created {
441            let should_exist = *i >= extras;
442            assert_eq!(p.exists(), should_exist, "i={i}");
443        }
444        assert!(other.exists(), "other-channel snapshot must survive");
445    }
446
447    #[test]
448    fn parse_ts_from_name_extracts_timestamp() {
449        let n = "stable-pre-v0.39.0-2024-05-25T11-00-00Z.bak";
450        let prefix = "stable-pre-v";
451        assert_eq!(
452            parse_ts_from_name(n, prefix).as_deref(),
453            Some("2024-05-25T11-00-00Z"),
454        );
455    }
456
457    #[test]
458    fn parse_ts_handles_semver_prerelease_in_code_version() {
459        let n = "stable-pre-v0.39.0-rc1-2024-05-25T11-00-00Z.bak";
460        let prefix = "stable-pre-v";
461        assert_eq!(
462            parse_ts_from_name(n, prefix).as_deref(),
463            Some("2024-05-25T11-00-00Z"),
464        );
465    }
466
467    #[test]
468    fn prune_noop_when_under_limit() {
469        let tmp = tempfile::tempdir().unwrap();
470        for i in 0..3 {
471            let t = UNIX_EPOCH + Duration::from_secs(1_700_000_000 + i as u64 * 60);
472            let p = tmp.path().join(snapshot_dir_name("stable", "0.39.0", t));
473            fs::create_dir_all(&p).unwrap();
474        }
475        assert_eq!(prune_snapshots(tmp.path(), "stable").unwrap(), 0);
476    }
477
478    #[test]
479    fn maybe_snapshot_returns_none_for_fresh_install() {
480        let tmp = tempfile::tempdir().unwrap();
481        let db_dir = tmp.path().join("db");
482        let snaps = tmp.path().join("snapshots");
483        fs::create_dir_all(&db_dir).unwrap();
484        let result =
485            maybe_snapshot_pre_migration(&db_dir, &snaps, "stable", "0.39.0", 4).unwrap();
486        assert!(result.is_none());
487        // Snapshots dir is NOT created when no snapshot is needed.
488        assert!(!snaps.exists());
489    }
490
491    #[test]
492    fn maybe_snapshot_runs_when_db_behind() {
493        let tmp = tempfile::tempdir().unwrap();
494        let db_dir = tmp.path().join("db");
495        let snaps = tmp.path().join("snapshots");
496        fs::create_dir_all(&db_dir).unwrap();
497        make_db_with_version(&db_dir.join("objects.db"), 2);
498        let result =
499            maybe_snapshot_pre_migration(&db_dir, &snaps, "stable", "0.39.0", 4).unwrap();
500        let snap = result.expect("snapshot should be created");
501        assert!(snap.is_dir());
502        assert!(snap.join("objects.db").exists());
503    }
504}