Skip to main content

vtcode_memory/event_log/
append.rs

1//! Append path: event serialization, turn-boundary persistence, and cap eviction.
2//!
3//! Appends batch in memory until a turn boundary (or an explicit read/flush);
4//! cap enforcement is the one append-time path that rewrites the on-disk file.
5
6use super::*;
7
8impl SessionEventLog {
9    pub(super) fn event_write_failed(&self) -> SessionStoreError {
10        SessionStoreError::io(
11            &self.events_path,
12            std::io::Error::other(
13                "event log writer quarantined after persistence failure; close all handles and reopen",
14            ),
15        )
16    }
17
18    /// Append an event to the log and update the in-memory index/manifest.
19    pub fn append(&self, event: &ThreadEvent) -> Result<(), SessionStoreError> {
20        let _eviction_guard = self.shared.eviction_lock.lock().map_err(poison)?;
21        let mut st = self.shared.state.lock().map_err(poison)?;
22
23        if st.write_failed {
24            return Err(self.event_write_failed());
25        }
26        if self.shared.file.lock().map_err(poison)?.is_none() {
27            return Err(self.event_file_unavailable());
28        }
29
30        if st.needs_separator {
31            st.write_buf.push(b'\n');
32            st.next_offset += 1;
33            st.needs_separator = false;
34        }
35
36        // Serialize into the write buffer with rollback on failure — the
37        // invariant that `write_buf` never contains partial JSON is
38        // encapsulated in `serialize_event`.
39        let (start, end) = st.serialize_event(event)?;
40
41        st.manifest.event_count += 1;
42        st.manifest.updated_at = now_rfc3339();
43
44        // Route through the single turn-lifecycle state machine.  When the
45        // event closes a turn, persist metadata immediately so a reopen
46        // after a mid-turn crash sees a consistent index.
47        let is_turn_boundary = st.apply_lifecycle_event(LifecycleKind::from_event(event), start, end);
48        if is_turn_boundary {
49            self.persist_meta_locked(&mut st)?;
50        }
51
52        if st.write_buf.len() >= MAX_WRITE_BUFFER_BYTES {
53            // Persist metadata with the bounded byte flush so a reopen after
54            // a mid-turn crash does not trust an index that predates these
55            // already-written events.
56            self.persist_meta_locked(&mut st)?;
57        }
58        drop(st);
59        self.enforce_event_cap()
60    }
61
62    /// Enforce the per-session event cap by evicting the oldest completed
63    /// turns when the log exceeds [`Self::max_events`]. Returns `Ok(())` even
64    /// when no truncation is needed or the cap is disabled (`max_events == 0`).
65    fn enforce_event_cap(&self) -> Result<(), SessionStoreError> {
66        let mut st = self.shared.state.lock().map_err(poison)?;
67
68        // `plan_cap_eviction` encapsulates the index arithmetic and returns
69        // `None` when the cap is disabled or not yet exceeded.
70        let Some(plan) = st.plan_cap_eviction(self.max_events) else {
71            return Ok(());
72        };
73
74        // Keep ordinary appends in memory until a turn boundary or an
75        // explicit read. Cap enforcement is the one append-time path that
76        // needs the complete on-disk file before rewriting it.
77        self.flush_write_buf_locked(&mut st)?;
78
79        let (evicted, mut remaining, previous_file_len) = {
80            let mut file_slot = self.shared.file.lock().map_err(poison)?;
81            let file = file_slot.as_mut().ok_or_else(|| self.event_file_unavailable())?;
82            let file_len = file
83                .metadata()
84                .map_err(|error| SessionStoreError::io(&self.events_path, error))?
85                .len();
86            if plan.truncate_offset > file_len {
87                return Err(SessionStoreError::io(
88                    &self.events_path,
89                    std::io::Error::new(std::io::ErrorKind::InvalidData, "cap offset exceeds event log length"),
90                ));
91            }
92            file.seek(SeekFrom::Start(0))
93                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
94            let mut evicted = vec![
95                0u8;
96                usize::try_from(plan.truncate_offset).map_err(|error| {
97                    SessionStoreError::io(
98                        &self.events_path,
99                        std::io::Error::new(std::io::ErrorKind::InvalidData, error),
100                    )
101                })?
102            ];
103            file.read_exact(&mut evicted)
104                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
105            file.seek(SeekFrom::Start(plan.truncate_offset))
106                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
107            let mut remaining = Vec::new();
108            file.read_to_end(&mut remaining)
109                .map_err(|e| SessionStoreError::io(&self.events_path, e))?;
110            (evicted, remaining, file_len)
111        };
112        let retained_turn_base = st.retained_turn_base_after_eviction(plan.evicted_turn_count);
113        drop(st);
114
115        // The turn index counts only records inside indexed turns. The bytes
116        // removed by a cap rewrite may also contain valid session-level
117        // records (for example `thread.started`) before the first turn, so
118        // reconcile the manifest against the actual persisted prefix rather
119        // than the turn-only estimate from `plan_cap_eviction`.
120        let mut plan = plan;
121        plan.evicted_event_count = count_persisted_event_records(&evicted);
122        let evicted_events = decode_events(&evicted);
123        (self.eviction_summary_hook)(&evicted_events)?;
124
125        // Matrix snapshots are complete session-level checkpoints. Preserve the
126        // latest evicted checkpoint only when no newer snapshot survives.
127        let mut matrix_checkpoints = BTreeMap::new();
128        let mut planning_checkpoint = None;
129        for event in &evicted_events {
130            if let ThreadEvent::PlanDelta(delta) = event
131                && delta.recovery.is_some()
132            {
133                planning_checkpoint = Some(event);
134            }
135            if let ThreadEvent::MatrixUpdated(snapshot) = event {
136                matrix_checkpoints.insert(snapshot.spec.id.clone(), event);
137            }
138        }
139        for event in decode_events(&remaining) {
140            if let ThreadEvent::PlanDelta(delta) = &event
141                && delta.recovery.is_some()
142            {
143                planning_checkpoint = None;
144            }
145            if let ThreadEvent::MatrixUpdated(snapshot) = event {
146                matrix_checkpoints.remove(&snapshot.spec.id);
147            }
148        }
149        let mut checkpoint_prefix = Vec::new();
150        for event in matrix_checkpoints.values().copied().chain(planning_checkpoint) {
151            serde_json::to_writer(&mut checkpoint_prefix, &VersionedThreadEvent::new((*event).clone()))
152                .map_err(|error| SessionStoreError::io(&self.events_path, std::io::Error::other(error)))?;
153            checkpoint_prefix.push(b'\n');
154        }
155        let checkpoint_bytes = checkpoint_prefix.len() as u64;
156        let checkpoint_count = matrix_checkpoints.len() as u64 + u64::from(planning_checkpoint.is_some());
157        if !checkpoint_prefix.is_empty() {
158            checkpoint_prefix.extend_from_slice(&remaining);
159            remaining = checkpoint_prefix;
160        }
161
162        let new_file_len = u64::try_from(remaining.len()).map_err(|error| {
163            SessionStoreError::io(&self.events_path, std::io::Error::new(std::io::ErrorKind::InvalidData, error))
164        })?;
165        self.manifest_store.write_pending_cap_rewrite(&PendingCapRewrite {
166            previous_file_len,
167            new_file_len,
168            retained_turn_base,
169        })?;
170        let next_offset = self.replace_event_file_contents(&remaining)?;
171        let mut st = self.shared.state.lock().map_err(poison)?;
172        st.apply_cap_eviction(plan, next_offset);
173        for entry in &mut st.index.entries {
174            entry.start_offset += checkpoint_bytes;
175            entry.end_offset += checkpoint_bytes;
176        }
177        st.manifest.event_count += checkpoint_count;
178        // The rewrite changed byte offsets and retained counts; persist the
179        // derived metadata before exposing the append as successful.
180        if let Err(error) = self.persist_meta_locked(&mut st) {
181            // Keep the marker's recorded file length valid until reopen can
182            // rebuild the derived metadata from the rewritten log.
183            st.write_failed = true;
184            return Err(error);
185        }
186        self.manifest_store.clear_pending_cap_rewrite()?;
187        Ok(())
188    }
189}