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