artifactize-core 0.27.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
use std::fs;
use std::{
    cell::RefCell,
    collections::BTreeMap,
    path::PathBuf,
    time::{Duration, UNIX_EPOCH},
};

use super::*;

thread_local! {
    // Collection is synchronous. Each test's owned state gets independent metadata
    // on its own thread, without changing or trusting filesystem timestamps.
    static WRITTEN: RefCell<BTreeMap<PathBuf, BTreeMap<String, SystemTime>>> =
        const { RefCell::new(BTreeMap::new()) };
}

pub(super) fn written(state: &Path, id: &SessionId) -> Option<SystemTime> {
    WRITTEN.with(|times| times.borrow().get(state)?.get(id.as_str()).copied())
}

/// Owns the real files and the injected write times until the collection finishes.
struct Store {
    root: tempfile::TempDir,
}
impl Store {
    fn path(&self) -> &Path {
        self.root.path()
    }

    fn set_written(&self, id: &str, seconds: u64) {
        WRITTEN.with(|times| {
            let mut times = times.borrow_mut();
            let written = times
                .get_mut(self.path())
                .expect("owned state's metadata")
                .get_mut(id)
                .expect("declared session");
            *written = UNIX_EPOCH + Duration::from_secs(seconds);
        });
    }
}
impl Drop for Store {
    fn drop(&mut self) {
        WRITTEN.with(|times| {
            times.borrow_mut().remove(self.path());
        });
    }
}

/// Equal synthetic write times make identity the deterministic tie breaker.
fn store(sizes: &[(&str, usize)]) -> Store {
    let state = Store {
        root: crate::test_os::tempdir(),
    };
    let sessions = directory(state.path());
    fs::create_dir_all(&sessions).unwrap();
    for (id, bytes) in sizes {
        fs::write(sessions.join(format!("{id}.jsonl")), vec![b'x'; *bytes]).unwrap();
    }
    WRITTEN.with(|times| {
        times.borrow_mut().insert(
            state.path().to_path_buf(),
            sizes
                .iter()
                .map(|(id, _)| ((*id).to_owned(), UNIX_EPOCH))
                .collect(),
        );
    });
    state
}

#[test]
fn ordering_uses_explicit_times_then_identity() {
    let state = store(&[("a", 1), ("c", 1), ("b", 1)]);
    for (id, seconds) in [("a", 20), ("c", 10), ("b", 10)] {
        state.set_written(id, seconds);
    }
    let collection = collect(state.path(), bounds(1, 0), false).unwrap();
    assert_eq!(
        collection
            .removed
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>(),
        ["b", "c", "a"]
    );
    assert_eq!(usage(state.path()).unwrap().sessions, 0);
}

fn bounds(max_bytes: u64, target_bytes: u64) -> AgentSessions {
    AgentSessions::new(true, max_bytes, target_bytes).unwrap()
}

#[test]
fn collects_oldest_first_down_to_the_target_only_past_the_maximum() {
    let state = store(&[("a", 100), ("b", 100), ("c", 100), ("d", 100)]);
    // At the maximum, nothing is collected.
    let collection = collect(state.path(), bounds(400, 150), false).unwrap();
    assert!(collection.removed.is_empty());
    assert_eq!(usage(state.path()).unwrap().sessions, 4);

    let dry = collect(state.path(), bounds(399, 150), true).unwrap();
    assert_eq!(
        dry.removed
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>(),
        ["a", "b", "c"]
    );
    assert_eq!((dry.bytes, dry.remaining), (400, 100));
    assert_eq!(usage(state.path()).unwrap().sessions, 4);

    // A held lock keeps its session.
    let lock = directory(state.path()).join("b.lock");
    let held = File::create(&lock).unwrap();
    held.lock().unwrap();
    let collection = collect(state.path(), bounds(399, 200), false).unwrap();
    assert_eq!(
        collection
            .removed
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>(),
        ["a", "c"]
    );
    assert_eq!(collection.remaining, 200);
    drop(held);
    let left: BTreeSet<_> = fs::read_dir(directory(state.path()))
        .unwrap()
        .map(|entry| entry.unwrap().file_name().into_string().unwrap())
        .collect();
    assert_eq!(
        left,
        ["b.jsonl", "b.lock", "d.jsonl"]
            .map(str::to_owned)
            .into_iter()
            .collect()
    );
}

#[test]
fn invalid_session_filenames_are_not_collected() {
    let state = store(&[("valid", 100), ("..", 100), ("bad name", 100)]);
    assert_eq!(usage(state.path()).unwrap().sessions, 1);
    let collection = collect(state.path(), bounds(1, 0), false).unwrap();
    assert_eq!(
        collection
            .removed
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>(),
        ["valid"]
    );
    assert!(directory(state.path()).join("...jsonl").is_file());
    assert!(directory(state.path()).join("bad name.jsonl").is_file());
}

#[test]
fn running_session_ids_are_validated_at_the_sql_edge() {
    let state = store(&[("active", 100), ("finished", 100)]);
    let db = rusqlite::Connection::open(state.path().join(DATABASE)).unwrap();
    db.execute_batch(
        "CREATE TABLE requests(status TEXT, data TEXT);
            INSERT INTO requests VALUES('RUNNING','{\"sessionId\":\"active\"}');",
    )
    .unwrap();
    let collection = collect(state.path(), bounds(1, 0), false).unwrap();
    assert_eq!(
        collection
            .removed
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>(),
        ["finished"]
    );
    db.execute_batch("UPDATE requests SET data='{\"sessionId\":\"../invalid\"}';")
        .unwrap();
    assert!(collect(state.path(), bounds(1, 0), false).is_err());
    assert!(directory(state.path()).join("active.jsonl").is_file());
}

#[test]
fn a_missing_store_is_empty() {
    let state = crate::test_os::tempdir();
    let collection = collect(state.path(), bounds(1, 0), false).unwrap();
    assert_eq!((collection.bytes, collection.removed.len()), (0, 0));
}