Skip to main content

vtcode_memory/
snapshot.rs

1//! Bounded read-only projections of canonical history for external clients.
2
3use std::io::{Read, Seek, SeekFrom};
4use std::path::Path;
5
6use vtcode_exec_events::VersionedThreadEvent;
7
8use crate::SessionStoreError;
9
10type Result<T> = std::result::Result<T, SessionStoreError>;
11
12/// Complete records from the end of a canonical event log, in persisted order.
13#[derive(Debug)]
14pub struct EventTail {
15    /// Schema-versioned canonical records; never synthesized lifecycle events.
16    pub events: Vec<VersionedThreadEvent>,
17    /// The byte limit or an incomplete final record excluded history.
18    pub truncated: bool,
19}
20
21/// Read at most `max_bytes` from a session without creating files, taking a
22/// writer handle, changing metadata, or loading history into agent context.
23/// Missing logs return `None` for compatibility with legacy archives.
24/// The workspace must be an absolute, resolved root; symlink paths are rejected.
25/// Platforms without handle-bound reads return an `Unsupported` I/O error.
26/// Returns an I/O error if an observed truncation, modification, or replacement
27/// makes the bounded snapshot inconsistent; callers may retry.
28pub fn read_event_tail(workspace: &Path, session_id: &str, max_bytes: usize) -> Result<Option<EventTail>> {
29    if max_bytes == 0
30        || max_bytes > 16 * 1024 * 1024
31        || session_id.is_empty()
32        || session_id != crate::sanitize_id(session_id)
33    {
34        return Err(SessionStoreError::io(
35            workspace,
36            std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid session identifier or event tail limit"),
37        ));
38    }
39    let relative = Path::new(crate::SESSIONS_DIR).join(session_id).join("events.jsonl");
40    let mut file = match vtcode_commons::fs::bound_file::open_file_beneath(workspace, &relative) {
41        Ok(file) => file,
42        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
43        Err(error) => return Err(SessionStoreError::io(workspace.join(&relative), error)),
44    };
45    let initial = file
46        .metadata()
47        .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
48    let length = initial.len();
49    let start = length.saturating_sub(max_bytes as u64);
50    let partial_prefix = if start > 0 {
51        file.seek(SeekFrom::Start(start - 1))
52            .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
53        let mut preceding = [0];
54        file.read_exact(&mut preceding)
55            .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
56        preceding[0] != b'\n'
57    } else {
58        false
59    };
60    file.seek(SeekFrom::Start(start))
61        .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
62    let bytes = read_exact_tail(&mut file, length - start)
63        .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
64    let final_metadata = file
65        .metadata()
66        .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
67    let current = vtcode_commons::fs::bound_file::open_file_beneath(workspace, &relative)
68        .and_then(|file| file.metadata())
69        .map_err(|error| SessionStoreError::io(workspace.join(&relative), error))?;
70    if !same_snapshot(&initial, &final_metadata) || !same_snapshot(&initial, &current) {
71        return Err(SessionStoreError::io(
72            workspace.join(&relative),
73            std::io::Error::other("event log changed while reading its tail"),
74        ));
75    }
76    decode_tail(&bytes, start > 0, partial_prefix).map(Some)
77}
78
79#[cfg(unix)]
80fn same_snapshot(first: &std::fs::Metadata, second: &std::fs::Metadata) -> bool {
81    use std::os::unix::fs::MetadataExt;
82    first.dev() == second.dev()
83        && first.ino() == second.ino()
84        && first.len() == second.len()
85        && first.mtime() == second.mtime()
86        && first.mtime_nsec() == second.mtime_nsec()
87        && first.ctime() == second.ctime()
88        && first.ctime_nsec() == second.ctime_nsec()
89}
90
91#[cfg(not(unix))]
92fn same_snapshot(first: &std::fs::Metadata, second: &std::fs::Metadata) -> bool {
93    first.len() == second.len()
94        && first
95            .modified()
96            .ok()
97            .zip(second.modified().ok())
98            .is_some_and(|(left, right)| left == right)
99}
100
101fn read_exact_tail(reader: &mut impl Read, expected: u64) -> std::io::Result<Vec<u8>> {
102    let mut bytes = Vec::new();
103    reader.take(expected).read_to_end(&mut bytes)?;
104    if bytes.len() as u64 != expected {
105        return Err(std::io::Error::new(
106            std::io::ErrorKind::UnexpectedEof,
107            "event log shortened while reading its tail",
108        ));
109    }
110    Ok(bytes)
111}
112
113fn decode_tail(bytes: &[u8], omitted_prefix: bool, partial_prefix: bool) -> Result<EventTail> {
114    let mut records = bytes.split_inclusive(|byte| *byte == b'\n');
115    // A bounded tail can begin inside a JSON record. Discard that entire record
116    // rather than treating the suffix as authoritative evidence.
117    if partial_prefix {
118        records.next();
119    }
120    let mut tail = EventTail { events: Vec::new(), truncated: omitted_prefix };
121    for record in records {
122        if !record.ends_with(b"\n") {
123            tail.truncated = true;
124            break;
125        }
126        if record.iter().all(u8::is_ascii_whitespace) {
127            continue;
128        }
129        tail.events.push(serde_json::from_slice(record)?);
130    }
131    Ok(tail)
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use vtcode_exec_events::{ThreadEvent, ThreadStartedEvent};
138
139    fn record(id: &str) -> Vec<u8> {
140        let mut bytes =
141            serde_json::to_vec(&VersionedThreadEvent::new(ThreadEvent::ThreadStarted(ThreadStartedEvent {
142                thread_id: id.into(),
143            })))
144            .unwrap();
145        bytes.push(b'\n');
146        bytes
147    }
148
149    #[test]
150    fn tail_preserves_order_and_excludes_partial_records_at_both_edges() {
151        let mut bytes = record("first");
152        bytes.extend(record("second"));
153        bytes.extend(b"{unfinished");
154        let full = decode_tail(&bytes, false, false).unwrap();
155        assert_eq!(full.events.len(), 2);
156        assert!(full.truncated);
157        let bounded = decode_tail(&bytes[5..], true, true).unwrap();
158        assert_eq!(bounded.events, vec![serde_json::from_slice::<VersionedThreadEvent>(&record("second")).unwrap()]);
159        assert!(bounded.truncated);
160        assert!(decode_tail(b"bad\n", false, false).is_err());
161    }
162
163    #[test]
164    fn tail_read_rejects_early_eof_even_at_a_record_boundary() {
165        let first = record("first");
166        let second = record("second");
167        let expected = (first.len() + second.len()) as u64;
168        let mut shortened = std::io::Cursor::new(first.clone());
169        let error = read_exact_tail(&mut shortened, expected).unwrap_err();
170        assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
171
172        let mut complete = std::io::Cursor::new([first.clone(), second].concat());
173        let bytes = read_exact_tail(&mut complete, expected).unwrap();
174        assert_eq!(decode_tail(&bytes, false, false).unwrap().events.len(), 2);
175    }
176
177    #[cfg(unix)]
178    #[test]
179    fn snapshot_identity_rejects_same_length_atomic_replacement() {
180        let dir = tempfile::tempdir().unwrap();
181        let path = dir.path().join("events.jsonl");
182        let replacement = dir.path().join("replacement");
183        std::fs::write(&path, b"old\n").unwrap();
184        let open = std::fs::File::open(&path).unwrap();
185        let initial = open.metadata().unwrap();
186        assert!(same_snapshot(&initial, &open.metadata().unwrap()));
187        std::fs::write(&replacement, b"new\n").unwrap();
188        std::fs::rename(replacement, &path).unwrap();
189        assert!(!same_snapshot(&initial, &std::fs::metadata(&path).unwrap()));
190    }
191
192    #[cfg(unix)]
193    #[test]
194    fn read_is_bounded_and_missing_history_does_not_create_a_store() {
195        let dir = tempfile::tempdir().unwrap();
196        let root = vtcode_commons::canonicalize(dir.path()).unwrap();
197        assert!(read_event_tail(&root, "missing", 1024).unwrap().is_none());
198        assert!(!root.join(".vtcode").exists());
199        let log = crate::open(&root, "saved", crate::DEFAULT_MAX_EVENTS).unwrap();
200        log.append(&ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "first".into() }))
201            .unwrap();
202        log.append(&ThreadEvent::ThreadStarted(ThreadStartedEvent { thread_id: "second".into() }))
203            .unwrap();
204        log.flush().unwrap();
205        let path = crate::session_directory(&root, "saved").join("events.jsonl");
206        let before = std::fs::read(&path).unwrap();
207        let tail = read_event_tail(&root, "saved", record("second").len()).unwrap().unwrap();
208        assert_eq!(tail.events.len(), 1);
209        assert!(tail.truncated);
210        assert_eq!(std::fs::read(path).unwrap(), before);
211        assert!(read_event_tail(&root, "../escape", 1024).is_err());
212        assert!(read_event_tail(&root, "saved", 0).is_err());
213    }
214
215    #[cfg(unix)]
216    #[test]
217    fn history_rejects_symlinked_session_directories() {
218        let dir = tempfile::tempdir().unwrap();
219        let root = vtcode_commons::canonicalize(dir.path()).unwrap();
220        let outside = tempfile::tempdir().unwrap();
221        std::fs::create_dir_all(root.join(".vtcode/sessions")).unwrap();
222        std::os::unix::fs::symlink(outside.path(), root.join(".vtcode/sessions/linked")).unwrap();
223        assert!(read_event_tail(&root, "linked", 1024).is_err());
224    }
225}