yk-session 0.1.0

Append-only JSONL sessions as a tree of entries
Documentation
//! The tree against real files.
//!
//! `tree.rs` covers the walk with entries in memory. These cover the thing that
//! actually matters about an append-only tree: that a fork, a rewind, and a
//! compaction leave the original readable afterwards, and that none of them
//! destroys what the model was told.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::as_conversions,
    clippy::arithmetic_side_effects
)]

use std::path::PathBuf;

use yk_core::Message;
use yk_session::{Entry, SessionLog};

/// A scratch directory that cleans itself up.
///
/// `tempfile` rather than a fixed path under `std::env::temp_dir`: the old
/// version derived its directory from the test name alone, so two test binaries
/// running at once shared one directory.
struct Scratch(tempfile::TempDir);

impl Scratch {
    fn new(name: &str) -> Self {
        Self(tempfile::TempDir::with_prefix(name).expect("makes the directory"))
    }

    fn at(&self, name: &str) -> PathBuf {
        self.0.path().join(name)
    }

    fn open(&self, name: &str) -> SessionLog {
        SessionLog::open(self.at(name)).expect("opens")
    }
}

/// Append a user message, chaining it onto whatever came before.
///
/// The parent is the whole point of the format, so a helper that wrote
/// `parent: None` every time would produce four sibling roots rather than a
/// chain, and the walk would correctly return only the last of them.
fn say(store: &mut SessionLog, count: usize, text: &str) -> String {
    let id = format!("e{count}");
    let parent = count
        .checked_sub(1)
        .filter(|n| *n > 0)
        .map(|n| format!("e{n}"));

    store
        .append(&Entry::Message {
            id: id.clone(),
            parent,
            message: Message::user(text),
        })
        .expect("appends");
    id
}

fn texts(store: &SessionLog) -> Vec<String> {
    store
        .active_messages()
        .expect("reads")
        .iter()
        .map(yk_core::Message::text)
        .map(ToOwned::to_owned)
        .collect()
}

#[test]
fn an_empty_file_has_an_empty_branch() {
    let scratch = Scratch::new("empty");
    let store = scratch.open("s.jsonl");

    assert_eq!(texts(&store), Vec::<String>::new());
    assert_eq!(store.head_id().expect("reads"), None);
}

#[test]
fn a_flat_history_reads_back_in_order() {
    let scratch = Scratch::new("flat");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    say(&mut store, 2, "two");
    say(&mut store, 3, "three");

    assert_eq!(texts(&store), ["one", "two", "three"]);
    assert_eq!(store.head_id().expect("reads").as_deref(), Some("e3"));
}

#[test]
fn a_rewind_moves_the_head_back_without_deleting_anything() {
    let scratch = Scratch::new("rewind");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    say(&mut store, 2, "two");
    say(&mut store, 3, "three");

    store.rewind(&"e2".to_owned()).expect("rewinds");

    // The branch now stops at e2.
    assert_eq!(texts(&store), ["one", "two"]);
    assert_eq!(store.head_id().expect("reads").as_deref(), Some("e2"));

    // And the dropped entry is still on disk.
    assert_eq!(store.all_entries().expect("reads").len(), 4);
    assert!(
        store
            .all_entries()
            .expect("reads")
            .iter()
            .any(|entry| entry.id() == "e3")
    );
}

#[test]
fn something_appended_after_a_rewind_becomes_the_new_branch() {
    let scratch = Scratch::new("rewind-then-append");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    say(&mut store, 2, "two");
    say(&mut store, 3, "three");
    store.rewind(&"e1".to_owned()).expect("rewinds");

    let id = format!("e{}", store.all_entries().expect("reads").len() + 1);
    store
        .append(&Entry::Message {
            id,
            parent: Some("e1".to_owned()),
            message: Message::user("different"),
        })
        .expect("appends");

    assert_eq!(texts(&store), ["one", "different"]);
}

#[test]
fn a_rewind_to_a_missing_entry_is_refused() {
    let scratch = Scratch::new("rewind-missing");
    let mut store = scratch.open("s.jsonl");
    say(&mut store, 1, "one");

    let error = store.rewind(&"e99".to_owned()).expect_err("must fail");
    assert!(error.to_string().contains("e99"), "{error}");
}

#[test]
fn a_fork_gives_two_files_that_diverge_from_a_common_past() {
    let scratch = Scratch::new("fork");
    let mut original = scratch.open("main.jsonl");

    say(&mut original, 1, "shared one");
    say(&mut original, 2, "shared two");

    // Forked from a shared past, so both files can reach e1 and e2.
    original.fork(&scratch.at("branch.jsonl")).expect("forks");

    let main_id = "e3".to_owned();
    original
        .append(&Entry::Message {
            id: main_id,
            parent: Some("e2".to_owned()),
            message: Message::user("only on main"),
        })
        .expect("appends");

    let mut branch = scratch.open("branch.jsonl");
    let branch_id = "e3".to_owned();
    branch
        .append(&Entry::Message {
            id: branch_id,
            parent: Some("e2".to_owned()),
            message: Message::user("only on the branch"),
        })
        .expect("appends");

    assert_eq!(
        texts(&original),
        ["shared one", "shared two", "only on main"]
    );
    assert_eq!(
        texts(&branch),
        ["shared one", "shared two", "only on the branch"]
    );
}

#[test]
fn forking_does_not_damage_either_file() {
    let scratch = Scratch::new("fork-safety");
    let mut original = scratch.open("main.jsonl");
    say(&mut original, 1, "one");
    say(&mut original, 2, "two");

    original.fork(&scratch.at("branch.jsonl")).expect("forks");

    // Dropping the original and reopening both must give the same bytes.
    drop(original);
    assert_eq!(texts(&scratch.open("main.jsonl")), ["one", "two"]);
    assert_eq!(texts(&scratch.open("branch.jsonl")), ["one", "two"]);
}

#[test]
fn a_compaction_shadows_what_came_before_it() {
    let scratch = Scratch::new("compact");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    say(&mut store, 2, "two");
    say(&mut store, 3, "three");

    store
        .compact("the first three messages", None)
        .expect("compacts");

    let branch = texts(&store);
    assert_eq!(branch.len(), 1, "{branch:?}");
    assert_eq!(
        branch[0],
        yk_session::summary_message("the first three messages").text()
    );
}

#[test]
fn a_compaction_keeps_what_comes_after_it() {
    let scratch = Scratch::new("compact-then");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    store.compact("summary", None).expect("compacts");

    let next = format!("e{}", store.all_entries().expect("reads").len() + 1);
    store
        .append(&Entry::Message {
            id: next,
            parent: Some("e2".to_owned()),
            message: Message::user("after the summary"),
        })
        .expect("appends");

    let branch = texts(&store);
    assert_eq!(branch.len(), 2, "{branch:?}");
    assert_eq!(branch[0], yk_session::summary_message("summary").text());
    assert_eq!(branch[1], "after the summary");
}

#[test]
fn a_compaction_leaves_the_originals_readable_in_the_file() {
    let scratch = Scratch::new("compact-keeps");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    say(&mut store, 2, "two");
    store.compact("summary", None).expect("compacts");

    // The shadowed messages are still there; only the walk skips them.
    let all = store.all_entries().expect("reads");
    let on_disk: Vec<String> = all
        .iter()
        .filter_map(|entry| match entry {
            Entry::Message { message, .. } => Some(message.text().to_owned()),
            _ => None,
        })
        .collect();

    assert_eq!(on_disk, ["one", "two"]);
}

#[test]
fn a_dangling_parent_is_reported_rather_than_silently_truncating() {
    let scratch = Scratch::new("dangling");
    let store = scratch.open("s.jsonl");

    // Written by hand so the parent cannot exist.
    std::fs::write(
        scratch.at("s.jsonl"),
        "{\"kind\":\"message\",\"id\":\"e1\",\"parent\":\"e9\",\"message\":{\"role\":\"user\",\"content\":\"hi\"}}\n",
    )
    .expect("writes");

    let error = store.active_messages().expect_err("must fail");
    assert!(error.to_string().contains("e9"), "{error}");
}

#[test]
fn a_cycle_does_not_hang_the_walk() {
    let scratch = Scratch::new("cycle");
    std::fs::write(
        scratch.at("s.jsonl"),
        concat!(
            "{\"kind\":\"message\",\"id\":\"e1\",\"parent\":\"e2\",\"message\":{\"role\":\"user\",\"content\":\"a\"}}\n",
            "{\"kind\":\"message\",\"id\":\"e2\",\"parent\":\"e1\",\"message\":{\"role\":\"user\",\"content\":\"b\"}}\n"
        ),
    )
    .expect("writes");

    let store = scratch.open("s.jsonl");
    let error = store.active_messages().expect_err("must fail");
    assert!(error.to_string().contains("ancestor"), "{error}");
}

#[test]
fn the_head_of_a_forked_file_is_the_last_thing_written_to_it() {
    let scratch = Scratch::new("head");
    let mut store = scratch.open("s.jsonl");

    say(&mut store, 1, "one");
    say(&mut store, 2, "two");
    store.rewind(&"e1".to_owned()).expect("rewinds");

    assert_eq!(store.head_id().expect("reads").as_deref(), Some("e1"));
}

#[test]
fn a_head_that_cannot_be_read_is_an_error_not_an_empty_session() {
    // The file is deleted after the store opened it, which is the window the old
    // `head` covered with `.ok()?`: a read that fails between `open` and `head`.
    // It used to come back as `None`, which is indistinguishable from a session
    // nobody has written to.
    let scratch = Scratch::new("unreadable");
    let store = scratch.open("s.jsonl");
    std::fs::remove_file(scratch.at("s.jsonl")).expect("removes");

    let error = store.head_id().expect_err("a deleted file cannot be read");
    assert!(
        error.to_string().contains("s.jsonl"),
        "the error names the file: {error}"
    );
}