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    let root_metadata = match std::fs::symlink_metadata(&root) {
55        Ok(metadata) => metadata,
56        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
57        Err(error) => return Err(SessionStoreError::io(root.clone(), error)),
58    };
59    if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() {
60        return Ok(0);
61    }
62    // Crashed/killed threads never emit thread.completed; surface those
63    // abandoned `active` stores as completed so the eviction phases can
64    // reclaim them. Live sessions stay `active` and remain unpinned.
65    mark_abandoned_active_sessions(workspace, policy.max_age_days, preserve_session_id)?;
66    let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
67    let mut sessions = retention_candidates(&root, preserve_path.as_deref())?;
68    let mut removed = 0usize;
69
70    // Phase 1: evict oldest sessions beyond the count cap.
71    if sessions.len() > policy.max_sessions {
72        sessions.sort_by(|a, b| a.summary.updated_at.cmp(&b.summary.updated_at));
73        let to_remove = sessions.len() - policy.max_sessions;
74        for s in sessions.iter().take(to_remove) {
75            remove_session(&root, &s.path)?;
76            removed += 1;
77        }
78        // Drop evicted entries so phase 2 doesn't double-remove.
79        sessions.drain(..to_remove);
80    }
81
82    // Phase 2: evict sessions older than max_age_days (regardless of count).
83    let cutoff = age_cutoff(policy.max_age_days);
84    for s in &sessions {
85        if older_than(s.summary.updated_at.as_str(), cutoff) {
86            remove_session(&root, &s.path)?;
87            removed += 1;
88        }
89    }
90
91    Ok(removed)
92}
93
94/// Sidecar marker written when a session must outlive ordinary retention
95/// because an unresolved blocker archive references it.
96pub const RETENTION_PIN_FILE: &str = "retention-pin.json";
97
98/// Whether a session directory is pinned against ordinary retention eviction.
99#[must_use]
100pub fn session_retention_pinned(session_dir: &Path) -> bool {
101    session_dir.join(RETENTION_PIN_FILE).is_file()
102}
103
104/// Whether a live process still holds the session's event-log handles open.
105///
106/// `session.lock` is flock-held for as long as any event-log handle to the
107/// session exists (see `event_log::acquire_liveness_lock`). `WouldBlock`
108/// proves a live holder; a missing lock file (older or crashed sessions) or
109/// an acquirable lock means nothing alive keeps the session open. Unreadable
110/// lock files count as live: deletion paths must not evict what they cannot
111/// inspect.
112pub(crate) fn session_dir_is_live(session_dir: &Path) -> bool {
113    use crate::event_log::SESSION_LOCK_FILE;
114
115    let lock_path = session_dir.join(SESSION_LOCK_FILE);
116    let file = match std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) {
117        Ok(file) => file,
118        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return false,
119        Err(_) => return true,
120    };
121    file.try_lock()
122        .map_err(std::io::Error::from)
123        .is_err_and(|error| error.kind() == std::io::ErrorKind::WouldBlock)
124}
125
126/// Session ids whose stores are retention-pinned against ordinary eviction.
127///
128/// Companion to [`session_retention_pinned`]: a blocked session pins its store
129/// so ordinary retention cannot erase its evidence. Callers pruning other
130/// session-derived data (e.g. legacy history envelopes) must exclude these ids
131/// or they would erase through a different path what the pin protects.
132#[must_use]
133pub fn retention_pinned_session_ids(workspace: &Path) -> Vec<String> {
134    let Ok(entries) = std::fs::read_dir(sessions_root(workspace)) else {
135        return Vec::new();
136    };
137    entries
138        .flatten()
139        .filter(|entry| entry.file_type().map(|file_type| file_type.is_dir()).unwrap_or(false))
140        .filter(|entry| session_retention_pinned(&entry.path()))
141        .filter_map(|entry| entry.file_name().into_string().ok())
142        .collect()
143}
144
145/// Write a retention pin for a session (best-effort path check by caller).
146pub fn pin_session_retention(session_dir: &Path, reason: &str) -> Result<(), SessionStoreError> {
147    let path = session_dir.join(RETENTION_PIN_FILE);
148    let body = serde_json::json!({
149        "reason": reason,
150        "pinned_at": chrono::Utc::now().to_rfc3339(),
151    });
152    std::fs::write(&path, body.to_string()).map_err(|e| SessionStoreError::io(path, e))
153}
154
155/// Remove a retention pin if present.
156pub fn unpin_session_retention(session_dir: &Path) -> Result<bool, SessionStoreError> {
157    let path = session_dir.join(RETENTION_PIN_FILE);
158    if !path.is_file() {
159        return Ok(false);
160    }
161    std::fs::remove_file(&path).map_err(|e| SessionStoreError::io(path, e))?;
162    Ok(true)
163}
164
165/// Enumerate session stores from their filesystem entries, never from the
166/// session ID contained in a manifest. This keeps retention confined to
167/// validated direct children of the sessions root.
168fn retention_candidates(
169    root: &Path,
170    preserve_path: Option<&Path>,
171) -> Result<Vec<RetentionCandidate>, SessionStoreError> {
172    let entries = std::fs::read_dir(root).map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
173    let mut candidates = Vec::new();
174    for entry in entries {
175        let entry = entry.map_err(|e| SessionStoreError::io(root.to_path_buf(), e))?;
176        let file_type = entry.file_type().map_err(|e| SessionStoreError::io(entry.path(), e))?;
177        if !file_type.is_dir() || file_type.is_symlink() {
178            continue;
179        }
180        let path = entry.path();
181        if preserve_path.is_some_and(|preserve_path| preserve_path == path) {
182            continue;
183        }
184        // Unresolved blocker forensics must survive count/age eviction.
185        if session_retention_pinned(&path) {
186            continue;
187        }
188        // A session still open in a live process must not be evicted even
189        // when its manifest says completed: the user may resume or keep
190        // reading it.
191        if session_dir_is_live(&path) {
192            continue;
193        }
194        let manifest_path = path.join("manifest.json");
195        let Ok(bytes) = std::fs::read(&manifest_path) else {
196            continue;
197        };
198        let Ok(summary) = serde_json::from_slice::<SessionSummary>(&bytes) else {
199            continue;
200        };
201        if summary.status == "active" {
202            continue;
203        }
204        candidates.push(RetentionCandidate { path, summary });
205    }
206    Ok(candidates)
207}
208
209/// Flip `active` manifests that have been idle past `max_age_days` to
210/// `completed` so ordinary retention can evict them.
211///
212/// A crashed or killed thread never emits `thread.completed`, so its manifest
213/// stays `active` forever and would otherwise pin the store. Live sessions are
214/// younger than the cutoff and are left untouched. `max_age_days == 0` disables
215/// the sweep (the hard "never evict active" contract used by force-evict tests).
216/// Returns how many manifests were marked abandoned.
217pub fn mark_abandoned_active_sessions(
218    workspace: &Path,
219    max_age_days: u64,
220    preserve_session_id: Option<&str>,
221) -> Result<usize, SessionStoreError> {
222    if max_age_days == 0 {
223        return Ok(0);
224    }
225    let root = sessions_root(workspace);
226    let preserve_path = preserve_session_id.map(|session_id| crate::session_dir(workspace, session_id));
227    let Ok(entries) = std::fs::read_dir(&root) else {
228        return Ok(0);
229    };
230    let cutoff = age_cutoff(max_age_days);
231    let mut marked = 0usize;
232    for entry in entries.flatten() {
233        let path = entry.path();
234        let file_type = match entry.file_type() {
235            Ok(file_type) => file_type,
236            Err(_) => continue,
237        };
238        // Same symlink-safe enumeration as `retention_candidates`: never
239        // rewrite a manifest through a planted symlink.
240        if !file_type.is_dir() || file_type.is_symlink() {
241            continue;
242        }
243        if preserve_path.as_deref() == Some(path.as_path()) {
244            continue;
245        }
246        if session_retention_pinned(&path) {
247            continue;
248        }
249        // A live process still holds this session open (open-but-idle):
250        // marking it completed would let phase-2 evict a session the user
251        // may still resume.
252        if session_dir_is_live(&path) {
253            continue;
254        }
255        let manifest_path = path.join("manifest.json");
256        let Ok(bytes) = std::fs::read(&manifest_path) else {
257            continue;
258        };
259        let Ok(mut summary) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
260            continue;
261        };
262        let is_active = summary.get("status").and_then(serde_json::Value::as_str) == Some("active");
263        if !is_active {
264            continue;
265        }
266        let updated_at = summary
267            .get("updated_at")
268            .and_then(serde_json::Value::as_str)
269            .unwrap_or_default();
270        if !older_than(updated_at, cutoff) {
271            continue;
272        }
273        if let Some(object) = summary.as_object_mut() {
274            object.insert("status".to_string(), serde_json::Value::String("completed".to_string()));
275        } else {
276            continue;
277        }
278        let body = serde_json::to_vec_pretty(&summary)
279            .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
280        // Same primitive as ManifestStore: 0600 private temp + fsync + rename,
281        // so a crash cannot leave a truncated manifest, the rewritten manifest
282        // keeps session-file permissions, and a planted symlink cannot be
283        // followed to an outside destination.
284        vtcode_commons::VtCodePaths::write_private_file_atomic(&manifest_path, &body)
285            .map_err(|error| SessionStoreError::io(manifest_path.clone(), std::io::Error::other(error)))?;
286        marked += 1;
287    }
288    Ok(marked)
289}
290
291/// Remove the legacy `history/` and `logs/` directories after they have been
292/// imported into the unified store by [`crate::migrate_legacy`].
293///
294/// Returns the number of bytes freed. The legacy `checkpoints/` directory is
295/// intentionally left in place until `/revert` is rewired to the unified
296/// store; callers should confirm revert behavior before deleting it manually.
297pub fn gc_legacy(workspace: &Path) -> Result<u64, SessionStoreError> {
298    let vt = workspace.join(".vtcode");
299    let mut freed = 0u64;
300    for name in ["history", "logs"] {
301        let dir = vt.join(name);
302        if dir.exists() {
303            freed += dir_size(&dir);
304            std::fs::remove_dir_all(&dir).map_err(|e| SessionStoreError::io(dir.clone(), e))?;
305        }
306    }
307    Ok(freed)
308}
309
310fn remove_session(root: &Path, dir: &Path) -> Result<(), SessionStoreError> {
311    // Retention is allowed to remove only one validated child of the sessions
312    // root. Never trust a manifest-controlled identifier or follow a symlink.
313    if dir.parent() != Some(root) {
314        return Ok(());
315    }
316    let metadata = match std::fs::symlink_metadata(dir) {
317        Ok(metadata) => metadata,
318        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
319        Err(error) => return Err(SessionStoreError::io(dir.to_path_buf(), error)),
320    };
321    if metadata.file_type().is_symlink() || !metadata.is_dir() {
322        return Ok(());
323    }
324    std::fs::remove_dir_all(dir).map_err(|e| SessionStoreError::io(dir.to_path_buf(), e))?;
325    Ok(())
326}
327
328fn dir_size(dir: &Path) -> u64 {
329    WalkDir::new(dir)
330        .into_iter()
331        .filter_map(Result::ok)
332        .filter(|e| e.file_type().is_file())
333        .filter_map(|e| e.metadata().ok())
334        .map(|m| m.len())
335        .sum()
336}
337
338fn age_cutoff(max_age_days: u64) -> SystemTime {
339    let seconds = max_age_days.saturating_mul(24 * 3600);
340    SystemTime::now() - Duration::from_secs(seconds)
341}
342
343fn older_than(rfc3339: &str, cutoff: SystemTime) -> bool {
344    let Ok(dt) = chrono::DateTime::parse_from_rfc3339(rfc3339) else {
345        return false;
346    };
347    let cutoff_secs = cutoff
348        .duration_since(UNIX_EPOCH)
349        .map(|d| d.as_secs() as i64)
350        .unwrap_or(i64::MAX);
351    dt.timestamp() < cutoff_secs
352}