Skip to main content

vtcode_exec_events/
lifecycle_guard.rs

1//! Lifecycle guard for [`ThreadEvent`] streams.
2//!
3//! The turn and item lifecycle used to be enforced only by call-site
4//! convention, so each violation was repaired by hand where it was noticed
5//! (`item.completed` after `turn.completed`, `item.completed` repeated for one
6//! item, a turn that failed before it started). [`LifecycleGuard`] is the one
7//! place that knows the rules. Every emitter funnel passes events through
8//! [`LifecycleGuard::admit`]; the pure [`audit`] runs the same rules over a
9//! recorded stream.
10//!
11//! The guard is pure state: no I/O, no clock, no locking. Callers own the
12//! synchronization (the interactive emitter already serializes emission).
13//!
14//! # Rules
15//!
16//! - An item that was started inside a turn is completed before that turn's
17//!   terminal event. Open items are closed by the guard when a producer forgot.
18//! - An item id completes at most once. A repeat is dropped.
19//! - A terminal turn event without a started turn gets a `turn.started` first.
20//! - `turn.blocked` annotates a turn and never ends it, so the interactive loop
21//!   (failed, blocked) and the runner (blocked, failed) orderings are both valid.
22//! - Harness and error items, items with no `item.started`, and exec-session
23//!   output items are exempt: they legitimately occur outside a turn or outlive
24//!   one.
25
26use std::collections::VecDeque;
27
28use hashbrown::HashSet;
29
30use crate::{
31    Diagnostic, DiagnosticSeverity, ItemCompletedEvent, ItemUpdatedEvent, ReasoningItem, ThreadEvent, ThreadItem,
32    ThreadItemDetails, ToolCallStatus, ToolOutcome, TurnStartedEvent,
33};
34
35/// Suffix of the item id that tracks a still-running exec session's output.
36///
37/// These items are updated while the command runs and completed once on exit,
38/// which can be a later turn, so the guard never closes them at a turn end.
39pub const EXEC_SESSION_OUTPUT_ITEM_SUFFIX: &str = ":exec-session-output";
40
41/// Completed item ids remembered for duplicate detection. Item ids are unique
42/// per session, so a bounded window is enough to catch a repeat that follows
43/// its original closely, which is how every observed duplicate arrived.
44const COMPLETED_ID_WINDOW: usize = 4096;
45
46/// What the guard does when it can repair a violation.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum RepairPolicy {
49    /// Report violations and pass every event through unchanged.
50    Observe,
51    /// Report violations and repair the ones with a lossless fix: close open
52    /// items before a terminal event, drop a duplicate `item.completed`, and
53    /// open a turn before an orphan terminal turn event.
54    Repair,
55}
56
57/// A broken lifecycle rule.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum ViolationKind {
60    /// `turn.started` while a turn was already open.
61    TurnReopened,
62    /// `turn.completed` or `turn.failed` with no turn to end.
63    TerminalWithoutTurn,
64    /// A second `turn.completed` or `turn.failed` for one turn.
65    DuplicateTerminal,
66    /// A terminal turn event while items started in the turn were still open.
67    OpenItemAtTerminal,
68    /// `item.completed` for an id that already completed.
69    DuplicateItemCompleted,
70    /// An item event for an item started in a turn that has already ended.
71    ItemAfterTurnEnd,
72    /// `item.started` or `item.updated` for an id that already completed: a
73    /// completed handle was reused for different content.
74    ItemReusedAfterCompleted,
75}
76
77impl ViolationKind {
78    /// Stable machine-readable diagnostic code.
79    pub const fn code(self) -> &'static str {
80        match self {
81            Self::TurnReopened => "lifecycle.turn_reopened",
82            Self::TerminalWithoutTurn => "lifecycle.terminal_without_turn",
83            Self::DuplicateTerminal => "lifecycle.duplicate_terminal",
84            Self::OpenItemAtTerminal => "lifecycle.open_item_at_terminal",
85            Self::DuplicateItemCompleted => "lifecycle.duplicate_item_completed",
86            Self::ItemAfterTurnEnd => "lifecycle.item_after_turn_end",
87            Self::ItemReusedAfterCompleted => "lifecycle.item_reused_after_completed",
88        }
89    }
90
91    const fn summary(self) -> &'static str {
92        match self {
93            Self::TurnReopened => "A turn started while another turn was still open.",
94            Self::TerminalWithoutTurn => "A turn ended without having started.",
95            Self::DuplicateTerminal => "A turn ended more than once.",
96            Self::OpenItemAtTerminal => "A turn ended while items it started were still open.",
97            Self::DuplicateItemCompleted => "An item completed more than once.",
98            Self::ItemAfterTurnEnd => "An item event arrived after its turn ended.",
99            Self::ItemReusedAfterCompleted => "An item id was reused after the item completed.",
100        }
101    }
102}
103
104/// One lifecycle violation and the item it concerns, when there is one.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct Violation {
107    pub kind: ViolationKind,
108    pub item_id: Option<String>,
109}
110
111impl Violation {
112    /// Operational diagnostic for this violation. The correlation id is stable
113    /// per kind and item so repeated reports replace one another.
114    pub fn diagnostic(&self) -> Diagnostic {
115        let code = self.kind.code();
116        let subject = self.item_id.as_deref().unwrap_or("turn");
117        Diagnostic {
118            severity: DiagnosticSeverity::Warning,
119            code: code.to_string(),
120            summary: self.kind.summary().to_string(),
121            agent_details: self.item_id.as_ref().map(|id| format!("item: {id}")).unwrap_or_default(),
122            correlation_id: format!("{code}:{subject}"),
123            actions: Vec::new(),
124        }
125    }
126}
127
128impl Violation {
129    /// The diagnostic as an `item.updated` event, the shape every other
130    /// operational diagnostic uses. It is an update to an item that was never
131    /// started, which the guard exempts, so reporting a violation cannot itself
132    /// violate the rules.
133    pub fn event(&self) -> ThreadEvent {
134        let diagnostic = self.diagnostic();
135        ThreadEvent::ItemUpdated(ItemUpdatedEvent {
136            item: ThreadItem {
137                context: None,
138                id: diagnostic.correlation_id.clone(),
139                details: ThreadItemDetails::Reasoning(Box::new(ReasoningItem {
140                    text: diagnostic.summary.clone(),
141                    stage: Some("diagnosis".into()),
142                    diagnostic: Some(Box::new(diagnostic)),
143                })),
144            },
145        })
146    }
147}
148
149/// Result of admitting one event.
150#[derive(Debug, Default, PartialEq, Eq)]
151pub struct Admission {
152    /// Repair events to emit before [`Admission::event`].
153    pub before: Vec<ThreadEvent>,
154    /// The admitted event, or `None` when it was dropped as a duplicate.
155    pub event: Option<ThreadEvent>,
156    /// Violations found while admitting the event.
157    pub violations: Vec<Violation>,
158}
159
160impl Admission {
161    /// Every event to emit, in order: repairs first, then the admitted event.
162    pub fn into_events(self) -> impl Iterator<Item = ThreadEvent> {
163        self.before.into_iter().chain(self.event)
164    }
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168enum Phase {
169    /// No turn has started yet.
170    Idle,
171    Open,
172    /// The turn reached `turn.completed` or `turn.failed`.
173    Closed,
174}
175
176/// Tracks the turn and item lifecycle of one event stream.
177#[derive(Debug)]
178pub struct LifecycleGuard {
179    policy: RepairPolicy,
180    phase: Phase,
181    /// Items started in the open turn, with their latest snapshot.
182    open: Vec<ThreadItem>,
183    completed: HashSet<String>,
184    completed_order: VecDeque<String>,
185}
186
187impl Default for LifecycleGuard {
188    /// Emitter funnels repair by default: the repairs are lossless and match
189    /// what call sites used to hand-roll.
190    fn default() -> Self {
191        Self::new(RepairPolicy::Repair)
192    }
193}
194
195impl LifecycleGuard {
196    pub fn new(policy: RepairPolicy) -> Self {
197        Self {
198            policy,
199            phase: Phase::Idle,
200            open: Vec::new(),
201            completed: HashSet::new(),
202            completed_order: VecDeque::new(),
203        }
204    }
205
206    /// Whether the guard is currently inside a turn.
207    pub fn turn_is_open(&self) -> bool {
208        self.phase == Phase::Open
209    }
210
211    /// Admit one event, returning what to emit and what was violated.
212    pub fn admit(&mut self, event: ThreadEvent) -> Admission {
213        let mut admission = Admission::default();
214        match &event {
215            ThreadEvent::TurnStarted(_) => {
216                if self.phase == Phase::Open {
217                    admission
218                        .violations
219                        .push(Violation { kind: ViolationKind::TurnReopened, item_id: None });
220                }
221                self.phase = Phase::Open;
222            }
223            ThreadEvent::TurnCompleted(_) | ThreadEvent::TurnFailed(_) => {
224                self.admit_terminal(&mut admission);
225            }
226            ThreadEvent::ItemStarted(started) => self.admit_item_started(&started.item, &mut admission),
227            ThreadEvent::ItemUpdated(updated) => self.admit_item_updated(&updated.item, &mut admission),
228            ThreadEvent::ItemCompleted(completed) => {
229                let keep = self.admit_item_completed(&completed.item, &mut admission);
230                if !keep {
231                    return admission;
232                }
233            }
234            _ => {}
235        }
236        admission.event = Some(event);
237        admission
238    }
239
240    fn admit_terminal(&mut self, admission: &mut Admission) {
241        match self.phase {
242            Phase::Open => {
243                let open = std::mem::take(&mut self.open);
244                for item in open {
245                    admission.violations.push(Violation {
246                        kind: ViolationKind::OpenItemAtTerminal,
247                        item_id: Some(item.id.clone()),
248                    });
249                    if self.policy == RepairPolicy::Repair {
250                        let closed = close_item(item);
251                        self.remember_completed(&closed.id);
252                        admission
253                            .before
254                            .push(ThreadEvent::ItemCompleted(ItemCompletedEvent { item: closed }));
255                    }
256                }
257            }
258            Phase::Idle => {
259                admission.violations.push(Violation {
260                    kind: ViolationKind::TerminalWithoutTurn,
261                    item_id: None,
262                });
263                if self.policy == RepairPolicy::Repair {
264                    admission.before.push(ThreadEvent::TurnStarted(TurnStartedEvent::default()));
265                }
266            }
267            Phase::Closed => {
268                admission.violations.push(Violation {
269                    kind: ViolationKind::DuplicateTerminal,
270                    item_id: None,
271                });
272            }
273        }
274        self.phase = Phase::Closed;
275    }
276
277    fn admit_item_started(&mut self, item: &ThreadItem, admission: &mut Admission) {
278        if is_exempt(item) {
279            return;
280        }
281        if self.completed.contains(&item.id) {
282            // Not tracked as open: the id already has its terminal state, and
283            // closing it again would repeat `item.completed`.
284            admission.violations.push(Violation {
285                kind: ViolationKind::ItemReusedAfterCompleted,
286                item_id: Some(item.id.clone()),
287            });
288            return;
289        }
290        match self.phase {
291            Phase::Closed => admission.violations.push(Violation {
292                kind: ViolationKind::ItemAfterTurnEnd,
293                item_id: Some(item.id.clone()),
294            }),
295            Phase::Open => self.track_open(item),
296            Phase::Idle => {}
297        }
298    }
299
300    fn admit_item_updated(&mut self, item: &ThreadItem, admission: &mut Admission) {
301        if let Some(open) = self.open.iter_mut().find(|open| open.id == item.id) {
302            *open = item.clone();
303        } else if self.completed.contains(&item.id) && !is_exempt(item) {
304            admission.violations.push(Violation {
305                kind: ViolationKind::ItemReusedAfterCompleted,
306                item_id: Some(item.id.clone()),
307            });
308        }
309    }
310
311    /// Returns whether the event is admitted (`false` drops a duplicate).
312    fn admit_item_completed(&mut self, item: &ThreadItem, admission: &mut Admission) -> bool {
313        if self.completed.contains(&item.id) {
314            admission.violations.push(Violation {
315                kind: ViolationKind::DuplicateItemCompleted,
316                item_id: Some(item.id.clone()),
317            });
318            return self.policy != RepairPolicy::Repair;
319        }
320        let was_open = self.open.iter().any(|open| open.id == item.id);
321        self.open.retain(|open| open.id != item.id);
322        if !was_open && self.phase == Phase::Closed && !is_exempt(item) {
323            admission.violations.push(Violation {
324                kind: ViolationKind::ItemAfterTurnEnd,
325                item_id: Some(item.id.clone()),
326            });
327        }
328        self.remember_completed(&item.id);
329        true
330    }
331
332    fn track_open(&mut self, item: &ThreadItem) {
333        match self.open.iter_mut().find(|open| open.id == item.id) {
334            Some(open) => *open = item.clone(),
335            None => self.open.push(item.clone()),
336        }
337    }
338
339    fn remember_completed(&mut self, id: &str) {
340        if self.completed.insert(id.to_string()) {
341            self.completed_order.push_back(id.to_string());
342            if self.completed_order.len() > COMPLETED_ID_WINDOW
343                && let Some(oldest) = self.completed_order.pop_front()
344            {
345                let _forgotten = self.completed.remove(&oldest);
346            }
347        }
348    }
349}
350
351/// Run the lifecycle rules over a recorded stream without repairing it.
352pub fn audit(events: &[ThreadEvent]) -> Vec<Violation> {
353    let mut guard = LifecycleGuard::new(RepairPolicy::Observe);
354    events.iter().flat_map(|event| guard.admit(event.clone()).violations).collect()
355}
356
357/// Items the lifecycle rules do not apply to: they occur outside a turn
358/// (harness notices, errors) or outlive one (running exec sessions).
359fn is_exempt(item: &ThreadItem) -> bool {
360    item.id.ends_with(EXEC_SESSION_OUTPUT_ITEM_SUFFIX)
361        || matches!(item.details, ThreadItemDetails::Harness(_) | ThreadItemDetails::Error(_))
362}
363
364/// Terminal snapshot for an item the producer never completed. Tool items end
365/// as cancelled failures; streamed text keeps the text it had.
366fn close_item(mut item: ThreadItem) -> ThreadItem {
367    match &mut item.details {
368        ThreadItemDetails::ToolInvocation(invocation) => {
369            invocation.status = ToolCallStatus::Failed;
370            invocation.outcome = Some(ToolOutcome::Cancelled);
371        }
372        ThreadItemDetails::ToolOutput(output) => {
373            output.status = ToolCallStatus::Failed;
374            output.is_delta = None;
375        }
376        _ => {}
377    }
378    item
379}
380
381#[cfg(test)]
382mod tests;