From e039c82f0bb0359e79a81413408a7962e6c2c14e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 25 Nov 2026 15:00:23 +0800 Subject: [PATCH] feat(agent-sessions): add the local agent session record store Add lithe-agent-sessions, a pure crate that keeps a SQLite cache of the call records agent plugins parse from session files on disk. Core holds no agent names, directories or formats: a plugin backend lists the files to read and turns each chunk of complete lines into session, call and index records; Core reads, validates, stores, counts and searches them. - discover: list the files a plugin's root and glob patterns match, without following symbolic links, with bounded counts. - ingest/store: read appended lines from a cursor, detect rewrites and truncation by size and a fingerprint of the first and last bytes read, skip overlong lines, retry a failed chunk, and forget files that are unlisted or deleted. - store: query calls with copies of a resumed session counted once, list sessions merged across their files, and read back a byte range only while the file is unchanged. - text: index CJK and other unspaced scripts as character pairs and words as prefixes in a contentless FTS5 table, so the cache keeps no conversation text; query syntax never reaches FTS5. - stats/pricing: sum tokens, cache hit rate and failures by agent, model, session, directory or local day; price calls from a models.dev table as an API-price equivalent; rank models by median output speed. The plugin API (API-45), MCP tools and log events come in a later change. --- rust/Cargo.lock | 13 + rust/crates/agent-sessions/Cargo.toml | 18 + rust/crates/agent-sessions/src/discover.rs | 121 ++ rust/crates/agent-sessions/src/ingest.rs | 239 +++ rust/crates/agent-sessions/src/lib.rs | 46 + rust/crates/agent-sessions/src/model.rs | 220 +++ rust/crates/agent-sessions/src/pricing.rs | 262 ++++ rust/crates/agent-sessions/src/stats.rs | 440 ++++++ rust/crates/agent-sessions/src/store.rs | 1385 +++++++++++++++++ .../agent-sessions/src/tests/discover.rs | 100 ++ rust/crates/agent-sessions/src/tests/mod.rs | 184 +++ .../agent-sessions/src/tests/pricing.rs | 211 +++ rust/crates/agent-sessions/src/tests/stats.rs | 335 ++++ rust/crates/agent-sessions/src/tests/store.rs | 826 ++++++++++ rust/crates/agent-sessions/src/tests/text.rs | 70 + rust/crates/agent-sessions/src/text.rs | 154 ++ 16 files changed, 4624 insertions(+) create mode 100644 rust/crates/agent-sessions/Cargo.toml create mode 100644 rust/crates/agent-sessions/src/discover.rs create mode 100644 rust/crates/agent-sessions/src/ingest.rs create mode 100644 rust/crates/agent-sessions/src/lib.rs create mode 100644 rust/crates/agent-sessions/src/model.rs create mode 100644 rust/crates/agent-sessions/src/pricing.rs create mode 100644 rust/crates/agent-sessions/src/stats.rs create mode 100644 rust/crates/agent-sessions/src/store.rs create mode 100644 rust/crates/agent-sessions/src/tests/discover.rs create mode 100644 rust/crates/agent-sessions/src/tests/mod.rs create mode 100644 rust/crates/agent-sessions/src/tests/pricing.rs create mode 100644 rust/crates/agent-sessions/src/tests/stats.rs create mode 100644 rust/crates/agent-sessions/src/tests/store.rs create mode 100644 rust/crates/agent-sessions/src/tests/text.rs create mode 100644 rust/crates/agent-sessions/src/text.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 1c19fe85..5cbb6fd8 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -929,6 +929,19 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +[[package]] +name = "lithe-agent-sessions" +version = "0.1.0" +dependencies = [ + "globset", + "lithe-protocol", + "rusqlite", + "serde", + "serde_json", + "sha2", + "walkdir", +] + [[package]] name = "lithe-ai" version = "0.1.0" diff --git a/rust/crates/agent-sessions/Cargo.toml b/rust/crates/agent-sessions/Cargo.toml new file mode 100644 index 00000000..e1fa0460 --- /dev/null +++ b/rust/crates/agent-sessions/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "lithe-agent-sessions" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Cache of the model calls, token counts and search index Lithe derives from the session files agent CLIs keep on this machine" +publish = false + +[dependencies] +globset = "0.4" +lithe-protocol = { path = "../protocol" } +# SQLite is bundled because Windows has no system library, and the cache needs +# FTS5 with contentless deletes (SQLite 3.43 or later). +rusqlite = { version = "0.32", features = ["bundled"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +sha2 = "0.10" +walkdir = "2" diff --git a/rust/crates/agent-sessions/src/discover.rs b/rust/crates/agent-sessions/src/discover.rs new file mode 100644 index 00000000..66d69f72 --- /dev/null +++ b/rust/crates/agent-sessions/src/discover.rs @@ -0,0 +1,121 @@ +//! Lists the session files a plugin's declared source matches. +//! +//! A source is a root directory, already resolved from the plugin's +//! declaration, and glob patterns relative to it. Symbolic links are not +//! followed, so a listing never leaves the root the user agreed to. + +use std::path::{Path, PathBuf}; + +use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use lithe_protocol::{CoreError, ErrorCode}; +use walkdir::WalkDir; + +/// Deepest directory level below a root that a listing enters. +pub const MAX_DISCOVERY_DEPTH: usize = 16; + +/// Most files one source lists; a listing that reaches it stops and says so. +pub const MAX_FILES_PER_SOURCE: usize = 100_000; + +/// A directory of session files and the files in it to read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionSource { + /// The directory, with the plugin's templates already resolved. + pub root: PathBuf, + /// Glob patterns matched against paths relative to `root`, with `/` + /// between components on every platform. `*` stays within one component; + /// `**` crosses components. + pub include: Vec, +} + +/// The files a source matches. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Discovery { + /// Matching regular files, sorted, so syncs read them in the same order. + pub files: Vec, + /// Whether the listing stopped at [`MAX_FILES_PER_SOURCE`]. + pub truncated: bool, + /// Entries that could not be listed, for example a directory without + /// read permission, or names that are not valid Unicode, which the cache + /// cannot record. + pub unreadable_entries: u64, +} + +/// Lists the files of `source`. A root that does not exist lists nothing: the +/// agent has not written a session yet. +pub fn discover(source: &SessionSource) -> Result { + let patterns = glob_set(&source.include)?; + let mut discovery = Discovery::default(); + if !source.root.is_dir() { + return Ok(discovery); + } + let walker = WalkDir::new(&source.root) + .follow_links(false) + .max_depth(MAX_DISCOVERY_DEPTH) + .sort_by_file_name(); + for entry in walker { + let entry = match entry { + Ok(entry) => entry, + Err(_) => { + discovery.unreadable_entries += 1; + continue; + } + }; + if !entry.file_type().is_file() { + continue; + } + let Some(relative) = relative_glob_path(&source.root, entry.path()) else { + discovery.unreadable_entries += 1; + continue; + }; + if !patterns.is_match(&relative) { + continue; + } + if discovery.files.len() == MAX_FILES_PER_SOURCE { + discovery.truncated = true; + break; + } + discovery.files.push(entry.into_path()); + } + discovery.files.sort(); + Ok(discovery) +} + +fn glob_set(patterns: &[String]) -> Result { + let mut builder = GlobSetBuilder::new(); + for pattern in patterns { + let glob = GlobBuilder::new(pattern) + .literal_separator(true) + .backslash_escape(true) + .build() + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "A session source has an invalid file pattern", + ) + .with_details(error.to_string()) + })?; + builder.add(glob); + } + builder.build().map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "A session source has an invalid file pattern", + ) + .with_details(error.to_string()) + }) +} + +/// The path of `path` below `root` with `/` separators, or `None` when a +/// component is not valid Unicode. +fn relative_glob_path(root: &Path, path: &Path) -> Option { + let relative = path.strip_prefix(root).ok()?; + let mut joined = String::new(); + for component in relative.components() { + if !joined.is_empty() { + joined.push('/'); + } + joined.push_str(component.as_os_str().to_str()?); + } + path.to_str()?; + Some(joined) +} diff --git a/rust/crates/agent-sessions/src/ingest.rs b/rust/crates/agent-sessions/src/ingest.rs new file mode 100644 index 00000000..eba6d182 --- /dev/null +++ b/rust/crates/agent-sessions/src/ingest.rs @@ -0,0 +1,239 @@ +//! Incremental reading of session files: deciding whether a file only grew +//! or was rewritten, and cutting the new bytes into bounded chunks of whole +//! lines. +//! +//! Agents append to their session files, so a sync normally reads only what +//! was added. A file that shrank, or whose already read bytes changed, is +//! read again from the start; the fingerprint below detects the change +//! without reading the whole file. + +use std::fs::{File, Metadata}; +use std::io::{self, BufRead, Read, Seek, SeekFrom}; +use std::time::UNIX_EPOCH; + +use lithe_protocol::CoreError; +use sha2::{Digest, Sha256}; + +/// Most bytes of whole lines handed to a parser at once. A single longer line +/// (up to [`MAX_LINE_BYTES`]) is handed over alone. +pub const MAX_CHUNK_BYTES: usize = 4 * 1024 * 1024; + +/// Longest line, newline included, handed to a parser. Agents can write a +/// whole attachment on one line; longer lines are skipped, counted in the +/// sync report, and never held in memory whole. +pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024; + +/// Bytes at each end of the read part of a file that its fingerprint covers. +const FINGERPRINT_EDGE_BYTES: u64 = 4096; + +/// Marks a modification time the platform did not report. It never equals a +/// real time, so such a file is always checked against its fingerprint. +pub(crate) const UNKNOWN_MODIFIED_MS: i64 = i64::MIN; + +/// Bounds of one pass over a file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ChunkLimits { + pub(crate) max_chunk_bytes: usize, + pub(crate) max_line_bytes: usize, +} + +impl Default for ChunkLimits { + fn default() -> Self { + Self { + max_chunk_bytes: MAX_CHUNK_BYTES, + max_line_bytes: MAX_LINE_BYTES, + } + } +} + +/// Size and modification time of a file when a sync looked at it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct FileStamp { + pub(crate) size: u64, + pub(crate) modified_ms: i64, +} + +impl FileStamp { + pub(crate) fn of(metadata: &Metadata) -> Self { + // Platforms without modification times still sync correctly: the + // fingerprint check below decides instead of the stamp. + let modified_ms = match metadata.modified() { + Ok(time) => match time.duration_since(UNIX_EPOCH) { + Ok(elapsed) => i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX), + Err(before_epoch) => { + -i64::try_from(before_epoch.duration().as_millis()).unwrap_or(i64::MAX) + } + }, + Err(_) => UNKNOWN_MODIFIED_MS, + }; + Self { + size: metadata.len(), + modified_ms, + } + } +} + +/// What the store remembers about a file between syncs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Cursor { + /// End of the last whole line read; everything before it is in the cache. + pub(crate) offset: u64, + /// The stamp of the file when it was last read to the end. `None` while + /// a pass is unfinished, so the next sync never takes the file as + /// unchanged. + pub(crate) stamp: Option, + /// [`fingerprint`] of the bytes before `offset`. + pub(crate) fingerprint: Vec, +} + +/// How a sync reads a file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Plan { + /// The file has the stamp it had when it was last read to the end. + Unchanged, + /// The read bytes are as they were; read on from `offset`. + Append { offset: u64 }, + /// The file is new, shrank or changed; drop what came from it and read it + /// from the start. + FromStart, +} + +/// Decides how to read `file`, which has `stamp` now and `cursor` from the +/// previous sync. +pub(crate) fn plan(file: &mut File, stamp: FileStamp, cursor: Option<&Cursor>) -> io::Result { + let Some(cursor) = cursor else { + return Ok(Plan::FromStart); + }; + if cursor.stamp == Some(stamp) && stamp.modified_ms != UNKNOWN_MODIFIED_MS { + return Ok(Plan::Unchanged); + } + if stamp.size < cursor.offset { + return Ok(Plan::FromStart); + } + if fingerprint(file, cursor.offset)? != cursor.fingerprint { + return Ok(Plan::FromStart); + } + Ok(Plan::Append { + offset: cursor.offset, + }) +} + +/// SHA-256 of the first and the last [`FINGERPRINT_EDGE_BYTES`] before +/// `offset`, without overlap. Appending never changes it; rewriting the +/// start of the file, or the lines read last, does. A rewrite that keeps +/// both ends and the length is not detected, which agents that append to +/// their files do not do. +pub(crate) fn fingerprint(file: &mut File, offset: u64) -> io::Result> { + let head_end = offset.min(FINGERPRINT_EDGE_BYTES); + let tail_start = offset.saturating_sub(FINGERPRINT_EDGE_BYTES).max(head_end); + let mut hasher = Sha256::new(); + hash_range(file, 0, head_end, &mut hasher)?; + hash_range(file, tail_start, offset, &mut hasher)?; + Ok(hasher.finalize().to_vec()) +} + +fn hash_range(file: &mut File, start: u64, end: u64, hasher: &mut Sha256) -> io::Result<()> { + if start >= end { + return Ok(()); + } + file.seek(SeekFrom::Start(start))?; + let length = usize::try_from(end - start).unwrap_or(usize::MAX); + let mut bytes = vec![0; length]; + file.read_exact(&mut bytes)?; + hasher.update(&bytes); + Ok(()) +} + +/// What one pass over a file read. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct LineProgress { + /// Offset just past the last whole line, handed over or skipped. + pub(crate) end: u64, + /// Bytes consumed from the file, a trailing partial line included. + pub(crate) bytes_read: u64, + /// Lines longer than the limit, which were skipped. + pub(crate) skipped_lines: u64, +} + +/// Reads whole lines from `reader`, which is positioned at file offset +/// `start`, consuming at most `limit` bytes. `on_chunk` receives each chunk +/// with the file offset of its first byte. The bytes of a chunk are +/// contiguous in the file: a skipped line ends the chunk before it. A last +/// line without a newline is left for a later pass, when the agent has +/// finished writing it. A read failure becomes `E` through [`read_failed`]; +/// an error of `on_chunk` stops the pass and is returned as is. +pub(crate) fn read_lines>( + reader: &mut impl BufRead, + start: u64, + limit: u64, + limits: ChunkLimits, + mut on_chunk: impl FnMut(u64, &[u8]) -> Result<(), E>, +) -> Result { + let read_end = start.saturating_add(limit); + let mut position = start; + let mut progress = LineProgress { + end: start, + ..LineProgress::default() + }; + let mut chunk: Vec = Vec::new(); + let mut chunk_start = start; + let mut line: Vec = Vec::new(); + let mut skipping = false; + + while position < read_end { + let available = reader + .fill_buf() + .map_err(|error| E::from(read_failed(error)))?; + if available.is_empty() { + break; + } + let allowed = usize::try_from(read_end - position).unwrap_or(usize::MAX); + let available = &available[..available.len().min(allowed)]; + let (taken, line_ended) = match available.iter().position(|byte| *byte == b'\n') { + Some(index) => (index + 1, true), + None => (available.len(), false), + }; + if !skipping { + if line.len() + taken > limits.max_line_bytes { + skipping = true; + line = Vec::new(); + } else { + line.extend_from_slice(&available[..taken]); + } + } + reader.consume(taken); + position += taken as u64; + if !line_ended { + continue; + } + + if skipping { + progress.skipped_lines += 1; + skipping = false; + if !chunk.is_empty() { + on_chunk(chunk_start, &chunk)?; + chunk.clear(); + } + } else { + if !chunk.is_empty() && chunk.len() + line.len() > limits.max_chunk_bytes { + on_chunk(chunk_start, &chunk)?; + chunk.clear(); + } + if chunk.is_empty() { + chunk_start = position - line.len() as u64; + } + chunk.extend_from_slice(&line); + line.clear(); + } + progress.end = position; + } + if !chunk.is_empty() { + on_chunk(chunk_start, &chunk)?; + } + progress.bytes_read = position - start; + Ok(progress) +} + +pub(crate) fn read_failed(error: io::Error) -> CoreError { + crate::store::io_error("Could not read an agent session file", error) +} diff --git a/rust/crates/agent-sessions/src/lib.rs b/rust/crates/agent-sessions/src/lib.rs new file mode 100644 index 00000000..9fda99fb --- /dev/null +++ b/rust/crates/agent-sessions/src/lib.rs @@ -0,0 +1,46 @@ +//! Local agent session records: the model calls, token counts and search +//! index Lithe derives from the session files agent CLIs keep on this machine. +//! +//! Agent CLIs record every conversation in their own files. This crate reads +//! those files incrementally and keeps a cache that can be deleted at any time +//! and rebuilt from them; Lithe never writes the agents' files. +//! +//! Core knows no agent. Which directories hold sessions and how their lines are +//! read both come from the agent's plugin: [`discover`] lists the files a +//! declared source matches, and a [`SessionParser`], backed by the plugin's +//! backend, turns whole lines into the records in [`model`]. Each plugin only +//! sees the files of its own agents. +//! +//! The cache ([`SessionStore`]) is one SQLite database in the platform's Caches +//! directory. It holds, per file, a cursor of what has been read; per call, +//! metadata and token counts; and a full-text index that keeps no text. The +//! index stores the words of each indexed span, not the span: its rows hold no +//! positions, so neither the text nor the order of its words can be read back. +//! Every record points at a byte range of its source file, which is read again +//! when a message is shown. +//! +//! The cost, cache hit rate and speed of calls are computed once, here, in +//! [`stats`], with prices from a models.dev table ([`pricing`]). + +mod discover; +mod ingest; +pub mod model; +pub mod pricing; +pub mod stats; +mod store; +mod text; + +#[cfg(test)] +mod tests; + +pub use discover::{discover, Discovery, SessionSource, MAX_DISCOVERY_DEPTH, MAX_FILES_PER_SOURCE}; +pub use ingest::{MAX_CHUNK_BYTES, MAX_LINE_BYTES}; +pub use model::{ + ByteRange, CallRecord, IndexSpan, ScanChunk, ScanOutput, SessionMeta, SessionParser, Tokens, +}; +pub use store::{ + database_file_name, CallEntry, CallFilter, FileFailure, SearchHit, SearchQuery, SessionEntry, + SessionFilter, SessionStore, SyncReport, MAX_ID_BYTES, MAX_INDEXED_SPAN_BYTES, MAX_LABEL_BYTES, + MAX_READ_BYTES, MAX_RECORDS_PER_CHUNK, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, MAX_STATE_BYTES, + SCHEMA_VERSION, +}; diff --git a/rust/crates/agent-sessions/src/model.rs b/rust/crates/agent-sessions/src/model.rs new file mode 100644 index 00000000..7d3c31f9 --- /dev/null +++ b/rust/crates/agent-sessions/src/model.rs @@ -0,0 +1,220 @@ +//! The records a session parser derives from an agent's session file, and the +//! parser interface Core calls with whole lines of that file. +//! +//! The types decode from the camelCase JSON a plugin backend returns, so the +//! adapter that calls the backend needs no types of its own. Absent fields stay +//! absent: a parser that cannot see a value leaves it out instead of guessing, +//! and nothing downstream fills it in. +//! +//! None of these records carries conversation text except [`IndexSpan::text`], +//! which the store splits into index terms and drops. + +use std::path::Path; + +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; + +/// A half-open byte range `[start, end)` of a session file. Records point at +/// the bytes they came from, so a viewer reads the original lines again +/// instead of the cache keeping a copy. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ByteRange { + /// Offset of the first byte, from the start of the file. + pub start: u64, + /// Offset just past the last byte; greater than `start`. + pub end: u64, +} + +/// Token counts of one model call. A count the agent does not record is +/// absent, which differs from zero: statistics leave absent counts out +/// instead of treating them as nothing used. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Tokens { + /// Input tokens read without the prompt cache: neither cache reads nor + /// cache writes. A parser for an agent whose count includes cached tokens + /// subtracts them, so the cache hit rate has one definition. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input: Option, + /// Output tokens, reasoning tokens included. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, + /// Input tokens read from the prompt cache. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read: Option, + /// Input tokens written to a prompt cache entry that lives five minutes. + /// A provider with a single cache lifetime reports its writes here. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_write_5m: Option, + /// Input tokens written to a prompt cache entry that lives one hour. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_write_1h: Option, + /// The part of `output` spent on reasoning, when the agent records it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning: Option, +} + +impl Tokens { + /// Whether the call reports any prompt cache count. Calls that report none + /// come from providers without cache data and stay out of the hit rate. + pub fn reports_cache(&self) -> bool { + self.cache_read.is_some() || self.cache_write_5m.is_some() || self.cache_write_1h.is_some() + } +} + +/// One model request an agent made, as its session file records it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CallRecord { + /// Identifies the request within its agent, for example the response ID + /// the provider returned. The same request recorded twice, in one file or + /// in a session file copied into another, has the same key and is counted + /// once. + pub key: String, + /// The session the request belongs to, in the agent's own ID format. + pub session_id: String, + /// The thread or sub-agent within the session, when the agent has them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thread_id: Option, + /// When the request started, in milliseconds since the Unix epoch (UTC). + pub started_at_ms: i64, + /// The model the agent asked for, which may be an alias. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub requested_model: Option, + /// The model that answered, as the provider reported it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + /// The context window the request selected. A parser for an agent that + /// writes it into the model name splits it off, so `model` names the + /// model alone and prices can be looked up. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context_window: Option, + /// The reasoning effort the request selected, as the agent names it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effort: Option, + /// The provider that served the request, as a models.dev provider ID. + /// Only set when the session file identifies it; never inferred from the + /// model name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider: Option, + /// Token counts of the request. + #[serde(default)] + pub tokens: Tokens, + /// Milliseconds from the start of the request to its first output token. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub first_token_ms: Option, + /// Milliseconds from the start of the request to its last output token. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_ms: Option, + /// Whether the agent made the request to compact its context rather than + /// to answer the user. + #[serde(default)] + pub compaction: bool, + /// The provider's request ID, kept for matching with provider dashboards. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, + /// A short category of the failure when the request failed, as the agent + /// names it (for example `rateLimited`). Never the error message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error_category: Option, + /// The bytes of the session file that record the request. + pub range: ByteRange, +} + +/// What a session file says about a session. A parser reports it whenever +/// it learns more; the store keeps the latest present value of each field. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionMeta { + /// The session, in the agent's own ID format. + pub session_id: String, + /// The session this one was resumed or forked from. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent_session_id: Option, + /// The working directory the agent ran in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// When the session started, in milliseconds since the Unix epoch (UTC). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub started_at_ms: Option, + /// When the session last changed, in milliseconds since the Unix epoch. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updated_at_ms: Option, + /// The version of the agent CLI that wrote the session. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_version: Option, + /// The bytes that hold the session's title. A title is conversation text, + /// so the cache keeps where it is, and a viewer reads it like a message. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title_range: Option, +} + +/// Text of a session file to make searchable, with the bytes it came from. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct IndexSpan { + /// The session the text belongs to. + pub session_id: String, + /// When the text was written, in milliseconds since the Unix epoch. + /// Search lists newer text first. + #[serde(default)] + pub at_ms: Option, + /// The bytes a search hit points at. + pub range: ByteRange, + /// The text to index. The store splits it into terms and keeps neither + /// the text nor the order of its terms; only the first + /// [`MAX_INDEXED_SPAN_BYTES`](crate::MAX_INDEXED_SPAN_BYTES) are indexed. + pub text: String, +} + +/// Whole lines of a session file, handed to a parser. +#[derive(Debug, Clone, Copy)] +pub struct ScanChunk<'a> { + /// The session file. + pub path: &'a Path, + /// The file offset of `bytes[0]`. Ranges the parser returns are file + /// offsets, so they add this to positions within `bytes`. + pub offset: u64, + /// One or more complete lines, each ending with `\n`. Lines longer than + /// [`MAX_LINE_BYTES`](crate::MAX_LINE_BYTES) are never handed over, and a + /// line still being written waits for its newline. + pub bytes: &'a [u8], + /// What the parser returned as [`ScanOutput::state`] after the previous + /// chunk of this file; absent at the start of the file. + pub state: Option<&'a serde_json::Value>, +} + +/// What a parser derived from one chunk. +#[derive(Debug, Clone, Default, PartialEq, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScanOutput { + /// Sessions the chunk describes. + #[serde(default)] + pub sessions: Vec, + /// Model requests the chunk records. + #[serde(default)] + pub calls: Vec, + /// Text of the chunk to make searchable. + #[serde(default)] + pub spans: Vec, + /// What the parser needs to read the next chunk of the file, at most + /// [`MAX_STATE_BYTES`](crate::MAX_STATE_BYTES) as JSON, for example the + /// current session ID or a request whose usage arrives on a later line. + /// It is stored with the file's cursor, so it must hold no conversation + /// text. + #[serde(default)] + pub state: Option, +} + +/// Turns whole lines of an agent's session file into records. Core implements +/// it with a call to the agent plugin's backend; tests implement it directly. +/// +/// A parser must give the same records for a file however its lines are split +/// into chunks: an incremental read and a rebuild from scratch then agree. +pub trait SessionParser { + /// Derives the records of one chunk. An error stops reading the file + /// without moving its cursor, so the same chunk is offered again by the + /// next sync. + fn scan(&mut self, chunk: ScanChunk<'_>) -> Result; +} diff --git a/rust/crates/agent-sessions/src/pricing.rs b/rust/crates/agent-sessions/src/pricing.rs new file mode 100644 index 00000000..95a1acbc --- /dev/null +++ b/rust/crates/agent-sessions/src/pricing.rs @@ -0,0 +1,262 @@ +//! Model prices from a models.dev table, and what a call would cost at them. +//! +//! Agents that run on a subscription do not bill per call, so the cost here +//! is what the same tokens would cost at the provider's API prices. The table +//! is models.dev's `api.json`: providers by ID, each with models by ID, each +//! with a `cost` in US dollars per million tokens. + +use std::collections::HashMap; + +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::Value; + +use crate::model::Tokens; + +/// Largest price table accepted, in bytes. +pub const MAX_PRICE_TABLE_BYTES: usize = 32 * 1024 * 1024; + +/// The prompt size above which models.dev's `context_over_200k` prices apply. +const CONTEXT_OVER_200K_TOKENS: u64 = 200_000; + +/// Prices of one model in one context range, in US dollars per million tokens. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Rates { + /// Uncached input. + pub input: f64, + /// Output, reasoning included unless `reasoning` is set. + pub output: f64, + /// Reasoning output, when priced apart from other output. + pub reasoning: Option, + /// Input read from the prompt cache. + pub cache_read: Option, + /// Input written to the prompt cache. + pub cache_write: Option, +} + +/// Prices that apply when a prompt is larger than `above_prompt_tokens`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Tier { + /// Prompt tokens (input, cache reads and cache writes) the prompt must exceed. + pub above_prompt_tokens: u64, + /// The prices. + pub rates: Rates, +} + +/// Prices of one model. +#[derive(Debug, Clone, PartialEq)] +pub struct Price { + /// Prices of prompts no larger than the first tier. + pub base: Rates, + /// Prices of larger prompts, by ascending `above_prompt_tokens`. + pub tiers: Vec, +} + +impl Price { + /// The prices of a prompt of `prompt_tokens`: those of the largest tier it + /// exceeds, or the base prices. + pub fn rates_for(&self, prompt_tokens: u64) -> &Rates { + self.tiers + .iter() + .rev() + .find(|tier| prompt_tokens > tier.above_prompt_tokens) + .map_or(&self.base, |tier| &tier.rates) + } +} + +/// What a call would cost at API prices. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CallCost { + /// The cost in US dollars. + pub usd: f64, + /// Whether a count was priced at a substitute: cache tokens without a + /// cache price are priced as input, and one-hour cache writes at the + /// table's single cache-write price. + pub approximate: bool, +} + +/// Prices by provider and model. +#[derive(Debug, Clone, Default)] +pub struct PriceTable { + prices: HashMap>, + /// For a model without a known provider: the provider whose price to use, + /// or `None` when providers price it differently. + by_model: HashMap>, +} + +impl PriceTable { + /// Reads models.dev's `api.json`. Models without a valid input and output + /// price are left out, and so are tiers of a kind other than context size. + pub fn from_models_dev(json: &[u8]) -> Result { + if json.len() > MAX_PRICE_TABLE_BYTES { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The model price table is too large", + )); + } + let root: Value = serde_json::from_slice(json).map_err(|_| { + CoreError::new( + ErrorCode::ParseFailed, + "The model price table is not valid JSON", + ) + })?; + let Some(providers) = root.as_object() else { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "The model price table is not a map of providers", + )); + }; + let mut table = PriceTable::default(); + for (provider_id, provider) in providers { + let Some(models) = provider.get("models").and_then(Value::as_object) else { + continue; + }; + let mut prices = HashMap::new(); + for (model_id, model) in models { + if let Some(price) = model.get("cost").and_then(price) { + prices.insert(model_id.clone(), price); + } + } + if !prices.is_empty() { + table.prices.insert(provider_id.clone(), prices); + } + } + table.index_models(); + Ok(table) + } + + /// The price of `model` from `provider`. Without a provider, the model's + /// price when every provider that lists it charges the same; otherwise + /// the call cannot be priced. + pub fn lookup(&self, provider: Option<&str>, model: &str) -> Option<&Price> { + let provider = match provider { + Some(provider) => provider, + None => self.by_model.get(model)?.as_deref()?, + }; + self.prices.get(provider)?.get(model) + } + + /// Models with a price, counted once per provider. + pub fn len(&self) -> usize { + self.prices.values().map(HashMap::len).sum() + } + + /// Whether the table has no prices. + pub fn is_empty(&self) -> bool { + self.prices.is_empty() + } + + fn index_models(&mut self) { + let mut providers: Vec<&String> = self.prices.keys().collect(); + providers.sort(); + let mut by_model: HashMap> = HashMap::new(); + for provider in providers { + for (model, price) in &self.prices[provider] { + match by_model.get(model) { + None => { + by_model.insert(model.clone(), Some(provider.clone())); + } + Some(Some(first)) if &self.prices[first][model] != price => { + by_model.insert(model.clone(), None); + } + Some(_) => {} + } + } + } + self.by_model = by_model; + } +} + +/// What a call would cost, or `None` without its input or output count. +pub fn call_cost(price: &Price, tokens: &Tokens) -> Option { + let input = tokens.input?; + let output = tokens.output?; + let cache_read = tokens.cache_read.unwrap_or(0); + let write_5m = tokens.cache_write_5m.unwrap_or(0); + let write_1h = tokens.cache_write_1h.unwrap_or(0); + let prompt = input + .saturating_add(cache_read) + .saturating_add(write_5m) + .saturating_add(write_1h); + let rates = price.rates_for(prompt); + let mut approximate = false; + let mut substitute = |count: u64, rate: Option, exact: bool| -> f64 { + if count == 0 { + return 0.0; + } + match rate { + Some(rate) => { + approximate |= !exact; + count as f64 * rate + } + None => { + approximate = true; + count as f64 * rates.input + } + } + }; + let mut micro_usd = input as f64 * rates.input; + micro_usd += match (tokens.reasoning, rates.reasoning) { + (Some(reasoning), Some(rate)) => { + output.saturating_sub(reasoning) as f64 * rates.output + reasoning as f64 * rate + } + _ => output as f64 * rates.output, + }; + micro_usd += substitute(cache_read, rates.cache_read, true); + micro_usd += substitute(write_5m, rates.cache_write, true); + micro_usd += substitute(write_1h, rates.cache_write, false); + Some(CallCost { + usd: micro_usd / 1_000_000.0, + approximate, + }) +} + +fn price(cost: &Value) -> Option { + let base = rates(cost)?; + let mut tiers = Vec::new(); + if let Some(rates) = cost.get("context_over_200k").and_then(rates) { + tiers.push(Tier { + above_prompt_tokens: CONTEXT_OVER_200K_TOKENS, + rates, + }); + } + for tier in cost + .get("tiers") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let Some(kind) = tier.get("tier") else { + continue; + }; + if kind.get("type").and_then(Value::as_str) != Some("context") { + continue; + } + let (Some(size), Some(rates)) = (kind.get("size").and_then(Value::as_u64), rates(tier)) + else { + continue; + }; + tiers.push(Tier { + above_prompt_tokens: size, + rates, + }); + } + tiers.sort_by_key(|tier| tier.above_prompt_tokens); + tiers.dedup_by_key(|tier| tier.above_prompt_tokens); + Some(Price { base, tiers }) +} + +fn rates(cost: &Value) -> Option { + Some(Rates { + input: rate(cost, "input")?, + output: rate(cost, "output")?, + reasoning: rate(cost, "reasoning"), + cache_read: rate(cost, "cache_read"), + cache_write: rate(cost, "cache_write"), + }) +} + +fn rate(cost: &Value, field: &str) -> Option { + cost.get(field) + .and_then(Value::as_f64) + .filter(|rate| rate.is_finite() && *rate >= 0.0) +} diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs new file mode 100644 index 00000000..4bf2fb9d --- /dev/null +++ b/rust/crates/agent-sessions/src/stats.rs @@ -0,0 +1,440 @@ +//! Statistics of calls: token totals, cache hit rate, cost and output speed. +//! +//! Every client shows these numbers from here, so they have one definition: +//! +//! - token totals add the counts calls report, leaving absent counts out; +//! - the cache hit rate is cache reads over all input (uncached input, cache +//! reads and cache writes), over the calls that report cache counts; +//! - cost is what the tokens would cost at API prices ([`CostBasis`]); calls +//! without a price are counted apart, never as free; +//! - speed is output tokens per second after the first token; without the +//! time of the first token, a long call gives a lower bound. + +use std::collections::BTreeMap; + +use serde::Serialize; + +use crate::model::CallRecord; +use crate::pricing::{call_cost, PriceTable}; +use crate::store::CallEntry; + +/// Fastest plausible output; faster measurements come from bad timestamps. +pub const MAX_TOKENS_PER_SECOND: f64 = 10_000.0; + +/// Fewest output tokens of a call that a speed ranking uses: shorter answers +/// are dominated by latency. +pub const MIN_RANKED_OUTPUT_TOKENS: u64 = 100; + +/// Fewest output tokens and milliseconds a call without a first-token time +/// needs for its overall rate to say something about speed. +const MIN_LOWER_BOUND_OUTPUT_TOKENS: u64 = 1000; +const MIN_LOWER_BOUND_DURATION_MS: u64 = 1000; + +const MILLISECONDS_PER_DAY: i64 = 86_400_000; + +/// How [`summarize`] groups calls. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GroupBy { + /// By calendar day of the start time, at a UTC offset in seconds (east is + /// positive). + Day { + /// The offset of the user's time zone. + utc_offset_seconds: i32, + }, + /// By agent. + Agent, + /// By the model that answered, or the requested one when the answer did + /// not name it. + Model, + /// By session. + Session, + /// By the working directory of the session. + Cwd, +} + +/// The group a [`Summary`] covers. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum GroupKey { + /// A calendar day, as `YYYY-MM-DD`. + Day { + /// The date. + date: String, + }, + /// An agent. + Agent { + /// The agent. + agent: String, + }, + /// A model; absent for calls that name none. + Model { + /// The model. + #[serde(skip_serializing_if = "Option::is_none")] + model: Option, + }, + /// A session of an agent. + #[serde(rename_all = "camelCase")] + Session { + /// The agent. + agent: String, + /// The session. + session_id: String, + }, + /// A working directory; absent for sessions that do not record it. + Cwd { + /// The directory. + #[serde(skip_serializing_if = "Option::is_none")] + cwd: Option, + }, +} + +/// Sums of the token counts calls report. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TokenTotals { + /// Uncached input tokens. + pub input: u64, + /// Output tokens, reasoning included. + pub output: u64, + /// Input tokens read from the prompt cache. + pub cache_read: u64, + /// Input tokens written to five-minute cache entries. + pub cache_write_5m: u64, + /// Input tokens written to one-hour cache entries. + pub cache_write_1h: u64, + /// Reasoning tokens, where agents record them. + pub reasoning: u64, +} + +/// What a cost stands for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum CostBasis { + /// The tokens priced at the provider's API prices, whatever the user + /// actually pays; a subscription is not billed per call. + ApiPriceEquivalent, +} + +/// The cost of a group of calls. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CostTotal { + /// US dollars, over the priced calls. + pub usd: f64, + /// What `usd` stands for. + pub basis: CostBasis, + /// Calls with a price. + pub priced_calls: u64, + /// Calls without a price or without input and output counts; `usd` leaves + /// them out. + pub unpriced_calls: u64, + /// Priced calls with a count priced at a substitute (see + /// [`CallCost::approximate`](crate::pricing::CallCost::approximate)). + pub approximate_calls: u64, +} + +/// Statistics of one group of calls. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Summary { + /// The group. + pub key: GroupKey, + /// Calls in the group. + pub calls: u64, + /// Calls that failed. + pub failed_calls: u64, + /// Calls the agent made to compact its context. + pub compaction_calls: u64, + /// Token totals. + pub tokens: TokenTotals, + /// Cache reads over all input of the calls that report cache counts, or + /// `None` when none does. + #[serde(skip_serializing_if = "Option::is_none")] + pub cache_hit_rate: Option, + /// The cost at API prices, when a price table was given. + #[serde(skip_serializing_if = "Option::is_none")] + pub cost: Option, + /// The start of the first call, in Unix milliseconds. + pub first_started_at_ms: i64, + /// The start of the last call, in Unix milliseconds. + pub last_started_at_ms: i64, +} + +/// Adds calls into groups one at a time, so a large history never has to be +/// in memory at once. +#[derive(Debug)] +pub struct Summarizer<'a> { + group_by: GroupBy, + prices: Option<&'a PriceTable>, + groups: BTreeMap, +} + +#[derive(Debug)] +struct Accumulator { + summary: Summary, + cache_read: u64, + cache_input: u64, +} + +impl<'a> Summarizer<'a> { + /// Groups calls by `group_by`, pricing them with `prices` when given. + pub fn new(group_by: GroupBy, prices: Option<&'a PriceTable>) -> Self { + Self { + group_by, + prices, + groups: BTreeMap::new(), + } + } + + /// Adds a call. + pub fn add(&mut self, entry: &CallEntry) { + let call = &entry.call; + let key = group_key(self.group_by, entry); + let accumulator = self + .groups + .entry(key.clone()) + .or_insert_with(|| Accumulator { + summary: Summary { + key, + calls: 0, + failed_calls: 0, + compaction_calls: 0, + tokens: TokenTotals::default(), + cache_hit_rate: None, + cost: self.prices.map(|_| CostTotal { + usd: 0.0, + basis: CostBasis::ApiPriceEquivalent, + priced_calls: 0, + unpriced_calls: 0, + approximate_calls: 0, + }), + first_started_at_ms: call.started_at_ms, + last_started_at_ms: call.started_at_ms, + }, + cache_read: 0, + cache_input: 0, + }); + let summary = &mut accumulator.summary; + summary.calls += 1; + summary.failed_calls += u64::from(call.error_category.is_some()); + summary.compaction_calls += u64::from(call.compaction); + summary.first_started_at_ms = summary.first_started_at_ms.min(call.started_at_ms); + summary.last_started_at_ms = summary.last_started_at_ms.max(call.started_at_ms); + + let tokens = &call.tokens; + let totals = &mut summary.tokens; + for (total, count) in [ + (&mut totals.input, tokens.input), + (&mut totals.output, tokens.output), + (&mut totals.cache_read, tokens.cache_read), + (&mut totals.cache_write_5m, tokens.cache_write_5m), + (&mut totals.cache_write_1h, tokens.cache_write_1h), + (&mut totals.reasoning, tokens.reasoning), + ] { + *total = total.saturating_add(count.unwrap_or(0)); + } + if tokens.reports_cache() { + let read = tokens.cache_read.unwrap_or(0); + accumulator.cache_read = accumulator.cache_read.saturating_add(read); + accumulator.cache_input = [ + tokens.input, + Some(read), + tokens.cache_write_5m, + tokens.cache_write_1h, + ] + .into_iter() + .flatten() + .fold(accumulator.cache_input, u64::saturating_add); + } + + if let (Some(prices), Some(cost)) = (self.prices, summary.cost.as_mut()) { + let priced = model_name(call) + .and_then(|model| prices.lookup(call.provider.as_deref(), model)) + .and_then(|price| call_cost(price, tokens)); + match priced { + Some(priced) => { + cost.usd += priced.usd; + cost.priced_calls += 1; + cost.approximate_calls += u64::from(priced.approximate); + } + None => cost.unpriced_calls += 1, + } + } + } + + /// The groups, in order of their keys. + pub fn finish(self) -> Vec { + self.groups + .into_values() + .map(|accumulator| { + let mut summary = accumulator.summary; + summary.cache_hit_rate = (accumulator.cache_input > 0) + .then(|| accumulator.cache_read as f64 / accumulator.cache_input as f64); + summary + }) + .collect() + } +} + +/// Groups `entries` by `group_by`; see [`Summarizer`]. +pub fn summarize<'e>( + entries: impl IntoIterator, + group_by: GroupBy, + prices: Option<&PriceTable>, +) -> Vec { + let mut summarizer = Summarizer::new(group_by, prices); + for entry in entries { + summarizer.add(entry); + } + summarizer.finish() +} + +/// The output speed of a call, in tokens per second. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", tag = "kind", content = "tokensPerSecond")] +pub enum Speed { + /// Output tokens over the time from the first token to the last. + Measured(f64), + /// Output tokens over the whole call, the wait for the first token + /// included: the actual speed is at least this. + AtLeast(f64), +} + +impl Speed { + /// The tokens per second. + pub fn tokens_per_second(self) -> f64 { + match self { + Speed::Measured(speed) | Speed::AtLeast(speed) => speed, + } + } +} + +/// The speed of a call, or `None` when it failed, lacks the counts, or its +/// timing says nothing reliable. +pub fn call_speed(call: &CallRecord) -> Option { + if call.error_category.is_some() { + return None; + } + let output = call.tokens.output.filter(|output| *output > 0)?; + let duration = call.duration_ms?; + let speed = match call.first_token_ms { + Some(first) if duration > first => Speed::Measured(per_second(output, duration - first)), + _ if output >= MIN_LOWER_BOUND_OUTPUT_TOKENS && duration >= MIN_LOWER_BOUND_DURATION_MS => { + Speed::AtLeast(per_second(output, duration)) + } + _ => return None, + }; + (speed.tokens_per_second() <= MAX_TOKENS_PER_SECOND).then_some(speed) +} + +/// The median speed of a model. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpeedRank { + /// The model that answered, or the requested one. + pub model: String, + /// Calls the median covers. + pub calls: u64, + /// The median, in tokens per second. + pub median_tokens_per_second: f64, + /// Whether a lower bound is among the speeds, so the median may be low. + pub lower_bound: bool, +} + +/// Ranks models by median speed, fastest first, over calls with at least +/// [`MIN_RANKED_OUTPUT_TOKENS`] output tokens and a speed. +pub fn rank_speed<'c>(calls: impl IntoIterator) -> Vec { + let mut by_model: BTreeMap<&str, (Vec, bool)> = BTreeMap::new(); + for call in calls { + if call.tokens.output.unwrap_or(0) < MIN_RANKED_OUTPUT_TOKENS { + continue; + } + let (Some(model), Some(speed)) = (model_name(call), call_speed(call)) else { + continue; + }; + let (speeds, lower_bound) = by_model.entry(model).or_default(); + speeds.push(speed.tokens_per_second()); + *lower_bound |= matches!(speed, Speed::AtLeast(_)); + } + let mut ranks: Vec = by_model + .into_iter() + .map(|(model, (mut speeds, lower_bound))| SpeedRank { + model: model.to_string(), + calls: speeds.len() as u64, + median_tokens_per_second: median(&mut speeds), + lower_bound, + }) + .collect(); + ranks.sort_by(|left, right| { + right + .median_tokens_per_second + .total_cmp(&left.median_tokens_per_second) + .then_with(|| left.model.cmp(&right.model)) + }); + ranks +} + +/// The model a call is counted under: the one that answered, or the one asked +/// for when the answer did not name it. +pub fn model_name(call: &CallRecord) -> Option<&str> { + call.model.as_deref().or(call.requested_model.as_deref()) +} + +/// The median of non-empty `values`; the mean of the middle two for an even count. +fn median(values: &mut [f64]) -> f64 { + values.sort_by(f64::total_cmp); + let middle = values.len() / 2; + if values.len().is_multiple_of(2) { + (values[middle - 1] + values[middle]) / 2.0 + } else { + values[middle] + } +} + +fn per_second(tokens: u64, milliseconds: u64) -> f64 { + tokens as f64 * 1000.0 / milliseconds as f64 +} + +fn group_key(group_by: GroupBy, entry: &CallEntry) -> GroupKey { + match group_by { + GroupBy::Day { utc_offset_seconds } => GroupKey::Day { + date: civil_date(entry.call.started_at_ms, utc_offset_seconds), + }, + GroupBy::Agent => GroupKey::Agent { + agent: entry.agent.clone(), + }, + GroupBy::Model => GroupKey::Model { + model: model_name(&entry.call).map(str::to_string), + }, + GroupBy::Session => GroupKey::Session { + agent: entry.agent.clone(), + session_id: entry.call.session_id.clone(), + }, + GroupBy::Cwd => GroupKey::Cwd { + cwd: entry.cwd.clone(), + }, + } +} + +/// The calendar date, as `YYYY-MM-DD`, of `at_ms` at a UTC offset. +pub(crate) fn civil_date(at_ms: i64, utc_offset_seconds: i32) -> String { + let local_ms = at_ms.saturating_add(i64::from(utc_offset_seconds) * 1000); + let days = local_ms.div_euclid(MILLISECONDS_PER_DAY); + // Days since 1970-01-01 to a proleptic Gregorian date, counting in + // 400-year eras that start on March 1st so leap days end each year. + let shifted = days + 719_468; + let era = shifted.div_euclid(146_097); + let day_of_era = shifted.rem_euclid(146_097); + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_index = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_index + 2) / 5 + 1; + let month = if month_index < 10 { + month_index + 3 + } else { + month_index - 9 + }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs new file mode 100644 index 00000000..f884264b --- /dev/null +++ b/rust/crates/agent-sessions/src/store.rs @@ -0,0 +1,1385 @@ +//! The SQLite cache of session records. +//! +//! Rows are kept per source file: a file's calls, sessions and indexed spans +//! are dropped together when the file is rewritten, deleted or no longer +//! listed, and read again from it. Queries remove the copies a session file +//! copied from another one (an agent that resumes or forks a session can copy +//! its history), so dropping one file never loses a call another file also +//! records, and a cache rebuilt from scratch answers the same. +//! +//! The database holds no conversation text. Parsers return text only in +//! [`IndexSpan::text`], which becomes index terms here; the full-text table +//! is contentless and stores no positions. Identifiers and labels must be +//! ASCII without spaces, so a sentence cannot be stored in them. + +use std::fs::{self, File}; +use std::io::{self, BufReader, Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use lithe_protocol::{cancellation, CoreError, ErrorCode}; +use rusqlite::{params, Connection, OptionalExtension, Row, Transaction}; +use serde::Serialize; + +use crate::ingest::{self, ChunkLimits, Cursor, FileStamp, Plan}; +use crate::model::{ + ByteRange, CallRecord, IndexSpan, ScanChunk, ScanOutput, SessionParser, Tokens, +}; +use crate::text; + +/// Version of the database layout. A cache of another version is deleted and +/// rebuilt from the session files, so it is never migrated. +pub const SCHEMA_VERSION: u32 = 1; + +/// Longest identifier, in bytes: agent, session, call, thread and request IDs. +pub const MAX_ID_BYTES: usize = 256; + +/// Longest label, in bytes: model, provider, effort, context window, error +/// category and agent version. +pub const MAX_LABEL_BYTES: usize = 256; + +/// Longest working directory, in bytes. +const MAX_CWD_BYTES: usize = 4096; + +/// Largest parser state, as JSON, kept with a file's cursor. +pub const MAX_STATE_BYTES: usize = 64 * 1024; + +/// Bytes of an indexed span's text that are split into terms; the rest is not +/// searchable. +pub const MAX_INDEXED_SPAN_BYTES: usize = 256 * 1024; + +/// Most sessions, calls and spans together that one chunk may produce. +pub const MAX_RECORDS_PER_CHUNK: usize = 100_000; + +/// Most hits one search returns. +pub const MAX_SEARCH_HITS: usize = 200; + +/// Most sessions one page of [`SessionStore::sessions`] lists. +pub const MAX_SESSIONS_PAGE: usize = 500; + +/// Most bytes [`SessionStore::read_range`] returns at once. +pub const MAX_READ_BYTES: u64 = 16 * 1024 * 1024; + +/// Most failed files a [`SyncReport`] names; it counts the rest. +const MAX_REPORTED_FAILURES: usize = 32; + +/// How long a write waits for another connection, for example a second Lithe +/// window syncing the same cache. +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); + +const DATABASE_PREFIX: &str = "agent-sessions-v"; + +const READ_BUFFER_BYTES: usize = 64 * 1024; + +/// File name of the database in the cache directory. It carries +/// [`SCHEMA_VERSION`], so a Lithe of another version uses its own file. +pub fn database_file_name() -> String { + format!("{DATABASE_PREFIX}{SCHEMA_VERSION}.sqlite3") +} + +const SCHEMA: &str = " +CREATE TABLE files ( + id INTEGER PRIMARY KEY, + agent TEXT NOT NULL, + path TEXT NOT NULL, + cursor_offset INTEGER NOT NULL, + stamp_size INTEGER, + stamp_modified_ms INTEGER, + fingerprint BLOB NOT NULL, + state TEXT, + UNIQUE (agent, path) +) STRICT; + +CREATE TABLE sessions ( + file_id INTEGER NOT NULL, + session_id TEXT NOT NULL, + described INTEGER NOT NULL, + parent_session_id TEXT, + cwd TEXT, + started_at_ms INTEGER, + updated_at_ms INTEGER, + agent_version TEXT, + title_start INTEGER, + title_end INTEGER, + PRIMARY KEY (file_id, session_id) +) STRICT, WITHOUT ROWID; +CREATE INDEX sessions_by_id ON sessions (session_id); + +CREATE TABLE calls ( + file_id INTEGER NOT NULL, + call_key TEXT NOT NULL, + session_id TEXT NOT NULL, + thread_id TEXT, + started_at_ms INTEGER NOT NULL, + requested_model TEXT, + model TEXT, + context_window TEXT, + effort TEXT, + provider TEXT, + input_tokens INTEGER, + output_tokens INTEGER, + cache_read_tokens INTEGER, + cache_write_5m_tokens INTEGER, + cache_write_1h_tokens INTEGER, + reasoning_tokens INTEGER, + first_token_ms INTEGER, + duration_ms INTEGER, + compaction INTEGER NOT NULL, + request_id TEXT, + error_category TEXT, + range_start INTEGER NOT NULL, + range_end INTEGER NOT NULL, + PRIMARY KEY (file_id, call_key) +) STRICT, WITHOUT ROWID; +CREATE INDEX calls_by_key ON calls (call_key); + +CREATE TABLE spans ( + id INTEGER PRIMARY KEY, + file_id INTEGER NOT NULL, + session_id TEXT NOT NULL, + at_ms INTEGER, + range_start INTEGER NOT NULL, + range_end INTEGER NOT NULL +) STRICT; +CREATE INDEX spans_by_file ON spans (file_id); + +-- Terms only: no content, no positions. The rowid is the span's id. +CREATE VIRTUAL TABLE span_terms USING fts5 ( + terms, + tokenize = 'ascii', + content = '', + contentless_delete = 1, + detail = 'none' +); +"; + +/// The local cache of session records. +pub struct SessionStore { + connection: Connection, + pub(crate) limits: ChunkLimits, +} + +/// What one [`SessionStore::sync_agent`] did. +#[derive(Debug, Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SyncReport { + /// Distinct files the sync was given. + pub files_listed: u64, + /// Files with the size and modification time of their last full read. + pub files_unchanged: u64, + /// Files read, from the start or from where the last sync stopped. + pub files_read: u64, + /// Files that had changed and were read again from the start. + pub files_restarted: u64, + /// Files no longer listed or no longer on disk, whose records were dropped. + pub files_removed: u64, + /// Files that could not be read or parsed. Their cursor stays where it + /// was, so the next sync tries the same bytes again. + pub files_failed: u64, + /// The first failed files, at most 32. + pub failures: Vec, + /// Bytes read from session files. + pub bytes_read: u64, + /// Lines skipped for being longer than + /// [`MAX_LINE_BYTES`](crate::MAX_LINE_BYTES). + pub skipped_lines: u64, + /// Session descriptions written. + pub sessions: u64, + /// Calls written, copies included. + pub calls: u64, + /// Indexed spans written. + pub spans: u64, +} + +/// A file a sync could not read or parse. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileFailure { + /// The file. + pub path: PathBuf, + /// Why: for example [`ErrorCode::ParseFailed`] for invalid parser output. + pub code: ErrorCode, +} + +/// Which calls [`SessionStore::for_each_call`] visits. Empty and absent +/// fields do not filter. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CallFilter { + /// Agents to include; empty includes every agent. + pub agents: Vec, + /// Only calls of this session. + pub session_id: Option, + /// Only calls that started at or after this time, in Unix milliseconds. + pub since_ms: Option, + /// Only calls that started before this time, in Unix milliseconds. + pub until_ms: Option, +} + +/// A call with what the statistics group it by. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CallEntry { + /// The agent whose session recorded the call. + pub agent: String, + /// The session file the call was read from. + pub path: String, + /// The working directory of the call's session, when known. + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// The call. + pub call: CallRecord, +} + +/// Which sessions [`SessionStore::sessions`] lists. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SessionFilter { + /// Agents to include; empty includes every agent. + pub agents: Vec, + /// Only sessions that ran in this working directory. + pub cwd: Option, + /// Only sessions last active at or after this time, in Unix milliseconds. + pub active_since_ms: Option, + /// Sessions to skip, for the next page. + pub offset: u64, + /// Sessions to list, at most [`MAX_SESSIONS_PAGE`]. + pub limit: usize, +} + +/// A session, merged from every file that describes it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionEntry { + /// The agent that ran the session. + pub agent: String, + /// The session, in the agent's own ID format. + pub session_id: String, + /// The file the other fields come from: the first, by path, of the files + /// that describe the session, or of those that only mention it. + pub path: String, + /// Files that mention the session. + pub file_count: u64, + /// The session this one was resumed or forked from. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_session_id: Option, + /// The working directory the agent ran in. + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// The earliest start any file records. + #[serde(skip_serializing_if = "Option::is_none")] + pub started_at_ms: Option, + /// The latest change any file records. + #[serde(skip_serializing_if = "Option::is_none")] + pub updated_at_ms: Option, + /// The version of the agent CLI that wrote `path`. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_version: Option, + /// The bytes of `path` that hold the title. + #[serde(skip_serializing_if = "Option::is_none")] + pub title_range: Option, +} + +/// A full-text search. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SearchQuery { + /// Words to find; a span matches when it contains every term of them. + /// Words of a spaced script also match as prefixes of longer words. + pub text: String, + /// Agents to include; empty includes every agent. + pub agents: Vec, + /// Only spans of this session. + pub session_id: Option, + /// Hits to return, at most [`MAX_SEARCH_HITS`]. + pub limit: usize, +} + +/// Where a search found its terms. The text is read again from `path` with +/// [`SessionStore::read_range`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchHit { + /// The agent whose session holds the text. + pub agent: String, + /// The session file. + pub path: String, + /// The session the text belongs to. + pub session_id: String, + /// When the text was written, when the parser knew. + #[serde(skip_serializing_if = "Option::is_none")] + pub at_ms: Option, + /// The bytes of `path` the span covers. + pub range: ByteRange, +} + +/// How a failure while syncing one file affects the rest of the sync. +enum SyncFailure { + /// The file could not be read or parsed; the sync goes on with the next. + File(CoreError), + /// The cache could not be written, or the operation was cancelled. + Abort(CoreError), +} + +impl From for SyncFailure { + fn from(error: CoreError) -> Self { + SyncFailure::File(error) + } +} + +/// A file the cache has read, as its row holds it. +struct KnownFile { + id: i64, + cursor: Cursor, + state: Option, +} + +enum OpenFailure { + /// The file is not a cache of this version; delete it and start again. + Rebuild, + Failed(CoreError), +} + +impl SessionStore { + /// Opens the cache in `cache_dir`, which must be in the platform's caches + /// directory, never in the application bundle. Caches of other schema + /// versions in it are deleted, and so is a damaged cache. + pub fn open(cache_dir: &Path) -> Result { + fs::create_dir_all(cache_dir).map_err(|error| { + io_error("Could not create the agent session cache directory", error) + })?; + remove_other_versions(cache_dir)?; + let path = cache_dir.join(database_file_name()); + let connection = match open_database(&path) { + Ok(connection) => connection, + Err(OpenFailure::Rebuild) => { + remove_database(&path)?; + match open_database(&path) { + Ok(connection) => connection, + Err(OpenFailure::Rebuild) => { + return Err(CoreError::new( + ErrorCode::Unknown, + "Could not rebuild the agent session cache", + )) + } + Err(OpenFailure::Failed(error)) => return Err(error), + } + } + Err(OpenFailure::Failed(error)) => return Err(error), + }; + Ok(Self { + connection, + limits: ChunkLimits::default(), + }) + } + + /// Brings the records of `agent` up to date with `files`, its session + /// files as [`discover`](crate::discover) listed them. Files of the agent + /// that are not listed any more are dropped. A file that fails is counted + /// in the report and the sync goes on; cancellation and cache write + /// failures stop it, keeping what was written so far. + pub fn sync_agent( + &mut self, + agent: &str, + files: &[PathBuf], + parser: &mut dyn SessionParser, + ) -> Result { + check_caller_id("agent", agent)?; + let mut report = SyncReport::default(); + let mut listed: Vec<(&str, &Path)> = Vec::with_capacity(files.len()); + for path in files { + match path.to_str() { + Some(text) => listed.push((text, path.as_path())), + None => report.record_failure(path, ErrorCode::InvalidRequest), + } + } + listed.sort_unstable_by(|left, right| left.0.cmp(right.0)); + listed.dedup_by(|left, right| left.0 == right.0); + report.files_listed = listed.len() as u64; + + let known = self.known_files(agent)?; + let transaction = self.transaction()?; + for (id, path) in &known { + if listed + .binary_search_by(|(text, _)| (*text).cmp(path.as_str())) + .is_err() + { + forget_file(&transaction, *id)?; + report.files_removed += 1; + } + } + commit(transaction)?; + + for (text, path) in listed { + cancellation::check()?; + match self.sync_file(agent, text, path, parser, &mut report) { + Ok(()) => {} + Err(SyncFailure::File(error)) => report.record_failure(path, error.code), + Err(SyncFailure::Abort(error)) => return Err(error), + } + } + Ok(report) + } + + /// Drops every record of `agent`, for example when its plugin is removed + /// or the user withdraws access to its sessions. Returns the files dropped. + pub fn remove_agent(&mut self, agent: &str) -> Result { + check_caller_id("agent", agent)?; + let known = self.known_files(agent)?; + let transaction = self.transaction()?; + for (id, _) in &known { + forget_file(&transaction, *id)?; + } + commit(transaction)?; + Ok(known.len() as u64) + } + + /// Visits the calls `filter` selects, each once, in order of start time. + /// A call recorded in several files is visited as its copy in the first + /// file by path. Returns the calls visited. + pub fn for_each_call( + &self, + filter: &CallFilter, + mut visit: impl FnMut(CallEntry) -> Result<(), CoreError>, + ) -> Result { + const SQL: &str = " + WITH ranked AS ( + SELECT f.agent, f.path, c.*, + ROW_NUMBER() OVER ( + PARTITION BY f.agent, c.call_key + ORDER BY f.path, c.range_start + ) AS copy_rank + FROM calls c JOIN files f ON f.id = c.file_id + WHERE json_array_length(?1) = 0 + OR f.agent IN (SELECT value FROM json_each(?1)) + ) + SELECT r.agent, r.path, + COALESCE( + (SELECT s.cwd FROM sessions s + WHERE s.file_id = r.file_id AND s.session_id = r.session_id), + (SELECT s.cwd FROM sessions s JOIN files sf ON sf.id = s.file_id + WHERE s.session_id = r.session_id AND sf.agent = r.agent + AND s.cwd IS NOT NULL + ORDER BY sf.path LIMIT 1)), + r.call_key, r.session_id, r.thread_id, r.started_at_ms, + r.requested_model, r.model, r.context_window, r.effort, r.provider, + r.input_tokens, r.output_tokens, r.cache_read_tokens, + r.cache_write_5m_tokens, r.cache_write_1h_tokens, r.reasoning_tokens, + r.first_token_ms, r.duration_ms, r.compaction, r.request_id, + r.error_category, r.range_start, r.range_end + FROM ranked r + WHERE r.copy_rank = 1 + AND (?2 IS NULL OR r.session_id = ?2) + AND (?3 IS NULL OR r.started_at_ms >= ?3) + AND (?4 IS NULL OR r.started_at_ms < ?4) + ORDER BY r.started_at_ms, r.agent, r.call_key"; + let mut statement = self + .connection + .prepare_cached(SQL) + .map_err(|error| sql_error("Could not query agent calls", error))?; + let mut rows = statement + .query(params![ + agents_json(&filter.agents)?, + filter.session_id, + filter.since_ms, + filter.until_ms + ]) + .map_err(|error| sql_error("Could not query agent calls", error))?; + let mut visited = 0; + while let Some(row) = rows + .next() + .map_err(|error| sql_error("Could not query agent calls", error))? + { + cancellation::check()?; + let entry = + call_entry(row).map_err(|error| sql_error("Could not query agent calls", error))?; + visit(entry)?; + visited += 1; + } + Ok(visited) + } + + /// Lists sessions, most recently active first. + pub fn sessions(&self, filter: &SessionFilter) -> Result, CoreError> { + const SQL: &str = " + WITH ranked AS ( + SELECT f.agent, f.path, s.*, + ROW_NUMBER() OVER ( + PARTITION BY f.agent, s.session_id + ORDER BY s.described DESC, f.path + ) AS copy_rank, + COUNT(*) OVER whole AS file_count, + MIN(s.started_at_ms) OVER whole AS first_started_ms, + MAX(s.updated_at_ms) OVER whole AS last_updated_ms + FROM sessions s JOIN files f ON f.id = s.file_id + WHERE json_array_length(?1) = 0 + OR f.agent IN (SELECT value FROM json_each(?1)) + WINDOW whole AS (PARTITION BY f.agent, s.session_id) + ) + SELECT agent, session_id, path, file_count, parent_session_id, cwd, + first_started_ms, last_updated_ms, agent_version, title_start, title_end + FROM ranked + WHERE copy_rank = 1 + AND (?2 IS NULL OR cwd = ?2) + AND (?3 IS NULL OR COALESCE(last_updated_ms, first_started_ms) >= ?3) + ORDER BY COALESCE(last_updated_ms, first_started_ms) DESC NULLS LAST, + agent, session_id + LIMIT ?4 OFFSET ?5"; + let limit = filter.limit.min(MAX_SESSIONS_PAGE); + let mut statement = self + .connection + .prepare_cached(SQL) + .map_err(|error| sql_error("Could not list agent sessions", error))?; + let rows = statement + .query_map( + params![ + agents_json(&filter.agents)?, + filter.cwd, + filter.active_since_ms, + limit, + filter.offset + ], + |row| { + Ok(SessionEntry { + agent: row.get(0)?, + session_id: row.get(1)?, + path: row.get(2)?, + file_count: row.get(3)?, + parent_session_id: row.get(4)?, + cwd: row.get(5)?, + started_at_ms: row.get(6)?, + updated_at_ms: row.get(7)?, + agent_version: row.get(8)?, + title_range: optional_range(row.get(9)?, row.get(10)?), + }) + }, + ) + .map_err(|error| sql_error("Could not list agent sessions", error))?; + rows.collect::, _>>() + .map_err(|error| sql_error("Could not list agent sessions", error)) + } + + /// Finds the spans that contain every term of `query.text`, newest first. + /// A query without letters or digits finds nothing. + pub fn search(&self, query: &SearchQuery) -> Result, CoreError> { + const SQL: &str = " + SELECT f.agent, f.path, s.session_id, s.at_ms, s.range_start, s.range_end + FROM span_terms + JOIN spans s ON s.id = span_terms.rowid + JOIN files f ON f.id = s.file_id + WHERE span_terms MATCH ?1 + AND (json_array_length(?2) = 0 + OR f.agent IN (SELECT value FROM json_each(?2))) + AND (?3 IS NULL OR s.session_id = ?3) + ORDER BY s.at_ms DESC NULLS LAST, f.path, s.range_start + LIMIT ?4"; + let Some(expression) = text::match_expression(&query.text) else { + return Ok(Vec::new()); + }; + let limit = query.limit.min(MAX_SEARCH_HITS); + let mut statement = self + .connection + .prepare_cached(SQL) + .map_err(|error| sql_error("Could not search agent sessions", error))?; + let rows = statement + .query_map( + params![ + expression, + agents_json(&query.agents)?, + query.session_id, + limit + ], + |row| { + Ok(SearchHit { + agent: row.get(0)?, + path: row.get(1)?, + session_id: row.get(2)?, + at_ms: row.get(3)?, + range: ByteRange { + start: row.get(4)?, + end: row.get(5)?, + }, + }) + }, + ) + .map_err(|error| sql_error("Could not search agent sessions", error))?; + rows.collect::, _>>() + .map_err(|error| sql_error("Could not search agent sessions", error)) + } + + /// Reads `range` of a session file of `agent` the cache has read. Returns + /// `None` when the file is gone or changed since, so the range may no + /// longer hold what the record says; a sync brings the records up to date. + pub fn read_range( + &self, + agent: &str, + path: &str, + range: ByteRange, + ) -> Result>, CoreError> { + check_caller_id("agent", agent)?; + let Some(known) = self.known_file(agent, path)? else { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The agent session cache has not read this file", + )); + }; + if range.start >= range.end + || range.end > known.cursor.offset + || range.end - range.start > MAX_READ_BYTES + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The byte range is outside what the cache has read of the file", + )); + } + let mut file = match File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(io_error("Could not open an agent session file", error)), + }; + let size = file.metadata().map_err(ingest::read_failed)?.len(); + if size < known.cursor.offset + || ingest::fingerprint(&mut file, known.cursor.offset).map_err(ingest::read_failed)? + != known.cursor.fingerprint + { + return Ok(None); + } + file.seek(SeekFrom::Start(range.start)) + .map_err(ingest::read_failed)?; + let mut bytes = vec![0; usize::try_from(range.end - range.start).unwrap_or(usize::MAX)]; + file.read_exact(&mut bytes).map_err(ingest::read_failed)?; + Ok(Some(bytes)) + } + + fn sync_file( + &mut self, + agent: &str, + path_text: &str, + path: &Path, + parser: &mut dyn SessionParser, + report: &mut SyncReport, + ) -> Result<(), SyncFailure> { + let known = self + .known_file(agent, path_text) + .map_err(SyncFailure::Abort)?; + let mut file = match File::open(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // Deleted after it was listed: the same as not listed. + if let Some(known) = known { + let transaction = self.transaction().map_err(SyncFailure::Abort)?; + forget_file(&transaction, known.id).map_err(SyncFailure::Abort)?; + commit(transaction).map_err(SyncFailure::Abort)?; + report.files_removed += 1; + } + return Ok(()); + } + Err(error) => { + return Err(io_error("Could not open an agent session file", error).into()) + } + }; + let metadata = file.metadata().map_err(ingest::read_failed)?; + if !metadata.is_file() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "An agent session path is not a regular file", + ) + .into()); + } + let stamp = FileStamp::of(&metadata); + let plan = ingest::plan(&mut file, stamp, known.as_ref().map(|known| &known.cursor)) + .map_err(ingest::read_failed)?; + let (file_id, start, mut state) = match (plan, known) { + (Plan::Unchanged, _) => { + report.files_unchanged += 1; + return Ok(()); + } + (Plan::Append { offset }, Some(known)) => (known.id, offset, known.state), + (_, known) => { + let empty = ingest::fingerprint(&mut file, 0).map_err(ingest::read_failed)?; + let restarted = known.is_some(); + let id = self + .restart_file(agent, path_text, known.map(|known| known.id), &empty) + .map_err(SyncFailure::Abort)?; + if restarted { + report.files_restarted += 1; + } + (id, 0, None) + } + }; + report.files_read += 1; + + let mut reader = File::open(path).map_err(ingest::read_failed)?; + reader + .seek(SeekFrom::Start(start)) + .map_err(ingest::read_failed)?; + let mut reader = BufReader::with_capacity(READ_BUFFER_BYTES, reader); + // Read up to the size the stamp records, so a file that grows during + // the pass is read on from there next time. + let limit = stamp.size - start; + let limits = self.limits; + let connection = &mut self.connection; + let progress = ingest::read_lines(&mut reader, start, limit, limits, |offset, bytes| { + cancellation::check().map_err(SyncFailure::Abort)?; + let output = parser.scan(ScanChunk { + path, + offset, + bytes, + state: state.as_ref(), + })?; + let end = offset + bytes.len() as u64; + let output = validate(output, offset, end)?; + let fingerprint = ingest::fingerprint(&mut file, end).map_err(ingest::read_failed)?; + let state_json = state_json(output.state.as_ref())?; + write_chunk(connection, file_id, &output, report) + .and_then(|transaction| { + update_cursor( + &transaction, + file_id, + end, + &fingerprint, + state_json.as_deref(), + None, + )?; + commit(transaction) + }) + .map_err(SyncFailure::Abort)?; + state = output.state; + Ok::<(), SyncFailure>(()) + })?; + report.bytes_read += progress.bytes_read; + report.skipped_lines += progress.skipped_lines; + + // The stamp is stored only when the pass reached the size it records; + // otherwise the file shrank meanwhile and the next sync checks it. + let finished = (progress.bytes_read == limit).then_some(stamp); + let fingerprint = + ingest::fingerprint(&mut file, progress.end).map_err(ingest::read_failed)?; + let state_json = state_json(state.as_ref())?; + let transaction = self.transaction().map_err(SyncFailure::Abort)?; + update_cursor( + &transaction, + file_id, + progress.end, + &fingerprint, + state_json.as_deref(), + finished, + ) + .map_err(SyncFailure::Abort)?; + commit(transaction).map_err(SyncFailure::Abort) + } + + /// Drops the records of a file and resets its cursor, or adds the file. + fn restart_file( + &mut self, + agent: &str, + path: &str, + known_id: Option, + empty_fingerprint: &[u8], + ) -> Result { + let transaction = self.transaction()?; + let id = match known_id { + Some(id) => { + clear_file(&transaction, id)?; + update_cursor(&transaction, id, 0, empty_fingerprint, None, None)?; + id + } + None => transaction + .query_row( + "INSERT INTO files (agent, path, cursor_offset, fingerprint) + VALUES (?1, ?2, 0, ?3) RETURNING id", + params![agent, path, empty_fingerprint], + |row| row.get(0), + ) + .map_err(|error| sql_error("Could not write the agent session cache", error))?, + }; + commit(transaction)?; + Ok(id) + } + + fn known_files(&self, agent: &str) -> Result, CoreError> { + let mut statement = self + .connection + .prepare_cached("SELECT id, path FROM files WHERE agent = ?1") + .map_err(|error| sql_error("Could not read the agent session cache", error))?; + let rows = statement + .query_map([agent], |row| Ok((row.get(0)?, row.get(1)?))) + .map_err(|error| sql_error("Could not read the agent session cache", error))?; + rows.collect::, _>>() + .map_err(|error| sql_error("Could not read the agent session cache", error)) + } + + fn known_file(&self, agent: &str, path: &str) -> Result, CoreError> { + let row = self + .connection + .query_row( + "SELECT id, cursor_offset, stamp_size, stamp_modified_ms, fingerprint, state + FROM files WHERE agent = ?1 AND path = ?2", + params![agent, path], + |row| { + let stamp_size: Option = row.get(2)?; + let stamp_modified_ms: Option = row.get(3)?; + Ok(( + row.get::<_, i64>(0)?, + Cursor { + offset: row.get(1)?, + stamp: stamp_size + .zip(stamp_modified_ms) + .map(|(size, modified_ms)| FileStamp { size, modified_ms }), + fingerprint: row.get(4)?, + }, + row.get::<_, Option>(5)?, + )) + }, + ) + .optional() + .map_err(|error| sql_error("Could not read the agent session cache", error))?; + let Some((id, cursor, state)) = row else { + return Ok(None); + }; + let state = match state { + Some(state) => Some(serde_json::from_str(&state).map_err(|_| { + CoreError::new(ErrorCode::Unknown, "The agent session cache is damaged") + })?), + None => None, + }; + Ok(Some(KnownFile { id, cursor, state })) + } + + fn transaction(&mut self) -> Result, CoreError> { + self.connection + .transaction() + .map_err(|error| sql_error("Could not write the agent session cache", error)) + } +} + +impl SyncReport { + fn record_failure(&mut self, path: &Path, code: ErrorCode) { + self.files_failed += 1; + if self.failures.len() < MAX_REPORTED_FAILURES { + self.failures.push(FileFailure { + path: path.to_path_buf(), + code, + }); + } + } +} + +fn open_database(path: &Path) -> Result { + let connection = Connection::open(path).map_err(open_failure)?; + connection + .busy_timeout(BUSY_TIMEOUT) + .map_err(open_failure)?; + let version: u32 = connection + .pragma_query_value(None, "user_version", |row| row.get(0)) + .map_err(open_failure)?; + connection + .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get::<_, String>(0)) + .map_err(open_failure)?; + connection + .pragma_update(None, "synchronous", "NORMAL") + .map_err(open_failure)?; + match version { + SCHEMA_VERSION => Ok(connection), + 0 => { + // The schema and its version are written in one transaction, so + // a cache without the version has none of the tables either. + connection + .execute_batch(&format!( + "BEGIN; {SCHEMA} PRAGMA user_version = {SCHEMA_VERSION}; COMMIT;" + )) + .map_err(|_| OpenFailure::Rebuild)?; + Ok(connection) + } + _ => Err(OpenFailure::Rebuild), + } +} + +fn open_failure(error: rusqlite::Error) -> OpenFailure { + match error.sqlite_error_code() { + Some(rusqlite::ErrorCode::NotADatabase | rusqlite::ErrorCode::DatabaseCorrupt) => { + OpenFailure::Rebuild + } + _ => OpenFailure::Failed(sql_error("Could not open the agent session cache", error)), + } +} + +fn remove_database(path: &Path) -> Result<(), CoreError> { + let name = database_file_name(); + for suffix in ["", "-wal", "-shm", "-journal"] { + remove_if_present(&path.with_file_name(format!("{name}{suffix}")))?; + } + Ok(()) +} + +/// Deletes the caches of other schema versions in `cache_dir`. +fn remove_other_versions(cache_dir: &Path) -> Result<(), CoreError> { + let current = database_file_name(); + let entries = fs::read_dir(cache_dir) + .map_err(|error| io_error("Could not list the agent session cache directory", error))?; + for entry in entries { + let entry = entry + .map_err(|error| io_error("Could not list the agent session cache directory", error))?; + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + if name.starts_with(DATABASE_PREFIX) && !name.starts_with(¤t) { + match fs::remove_file(entry.path()) { + Ok(()) => {} + // Another Lithe of that version may still have it open, which + // Windows does not allow deleting. It uses its own file, so + // leaving it until a later start is harmless. + Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => { + return Err(io_error( + "Could not delete an old agent session cache", + error, + )) + } + } + } + } + Ok(()) +} + +fn remove_if_present(path: &Path) -> Result<(), CoreError> { + match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_error("Could not delete the agent session cache", error)), + } +} + +fn commit(transaction: Transaction<'_>) -> Result<(), CoreError> { + transaction + .commit() + .map_err(|error| sql_error("Could not write the agent session cache", error)) +} + +/// Drops the records of a file and the file itself. +fn forget_file(transaction: &Transaction<'_>, file_id: i64) -> Result<(), CoreError> { + clear_file(transaction, file_id)?; + transaction + .execute("DELETE FROM files WHERE id = ?1", [file_id]) + .map_err(|error| sql_error("Could not write the agent session cache", error))?; + Ok(()) +} + +/// Drops the records of a file, keeping its row. +fn clear_file(transaction: &Transaction<'_>, file_id: i64) -> Result<(), CoreError> { + let write = + |error: rusqlite::Error| sql_error("Could not write the agent session cache", error); + { + // Rows of a contentless index are deleted by rowid one at a time; a + // scan of the index cannot select them. + let mut spans = transaction + .prepare_cached("SELECT id FROM spans WHERE file_id = ?1") + .map_err(write)?; + let ids = spans + .query_map([file_id], |row| row.get::<_, i64>(0)) + .map_err(write)? + .collect::, _>>() + .map_err(write)?; + let mut delete = transaction + .prepare_cached("DELETE FROM span_terms WHERE rowid = ?1") + .map_err(write)?; + for id in ids { + delete.execute([id]).map_err(write)?; + } + } + for table in ["spans", "calls", "sessions"] { + transaction + .execute( + &format!("DELETE FROM {table} WHERE file_id = ?1"), + [file_id], + ) + .map_err(write)?; + } + Ok(()) +} + +fn update_cursor( + transaction: &Transaction<'_>, + file_id: i64, + offset: u64, + fingerprint: &[u8], + state: Option<&str>, + stamp: Option, +) -> Result<(), CoreError> { + transaction + .prepare_cached( + "UPDATE files SET cursor_offset = ?2, fingerprint = ?3, state = ?4, + stamp_size = ?5, stamp_modified_ms = ?6 + WHERE id = ?1", + ) + .and_then(|mut statement| { + statement.execute(params![ + file_id, + offset, + fingerprint, + state, + stamp.map(|stamp| stamp.size), + stamp.map(|stamp| stamp.modified_ms) + ]) + }) + .map_err(|error| sql_error("Could not write the agent session cache", error))?; + Ok(()) +} + +/// Writes the records of one chunk in a transaction the caller commits +/// together with the file's cursor. +fn write_chunk<'a>( + connection: &'a mut Connection, + file_id: i64, + output: &ScanOutput, + report: &mut SyncReport, +) -> Result, CoreError> { + let write = + |error: rusqlite::Error| sql_error("Could not write the agent session cache", error); + let transaction = connection.transaction().map_err(write)?; + { + let mut describe = transaction + .prepare_cached( + "INSERT INTO sessions (file_id, session_id, described, parent_session_id, cwd, + started_at_ms, updated_at_ms, agent_version, + title_start, title_end) + VALUES (?1, ?2, 1, ?3, ?4, ?5, ?6, ?7, ?8, ?9) + ON CONFLICT (file_id, session_id) DO UPDATE SET + described = 1, + parent_session_id = COALESCE(excluded.parent_session_id, parent_session_id), + cwd = COALESCE(excluded.cwd, cwd), + started_at_ms = COALESCE(excluded.started_at_ms, started_at_ms), + updated_at_ms = COALESCE(excluded.updated_at_ms, updated_at_ms), + agent_version = COALESCE(excluded.agent_version, agent_version), + title_start = COALESCE(excluded.title_start, title_start), + title_end = CASE WHEN excluded.title_start IS NULL + THEN title_end ELSE excluded.title_end END", + ) + .map_err(write)?; + for session in &output.sessions { + describe + .execute(params![ + file_id, + session.session_id, + session.parent_session_id, + session.cwd, + session.started_at_ms, + session.updated_at_ms, + session.agent_version, + session.title_range.map(|range| range.start), + session.title_range.map(|range| range.end) + ]) + .map_err(write)?; + report.sessions += 1; + } + + let mut mention = transaction + .prepare_cached( + "INSERT INTO sessions (file_id, session_id, described) VALUES (?1, ?2, 0) + ON CONFLICT (file_id, session_id) DO NOTHING", + ) + .map_err(write)?; + let mut call = transaction + .prepare_cached( + "INSERT OR REPLACE INTO calls ( + file_id, call_key, session_id, thread_id, started_at_ms, + requested_model, model, context_window, effort, provider, + input_tokens, output_tokens, cache_read_tokens, + cache_write_5m_tokens, cache_write_1h_tokens, reasoning_tokens, + first_token_ms, duration_ms, compaction, request_id, error_category, + range_start, range_end) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, + ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23)", + ) + .map_err(write)?; + for record in &output.calls { + mention + .execute(params![file_id, record.session_id]) + .map_err(write)?; + let tokens = &record.tokens; + call.execute(params![ + file_id, + record.key, + record.session_id, + record.thread_id, + record.started_at_ms, + record.requested_model, + record.model, + record.context_window, + record.effort, + record.provider, + tokens.input, + tokens.output, + tokens.cache_read, + tokens.cache_write_5m, + tokens.cache_write_1h, + tokens.reasoning, + record.first_token_ms, + record.duration_ms, + record.compaction, + record.request_id, + record.error_category, + record.range.start, + record.range.end + ]) + .map_err(write)?; + report.calls += 1; + } + + let mut span = transaction + .prepare_cached( + "INSERT INTO spans (file_id, session_id, at_ms, range_start, range_end) + VALUES (?1, ?2, ?3, ?4, ?5)", + ) + .map_err(write)?; + let mut terms = transaction + .prepare_cached("INSERT INTO span_terms (rowid, terms) VALUES (?1, ?2)") + .map_err(write)?; + for indexed in &output.spans { + let indexed_terms = text::index_terms(indexed_prefix(indexed)); + if indexed_terms.is_empty() { + continue; + } + mention + .execute(params![file_id, indexed.session_id]) + .map_err(write)?; + span.execute(params![ + file_id, + indexed.session_id, + indexed.at_ms, + indexed.range.start, + indexed.range.end + ]) + .map_err(write)?; + terms + .execute(params![transaction.last_insert_rowid(), indexed_terms]) + .map_err(write)?; + report.spans += 1; + } + } + Ok(transaction) +} + +/// The part of a span's text that is indexed, cut at a character boundary. +fn indexed_prefix(span: &IndexSpan) -> &str { + let text = span.text.as_str(); + if text.len() <= MAX_INDEXED_SPAN_BYTES { + return text; + } + let mut end = MAX_INDEXED_SPAN_BYTES; + while !text.is_char_boundary(end) { + end -= 1; + } + &text[..end] +} + +fn state_json(state: Option<&serde_json::Value>) -> Result, CoreError> { + let Some(state) = state else { + return Ok(None); + }; + let json = serde_json::to_string(state).map_err(|_| invalid_output("state is not JSON"))?; + if json.len() > MAX_STATE_BYTES { + return Err(invalid_output("state is too large")); + } + Ok(Some(json)) +} + +/// Checks the records of a chunk that spans `[start, end)` of its file. +fn validate(output: ScanOutput, start: u64, end: u64) -> Result { + if output.sessions.len() + output.calls.len() + output.spans.len() > MAX_RECORDS_PER_CHUNK { + return Err(invalid_output("a chunk produced too many records")); + } + let in_chunk = + |range: ByteRange| range.start < range.end && start <= range.start && range.end <= end; + for session in &output.sessions { + check_id(&session.session_id, "sessions[].sessionId")?; + check_optional_id( + session.parent_session_id.as_deref(), + "sessions[].parentSessionId", + )?; + check_optional_label(session.agent_version.as_deref(), "sessions[].agentVersion")?; + if let Some(cwd) = &session.cwd { + if cwd.is_empty() || cwd.len() > MAX_CWD_BYTES || cwd.chars().any(char::is_control) { + return Err(invalid_output("sessions[].cwd is not a directory path")); + } + } + if session.title_range.is_some_and(|range| !in_chunk(range)) { + return Err(invalid_output("sessions[].titleRange is outside the chunk")); + } + } + for call in &output.calls { + check_id(&call.key, "calls[].key")?; + check_id(&call.session_id, "calls[].sessionId")?; + check_optional_id(call.thread_id.as_deref(), "calls[].threadId")?; + check_optional_id(call.request_id.as_deref(), "calls[].requestId")?; + for (label, field) in [ + (&call.requested_model, "calls[].requestedModel"), + (&call.model, "calls[].model"), + (&call.context_window, "calls[].contextWindow"), + (&call.effort, "calls[].effort"), + (&call.provider, "calls[].provider"), + (&call.error_category, "calls[].errorCategory"), + ] { + check_optional_label(label.as_deref(), field)?; + } + check_tokens(&call.tokens)?; + if call.first_token_ms.is_some_and(too_large) || call.duration_ms.is_some_and(too_large) { + return Err(invalid_output("calls[] has a time out of range")); + } + if !in_chunk(call.range) { + return Err(invalid_output("calls[].range is outside the chunk")); + } + } + for span in &output.spans { + check_id(&span.session_id, "spans[].sessionId")?; + if !in_chunk(span.range) { + return Err(invalid_output("spans[].range is outside the chunk")); + } + } + Ok(output) +} + +fn check_tokens(tokens: &Tokens) -> Result<(), CoreError> { + let counts = [ + tokens.input, + tokens.output, + tokens.cache_read, + tokens.cache_write_5m, + tokens.cache_write_1h, + tokens.reasoning, + ]; + if counts.into_iter().flatten().any(too_large) { + return Err(invalid_output("calls[].tokens has a count out of range")); + } + if let (Some(reasoning), Some(output)) = (tokens.reasoning, tokens.output) { + if reasoning > output { + return Err(invalid_output( + "calls[].tokens.reasoning is more than calls[].tokens.output", + )); + } + } + Ok(()) +} + +fn too_large(value: u64) -> bool { + i64::try_from(value).is_err() +} + +fn check_id(value: &str, field: &str) -> Result<(), CoreError> { + if is_token(value, MAX_ID_BYTES) { + Ok(()) + } else { + Err(invalid_output(&format!("{field} is not an identifier"))) + } +} + +fn check_optional_id(value: Option<&str>, field: &str) -> Result<(), CoreError> { + value.map_or(Ok(()), |value| check_id(value, field)) +} + +fn check_optional_label(value: Option<&str>, field: &str) -> Result<(), CoreError> { + match value { + Some(value) if !is_token(value, MAX_LABEL_BYTES) => { + Err(invalid_output(&format!("{field} is not a label"))) + } + _ => Ok(()), + } +} + +/// Checks an identifier a caller passed, such as an agent ID. +fn check_caller_id(field: &str, value: &str) -> Result<(), CoreError> { + if is_token(value, MAX_ID_BYTES) { + Ok(()) + } else { + Err(CoreError::new( + ErrorCode::InvalidRequest, + format!("The {field} is not an identifier"), + )) + } +} + +/// Non-empty printable ASCII without spaces, at most `max_bytes` long. +fn is_token(value: &str, max_bytes: usize) -> bool { + !value.is_empty() + && value.len() <= max_bytes + && value.bytes().all(|byte| byte.is_ascii_graphic()) +} + +/// `field` names the record field, never its value: the value may be text the +/// parser should not have returned. +fn invalid_output(field: &str) -> CoreError { + CoreError::new( + ErrorCode::ParseFailed, + "An agent plugin returned an invalid session record", + ) + .with_details(field.to_string()) +} + +fn agents_json(agents: &[String]) -> Result { + serde_json::to_string(agents) + .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "The agent filter is not valid")) +} + +fn optional_range(start: Option, end: Option) -> Option { + start.zip(end).map(|(start, end)| ByteRange { start, end }) +} + +fn call_entry(row: &Row<'_>) -> rusqlite::Result { + Ok(CallEntry { + agent: row.get(0)?, + path: row.get(1)?, + cwd: row.get(2)?, + call: CallRecord { + key: row.get(3)?, + session_id: row.get(4)?, + thread_id: row.get(5)?, + started_at_ms: row.get(6)?, + requested_model: row.get(7)?, + model: row.get(8)?, + context_window: row.get(9)?, + effort: row.get(10)?, + provider: row.get(11)?, + tokens: Tokens { + input: row.get(12)?, + output: row.get(13)?, + cache_read: row.get(14)?, + cache_write_5m: row.get(15)?, + cache_write_1h: row.get(16)?, + reasoning: row.get(17)?, + }, + first_token_ms: row.get(18)?, + duration_ms: row.get(19)?, + compaction: row.get(20)?, + request_id: row.get(21)?, + error_category: row.get(22)?, + range: ByteRange { + start: row.get(23)?, + end: row.get(24)?, + }, + }, + }) +} + +/// An I/O failure, without the path: the caller knows which file it asked for. +pub(crate) fn io_error(message: &str, error: io::Error) -> CoreError { + let code = match error.kind() { + io::ErrorKind::PermissionDenied => ErrorCode::PermissionDenied, + _ => ErrorCode::Unknown, + }; + CoreError::new(code, message).with_details(error.to_string()) +} + +/// A SQLite failure. SQLite's own message can quote a statement or a value, +/// so only its result code is kept. +fn sql_error(message: &str, error: rusqlite::Error) -> CoreError { + let details = match &error { + rusqlite::Error::SqliteFailure(failure, _) + | rusqlite::Error::SqlInputError { error: failure, .. } => { + format!( + "SQLite result code {} ({:?})", + failure.extended_code, failure.code + ) + } + _ => "SQLite access failed".to_string(), + }; + CoreError::new(ErrorCode::Unknown, message).with_details(details) +} diff --git a/rust/crates/agent-sessions/src/tests/discover.rs b/rust/crates/agent-sessions/src/tests/discover.rs new file mode 100644 index 00000000..f5f80f9f --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/discover.rs @@ -0,0 +1,100 @@ +//! Listing the session files a source matches. + +use std::fs; +use std::path::Path; + +use lithe_protocol::ErrorCode; + +use super::TempDir; +use crate::discover::{discover, Discovery, SessionSource}; + +fn tree() -> TempDir { + let dir = TempDir::new("discover"); + for file in ["a.jsonl", "b.txt", "sub/c.jsonl", "sub/deep/d.jsonl"] { + let path = dir.path().join(file); + fs::create_dir_all(path.parent().expect("a parent directory")).expect("create a directory"); + fs::write(&path, b"{}\n").expect("write a file"); + } + dir +} + +fn source(root: &Path, include: &[&str]) -> SessionSource { + SessionSource { + root: root.to_path_buf(), + include: include.iter().map(|pattern| pattern.to_string()).collect(), + } +} + +/// The files `include` lists, relative to the root, with `/` separators. +fn listed(dir: &TempDir, include: &[&str]) -> Vec { + let discovery = discover(&source(dir.path(), include)).expect("list the files"); + assert!(!discovery.truncated); + assert_eq!(discovery.unreadable_entries, 0); + discovery + .files + .iter() + .map(|path| { + path.strip_prefix(dir.path()) + .expect("a file below the root") + .components() + .map(|component| component.as_os_str().to_str().expect("a Unicode name")) + .collect::>() + .join("/") + }) + .collect() +} + +#[test] +fn patterns_match_paths_below_the_root() { + let dir = tree(); + assert_eq!(listed(&dir, &["*.jsonl"]), ["a.jsonl"]); + assert_eq!( + listed(&dir, &["**/*.jsonl"]), + ["a.jsonl", "sub/c.jsonl", "sub/deep/d.jsonl"] + ); + assert_eq!(listed(&dir, &["sub/*.jsonl"]), ["sub/c.jsonl"]); + assert_eq!( + listed(&dir, &["*.txt", "sub/deep/*"]), + ["b.txt", "sub/deep/d.jsonl"] + ); + // Directories are not files to read. + assert_eq!(listed(&dir, &["*"]), ["a.jsonl", "b.txt"]); + assert!(listed(&dir, &[]).is_empty()); +} + +#[test] +fn a_missing_root_lists_nothing() { + let dir = TempDir::new("discover-missing"); + let discovery = + discover(&source(&dir.path().join("never-written"), &["**/*"])).expect("list the files"); + assert_eq!(discovery, Discovery::default()); +} + +#[test] +fn an_invalid_pattern_is_refused() { + let dir = tree(); + for root in [dir.path().to_path_buf(), dir.path().join("never-written")] { + let error = discover(&source(&root, &["*.jsonl", "a["])).expect_err("an invalid pattern"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } +} + +#[cfg(unix)] +#[test] +fn symbolic_links_are_not_followed() { + use std::os::unix::fs::symlink; + + let dir = tree(); + let outside = TempDir::new("discover-outside"); + fs::write(outside.path().join("x.jsonl"), b"{}\n").expect("write a file"); + symlink(outside.path(), dir.path().join("linked-dir")).expect("link a directory"); + symlink( + outside.path().join("x.jsonl"), + dir.path().join("linked.jsonl"), + ) + .expect("link a file"); + assert_eq!( + listed(&dir, &["**/*.jsonl"]), + ["a.jsonl", "sub/c.jsonl", "sub/deep/d.jsonl"] + ); +} diff --git a/rust/crates/agent-sessions/src/tests/mod.rs b/rust/crates/agent-sessions/src/tests/mod.rs new file mode 100644 index 00000000..eb6ce69f --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/mod.rs @@ -0,0 +1,184 @@ +//! Tests of the session cache, with a synthetic agent whose session files are +//! JSON lines. The format belongs to no real agent: Core knows none. + +mod discover; +mod pricing; +mod stats; +mod store; +mod text; + +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::{json, Value}; + +use crate::model::{ + ByteRange, CallRecord, IndexSpan, ScanChunk, ScanOutput, SessionMeta, SessionParser, Tokens, +}; + +/// A directory removed when the test ends. +pub(crate) struct TempDir(PathBuf); + +impl TempDir { + pub(crate) fn new(prefix: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-agent-sessions {prefix} {} {}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + // A crashed earlier run with the same process ID may have left it. + if path.exists() { + fs::remove_dir_all(&path).expect("remove a stale temporary directory"); + } + fs::create_dir_all(&path).expect("create a temporary directory"); + Self(path) + } + + pub(crate) fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + eprintln!("could not remove {}: {error}", self.0.display()); + } + } +} + +/// Parses the synthetic format: one JSON object per line, with a `type` of +/// `session`, `use`, `call` or `text`. Calls and texts belong to the last +/// `session` or `use` line, which the parser carries across chunks in its +/// state. +#[derive(Default)] +pub(crate) struct LinesParser { + /// Fails any chunk that contains this text. + pub(crate) fail_on: Option<&'static str>, + /// Chunks scanned. + pub(crate) chunks: u64, +} + +impl SessionParser for LinesParser { + fn scan(&mut self, chunk: ScanChunk<'_>) -> Result { + self.chunks += 1; + let mut session = chunk + .state + .and_then(|state| state.get("session")) + .and_then(Value::as_str) + .map(str::to_string); + let mut output = ScanOutput::default(); + let mut position = chunk.offset; + for line in chunk.bytes.split_inclusive(|byte| *byte == b'\n') { + assert!(line.ends_with(b"\n"), "a chunk holds whole lines"); + let range = ByteRange { + start: position, + end: position + line.len() as u64, + }; + position = range.end; + if let Some(needle) = self.fail_on { + if String::from_utf8_lossy(line).contains(needle) { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "test parser failure", + )); + } + } + let Ok(value) = serde_json::from_slice::(line) else { + continue; + }; + let text = |field: &str| value.get(field).and_then(Value::as_str).map(str::to_string); + let number = |field: &str| value.get(field).and_then(Value::as_u64); + match value.get("type").and_then(Value::as_str) { + Some("session") => { + let id = text("id").expect("session id"); + session = Some(id.clone()); + output.sessions.push(SessionMeta { + session_id: id, + parent_session_id: text("parent"), + cwd: text("cwd"), + started_at_ms: value.get("at").and_then(Value::as_i64), + updated_at_ms: value.get("at").and_then(Value::as_i64), + agent_version: text("version"), + title_range: value.get("title").map(|_| range), + }); + } + // Continues a session without describing it, as a file that + // carries on another file's session does. + Some("use") => session = Some(text("id").expect("session id")), + Some("call") => output.calls.push(CallRecord { + key: text("key").expect("call key"), + session_id: session.clone().expect("a session line first"), + thread_id: None, + started_at_ms: value.get("at").and_then(Value::as_i64).expect("call time"), + requested_model: text("requested"), + model: text("model"), + context_window: None, + effort: None, + provider: text("provider"), + tokens: Tokens { + input: number("input"), + output: number("output"), + cache_read: number("cacheRead"), + cache_write_5m: number("cacheWrite5m"), + cache_write_1h: number("cacheWrite1h"), + reasoning: number("reasoning"), + }, + first_token_ms: number("firstTokenMs"), + duration_ms: number("durationMs"), + compaction: false, + request_id: None, + error_category: text("error"), + range: match value.get("badRange") { + Some(_) => ByteRange { + start: range.end + 10, + end: range.end + 20, + }, + None => range, + }, + }), + Some("text") => output.spans.push(IndexSpan { + session_id: session.clone().expect("a session line first"), + at_ms: value.get("at").and_then(Value::as_i64), + range, + text: text("text").expect("span text"), + }), + _ => {} + } + } + output.state = session.map(|session| json!({ "session": session })); + Ok(output) + } +} + +pub(crate) fn session_line(id: &str, cwd: &str, at: i64) -> String { + format!( + "{}\n", + json!({ "type": "session", "id": id, "cwd": cwd, "at": at, "title": true }) + ) +} + +pub(crate) fn call_line(key: &str, at: i64, model: &str, input: u64, output: u64) -> String { + format!( + "{}\n", + json!({ "type": "call", "key": key, "at": at, "model": model, "input": input, "output": output }) + ) +} + +pub(crate) fn text_line(at: i64, text: &str) -> String { + format!("{}\n", json!({ "type": "text", "at": at, "text": text })) +} + +pub(crate) fn append(path: &Path, text: &str) { + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(path) + .expect("open a session file"); + file.write_all(text.as_bytes()) + .expect("append to a session file"); +} diff --git a/rust/crates/agent-sessions/src/tests/pricing.rs b/rust/crates/agent-sessions/src/tests/pricing.rs new file mode 100644 index 00000000..8112e4a7 --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/pricing.rs @@ -0,0 +1,211 @@ +//! Prices from a models.dev table, and what calls cost at them. + +use lithe_protocol::ErrorCode; + +use crate::model::Tokens; +use crate::pricing::{call_cost, CallCost, Price, PriceTable, MAX_PRICE_TABLE_BYTES}; + +const TABLE: &str = r#"{ + "vendor-a": { + "name": "Vendor A", + "models": { + "shared": { "cost": { "input": 1, "output": 2 } }, + "split": { "cost": { "input": 1, "output": 2 } }, + "tiered": { + "cost": { + "input": 3, "output": 15, "cache_read": 0.3, "cache_write": 3.75, + "context_over_200k": { + "input": 6, "output": 22.5, "cache_read": 0.6, "cache_write": 7.5 + } + } + }, + "thinking": { "cost": { "input": 1, "output": 4, "reasoning": 8 } }, + "text-price": { "cost": { "input": "free", "output": 2 } }, + "negative": { "cost": { "input": -1, "output": 2 } }, + "no-cost": {} + } + }, + "vendor-b": { + "models": { + "shared": { "cost": { "input": 1, "output": 2 } }, + "split": { "cost": { "input": 5, "output": 2 } } + } + }, + "no-models": { "name": "Nothing priced" } +}"#; + +fn table() -> PriceTable { + PriceTable::from_models_dev(TABLE.as_bytes()).expect("read the price table") +} + +fn price<'t>(table: &'t PriceTable, model: &str) -> &'t Price { + table.lookup(None, model).expect("a price") +} + +fn tokens(input: u64, output: u64) -> Tokens { + Tokens { + input: Some(input), + output: Some(output), + ..Tokens::default() + } +} + +fn assert_cost(cost: Option, usd: f64, approximate: bool) { + let cost = cost.expect("a priced call"); + assert!((cost.usd - usd).abs() < 1e-12, "{} is not {usd}", cost.usd); + assert_eq!(cost.approximate, approximate); +} + +#[test] +fn models_without_a_valid_price_are_left_out() { + let table = table(); + assert_eq!(table.len(), 6); + assert!(!table.is_empty()); + for model in ["text-price", "negative", "no-cost"] { + assert!(table.lookup(Some("vendor-a"), model).is_none(), "{model}"); + } + assert!(PriceTable::from_models_dev(b"{}") + .expect("read the price table") + .is_empty()); +} + +#[test] +fn a_model_without_a_provider_needs_a_single_price() { + let table = table(); + assert_eq!( + table.lookup(None, "shared"), + table.lookup(Some("vendor-b"), "shared") + ); + assert!(table.lookup(None, "shared").is_some()); + // The providers charge differently, so the call cannot be priced. + assert!(table.lookup(None, "split").is_none()); + assert_eq!( + table + .lookup(Some("vendor-b"), "split") + .map(|price| price.base.input), + Some(5.0) + ); + assert!(table.lookup(None, "tiered").is_some()); + assert!(table.lookup(Some("vendor-c"), "shared").is_none()); + assert!(table.lookup(None, "unknown").is_none()); +} + +#[test] +fn cache_tokens_are_priced_at_their_rates() { + let table = table(); + let tiered = price(&table, "tiered"); + let mut used = Tokens { + cache_read: Some(10_000), + cache_write_5m: Some(1_000), + ..tokens(1_000, 2_000) + }; + // 1000 × 3 + 2000 × 15 + 10000 × 0.3 + 1000 × 3.75 millionths of a dollar. + assert_cost(call_cost(tiered, &used), 0.039_75, false); + // The table's one cache-write price is the five-minute one. + used.cache_write_1h = Some(1_000); + assert_cost(call_cost(tiered, &used), 0.043_5, true); +} + +#[test] +fn prompts_over_a_tier_use_its_rates() { + let table = table(); + let tiered = price(&table, "tiered"); + assert_eq!(tiered.tiers.len(), 1); + // A prompt of exactly the tier size is priced at the base rates. + assert_cost(call_cost(tiered, &tokens(200_000, 0)), 0.6, false); + // Cache reads count toward the prompt size: 150001 × 6 + 1000 × 22.5 + + // 50000 × 0.6. + let over = Tokens { + cache_read: Some(50_000), + ..tokens(150_001, 1_000) + }; + assert_cost(call_cost(tiered, &over), 0.952_506, false); +} + +#[test] +fn cache_tokens_without_a_cache_price_are_priced_as_input() { + let table = table(); + let shared = price(&table, "shared"); + let used = Tokens { + cache_read: Some(100), + cache_write_5m: Some(50), + ..tokens(10, 10) + }; + // (10 + 100 + 50) × 1 + 10 × 2. + assert_cost(call_cost(shared, &used), 0.000_18, true); + let none_cached = Tokens { + cache_read: Some(0), + ..tokens(10, 10) + }; + assert_cost(call_cost(shared, &none_cached), 0.000_03, false); +} + +#[test] +fn reasoning_is_priced_apart_when_the_table_prices_it() { + let table = table(); + let used = Tokens { + reasoning: Some(400), + ..tokens(0, 1_000) + }; + // 600 × 4 + 400 × 8. + assert_cost(call_cost(price(&table, "thinking"), &used), 0.005_6, false); + assert_cost( + call_cost(price(&table, "thinking"), &tokens(0, 1_000)), + 0.004, + false, + ); + assert_cost(call_cost(price(&table, "shared"), &used), 0.002, false); +} + +#[test] +fn a_call_without_input_or_output_is_not_priced() { + let table = table(); + let shared = price(&table, "shared"); + let output_only = Tokens { + output: Some(10), + ..Tokens::default() + }; + let input_only = Tokens { + input: Some(10), + ..Tokens::default() + }; + assert_eq!(call_cost(shared, &output_only), None); + assert_eq!(call_cost(shared, &input_only), None); +} + +#[test] +fn context_tiers_are_read_from_the_tier_list() { + let table = PriceTable::from_models_dev( + br#"{ "v": { "models": { "m": { "cost": { + "input": 1, "output": 2, + "tiers": [ + { "tier": { "type": "context", "size": 128000 }, "input": 2, "output": 4 }, + { "tier": { "type": "batch" }, "input": 0.5, "output": 1 }, + { "tier": { "type": "context", "size": 32000 }, "input": 1.5, "output": 3 }, + { "tier": { "type": "context" }, "input": 9, "output": 9 } + ] + } } } } }"#, + ) + .expect("read the price table"); + let price = price(&table, "m"); + let sizes: Vec = price + .tiers + .iter() + .map(|tier| tier.above_prompt_tokens) + .collect(); + assert_eq!(sizes, [32_000, 128_000]); + assert_eq!(price.rates_for(32_000).input, 1.0); + assert_eq!(price.rates_for(32_001).input, 1.5); + assert_eq!(price.rates_for(128_001).input, 2.0); +} + +#[test] +fn unreadable_tables_are_refused() { + let error = PriceTable::from_models_dev(b"{ not json").expect_err("invalid JSON"); + assert!(matches!(error.code, ErrorCode::ParseFailed)); + let error = PriceTable::from_models_dev(b"[]").expect_err("not a map of providers"); + assert!(matches!(error.code, ErrorCode::ParseFailed)); + let error = PriceTable::from_models_dev(&vec![b' '; MAX_PRICE_TABLE_BYTES + 1]) + .expect_err("a table too large"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); +} diff --git a/rust/crates/agent-sessions/src/tests/stats.rs b/rust/crates/agent-sessions/src/tests/stats.rs new file mode 100644 index 00000000..963e8e42 --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/stats.rs @@ -0,0 +1,335 @@ +//! Summaries, speeds and dates of calls. + +use crate::model::{ByteRange, CallRecord, Tokens}; +use crate::pricing::PriceTable; +use crate::stats::{ + call_speed, civil_date, rank_speed, summarize, CostBasis, CostTotal, GroupBy, GroupKey, Speed, + Summarizer, TokenTotals, +}; +use crate::store::CallEntry; + +const PRICES: &str = r#"{ "vendor": { "models": { + "m-a": { "cost": { "input": 1, "output": 2, "cache_read": 0.1, "cache_write": 1.25 } } +} } }"#; + +fn record(key: &str, at: i64) -> CallRecord { + CallRecord { + key: key.to_string(), + session_id: "s1".to_string(), + thread_id: None, + started_at_ms: at, + requested_model: None, + model: None, + context_window: None, + effort: None, + provider: None, + tokens: Tokens::default(), + first_token_ms: None, + duration_ms: None, + compaction: false, + request_id: None, + error_category: None, + range: ByteRange { start: 0, end: 1 }, + } +} + +fn entry(call: CallRecord) -> CallEntry { + CallEntry { + agent: "test-agent".to_string(), + path: "/sessions/a.jsonl".to_string(), + cwd: Some("/w".to_string()), + call, + } +} + +fn timed(model: &str, output: u64, first_token_ms: Option, duration_ms: u64) -> CallRecord { + CallRecord { + model: Some(model.to_string()), + tokens: Tokens { + output: Some(output), + ..Tokens::default() + }, + first_token_ms, + duration_ms: Some(duration_ms), + ..record("c", 0) + } +} + +fn model_of(key: &GroupKey) -> Option<&str> { + match key { + GroupKey::Model { model } => model.as_deref(), + other => panic!("not a model group: {other:?}"), + } +} + +#[test] +fn calls_are_summed_by_model() { + let prices = PriceTable::from_models_dev(PRICES.as_bytes()).expect("read the prices"); + let cached = CallRecord { + model: Some("m-a".to_string()), + tokens: Tokens { + input: Some(1_000), + output: Some(100), + cache_read: Some(10_000), + cache_write_5m: Some(1_000), + ..Tokens::default() + }, + compaction: true, + ..record("c1", 3_000) + }; + // Counted under the model asked for, as the answer named none; it reports + // no cache counts, so it is left out of the hit rate. + let requested = CallRecord { + requested_model: Some("m-a".to_string()), + tokens: Tokens { + input: Some(500), + output: Some(50), + ..Tokens::default() + }, + ..record("c2", 1_000) + }; + let failed = CallRecord { + model: Some("m-b".to_string()), + tokens: Tokens { + input: Some(10), + output: Some(10), + ..Tokens::default() + }, + error_category: Some("rate_limited".to_string()), + ..record("c3", 2_000) + }; + let unnamed = record("c4", 4_000); + let entries: Vec = [cached, requested, failed, unnamed] + .into_iter() + .map(entry) + .collect(); + + let summaries = summarize(&entries, GroupBy::Model, Some(&prices)); + let models: Vec> = summaries + .iter() + .map(|summary| model_of(&summary.key)) + .collect(); + assert_eq!(models, [None, Some("m-a"), Some("m-b")]); + + let unnamed = &summaries[0]; + assert_eq!(unnamed.calls, 1); + assert_eq!(unnamed.cache_hit_rate, None); + assert_eq!(unnamed.cost.map(|cost| cost.unpriced_calls), Some(1)); + + let priced = &summaries[1]; + assert_eq!( + (priced.calls, priced.failed_calls, priced.compaction_calls), + (2, 0, 1) + ); + assert_eq!( + priced.tokens, + TokenTotals { + input: 1_500, + output: 150, + cache_read: 10_000, + cache_write_5m: 1_000, + cache_write_1h: 0, + reasoning: 0, + } + ); + assert_eq!(priced.cache_hit_rate, Some(10_000.0 / 12_000.0)); + let cost = priced.cost.expect("a cost"); + // (1000 + 100 × 2 + 10000 × 0.1 + 1000 × 1.25) + (500 + 50 × 2) millionths. + assert!((cost.usd - 0.004_05).abs() < 1e-12, "{}", cost.usd); + assert_eq!( + CostTotal { usd: 0.0, ..cost }, + CostTotal { + usd: 0.0, + basis: CostBasis::ApiPriceEquivalent, + priced_calls: 2, + unpriced_calls: 0, + approximate_calls: 0, + } + ); + assert_eq!( + (priced.first_started_at_ms, priced.last_started_at_ms), + (1_000, 3_000) + ); + + let unpriced = &summaries[2]; + assert_eq!((unpriced.calls, unpriced.failed_calls), (1, 1)); + let cost = unpriced.cost.expect("a cost"); + assert_eq!( + (cost.usd, cost.priced_calls, cost.unpriced_calls), + (0.0, 0, 1) + ); + + // Without prices there is no cost at all, rather than a cost of zero. + let by_agent = summarize(&entries, GroupBy::Agent, None); + assert_eq!(by_agent.len(), 1); + assert_eq!( + by_agent[0].key, + GroupKey::Agent { + agent: "test-agent".to_string() + } + ); + assert_eq!(by_agent[0].calls, 4); + assert_eq!(by_agent[0].cost, None); + assert_eq!(by_agent[0].cache_hit_rate, Some(10_000.0 / 12_000.0)); +} + +#[test] +fn calls_group_by_session_and_directory() { + let mut elsewhere = entry(CallRecord { + session_id: "s2".to_string(), + ..record("c2", 0) + }); + elsewhere.cwd = None; + let entries = vec![entry(record("c1", 0)), elsewhere, entry(record("c3", 0))]; + + let sessions: Vec = summarize(&entries, GroupBy::Session, None) + .into_iter() + .map(|summary| summary.key) + .collect(); + let session = |id: &str| GroupKey::Session { + agent: "test-agent".to_string(), + session_id: id.to_string(), + }; + assert_eq!(sessions, [session("s1"), session("s2")]); + + let directories: Vec<(GroupKey, u64)> = summarize(&entries, GroupBy::Cwd, None) + .into_iter() + .map(|summary| (summary.key, summary.calls)) + .collect(); + assert_eq!( + directories, + [ + (GroupKey::Cwd { cwd: None }, 1), + ( + GroupKey::Cwd { + cwd: Some("/w".to_string()) + }, + 2 + ), + ] + ); +} + +#[test] +fn days_follow_the_user_time_zone() { + // 2026-11-24T20:00:00Z and 2026-11-25T02:00:00Z. + let entries = [ + entry(record("c1", 1_795_550_400_000)), + entry(record("c2", 1_795_572_000_000)), + ]; + let days = |utc_offset_seconds: i32| { + let mut summarizer = Summarizer::new(GroupBy::Day { utc_offset_seconds }, None); + for entry in &entries { + summarizer.add(entry); + } + summarizer + .finish() + .into_iter() + .map(|summary| match summary.key { + GroupKey::Day { date } => (date, summary.calls), + other => panic!("not a day: {other:?}"), + }) + .collect::>() + }; + let day = |date: &str, calls: u64| (date.to_string(), calls); + assert_eq!(days(0), [day("2026-11-24", 1), day("2026-11-25", 1)]); + assert_eq!(days(8 * 3_600), [day("2026-11-25", 2)]); + assert_eq!(days(-5 * 3_600), [day("2026-11-24", 2)]); +} + +#[test] +fn civil_dates_cover_leap_days_and_times_before_1970() { + assert_eq!(civil_date(0, 0), "1970-01-01"); + assert_eq!(civil_date(-1, 0), "1969-12-31"); + assert_eq!(civil_date(951_782_400_000, 0), "2000-02-29"); + assert_eq!(civil_date(946_684_799_000, 0), "1999-12-31"); + assert_eq!(civil_date(946_684_799_000, 1), "2000-01-01"); + // 2100 is not a leap year. + assert_eq!(civil_date(4_107_542_400_000, 0), "2100-03-01"); + assert_eq!(civil_date(4_107_542_400_000, -1), "2100-02-28"); +} + +#[test] +fn speed_is_measured_from_the_first_token() { + assert_eq!( + call_speed(&timed("m", 1_000, Some(500), 2_500)), + Some(Speed::Measured(500.0)) + ); + // Without a first-token time, a long enough call gives a lower bound. + assert_eq!( + call_speed(&timed("m", 1_000, None, 2_000)), + Some(Speed::AtLeast(500.0)) + ); + // So does a first token at the very end. + assert_eq!( + call_speed(&timed("m", 1_000, Some(2_000), 2_000)), + Some(Speed::AtLeast(500.0)) + ); + assert_eq!(call_speed(&timed("m", 999, None, 2_000)), None); + assert_eq!(call_speed(&timed("m", 1_000, None, 999)), None); +} + +#[test] +fn unreliable_speeds_are_left_out() { + let failed = CallRecord { + error_category: Some("overloaded".to_string()), + ..timed("m", 1_000, Some(500), 2_500) + }; + assert_eq!(call_speed(&failed), None); + assert_eq!(call_speed(&timed("m", 0, Some(0), 1_000)), None); + assert_eq!( + call_speed(&timed("m", 10_000, Some(0), 1_000)), + Some(Speed::Measured(10_000.0)) + ); + assert_eq!(call_speed(&timed("m", 10_001, Some(0), 1_000)), None); + let untimed = CallRecord { + duration_ms: None, + ..timed("m", 1_000, Some(500), 2_500) + }; + assert_eq!(call_speed(&untimed), None); +} + +#[test] +fn models_rank_by_median_speed() { + let calls = [ + timed("fast", 200, Some(0), 2_000), + timed("fast", 200, Some(0), 1_000), + timed("fast", 300, Some(0), 1_000), + timed("slow", 100, Some(0), 1_000), + timed("slow", 1_000, None, 10_000), + // Fast, but too short to rank. + timed("slow", 50, Some(0), 100), + CallRecord { + error_category: Some("overloaded".to_string()), + ..timed("broken", 1_000, Some(0), 1_000) + }, + ]; + let ranks: Vec<(String, u64, f64, bool)> = rank_speed(&calls) + .into_iter() + .map(|rank| { + ( + rank.model, + rank.calls, + rank.median_tokens_per_second, + rank.lower_bound, + ) + }) + .collect(); + assert_eq!( + ranks, + [ + ("fast".to_string(), 3, 200.0, false), + ("slow".to_string(), 2, 100.0, true), + ] + ); + + let tied = [ + timed("b", 100, Some(0), 1_000), + timed("a", 100, Some(0), 1_000), + ]; + let models: Vec = rank_speed(&tied) + .into_iter() + .map(|rank| rank.model) + .collect(); + assert_eq!(models, ["a", "b"]); +} diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs new file mode 100644 index 00000000..b370e209 --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -0,0 +1,826 @@ +//! Syncs, queries and the privacy of the cache. + +use std::fs; +use std::path::{Path, PathBuf}; + +use lithe_protocol::ErrorCode; +use serde_json::json; + +use super::{append, call_line, session_line, text_line, LinesParser, TempDir}; +use crate::ingest::ChunkLimits; +use crate::model::ByteRange; +use crate::store::{ + database_file_name, CallEntry, CallFilter, SearchHit, SearchQuery, SessionEntry, SessionFilter, + SessionStore, SyncReport, +}; +use crate::{MAX_CHUNK_BYTES, MAX_LINE_BYTES}; + +const AGENT: &str = "test-agent"; +const OTHER_AGENT: &str = "other-agent"; + +/// Every line in a chunk of its own. +const LINE_CHUNKS: ChunkLimits = ChunkLimits { + max_chunk_bytes: 1, + max_line_bytes: MAX_LINE_BYTES, +}; + +struct Fixture { + dir: TempDir, + store: SessionStore, +} + +impl Fixture { + fn new(prefix: &str) -> Self { + let dir = TempDir::new(prefix); + fs::create_dir_all(dir.path().join("sessions")).expect("create the sessions directory"); + let store = SessionStore::open(&dir.path().join("cache")).expect("open the cache"); + Self { dir, store } + } + + fn file(&self, name: &str) -> PathBuf { + self.dir.path().join("sessions").join(name) + } + + fn sync(&mut self, files: &[PathBuf]) -> SyncReport { + sync_as(&mut self.store, AGENT, files) + } + + fn calls(&self) -> Vec { + calls(&self.store, &CallFilter::default()) + } + + fn search(&self, text: &str) -> Vec { + search(&self.store, text, &[]) + } +} + +fn sync_as(store: &mut SessionStore, agent: &str, files: &[PathBuf]) -> SyncReport { + store + .sync_agent(agent, files, &mut LinesParser::default()) + .expect("sync the session files") +} + +fn calls(store: &SessionStore, filter: &CallFilter) -> Vec { + let mut entries = Vec::new(); + store + .for_each_call(filter, |entry| { + entries.push(entry); + Ok(()) + }) + .expect("query the calls"); + entries +} + +fn sessions(store: &SessionStore, filter: SessionFilter) -> Vec { + store.sessions(&filter).expect("list the sessions") +} + +fn every_session() -> SessionFilter { + SessionFilter { + limit: 100, + ..SessionFilter::default() + } +} + +fn search(store: &SessionStore, text: &str, agents: &[&str]) -> Vec { + store + .search(&SearchQuery { + text: text.to_string(), + agents: agents.iter().map(|agent| agent.to_string()).collect(), + session_id: None, + limit: 100, + }) + .expect("search the sessions") +} + +fn keys(entries: &[CallEntry]) -> Vec<&str> { + entries + .iter() + .map(|entry| entry.call.key.as_str()) + .collect() +} + +fn session_ids(entries: &[SessionEntry]) -> Vec<&str> { + entries + .iter() + .map(|entry| entry.session_id.as_str()) + .collect() +} + +fn hit_times(hits: &[SearchHit]) -> Vec> { + hits.iter().map(|hit| hit.at_ms).collect() +} + +fn use_line(id: &str) -> String { + format!("{}\n", json!({ "type": "use", "id": id })) +} + +fn path_text(path: &Path) -> &str { + path.to_str().expect("a Unicode test path") +} + +fn size(path: &Path) -> u64 { + fs::metadata(path).expect("read the file size").len() +} + +#[test] +fn appended_lines_are_read_from_the_cursor() { + let mut fixture = Fixture::new("append"); + let path = fixture.file("a.jsonl"); + append( + &path, + &(session_line("s1", "/work/app", 1_000) + &call_line("c1", 1_100, "model-a", 10, 20)), + ); + let report = fixture.sync(std::slice::from_ref(&path)); + assert_eq!( + ( + report.files_listed, + report.files_read, + report.sessions, + report.calls + ), + (1, 1, 1, 1) + ); + let first_size = size(&path); + assert_eq!(report.bytes_read, first_size); + + append(&path, &call_line("c2", 1_200, "model-a", 5, 6)); + let report = fixture.sync(std::slice::from_ref(&path)); + assert_eq!( + (report.files_read, report.files_restarted, report.calls), + (1, 0, 1) + ); + assert_eq!(report.bytes_read, size(&path) - first_size); + let entries = fixture.calls(); + assert_eq!(keys(&entries), ["c1", "c2"]); + // The parser state carried the session over to the appended line. + assert_eq!(entries[1].call.session_id, "s1"); + assert_eq!(entries[1].cwd.as_deref(), Some("/work/app")); + assert_eq!(entries[1].path, path_text(&path)); + + let report = fixture.sync(&[path.clone(), path]); + assert_eq!( + ( + report.files_listed, + report.files_unchanged, + report.files_read, + report.bytes_read + ), + (1, 1, 0, 0) + ); +} + +#[test] +fn rewritten_and_truncated_files_are_read_again() { + let mut fixture = Fixture::new("rewrite"); + let path = fixture.file("a.jsonl"); + append( + &path, + &(session_line("s1", "/w", 1_000) + + &call_line("c1", 1_100, "m", 1, 2) + + &call_line("c2", 1_200, "m", 1, 2)), + ); + fixture.sync(std::slice::from_ref(&path)); + + fs::write( + &path, + session_line("s2", "/w", 2_000) + + &call_line("c3", 2_100, "m", 1, 2) + + &call_line("c4", 2_200, "m", 1, 2) + + &call_line("c5", 2_300, "m", 1, 2), + ) + .expect("rewrite the file"); + let report = fixture.sync(std::slice::from_ref(&path)); + assert_eq!((report.files_read, report.files_restarted), (1, 1)); + assert_eq!(keys(&fixture.calls()), ["c3", "c4", "c5"]); + + fs::write(&path, session_line("s3", "/w", 3_000)).expect("truncate the file"); + let report = fixture.sync(&[path]); + assert_eq!(report.files_restarted, 1); + assert!(fixture.calls().is_empty()); + assert_eq!( + session_ids(&sessions(&fixture.store, every_session())), + ["s3"] + ); +} + +#[test] +fn overlong_lines_are_skipped() { + let mut fixture = Fixture::new("long-line"); + fixture.store.limits = ChunkLimits { + max_chunk_bytes: MAX_CHUNK_BYTES, + max_line_bytes: 256, + }; + let path = fixture.file("a.jsonl"); + append( + &path, + &(session_line("s1", "/w", 1_000) + + &text_line(1_050, &"word ".repeat(100)) + + &call_line("c1", 1_100, "m", 1, 2)), + ); + let report = fixture.sync(std::slice::from_ref(&path)); + assert_eq!((report.skipped_lines, report.spans), (1, 0)); + assert_eq!(report.bytes_read, size(&path)); + assert_eq!(keys(&fixture.calls()), ["c1"]); + assert!(fixture.search("word").is_empty()); +} + +#[test] +fn a_line_waits_for_its_newline() { + let mut fixture = Fixture::new("partial"); + let path = fixture.file("a.jsonl"); + let call = call_line("c1", 1_100, "m", 1, 2); + let (head, tail) = call.split_at(call.len() - 5); + append(&path, &(session_line("s1", "/w", 1_000) + head)); + fixture.sync(std::slice::from_ref(&path)); + assert!(fixture.calls().is_empty()); + assert_eq!(fixture.sync(std::slice::from_ref(&path)).files_unchanged, 1); + + append(&path, tail); + let report = fixture.sync(&[path]); + assert_eq!( + (report.files_read, report.files_restarted, report.calls), + (1, 0, 1) + ); + assert_eq!(keys(&fixture.calls()), ["c1"]); +} + +#[test] +fn unlisted_deleted_and_removed_files_lose_their_records() { + let mut fixture = Fixture::new("forget"); + let a = fixture.file("a.jsonl"); + let b = fixture.file("b.jsonl"); + let other = fixture.file("other.jsonl"); + append( + &a, + &(session_line("sa", "/w", 1_000) + &call_line("ca", 1_100, "m", 1, 2)), + ); + append( + &b, + &(session_line("sb", "/w", 2_000) + &call_line("cb", 2_100, "m", 1, 2)), + ); + append( + &other, + &(session_line("so", "/w", 3_000) + &call_line("co", 3_100, "m", 1, 2)), + ); + fixture.sync(&[a.clone(), b.clone()]); + sync_as(&mut fixture.store, OTHER_AGENT, &[other]); + assert_eq!(keys(&fixture.calls()), ["ca", "cb", "co"]); + + assert_eq!(fixture.sync(std::slice::from_ref(&a)).files_removed, 1); + assert_eq!(keys(&fixture.calls()), ["ca", "co"]); + + fixture.sync(&[a.clone(), b.clone()]); + fs::remove_file(&b).expect("delete a session file"); + assert_eq!(fixture.sync(&[a.clone(), b]).files_removed, 1); + assert_eq!(keys(&fixture.calls()), ["ca", "co"]); + + assert_eq!( + fixture.store.remove_agent(AGENT).expect("remove the agent"), + 1 + ); + assert_eq!(keys(&fixture.calls()), ["co"]); + assert_eq!( + session_ids(&sessions(&fixture.store, every_session())), + ["so"] + ); + // A removed agent's files are read from the start when it comes back. + let report = fixture.sync(&[a]); + assert_eq!((report.files_read, report.files_restarted), (1, 0)); +} + +#[test] +fn a_failed_chunk_is_offered_again() { + let mut fixture = Fixture::new("retry"); + fixture.store.limits = LINE_CHUNKS; + let path = fixture.file("a.jsonl"); + append( + &path, + &(session_line("s1", "/w", 1_000) + + &call_line("c1", 1_100, "m", 1, 2) + + &text_line(1_150, "boom") + + &call_line("c2", 1_200, "m", 1, 2)), + ); + let mut failing = LinesParser { + fail_on: Some("boom"), + ..LinesParser::default() + }; + let report = fixture + .store + .sync_agent(AGENT, std::slice::from_ref(&path), &mut failing) + .expect("sync the session files"); + assert_eq!((report.files_read, report.files_failed), (1, 1)); + assert_eq!(report.failures.len(), 1); + assert_eq!(report.failures[0].path, path); + assert!(matches!(report.failures[0].code, ErrorCode::ParseFailed)); + assert_eq!(keys(&fixture.calls()), ["c1"]); + + let mut parser = LinesParser::default(); + let report = fixture + .store + .sync_agent(AGENT, &[path], &mut parser) + .expect("sync the session files"); + assert_eq!((report.files_failed, report.files_restarted), (0, 0)); + // Only the failed line and the one after it are read again. + assert_eq!(parser.chunks, 2); + let entries = fixture.calls(); + assert_eq!(keys(&entries), ["c1", "c2"]); + assert_eq!(entries[1].call.session_id, "s1"); +} + +#[test] +fn invalid_records_fail_their_file_only() { + let mut fixture = Fixture::new("invalid"); + let line = |value: serde_json::Value| format!("{value}\n"); + let sentence_label = fixture.file("a.jsonl"); + append( + &sentence_label, + &(session_line("s1", "/w", 1_000) + + &line(json!({ "type": "call", "key": "c1", "at": 1, "model": "a whole sentence" }))), + ); + let outside_range = fixture.file("b.jsonl"); + append( + &outside_range, + &(session_line("s2", "/w", 1_000) + + &line(json!({ "type": "call", "key": "c2", "at": 1, "badRange": true }))), + ); + let text_id = fixture.file("c.jsonl"); + append( + &text_id, + &line(json!({ "type": "session", "id": "第一个会话", "cwd": "/w", "at": 1 })), + ); + let control_cwd = fixture.file("d.jsonl"); + append( + &control_cwd, + &line(json!({ "type": "session", "id": "s4", "cwd": "/w\nsecond line", "at": 1 })), + ); + let valid = fixture.file("e.jsonl"); + append( + &valid, + &(session_line("s5", "/w", 1_000) + &call_line("ok", 2, "m", 1, 2)), + ); + + let report = fixture.sync(&[ + sentence_label.clone(), + outside_range.clone(), + text_id.clone(), + control_cwd.clone(), + valid, + ]); + assert_eq!(report.files_failed, 4); + let failed: Vec<&Path> = report + .failures + .iter() + .map(|failure| failure.path.as_path()) + .collect(); + assert_eq!( + failed, + [&sentence_label, &outside_range, &text_id, &control_cwd] + ); + assert!(report + .failures + .iter() + .all(|failure| matches!(failure.code, ErrorCode::ParseFailed))); + assert_eq!(keys(&fixture.calls()), ["ok"]); + assert_eq!( + session_ids(&sessions(&fixture.store, every_session())), + ["s5"] + ); +} + +#[test] +fn caller_identifiers_are_checked() { + let mut fixture = Fixture::new("caller-ids"); + let error = fixture + .store + .sync_agent("an agent", &[], &mut LinesParser::default()) + .expect_err("an agent ID with a space is refused"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + let error = fixture + .store + .remove_agent("") + .expect_err("an empty agent ID is refused"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); +} + +#[test] +fn the_cache_holds_no_conversation_text() { + let mut fixture = Fixture::new("privacy"); + let path = fixture.file("a.jsonl"); + append( + &path, + &(session_line("s1", "/w", 1_000) + + &text_line(1_100, "The quick brown fox jumps over the lazy dog") + + &text_line(1_200, "今天去公园散步") + + &call_line("c1", 1_300, "m", 1, 2)), + ); + fixture.sync(&[path]); + assert_eq!(hit_times(&fixture.search("quick fox")), [Some(1_100)]); + assert_eq!(hit_times(&fixture.search("公园")), [Some(1_200)]); + + let cache = fixture.dir.path().join("cache"); + let mut files = 0; + for entry in fs::read_dir(&cache).expect("list the cache") { + let path = entry.expect("list the cache").path(); + let bytes = fs::read(&path).expect("read a cache file"); + for needle in [ + "quick brown", + "brown fox", + "lazy dog", + "今天去公园", + "去公园散步", + "公园散步", + ] { + assert!( + !bytes + .windows(needle.len()) + .any(|window| window == needle.as_bytes()), + "{} holds {needle:?}", + path.display() + ); + } + files += 1; + } + assert!(files >= 1); +} + +#[test] +fn copied_calls_are_counted_once() { + let mut fixture = Fixture::new("copies"); + let original = fixture.file("a.jsonl"); + let resumed = fixture.file("b.jsonl"); + append( + &original, + &(session_line("s1", "/w", 1_000) + + &call_line("c1", 1_100, "m", 10, 20) + + &call_line("c2", 1_200, "m", 10, 20)), + ); + // A resumed session copies an earlier call and carries on. + append( + &resumed, + &(use_line("s1") + + &call_line("c1", 1_100, "m", 10, 20) + + &call_line("c3", 1_300, "m", 1, 2)), + ); + let report = fixture.sync(&[original.clone(), resumed.clone()]); + assert_eq!(report.calls, 4); + let entries = fixture.calls(); + assert_eq!(keys(&entries), ["c1", "c2", "c3"]); + assert_eq!(entries[0].path, path_text(&original)); + // The resumed file only mentions the session; its cwd comes from the other. + assert_eq!(entries[2].cwd.as_deref(), Some("/w")); + let listed = sessions(&fixture.store, every_session()); + assert_eq!(session_ids(&listed), ["s1"]); + assert_eq!(listed[0].file_count, 2); + + fs::remove_file(&original).expect("delete the original"); + fixture.sync(&[original, resumed.clone()]); + let entries = fixture.calls(); + assert_eq!(keys(&entries), ["c1", "c3"]); + assert_eq!(entries[0].path, path_text(&resumed)); +} + +#[test] +fn sessions_merge_their_files_and_filter() { + let mut fixture = Fixture::new("sessions"); + let continued = fixture.file("a.jsonl"); + let described = fixture.file("b.jsonl"); + let other = fixture.file("c.jsonl"); + let other_agent = fixture.file("d.jsonl"); + // `a` sorts first but only continues the session `b` describes. + append( + &continued, + &(use_line("s1") + &call_line("c9", 5_000, "m", 1, 2)), + ); + append( + &described, + &(session_line("s1", "/w", 1_000) + &call_line("c1", 1_100, "m", 1, 2)), + ); + append(&other, &session_line("s2", "/x", 3_000)); + append(&other_agent, &session_line("s3", "/w", 2_000)); + fixture.sync(&[continued, described.clone(), other]); + sync_as(&mut fixture.store, OTHER_AGENT, &[other_agent]); + + let listed = sessions(&fixture.store, every_session()); + assert_eq!(session_ids(&listed), ["s2", "s3", "s1"]); + let merged = &listed[2]; + assert_eq!(merged.agent, AGENT); + assert_eq!(merged.path, path_text(&described)); + assert_eq!(merged.file_count, 2); + assert_eq!(merged.cwd.as_deref(), Some("/w")); + assert_eq!( + (merged.started_at_ms, merged.updated_at_ms), + (Some(1_000), Some(1_000)) + ); + assert!(merged.title_range.is_some()); + + let only = |filter: SessionFilter| session_ids(&sessions(&fixture.store, filter)).join(","); + assert_eq!( + only(SessionFilter { + agents: vec![AGENT.to_string()], + ..every_session() + }), + "s2,s1" + ); + assert_eq!( + only(SessionFilter { + cwd: Some("/w".to_string()), + ..every_session() + }), + "s3,s1" + ); + assert_eq!( + only(SessionFilter { + active_since_ms: Some(2_000), + ..every_session() + }), + "s2,s3" + ); + assert_eq!( + only(SessionFilter { + offset: 1, + limit: 1, + ..SessionFilter::default() + }), + "s3" + ); +} + +#[test] +fn calls_filter_by_agent_session_and_time() { + let mut fixture = Fixture::new("call-filter"); + let a = fixture.file("a.jsonl"); + let b = fixture.file("b.jsonl"); + append( + &a, + &(session_line("s1", "/w", 1_000) + + &call_line("c1", 1_000, "m", 1, 2) + + &session_line("s2", "/w", 2_000) + + &call_line("c2", 2_000, "m", 1, 2)), + ); + append( + &b, + &(session_line("s3", "/w", 3_000) + &call_line("c3", 3_000, "m", 1, 2)), + ); + fixture.sync(&[a]); + sync_as(&mut fixture.store, OTHER_AGENT, &[b]); + + let only = |filter: CallFilter| { + calls(&fixture.store, &filter) + .iter() + .map(|entry| entry.call.key.clone()) + .collect::>() + .join(",") + }; + assert_eq!(only(CallFilter::default()), "c1,c2,c3"); + assert_eq!( + only(CallFilter { + agents: vec![OTHER_AGENT.to_string()], + ..CallFilter::default() + }), + "c3" + ); + assert_eq!( + only(CallFilter { + session_id: Some("s2".to_string()), + ..CallFilter::default() + }), + "c2" + ); + // The start is inclusive and the end exclusive. + assert_eq!( + only(CallFilter { + since_ms: Some(2_000), + until_ms: Some(3_000), + ..CallFilter::default() + }), + "c2" + ); +} + +#[test] +fn a_rebuild_with_other_chunks_gives_the_same_records() { + let dir = TempDir::new("rebuild-equal"); + let sessions_dir = dir.path().join("sessions"); + fs::create_dir_all(&sessions_dir).expect("create the sessions directory"); + let a = sessions_dir.join("a.jsonl"); + let b = sessions_dir.join("b.jsonl"); + let files = [a.clone(), b.clone()]; + let first_half = session_line("s1", "/w", 1_000) + + &call_line("c1", 1_100, "m", 10, 20) + + &text_line(1_150, "数据库迁移 migration plan"); + let second_half = call_line("c2", 1_200, "m", 30, 40) + + &session_line("s2", "/x", 2_000) + + &text_line(2_100, "another migration") + + &call_line("c3", 2_200, "n", 50, 60); + append(&a, &first_half); + append(&b, &(use_line("s1") + &call_line("c1", 1_100, "m", 10, 20))); + + // One cache follows the files line by line as they grow; the other reads + // them once, whole. + let mut incremental = SessionStore::open(&dir.path().join("incremental")).expect("open"); + incremental.limits = LINE_CHUNKS; + sync_as(&mut incremental, AGENT, &files); + append(&a, &second_half); + append(&b, &call_line("c4", 3_000, "n", 1, 2)); + sync_as(&mut incremental, AGENT, &files); + let mut whole = SessionStore::open(&dir.path().join("whole")).expect("open"); + sync_as(&mut whole, AGENT, &files); + + assert_eq!( + calls(&incremental, &CallFilter::default()), + calls(&whole, &CallFilter::default()) + ); + assert_eq!( + keys(&calls(&whole, &CallFilter::default())), + ["c1", "c2", "c3", "c4"] + ); + assert_eq!( + sessions(&incremental, every_session()), + sessions(&whole, every_session()) + ); + for text in ["migration", "数据库", "数据库迁移", "an"] { + assert_eq!( + search(&incremental, text, &[]), + search(&whole, text, &[]), + "{text}" + ); + } + assert_eq!(search(&whole, "migration", &[]).len(), 2); +} + +#[test] +fn search_finds_chinese_and_english_words() { + let mut fixture = Fixture::new("search"); + let a = fixture.file("a.jsonl"); + let b = fixture.file("b.jsonl"); + append( + &a, + &(session_line("s1", "/w", 1_000) + + &text_line(1_000, "数据库连接失败了") + + &text_line(2_000, "Connection refused by the database") + + &text_line(3_000, "我在中间")), + ); + append( + &b, + &(session_line("s2", "/w", 4_000) + &text_line(4_000, "数据库很快")), + ); + fixture.sync(&[a]); + sync_as(&mut fixture.store, OTHER_AGENT, &[b]); + + assert_eq!( + hit_times(&fixture.search("数据库")), + [Some(4_000), Some(1_000)] + ); + assert_eq!( + hit_times(&search(&fixture.store, "数据库", &[AGENT])), + [Some(1_000)] + ); + assert_eq!(hit_times(&fixture.search("库连")), [Some(1_000)]); + // One character finds every run it is in, wherever it sits. + assert_eq!(hit_times(&fixture.search("中")), [Some(3_000)]); + assert_eq!(hit_times(&fixture.search("据")), [Some(4_000), Some(1_000)]); + assert_eq!(hit_times(&fixture.search("间")), [Some(3_000)]); + // A spaced word matches as a prefix, case-insensitively. + assert_eq!(hit_times(&fixture.search("CONNECT")), [Some(2_000)]); + assert_eq!( + hit_times(&fixture.search("connect database")), + [Some(2_000)] + ); + assert!(fixture.search("connect 数据库").is_empty()); + assert!(fixture.search("refusal").is_empty()); + assert!(fixture.search("!!! ...").is_empty()); + + let hits = fixture + .store + .search(&SearchQuery { + text: "数据库".to_string(), + agents: Vec::new(), + session_id: Some("s2".to_string()), + limit: 100, + }) + .expect("search the sessions"); + assert_eq!(hits.len(), 1); + assert_eq!( + (hits[0].agent.as_str(), hits[0].session_id.as_str()), + (OTHER_AGENT, "s2") + ); + let hits = fixture + .store + .search(&SearchQuery { + text: "数据库".to_string(), + limit: 1, + ..SearchQuery::default() + }) + .expect("search the sessions"); + assert_eq!(hit_times(&hits), [Some(4_000)]); +} + +#[test] +fn read_range_returns_the_bytes_until_the_file_changes() { + let mut fixture = Fixture::new("read-range"); + let path = fixture.file("a.jsonl"); + let text = text_line(1_100, "deploy the service"); + append(&path, &(session_line("s1", "/w", 1_000) + &text)); + fixture.sync(std::slice::from_ref(&path)); + let hits = fixture.search("deploy"); + assert_eq!(hits.len(), 1); + let hit = &hits[0]; + let read = |store: &SessionStore, range: ByteRange| store.read_range(AGENT, &hit.path, range); + assert_eq!( + read(&fixture.store, hit.range) + .expect("read the range") + .as_deref(), + Some(text.as_bytes()) + ); + + // Appending leaves the bytes already read as they were. + append(&path, &call_line("c1", 1_200, "m", 1, 2)); + assert!(read(&fixture.store, hit.range) + .expect("read the range") + .is_some()); + + for range in [ + ByteRange { start: 5, end: 5 }, + ByteRange { + start: 0, + end: size(&path), + }, + ] { + let error = read(&fixture.store, range).expect_err("a range past the cursor"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } + let error = fixture + .store + .read_range(AGENT, "/never/read.jsonl", hit.range) + .expect_err("a file the cache has not read"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + let error = fixture + .store + .read_range(OTHER_AGENT, &hit.path, hit.range) + .expect_err("a file of another agent"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + + fs::write(&path, session_line("s9", "/w", 9_000) + &text).expect("rewrite the file"); + assert_eq!( + read(&fixture.store, hit.range).expect("read the range"), + None + ); + fs::remove_file(&path).expect("delete the file"); + assert_eq!( + read(&fixture.store, hit.range).expect("read the range"), + None + ); +} + +#[test] +fn old_and_damaged_caches_are_rebuilt() { + let dir = TempDir::new("rebuild"); + let cache = dir.path().join("cache"); + fs::create_dir_all(&cache).expect("create the cache directory"); + let stale = cache.join("agent-sessions-v0.sqlite3"); + let stale_wal = cache.join("agent-sessions-v0.sqlite3-wal"); + let unrelated = cache.join("notes.txt"); + for path in [&stale, &stale_wal, &unrelated] { + fs::write(path, b"left by someone else").expect("write a file"); + } + let session = dir.path().join("a.jsonl"); + append( + &session, + &(session_line("s1", "/w", 1_000) + &call_line("c1", 1_100, "m", 1, 2)), + ); + + let mut store = SessionStore::open(&cache).expect("open the cache"); + assert!(!stale.exists() && !stale_wal.exists()); + assert!(unrelated.exists()); + sync_as(&mut store, AGENT, std::slice::from_ref(&session)); + drop(store); + let reopened = SessionStore::open(&cache).expect("open the cache"); + assert_eq!(keys(&calls(&reopened, &CallFilter::default())), ["c1"]); + drop(reopened); + + let database = cache.join(database_file_name()); + { + let connection = rusqlite::Connection::open(&database).expect("open the database"); + connection + .pragma_update(None, "user_version", 99) + .expect("set another schema version"); + } + let mut store = SessionStore::open(&cache).expect("rebuild the cache"); + assert!(calls(&store, &CallFilter::default()).is_empty()); + sync_as(&mut store, AGENT, std::slice::from_ref(&session)); + assert_eq!(keys(&calls(&store, &CallFilter::default())), ["c1"]); + drop(store); + + for suffix in ["-wal", "-shm"] { + let side_file = cache.join(format!("{}{suffix}", database_file_name())); + if side_file.exists() { + fs::remove_file(side_file).expect("delete a side file"); + } + } + fs::write(&database, vec![b'x'; 4096]).expect("damage the database"); + let mut store = SessionStore::open(&cache).expect("rebuild the cache"); + assert!(calls(&store, &CallFilter::default()).is_empty()); + sync_as(&mut store, AGENT, &[session]); + assert_eq!(keys(&calls(&store, &CallFilter::default())), ["c1"]); +} diff --git a/rust/crates/agent-sessions/src/tests/text.rs b/rust/crates/agent-sessions/src/tests/text.rs new file mode 100644 index 00000000..aa79b0b4 --- /dev/null +++ b/rust/crates/agent-sessions/src/tests/text.rs @@ -0,0 +1,70 @@ +//! Index terms and search queries. + +use crate::text::{index_terms, match_expression, MAX_QUERY_TERMS}; + +#[test] +fn unspaced_runs_become_pairs_and_a_last_character() { + assert_eq!(index_terms("今天去公园 ABC"), "今天 天去 去公 公园 园 abc"); + assert_eq!(index_terms("中"), "中"); + assert_eq!(index_terms("こんにちは"), "こん んに にち ちは は"); + assert_eq!(index_terms("한국어"), "한국 국어 어"); + assert_eq!(index_terms("用Rust写代码"), "用 rust 写代 代码 码"); + assert_eq!(index_terms(""), ""); + assert_eq!(index_terms("..., !!!"), ""); +} + +#[test] +fn queries_match_pairs_exactly_and_words_as_prefixes() { + assert_eq!( + match_expression("数据库").as_deref(), + Some(r#""数据" "据库""#) + ); + assert_eq!(match_expression("中").as_deref(), Some(r#""中"*"#)); + assert_eq!( + match_expression("Connect to DB").as_deref(), + Some(r#""connect"* "to"* "db"*"#) + ); + assert_eq!(match_expression("db DB Db").as_deref(), Some(r#""db"*"#)); + assert_eq!(match_expression("!!!"), None); + assert_eq!(match_expression(""), None); +} + +#[test] +fn query_syntax_never_reaches_the_index() { + assert_eq!( + match_expression(r#"foo" OR bar*"#).as_deref(), + Some(r#""foo"* "or"* "bar"*"#) + ); + assert_eq!( + match_expression("NEAR(a b) -c ^d col:e").as_deref(), + Some(r#""near"* "a"* "b"* "c"* "d"* "col"* "e"*"#) + ); + assert_eq!( + match_expression("snake_case").as_deref(), + Some(r#""snake"* "case"*"#) + ); +} + +#[test] +fn long_words_are_cut_at_a_character_boundary() { + assert_eq!(index_terms(&"a".repeat(100)), "a".repeat(64)); + assert_eq!(index_terms(&"é".repeat(40)), "é".repeat(32)); + // Query words are cut the same way, so they still match the index. + assert_eq!( + match_expression(&"a".repeat(100)), + Some(format!("\"{}\"*", "a".repeat(64))) + ); +} + +#[test] +fn a_query_keeps_its_first_terms() { + let words: Vec = (0..40).map(|number| format!("w{number}")).collect(); + let expression = match_expression(&words.join(" ")).expect("a query"); + let terms: Vec<&str> = expression.split(' ').collect(); + assert_eq!(terms.len(), MAX_QUERY_TERMS); + assert_eq!(terms[0], r#""w0"*"#); + assert_eq!( + terms[MAX_QUERY_TERMS - 1], + format!("\"w{}\"*", MAX_QUERY_TERMS - 1) + ); +} diff --git a/rust/crates/agent-sessions/src/text.rs b/rust/crates/agent-sessions/src/text.rs new file mode 100644 index 00000000..6daeb4af --- /dev/null +++ b/rust/crates/agent-sessions/src/text.rs @@ -0,0 +1,154 @@ +//! Splits indexed text and search queries into the same terms. +//! +//! SQLite's tokenizers split on spaces, which Chinese, Japanese and Korean +//! text rarely has. Text is therefore split here, before it reaches the index: +//! +//! - a run of letters and digits of other scripts is one lowercase word; +//! - a run of characters of the scripts above becomes every pair of adjacent +//! characters, plus its last character alone. Every character then starts +//! a term, so a one-character query, which matches as a prefix, finds the +//! run wherever the character sits. +//! +//! The terms contain only letters and digits and are joined by spaces, and +//! the index uses the `ascii` tokenizer, which splits on ASCII punctuation and +//! spaces only. A term therefore stays one index token, and a quoted query +//! term can never become a phrase, which an index without positions rejects. + +/// Longest term, in bytes; longer words are cut at a character boundary, the +/// same way in the index and in queries, so a long identifier still matches +/// by its start, and an encoded blob does not bloat the index. +const MAX_TERM_BYTES: usize = 64; + +/// Most terms of one query; the rest of a longer query is ignored. +pub(crate) const MAX_QUERY_TERMS: usize = 32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TermKind { + /// Letters and digits of a spaced script; queried as a prefix. + Word, + /// Two adjacent characters of an unspaced run; queried exactly. + Pair, + /// A run of one unspaced character; queried as a prefix of pairs too. + Single, + /// The last character of a longer unspaced run. Only indexed: a query run + /// of two or more characters is covered by its pairs. + Tail, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Term { + text: String, + kind: TermKind, +} + +/// The index terms of `text`, joined by spaces. +pub(crate) fn index_terms(text: &str) -> String { + let mut joined = String::new(); + for term in terms(text) { + if !joined.is_empty() { + joined.push(' '); + } + joined.push_str(&term.text); + } + joined +} + +/// An FTS5 query that matches text containing every term of `query`, or +/// `None` when the query has no terms. +pub(crate) fn match_expression(query: &str) -> Option { + let mut expression = String::new(); + let mut seen: Vec = Vec::new(); + for term in terms(query) { + if term.kind == TermKind::Tail || seen.contains(&term.text) { + continue; + } + if seen.len() == MAX_QUERY_TERMS { + break; + } + if !expression.is_empty() { + expression.push(' '); + } + expression.push('"'); + expression.push_str(&term.text); + expression.push('"'); + if term.kind != TermKind::Pair { + expression.push('*'); + } + seen.push(term.text); + } + (!expression.is_empty()).then_some(expression) +} + +fn terms(text: &str) -> Vec { + let mut terms = Vec::new(); + let mut word = String::new(); + let mut run: Vec = Vec::new(); + for character in text.chars() { + if is_unspaced(character) { + flush_word(&mut word, &mut terms); + run.push(character); + } else if character.is_alphanumeric() { + flush_run(&mut run, &mut terms); + for lower in character.to_lowercase() { + if word.len() + lower.len_utf8() <= MAX_TERM_BYTES { + word.push(lower); + } + } + } else { + flush_word(&mut word, &mut terms); + flush_run(&mut run, &mut terms); + } + } + flush_word(&mut word, &mut terms); + flush_run(&mut run, &mut terms); + terms +} + +fn flush_word(word: &mut String, terms: &mut Vec) { + if !word.is_empty() { + terms.push(Term { + text: std::mem::take(word), + kind: TermKind::Word, + }); + } +} + +fn flush_run(run: &mut Vec, terms: &mut Vec) { + for pair in run.windows(2) { + terms.push(Term { + text: pair.iter().collect(), + kind: TermKind::Pair, + }); + } + if let Some(last) = run.last() { + terms.push(Term { + text: last.to_string(), + kind: if run.len() == 1 { + TermKind::Single + } else { + TermKind::Tail + }, + }); + } + run.clear(); +} + +/// Characters of scripts written without spaces between words: Han +/// ideographs, kana and Hangul syllables. +fn is_unspaced(character: char) -> bool { + matches!( + character as u32, + // Hiragana and Katakana + 0x3040..=0x30FF + // CJK Unified Ideographs Extension A + | 0x3400..=0x4DBF + // CJK Unified Ideographs + | 0x4E00..=0x9FFF + // Hangul Syllables + | 0xAC00..=0xD7AF + // CJK Compatibility Ideographs + | 0xF900..=0xFAFF + // CJK Unified Ideographs Extensions B to H + | 0x20000..=0x323AF + ) +}