Skip to main content

vtcode_core/core/agent/snapshots/
retention.rs

1//! Checkpoint retention: navigation protection, count budgets, age expiry,
2//! and filesnap content reclamation.
3//!
4//! Retention is best-effort and retryable: every failure path warns and defers
5//! rather than failing the turn. Protection is session-aware (see
6//! [`SnapshotRecordId`]); the count budget itself stays workspace-global.
7
8use super::*;
9
10impl SnapshotManager {
11    /// Checkpoint records still referenced by any *recent* session navigation
12    /// (active branch, redo stack, or pending recovery). Rewind/redo must
13    /// never lose these. Branch files older than the retention window are
14    /// ignored so a completed session cannot pin its turns forever.
15    ///
16    /// Scoped records are protected per owning branch; legacy (unscoped)
17    /// records stay protected by *any* branch referencing the turn, exactly
18    /// as before session scoping existed.
19    fn protected_turns(&self) -> BTreeSet<SnapshotRecordId> {
20        let cutoff = self.retention_cutoff_secs().ok().flatten();
21        self.protected_turns_with_cutoff(cutoff)
22    }
23
24    fn protected_turns_with_cutoff(&self, cutoff: Option<u64>) -> BTreeSet<SnapshotRecordId> {
25        let mut protected = BTreeSet::new();
26        let Ok(entries) = fs::read_dir(&self.storage_dir) else {
27            return protected;
28        };
29        for entry in entries.flatten() {
30            let path = entry.path();
31            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
32                continue;
33            };
34            let Some(branch_key) = stem.strip_prefix("branch_") else {
35                continue;
36            };
37            if path.extension().and_then(|e| e.to_str()) != Some("json") {
38                continue;
39            }
40            // A malformed branch key cannot own scoped records; its turns
41            // still protect the legacy layout below.
42            let scoped_key = (!branch_key.is_empty()
43                && branch_key.len() % 2 == 0
44                && branch_key.bytes().all(|b| b.is_ascii_hexdigit()))
45            .then(|| branch_key.to_owned());
46            if let Some(cutoff) = cutoff {
47                // Stale navigation (completed/abandoned session past retention)
48                // must not keep its turn files alive. `cutoff` is a UNIX
49                // timestamp: branch files last modified before it are stale.
50                let modified_secs = path
51                    .metadata()
52                    .and_then(|meta| meta.modified())
53                    .ok()
54                    .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
55                    .map(|since| since.as_secs());
56                if !modified_secs.is_some_and(|secs| secs > cutoff) {
57                    continue;
58                }
59            }
60            let Ok(bytes) = fs::read(&path) else {
61                continue;
62            };
63            let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
64                continue;
65            };
66            let mut turns = BTreeSet::new();
67            for key in ["active", "redo", "pending"] {
68                collect_turn_numbers(&value[key], &mut turns);
69            }
70            for turn in turns {
71                // Legacy records predate session attribution: any live branch
72                // keeps them, preserving pre-scoping retention behavior.
73                protected.insert(SnapshotRecordId { turn, session_key: None });
74                if let Some(key) = scoped_key.clone() {
75                    protected.insert(SnapshotRecordId { turn, session_key: Some(key) });
76                }
77            }
78        }
79        protected
80    }
81
82    /// Cheap retention prune: enforce the snapshot count budget without
83    /// reading checkpoint JSON bodies. Safe to call on the per-turn hot path
84    /// (`native::begin_prompt`); age-based expiry stays in
85    /// [`Self::cleanup_old_snapshots`], which needs each file's `created_at`.
86    pub async fn prune_snapshot_budget(&self) -> Result<()> {
87        if !self.enabled {
88            return Ok(());
89        }
90        let manager = self.clone();
91        let entries = tokio::task::spawn_blocking(move || -> Result<Vec<SnapshotFileEntry>> {
92            let protected = manager.protected_turns();
93            Ok(manager
94                .read_snapshot_files()?
95                .into_iter()
96                .filter(|entry| !protected.contains(&entry.id))
97                .collect())
98        })
99        .await
100        .context("checkpoint retention worker failed")??;
101        if self.max_snapshots != 0 && entries.len() > self.max_snapshots {
102            let excess = entries.len() - self.max_snapshots;
103            for entry in entries.into_iter().take(excess) {
104                if let Err(err) = self.retire_snapshot(&entry.path).await {
105                    tracing::warn!(
106                        path = %entry.path.display(),
107                        error = %err,
108                        "Failed to remove old checkpoint"
109                    );
110                }
111            }
112        }
113        self.cleanup_retired_snapshots(false).await;
114        Ok(())
115    }
116
117    /// Full retention: age-expire checkpoints past `max_age_days`, then apply
118    /// the count budget. Age scan reads each candidate's `created_at`, so prefer
119    /// [`Self::prune_snapshot_budget`] on hot paths.
120    pub async fn cleanup_old_snapshots(&self) -> Result<()> {
121        if !self.enabled {
122            return Ok(());
123        }
124
125        let protected = self.protected_turns();
126        if let Some(cutoff) = self.retention_cutoff_secs()? {
127            for entry in self.read_snapshot_files()? {
128                if protected.contains(&entry.id) {
129                    continue;
130                }
131                let data = match tokio::fs::read(&entry.path).await {
132                    Ok(data) => data,
133                    Err(err) => {
134                        tracing::warn!(
135                            path = %entry.path.display(),
136                            error = %err,
137                            "Failed to read checkpoint"
138                        );
139                        continue;
140                    }
141                };
142                let stored: StoredSnapshot = match serde_json::from_slice(&data) {
143                    Ok(value) => value,
144                    Err(err) => {
145                        tracing::warn!(
146                            path = %entry.path.display(),
147                            error = %err,
148                            "Failed to parse checkpoint"
149                        );
150                        continue;
151                    }
152                };
153                if stored.metadata.created_at <= cutoff
154                    && let Err(err) = self.retire_snapshot(&entry.path).await
155                {
156                    tracing::warn!(
157                        path = %entry.path.display(),
158                        error = %err,
159                        "Failed to remove expired checkpoint"
160                    );
161                }
162            }
163            // Session lock files outlive crashed sessions; reclaim the ones no
164            // live process can still be holding that are older than the
165            // retention window. The shared cleanup mutex itself persists, and
166            // locks that cannot be statted are conservatively kept.
167            if let Ok(entries) = fs::read_dir(&self.storage_dir) {
168                for entry in entries.flatten() {
169                    let path = entry.path();
170                    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
171                        continue;
172                    };
173                    if !name.starts_with("rewind-") || !name.ends_with(".lock") {
174                        continue;
175                    }
176                    let stale = path
177                        .metadata()
178                        .and_then(|meta| meta.modified())
179                        .ok()
180                        .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
181                        .map(|since| since.as_secs())
182                        .is_some_and(|secs| secs <= cutoff);
183                    if stale {
184                        remove_lock_file_if_unheld(&path);
185                    }
186                }
187            }
188        }
189
190        self.prune_snapshot_budget().await?;
191        self.cleanup_retired_snapshots(true).await;
192        Ok(())
193    }
194
195    pub(super) async fn retire_snapshot(&self, path: &Path) -> Result<()> {
196        let retired = path.with_extension(format!("retired-{}", uuid::Uuid::new_v4()));
197        tokio::fs::rename(path, retired).await?;
198        Ok(())
199    }
200
201    pub(super) async fn cleanup_retired_snapshots(&self, full_maintenance: bool) {
202        let storage = self.storage_dir.clone();
203        let workspace = self.canonical_workspace.clone();
204        let result = tokio::task::spawn_blocking(move || -> Result<()> {
205            // A replaced record can still be live if publication failed. Read
206            // every live record before deleting anything; corrupt metadata defers
207            // cleanup rather than guessing which content can be discarded.
208            let mut live_paths = Vec::new();
209            let mut retired = Vec::new();
210            for entry in fs::read_dir(&storage)? {
211                let path = entry?.path();
212                let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
213                    continue;
214                };
215                if !name.starts_with("turn_") {
216                    continue;
217                }
218                if name.ends_with(".json") {
219                    live_paths.push(path);
220                } else if path
221                    .extension()
222                    .and_then(|value| value.to_str())
223                    .is_some_and(|value| value.starts_with("retired-"))
224                {
225                    retired.push(path);
226                }
227            }
228            // The per-prompt path does not need live JSON or a content store
229            // when no records were retired. Explicit maintenance still runs GC.
230            // The mutex below is acquired only past this point so idle rounds
231            // create no lock file on the hot path.
232            if retired.is_empty() && !full_maintenance {
233                return Ok(());
234            }
235            // Retention is best-effort and retryable: when another process is
236            // already reclaiming checkpoint content, skip this round instead
237            // of interleaving filesnap deletes with its scan.
238            let _cleanup_guard = match acquire_verified_rewind_lock(&storage.join(WORKSPACE_CLEANUP_LOCK_FILE)) {
239                Ok(guard) => guard,
240                Err(error) => {
241                    tracing::debug!(%error, "Checkpoint cleanup already running elsewhere; deferring round");
242                    return Ok(());
243                }
244            };
245            let mut live = BTreeSet::new();
246            for path in live_paths {
247                let stored: StoredSnapshot = serde_json::from_slice(&fs::read(path)?)?;
248                for file in stored.files {
249                    if file.encoding == Some(FileEncoding::Filesnap) {
250                        live.insert(file.data.context("Missing checkpoint reference")?);
251                    }
252                }
253            }
254            let store = filesnap::WorkspaceStore::open(&storage, &workspace)?;
255            for path in retired {
256                let stored: StoredSnapshot = serde_json::from_slice(&fs::read(&path)?)?;
257                let mut sessions = BTreeSet::new();
258                for file in &stored.files {
259                    if file.encoding == Some(FileEncoding::Filesnap) {
260                        let session = file.data.as_deref().context("Missing retired checkpoint reference")?;
261                        let id = session.strip_prefix("vt-").context("Invalid retired checkpoint reference")?;
262                        uuid::Uuid::parse_str(id)?;
263                        if !live.contains(session) {
264                            sessions.insert(session.to_owned());
265                        }
266                    }
267                }
268                let outcome = store.delete_sessions(&sessions.into_iter().collect::<Vec<_>>());
269                anyhow::ensure!(
270                    outcome.refused.is_empty() && outcome.incomplete.is_empty(),
271                    "Checkpoint cleanup is incomplete: {outcome:?}"
272                );
273                fs::remove_file(path)?;
274            }
275            filesnap::collect_garbage(&storage)?;
276            Ok(())
277        })
278        .await;
279        if !matches!(&result, Ok(Ok(()))) {
280            tracing::warn!(?result, "Checkpoint content cleanup deferred; retired records remain retryable");
281        }
282    }
283
284    fn retention_cutoff_secs(&self) -> Result<Option<u64>> {
285        let Some(days) = self.max_age_days else {
286            return Ok(None);
287        };
288
289        let now = Self::current_timestamp()?;
290        if days == 0 {
291            return Ok(Some(now));
292        }
293
294        let seconds = days.saturating_mul(SECONDS_PER_DAY);
295        let cutoff_instant = SystemTime::now()
296            .checked_sub(Duration::from_secs(seconds))
297            .unwrap_or(SystemTime::UNIX_EPOCH);
298        let cutoff = cutoff_instant
299            .duration_since(UNIX_EPOCH)
300            .context("system clock before UNIX_EPOCH")?
301            .as_secs();
302        Ok(Some(cutoff))
303    }
304}