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