Skip to main content

vtcode_memory/
retention.rs

1//! Retention and garbage-collection for the unified session store.
2
3use std::path::Path;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use walkdir::WalkDir;
7
8use crate::error::SessionStoreError;
9use crate::query::SessionSummary;
10use crate::sessions_root;
11
12#[derive(Debug)]
13struct RetentionCandidate {
14    path: std::path::PathBuf,
15    summary: SessionSummary,
16}
17
18/// Retention policy applied to the set of per-session stores.
19#[derive(Debug, Clone, Copy)]
20pub struct RetentionPolicy {
21    /// Maximum number of sessions to keep (oldest evicted first).
22    pub max_sessions: usize,
23    /// Maximum age of a session in days before eviction.
24    pub max_age_days: u64,
25}
26
27impl Default for RetentionPolicy {
28    fn default() -> Self {
29        Self { max_sessions: 50, max_age_days: 30 }
30    }
31}
32
33/// Apply the retention policy, removing the oldest / stale sessions.
34///
35/// Returns the number of sessions removed. This bounds the otherwise
36/// unbounded growth of `.vtcode/sessions/` so overhead does not accumulate
37/// on disk across a long-lived agent.
38pub fn apply_retention(workspace: &Path, policy: RetentionPolicy) -> Result<usize, SessionStoreError> {
39    apply_retention_preserving(workspace, policy, None)
40}
41
42/// Apply retention while preserving one session directory, even when its
43/// existing manifest still says `completed` (for example, a resumed session).
44///
45/// The preserved path is resolved with the same session-id sanitization as the
46/// canonical store and is compared against the direct child discovered on
47/// disk. It is never taken from a manifest.
48pub fn apply_retention_preserving(
49    workspace: &Path,
50    policy: RetentionPolicy,
51    preserve_session_id: Option<&str>,
52) -> Result<usize, SessionStoreError> {
53    let root = sessions_root(workspace);
54    if !is_sessions_root(&root)? {
55        return Ok(0);
56    }
57    // Crashed/killed threads never emit thread.completed; surface those
58    // abandoned `active` stores as completed so the eviction phases can
59    // reclaim them. Live sessions stay `active` and remain unpinned.
60    mark_abandoned_active_sessions(workspace, policy.max_age_days, preserve_session_id)?;
61    let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
62    let sessions = retention_candidates(&root, preserve_path.as_deref())?;
63    let mut removed = 0usize;
64
65    // Phase 0: drop empty completed shells immediately. A 0-turn store is only
66    // `thread.started` + `thread.completed` noise; it never held work the user
67    // can resume. Age/count caps would otherwise keep these around for weeks.
68    let (empty, mut sessions): (Vec<_>, Vec<_>) = sessions
69        .into_iter()
70        .partition(|s| s.summary.turn_count == 0 && s.summary.status != "active");
71    for s in &empty {
72        removed += usize::from(remove_candidate(workspace, &root, s)?);
73    }
74
75    // Phase 1: evict oldest sessions beyond the count cap.
76    if sessions.len() > policy.max_sessions {
77        sessions.sort_by(|a, b| a.summary.updated_at.cmp(&b.summary.updated_at));
78        let to_remove = sessions.len() - policy.max_sessions;
79        for s in sessions.iter().take(to_remove) {
80            removed += usize::from(remove_candidate(workspace, &root, s)?);
81        }
82        // Drop evicted entries so phase 2 doesn't double-remove.
83        sessions.drain(..to_remove);
84    }
85
86    // Phase 2: evict sessions older than max_age_days (regardless of count).
87    let cutoff = age_cutoff(policy.max_age_days);
88    for s in &sessions {
89        if older_than(s.summary.updated_at.as_str(), cutoff) {
90            removed += usize::from(remove_candidate(workspace, &root, s)?);
91        }
92    }
93
94    Ok(removed)
95}
96
97/// Sidecar marker written when a session must outlive ordinary retention
98/// because an unresolved blocker archive references it.
99pub const RETENTION_PIN_FILE: &str = "retention-pin.json";
100
101/// Delete a 0-turn completed session store immediately (close-path hygiene).
102///
103/// Empty shells (`thread.started` + `thread.completed` only) never held work
104/// the user can resume; keeping them pollutes `.vtcode/sessions/` and hides
105/// real sessions. No-op when the store has turns, is still active, is pinned,
106/// is live in another process, or the id is not a validated direct child.
107/// Returns whether the store was removed.
108pub fn evict_zero_turn_completed_store(workspace: &Path, session_id: &str) -> Result<bool, SessionStoreError> {
109    let root = sessions_root(workspace);
110    if !is_sessions_root(&root)? {
111        return Ok(false);
112    }
113    let dir = crate::session_dir(workspace, session_id);
114    if dir.parent() != Some(&root) {
115        return Ok(false);
116    }
117    let Some(name) = dir.file_name() else { return Ok(false) };
118    let Some(_guard) = crate::session_guard::try_exclusive(workspace, name)? else {
119        return Ok(false);
120    };
121    if session_retention_pinned(&dir) || session_dir_may_be_live(&dir) {
122        return Ok(false);
123    }
124    let manifest_path = dir.join("manifest.json");
125    let Ok(bytes) = std::fs::read(&manifest_path) else {
126        return Ok(false);
127    };
128    let Ok(summary) = serde_json::from_slice::<SessionSummary>(&bytes) else {
129        return Ok(false);
130    };
131    if summary.turn_count > 0 || summary.status == "active" {
132        return Ok(false);
133    }
134    remove_session(&root, &dir)?;
135    Ok(true)
136}
137
138/// Whether a session is pinned or its pin marker cannot be safely inspected.
139#[must_use]
140pub fn session_retention_pinned(session_dir: &Path) -> bool {
141    match std::fs::symlink_metadata(session_dir.join(RETENTION_PIN_FILE)) {
142        Ok(_) => true,
143        Err(error) => error.kind() != std::io::ErrorKind::NotFound,
144    }
145}
146
147/// Whether a live process still holds the session's event-log handles open.
148///
149/// `session.lock` is flock-held for as long as any event-log handle to the
150/// session exists (see `event_log::acquire_liveness_lock`). `WouldBlock`
151/// proves a live holder; a missing lock file (older or crashed sessions) or
152/// an acquirable lock means nothing alive keeps the session open. Invalid or
153/// unreadable lock files do not establish liveness.
154pub(crate) fn session_dir_is_live(session_dir: &Path) -> bool {
155    matches!(session_lock_state(session_dir), SessionLockState::Live)
156}
157
158fn session_dir_may_be_live(session_dir: &Path) -> bool {
159    !matches!(session_lock_state(session_dir), SessionLockState::Inactive)
160}
161
162enum SessionLockState {
163    Live,
164    Inactive,
165    Unknown,
166}
167
168fn session_lock_state(session_dir: &Path) -> SessionLockState {
169    use crate::event_log::SESSION_LOCK_FILE;
170
171    let lock_path = session_dir.join(SESSION_LOCK_FILE);
172    match std::fs::symlink_metadata(&lock_path) {
173        Ok(metadata) if metadata.file_type().is_file() => {}
174        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return SessionLockState::Inactive,
175        _ => return SessionLockState::Unknown,
176    }
177    let file = match std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) {
178        Ok(file) => file,
179        Err(_) => return SessionLockState::Unknown,
180    };
181    match file.try_lock().map_err(std::io::Error::from) {
182        Ok(()) => SessionLockState::Inactive,
183        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => SessionLockState::Live,
184        Err(_) => SessionLockState::Unknown,
185    }
186}
187
188/// Session ids whose stores are retention-pinned against ordinary eviction.
189///
190/// Companion to [`session_retention_pinned`]: a blocked session pins its store
191/// so ordinary retention cannot erase its evidence. Callers pruning other
192/// session-derived data (e.g. legacy history envelopes) must exclude these ids
193/// or they would erase through a different path what the pin protects.
194#[must_use]
195pub fn retention_pinned_session_ids(workspace: &Path) -> Vec<String> {
196    let Ok(entries) = std::fs::read_dir(sessions_root(workspace)) else {
197        return Vec::new();
198    };
199    entries
200        .flatten()
201        .filter(|entry| entry.file_type().map(|file_type| file_type.is_dir()).unwrap_or(false))
202        .filter(|entry| session_retention_pinned(&entry.path()))
203        .filter_map(|entry| entry.file_name().into_string().ok())
204        .collect()
205}
206
207/// Atomically write a private retention pin for an existing session directory.
208pub fn pin_session_retention(session_dir: &Path, reason: &str) -> Result<(), SessionStoreError> {
209    let _guard = crate::session_guard::shared_for_session_dir(session_dir)?;
210    let path = session_dir.join(RETENTION_PIN_FILE);
211    let metadata = std::fs::symlink_metadata(session_dir).map_err(|error| SessionStoreError::io(session_dir, error))?;
212    if !metadata.is_dir() || metadata.file_type().is_symlink() {
213        return Err(SessionStoreError::io(session_dir, std::io::Error::other("session is not a directory")));
214    }
215    let body = serde_json::json!({
216        "reason": reason,
217        "pinned_at": chrono::Utc::now().to_rfc3339(),
218    });
219    vtcode_commons::VtCodePaths::write_private_file_atomic(&path, body.to_string().as_bytes())
220        .map_err(|error| SessionStoreError::io(path, std::io::Error::other(error)))
221}
222
223/// Remove a retention pin if present.
224pub fn unpin_session_retention(session_dir: &Path) -> Result<bool, SessionStoreError> {
225    let _guard = crate::session_guard::shared_for_session_dir(session_dir)?;
226    let path = session_dir.join(RETENTION_PIN_FILE);
227    if !path.is_file() {
228        return Ok(false);
229    }
230    std::fs::remove_file(&path).map_err(|e| SessionStoreError::io(path, e))?;
231    Ok(true)
232}
233
234/// Enumerate session stores from their filesystem entries, never from the
235/// session ID contained in a manifest. This keeps retention confined to
236/// validated direct children of the sessions root.
237fn retention_candidates(
238    root: &Path,
239    preserve_path: Option<&Path>,
240) -> Result<Vec<RetentionCandidate>, SessionStoreError> {
241    let entries = std::fs::read_dir(root).map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
242    let mut candidates = Vec::new();
243    for entry in entries {
244        let entry = entry.map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
245        let file_type = entry.file_type().map_err(|e| SessionStoreError::io(entry.path(), e))?;
246        if !file_type.is_dir() || file_type.is_symlink() {
247            continue;
248        }
249        let path = entry.path();
250        if preserve_path.is_some_and(|preserve_path| preserve_path == path) {
251            continue;
252        }
253        // Unresolved blocker forensics must survive count/age eviction.
254        if session_retention_pinned(&path) {
255            continue;
256        }
257        // A session still open in a live process must not be evicted even
258        // when its manifest says completed: the user may resume or keep
259        // reading it.
260        if session_dir_may_be_live(&path) {
261            continue;
262        }
263        let manifest_path = path.join("manifest.json");
264        let Ok(bytes) = std::fs::read(&manifest_path) else {
265            continue;
266        };
267        let Ok(summary) = serde_json::from_slice::<SessionSummary>(&bytes) else {
268            continue;
269        };
270        if summary.status == "active" {
271            continue;
272        }
273        candidates.push(RetentionCandidate { path, summary });
274    }
275    Ok(candidates)
276}
277
278/// Flip `active` manifests that have been idle past `max_age_days` to
279/// `completed` so ordinary retention can evict them.
280///
281/// A crashed or killed thread never emits `thread.completed`, so its manifest
282/// stays `active` forever and would otherwise pin the store. Live sessions are
283/// younger than the cutoff and are left untouched. `max_age_days == 0` disables
284/// the sweep (the hard "never evict active" contract used by force-evict tests).
285/// Returns how many manifests were marked abandoned.
286pub fn mark_abandoned_active_sessions(
287    workspace: &Path,
288    max_age_days: u64,
289    preserve_session_id: Option<&str>,
290) -> Result<usize, SessionStoreError> {
291    if max_age_days == 0 {
292        return Ok(0);
293    }
294    let root = sessions_root(workspace);
295    if !is_sessions_root(&root)? {
296        return Ok(0);
297    }
298    let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
299    let Ok(entries) = std::fs::read_dir(&root) else {
300        return Ok(0);
301    };
302    let cutoff = age_cutoff(max_age_days);
303    let mut marked = 0usize;
304    for entry in entries.flatten() {
305        let path = entry.path();
306        let file_type = match entry.file_type() {
307            Ok(file_type) => file_type,
308            Err(_) => continue,
309        };
310        // Same symlink-safe enumeration as `retention_candidates`: never
311        // rewrite a manifest through a planted symlink.
312        if !file_type.is_dir() || file_type.is_symlink() {
313            continue;
314        }
315        if preserve_path.as_deref() == Some(path.as_path()) {
316            continue;
317        }
318        let Some(name) = path.file_name() else { continue };
319        let Some(_guard) = crate::session_guard::try_exclusive(workspace, name)? else {
320            continue;
321        };
322        if session_retention_pinned(&path) {
323            continue;
324        }
325        // A live process still holds this session open (open-but-idle):
326        // marking it completed would let phase-2 evict a session the user
327        // may still resume.
328        if session_dir_may_be_live(&path) {
329            continue;
330        }
331        let manifest_path = path.join("manifest.json");
332        let Ok(bytes) = std::fs::read(&manifest_path) else {
333            continue;
334        };
335        let Ok(mut summary) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
336            continue;
337        };
338        let is_active = summary.get("status").and_then(serde_json::Value::as_str) == Some("active");
339        if !is_active {
340            continue;
341        }
342        let updated_at = summary
343            .get("updated_at")
344            .and_then(serde_json::Value::as_str)
345            .unwrap_or_default();
346        if !older_than(updated_at, cutoff) {
347            continue;
348        }
349        if let Some(object) = summary.as_object_mut() {
350            object.insert("status".to_string(), serde_json::Value::String("completed".to_string()));
351        } else {
352            continue;
353        }
354        let body = serde_json::to_vec_pretty(&summary)
355            .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
356        // Same primitive as ManifestStore: 0600 private temp + fsync + rename,
357        // so a crash cannot leave a truncated manifest, the rewritten manifest
358        // keeps session-file permissions, and a planted symlink cannot be
359        // followed to an outside destination.
360        vtcode_commons::VtCodePaths::write_private_file_atomic(&manifest_path, &body)
361            .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
362        marked += 1;
363    }
364    Ok(marked)
365}
366
367/// Remove the legacy `history/` and `logs/` directories after they have been
368/// imported into the unified store by [`crate::migrate_legacy`].
369///
370/// Returns the number of bytes freed. The legacy `checkpoints/` directory is
371/// intentionally left in place until `/revert` is rewired to the unified
372/// store; callers should confirm revert behavior before deleting it manually.
373///
374/// Deprecated: this removes whole directories, including files migration never
375/// imports (unrelated, nested, and symlinked entries). Re-run
376/// [`crate::migrate_legacy`] with `remove_legacy = true` instead: retries reuse
377/// exact imports and remove only verified sources.
378#[deprecated(note = "removes files migration never imports; re-run `migrate_legacy(workspace, true)` instead")]
379pub fn gc_legacy(workspace: &Path) -> Result<u64, SessionStoreError> {
380    let vt = workspace.join(".vtcode");
381    let mut freed = 0u64;
382    for name in ["history", "logs"] {
383        let dir = vt.join(name);
384        if dir.exists() {
385            freed += dir_size(&dir);
386            std::fs::remove_dir_all(&dir).map_err(|e| SessionStoreError::io(dir.clone(), e))?;
387        }
388    }
389    Ok(freed)
390}
391
392fn is_sessions_root(root: &Path) -> Result<bool, SessionStoreError> {
393    match std::fs::symlink_metadata(root) {
394        Ok(metadata) => Ok(!metadata.file_type().is_symlink() && metadata.is_dir()),
395        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
396        Err(error) => Err(SessionStoreError::io(root.to_path_buf(), error)),
397    }
398}
399
400fn remove_candidate(workspace: &Path, root: &Path, candidate: &RetentionCandidate) -> Result<bool, SessionStoreError> {
401    let Some(name) = candidate.path.file_name() else {
402        return Ok(false);
403    };
404    let Some(_guard) = crate::session_guard::try_exclusive(workspace, name)? else {
405        return Ok(false);
406    };
407    if session_retention_pinned(&candidate.path) || session_dir_may_be_live(&candidate.path) {
408        return Ok(false);
409    }
410    let Ok(bytes) = std::fs::read(candidate.path.join("manifest.json")) else {
411        return Ok(false);
412    };
413    if serde_json::from_slice::<SessionSummary>(&bytes).ok().as_ref() != Some(&candidate.summary) {
414        return Ok(false);
415    }
416    remove_session(root, &candidate.path)?;
417    Ok(true)
418}
419
420fn remove_session(root: &Path, dir: &Path) -> Result<(), SessionStoreError> {
421    // Retention is allowed to remove only one validated child of the sessions
422    // root. Never trust a manifest-controlled identifier or follow a symlink.
423    if dir.parent() != Some(root) {
424        return Ok(());
425    }
426    let metadata = match std::fs::symlink_metadata(dir) {
427        Ok(metadata) => metadata,
428        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
429        Err(error) => return Err(SessionStoreError::io(dir.to_path_buf(), error)),
430    };
431    if metadata.file_type().is_symlink() || !metadata.is_dir() {
432        return Ok(());
433    }
434    std::fs::remove_dir_all(dir).map_err(|e| SessionStoreError::io(dir.to_path_buf(), e))?;
435    Ok(())
436}
437
438fn dir_size(dir: &Path) -> u64 {
439    WalkDir::new(dir)
440        .into_iter()
441        .filter_map(Result::ok)
442        .filter(|e| e.file_type().is_file())
443        .filter_map(|e| e.metadata().ok())
444        .map(|m| m.len())
445        .sum()
446}
447
448fn age_cutoff(max_age_days: u64) -> SystemTime {
449    let seconds = max_age_days.saturating_mul(24 * 3600);
450    SystemTime::now() - Duration::from_secs(seconds)
451}
452
453fn older_than(rfc3339: &str, cutoff: SystemTime) -> bool {
454    let Ok(dt) = chrono::DateTime::parse_from_rfc3339(rfc3339) else {
455        return false;
456    };
457    let cutoff_secs = cutoff
458        .duration_since(UNIX_EPOCH)
459        .map(|d| d.as_secs() as i64)
460        .unwrap_or(i64::MAX);
461    dt.timestamp() < cutoff_secs
462}
463
464#[cfg(test)]
465mod candidate_tests {
466    use super::*;
467
468    #[test]
469    fn stale_candidate_is_rechecked_before_removal() {
470        let workspace = tempfile::tempdir().expect("workspace");
471        let root = sessions_root(workspace.path());
472        let dir = root.join("candidate");
473        std::fs::create_dir_all(&dir).expect("session dir");
474        let manifest = dir.join("manifest.json");
475        let mut summary = SessionSummary {
476            session_id: "candidate".to_string(),
477            turn_count: 1,
478            event_count: 2,
479            status: "completed".to_string(),
480            updated_at: "2020-01-01T00:00:00Z".to_string(),
481        };
482        std::fs::write(&manifest, serde_json::to_vec(&summary).expect("serialize")).expect("manifest");
483        let candidates = retention_candidates(&root, None).expect("candidates");
484        assert_eq!(candidates.len(), 1);
485        summary.turn_count = 2;
486        std::fs::write(&manifest, serde_json::to_vec(&summary).expect("serialize")).expect("update manifest");
487        assert!(!remove_candidate(workspace.path(), &root, &candidates[0]).expect("recheck"));
488        assert!(manifest.exists());
489    }
490}