Skip to main content

artifactize_core/agent/session/
gc.rs

1//! Size-bounded collection of the session store, with hysteresis: once the conversations
2//! exceed `maxBytes`, the oldest (by last write) are deleted until they take `targetBytes` or
3//! less. A session whose request is still RUNNING, or that a send holds, is never deleted.
4
5use std::{collections::BTreeSet, fs::File, path::Path, time::SystemTime};
6
7use rusqlite::OpenFlags;
8use serde::Serialize;
9
10use super::directory;
11use crate::{limits::AgentSessions, store::DATABASE, types::SessionId};
12
13/// What one collection found and did.
14#[derive(Debug, Default, Clone, Serialize)]
15#[serde(rename_all = "camelCase")]
16pub struct Collection {
17    /// The session store's size before the collection.
18    pub bytes: u64,
19    /// Its size after it, or with a dry run, after the deletions it reports.
20    pub remaining: u64,
21    /// The sessions deleted, or with a dry run those that would be, oldest first.
22    pub removed: Vec<SessionId>,
23}
24
25/// The session store's size.
26#[derive(Debug, Default, Clone, Copy, Serialize)]
27pub struct Usage {
28    pub sessions: usize,
29    pub bytes: u64,
30}
31
32struct Entry {
33    id: SessionId,
34    bytes: u64,
35    written: SystemTime,
36}
37
38/// The saved conversations, read without following links; a missing store is empty.
39fn entries(state: &Path) -> Result<Vec<Entry>, String> {
40    let directory = directory(state);
41    let handle = match crate::platform::open_no_follow(File::options().read(true), &directory) {
42        Ok(handle) => handle,
43        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
44        Err(error) => {
45            return Err(format!(
46                "{}: {error}",
47                crate::platform::path_text(&directory)
48            ));
49        }
50    };
51    let listing = crate::platform::read_dir(&handle).map_err(|e| e.to_string())?;
52    let mut entries = Vec::new();
53    for entry in listing {
54        let entry = entry.map_err(|e| e.to_string())?;
55        let name = entry.file_name();
56        let Some(id) = crate::platform::os_text(&name).and_then(|name| name.strip_suffix(".jsonl"))
57        else {
58            continue;
59        };
60        let Ok(id) = id.parse::<SessionId>() else {
61            // Not a session path; never collect arbitrary files in this directory.
62            continue;
63        };
64        if crate::platform::entry_kind(&handle, &name).map_err(|e| e.to_string())?
65            != crate::platform::FileKind::File
66        {
67            continue;
68        }
69        let name = crate::platform::EntryName::new(&name).ok_or("Invalid session entry name.")?;
70        let file = crate::platform::open_entry(&handle, &name).map_err(|e| e.to_string())?;
71        let metadata = file.metadata().map_err(|e| e.to_string())?;
72        if !metadata.is_file() {
73            continue;
74        }
75        let written = metadata.modified().map_err(|e| e.to_string())?;
76        // Tests replace only ordering metadata; file validation and collection stay real.
77        #[cfg(test)]
78        let written = tests::written(state, &id).unwrap_or(written);
79        entries.push(Entry {
80            id,
81            bytes: metadata.len(),
82            written,
83        });
84    }
85    Ok(entries)
86}
87
88/// Pure ordering shared by collection and the explicit-time contract test.
89fn order(entries: &mut [Entry]) {
90    entries.sort_by(|a, b| a.written.cmp(&b.written).then_with(|| a.id.cmp(&b.id)));
91}
92
93/// How many conversations the store holds and their bytes.
94pub fn usage(state: &Path) -> Result<Usage, String> {
95    let entries = entries(state)?;
96    Ok(Usage {
97        sessions: entries.len(),
98        bytes: entries.iter().map(|entry| entry.bytes).sum(),
99    })
100}
101
102/// The sessions of requests that are still RUNNING, read without a writer lock.
103fn running(state: &Path) -> Result<BTreeSet<SessionId>, String> {
104    crate::store::check_probe_files(state)?;
105    let database = state.join(DATABASE);
106    if !database.try_exists().map_err(|e| e.to_string())? {
107        return Ok(BTreeSet::new());
108    }
109    let read = || -> Result<BTreeSet<SessionId>, rusqlite::Error> {
110        let db =
111            rusqlite::Connection::open_with_flags(&database, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
112        crate::store::wait_when_busy(&db)?;
113        let initialized: bool = db.query_row(
114            "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='requests')",
115            [],
116            |row| row.get(0),
117        )?;
118        if !initialized {
119            return Ok(BTreeSet::new());
120        }
121        let mut statement = db.prepare(
122            "SELECT json_extract(data,'$.sessionId') FROM requests WHERE status='RUNNING' AND json_extract(data,'$.sessionId') IS NOT NULL",
123        )?;
124        statement
125            .query_map([], |row| row.get::<_, SessionId>(0))?
126            .collect()
127    };
128    read().map_err(|e| format!("Cannot read running Agent reviews: {e}"))
129}
130
131/// Collect the store under `bounds` (see the module). The sessions that are listed first and
132/// then found RUNNING were saved after their request turned RUNNING, so a review that starts
133/// during a collection is either seen as running or not listed at all.
134pub fn collect(state: &Path, bounds: AgentSessions, dry_run: bool) -> Result<Collection, String> {
135    let publisher = if dry_run {
136        crate::changes::Publisher::default()
137    } else {
138        crate::changes::Publisher::new(state)
139    };
140    let mut entries = entries(state)?;
141    let bytes = entries.iter().map(|entry| entry.bytes).sum();
142    let mut collection = Collection {
143        bytes,
144        remaining: bytes,
145        removed: Vec::new(),
146    };
147    if bytes <= bounds.max_bytes() {
148        return Ok(collection);
149    }
150    let running = running(state)?;
151    order(&mut entries);
152    let directory = directory(state);
153    for entry in entries {
154        if collection.remaining <= bounds.target_bytes() {
155            break;
156        }
157        if running.contains(&entry.id) {
158            continue;
159        }
160        if !dry_run {
161            let lock = directory.join(format!("{}.lock", entry.id));
162            // A session a send holds stays; its lock goes with it.
163            let held = match crate::platform::open_no_follow(
164                File::options().read(true).write(true),
165                &lock,
166            ) {
167                Ok(file) => match crate::platform::paths::try_lock(&file) {
168                    Ok(()) => Some(file),
169                    Err(std::fs::TryLockError::WouldBlock) => continue,
170                    Err(std::fs::TryLockError::Error(error)) => return Err(error.to_string()),
171                },
172                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
173                Err(error) => return Err(error.to_string()),
174            };
175            match crate::platform::paths::remove_open_file(
176                &directory.join(format!("{}.jsonl", entry.id)),
177            ) {
178                Ok(()) => {
179                    publisher.notify(crate::changes::Change::SessionInvalidated(entry.id.clone()))
180                }
181                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
182                Err(error) => {
183                    return Err(format!("Cannot remove Agent session {}: {error}", entry.id));
184                }
185            }
186            if held.is_some() {
187                let _ = crate::platform::paths::remove_open_file(&lock);
188            }
189        }
190        collection.remaining = collection.remaining.saturating_sub(entry.bytes);
191        collection.removed.push(entry.id);
192    }
193    Ok(collection)
194}
195
196#[cfg(test)]
197mod tests {
198    use std::fs;
199    use std::{
200        cell::RefCell,
201        collections::BTreeMap,
202        path::PathBuf,
203        time::{Duration, UNIX_EPOCH},
204    };
205
206    use super::*;
207
208    thread_local! {
209        // Collection is synchronous. Each test's owned state gets independent metadata
210        // on its own thread, without changing or trusting filesystem timestamps.
211        static WRITTEN: RefCell<BTreeMap<PathBuf, BTreeMap<String, SystemTime>>> =
212            const { RefCell::new(BTreeMap::new()) };
213    }
214
215    pub(super) fn written(state: &Path, id: &SessionId) -> Option<SystemTime> {
216        WRITTEN.with(|times| times.borrow().get(state)?.get(id.as_str()).copied())
217    }
218
219    /// Owns the real files and the injected write times until the collection finishes.
220    struct Store {
221        root: tempfile::TempDir,
222    }
223    impl Store {
224        fn path(&self) -> &Path {
225            self.root.path()
226        }
227
228        fn set_written(&self, id: &str, seconds: u64) {
229            WRITTEN.with(|times| {
230                let mut times = times.borrow_mut();
231                let written = times
232                    .get_mut(self.path())
233                    .expect("owned state's metadata")
234                    .get_mut(id)
235                    .expect("declared session");
236                *written = UNIX_EPOCH + Duration::from_secs(seconds);
237            });
238        }
239    }
240    impl Drop for Store {
241        fn drop(&mut self) {
242            WRITTEN.with(|times| {
243                times.borrow_mut().remove(self.path());
244            });
245        }
246    }
247
248    /// Equal synthetic write times make identity the deterministic tie breaker.
249    fn store(sizes: &[(&str, usize)]) -> Store {
250        let state = Store {
251            root: crate::test_os::tempdir(),
252        };
253        let sessions = directory(state.path());
254        fs::create_dir_all(&sessions).unwrap();
255        for (id, bytes) in sizes {
256            fs::write(sessions.join(format!("{id}.jsonl")), vec![b'x'; *bytes]).unwrap();
257        }
258        WRITTEN.with(|times| {
259            times.borrow_mut().insert(
260                state.path().to_path_buf(),
261                sizes
262                    .iter()
263                    .map(|(id, _)| ((*id).to_owned(), UNIX_EPOCH))
264                    .collect(),
265            );
266        });
267        state
268    }
269
270    #[test]
271    fn ordering_uses_explicit_times_then_identity() {
272        let state = store(&[("a", 1), ("c", 1), ("b", 1)]);
273        for (id, seconds) in [("a", 20), ("c", 10), ("b", 10)] {
274            state.set_written(id, seconds);
275        }
276        let collection = collect(state.path(), bounds(1, 0), false).unwrap();
277        assert_eq!(
278            collection
279                .removed
280                .iter()
281                .map(ToString::to_string)
282                .collect::<Vec<_>>(),
283            ["b", "c", "a"]
284        );
285        assert_eq!(usage(state.path()).unwrap().sessions, 0);
286    }
287
288    fn bounds(max_bytes: u64, target_bytes: u64) -> AgentSessions {
289        AgentSessions::new(true, max_bytes, target_bytes).unwrap()
290    }
291
292    #[test]
293    fn collects_oldest_first_down_to_the_target_only_past_the_maximum() {
294        let state = store(&[("a", 100), ("b", 100), ("c", 100), ("d", 100)]);
295        // At the maximum, nothing is collected.
296        let collection = collect(state.path(), bounds(400, 150), false).unwrap();
297        assert!(collection.removed.is_empty());
298        assert_eq!(usage(state.path()).unwrap().sessions, 4);
299
300        let dry = collect(state.path(), bounds(399, 150), true).unwrap();
301        assert_eq!(
302            dry.removed
303                .iter()
304                .map(ToString::to_string)
305                .collect::<Vec<_>>(),
306            ["a", "b", "c"]
307        );
308        assert_eq!((dry.bytes, dry.remaining), (400, 100));
309        assert_eq!(usage(state.path()).unwrap().sessions, 4);
310
311        // A held lock keeps its session.
312        let lock = directory(state.path()).join("b.lock");
313        let held = File::create(&lock).unwrap();
314        held.lock().unwrap();
315        let collection = collect(state.path(), bounds(399, 200), false).unwrap();
316        assert_eq!(
317            collection
318                .removed
319                .iter()
320                .map(ToString::to_string)
321                .collect::<Vec<_>>(),
322            ["a", "c"]
323        );
324        assert_eq!(collection.remaining, 200);
325        drop(held);
326        let left: BTreeSet<_> = fs::read_dir(directory(state.path()))
327            .unwrap()
328            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
329            .collect();
330        assert_eq!(
331            left,
332            ["b.jsonl", "b.lock", "d.jsonl"]
333                .map(str::to_owned)
334                .into_iter()
335                .collect()
336        );
337    }
338
339    #[test]
340    fn invalid_session_filenames_are_not_collected() {
341        let state = store(&[("valid", 100), ("..", 100), ("bad name", 100)]);
342        assert_eq!(usage(state.path()).unwrap().sessions, 1);
343        let collection = collect(state.path(), bounds(1, 0), false).unwrap();
344        assert_eq!(
345            collection
346                .removed
347                .iter()
348                .map(ToString::to_string)
349                .collect::<Vec<_>>(),
350            ["valid"]
351        );
352        assert!(directory(state.path()).join("...jsonl").is_file());
353        assert!(directory(state.path()).join("bad name.jsonl").is_file());
354    }
355
356    #[test]
357    fn running_session_ids_are_validated_at_the_sql_edge() {
358        let state = store(&[("active", 100), ("finished", 100)]);
359        let db = rusqlite::Connection::open(state.path().join(DATABASE)).unwrap();
360        db.execute_batch(
361            "CREATE TABLE requests(status TEXT, data TEXT);
362            INSERT INTO requests VALUES('RUNNING','{\"sessionId\":\"active\"}');",
363        )
364        .unwrap();
365        let collection = collect(state.path(), bounds(1, 0), false).unwrap();
366        assert_eq!(
367            collection
368                .removed
369                .iter()
370                .map(ToString::to_string)
371                .collect::<Vec<_>>(),
372            ["finished"]
373        );
374        db.execute_batch("UPDATE requests SET data='{\"sessionId\":\"../invalid\"}';")
375            .unwrap();
376        assert!(collect(state.path(), bounds(1, 0), false).is_err());
377        assert!(directory(state.path()).join("active.jsonl").is_file());
378    }
379
380    #[test]
381    fn a_missing_store_is_empty() {
382        let state = crate::test_os::tempdir();
383        let collection = collect(state.path(), bounds(1, 0), false).unwrap();
384        assert_eq!((collection.bytes, collection.removed.len()), (0, 0));
385    }
386}