Skip to main content

salvor_runtime/
runtime.rs

1//! [`Runtime`]: the batteries-included entry points over the built-in loop.
2//!
3//! Four verbs, one per way a run can need driving:
4//!
5//! - [`start`](Runtime::start) mints a run id and drives a fresh run.
6//! - [`recover`](Runtime::recover) re-drives an interrupted (crashed) run
7//!   over its recorded log: recorded steps replay, execution continues live
8//!   from the first unrecorded step. Driving an already-completed run this
9//!   way replays it end to end and is the cheapest full divergence check.
10//! - [`resume`](Runtime::resume) supplies input to a *parked* run (one whose
11//!   log ends at a `Suspended` or `BudgetExceeded` event). The input is
12//!   validated first: against the recorded suspension `input_schema` (see
13//!   [`crate::validate`] for what validation means in v0.1), or against the
14//!   budget-extension shape (see [`crate::budgets`]). Only then is it handed
15//!   to the loop, which records it as the `Resumed` event at the parked
16//!   position, through the cursor like every other event.
17//! - [`resolve`](Runtime::resolve) is the one human-driven override: it
18//!   records the completion of a dangling `Write` intent by hand, after a
19//!   human has verified externally what the write actually did. It executes
20//!   nothing and drives nothing; it appends exactly one `ToolCallCompleted`
21//!   so the run leaves `NeedsReconciliation` and a later `recover` can
22//!   continue it. Every other verb refuses a dangling write, by design; this
23//!   verb is the sanctioned way past it.
24//!
25//! A `Runtime` owns the store handle plus the injected clock and random
26//! source it builds each [`RunCtx`](crate::RunCtx) with. It holds no
27//! per-run state at all: dropping it mid-run loses nothing, because every
28//! event was persisted the moment it happened. That is the kill -9 story.
29
30use std::collections::BTreeMap;
31use std::sync::Arc;
32
33use salvor_core::{
34    Event, EventEnvelope, PendingCall, RunId, RunStatus, UnresolvedWrite, derive_state,
35};
36use salvor_store::EventStore;
37use serde_json::Value;
38
39// `ParkReason` is a plain value over the event vocabulary, so it lives in the
40// pure `salvor-replay` crate that `salvor-core` re-exports rather than at this
41// IO edge. Re-exported here so every `salvor_runtime::ParkReason` and
42// `crate::runtime::ParkReason` path keeps resolving.
43pub use salvor_core::ParkReason;
44
45use crate::agent::Agent;
46use crate::budgets::validate_extension_input;
47use crate::ctx::{ClockFn, RandomFn, RunCtx};
48use crate::driver::{self, LoopOutcome};
49use crate::error::RuntimeError;
50use crate::validate::validate_against_schema;
51
52/// How a drive of a run ended.
53#[derive(Debug, Clone)]
54pub enum RunOutcome {
55    /// The run completed with this output.
56    Completed {
57        /// The run that completed.
58        run_id: RunId,
59        /// The recorded final output.
60        output: Value,
61    },
62    /// The run is parked durably; it survives restarts and deploys, and
63    /// [`Runtime::resume`] continues it once input arrives.
64    Parked {
65        /// The parked run.
66        run_id: RunId,
67        /// Why it parked.
68        reason: ParkReason,
69    },
70}
71
72/// The batteries-included runtime. See the module docs for the three verbs.
73pub struct Runtime {
74    store: Arc<dyn EventStore>,
75    clock: ClockFn,
76    random: RandomFn,
77    /// Whether the [`RunCtx`](crate::RunCtx) this runtime builds records the
78    /// full model request body. Off unless
79    /// [`with_record_prompts`](Runtime::with_record_prompts) turns it on.
80    record_prompts: bool,
81    /// Correlation tags every [`RunCtx`](crate::RunCtx) this runtime builds
82    /// stamps on a genuinely fresh run. Unset unless
83    /// [`with_labels`](Runtime::with_labels) sets them.
84    labels: Option<BTreeMap<String, String>>,
85}
86
87impl Runtime {
88    /// A runtime over `store` with the default clock and OS randomness.
89    #[must_use]
90    pub fn new(store: Arc<dyn EventStore>) -> Self {
91        Self::with_hooks(
92            store,
93            Arc::new(time::OffsetDateTime::now_utc),
94            Arc::new(crate::ctx::os_random),
95        )
96    }
97
98    /// A runtime with an injected clock and random source, handed to every
99    /// [`RunCtx`](crate::RunCtx) it builds. Deterministic tests inject fixed
100    /// functions so full event logs compare equal across runs.
101    #[must_use]
102    pub fn with_hooks(store: Arc<dyn EventStore>, clock: ClockFn, random: RandomFn) -> Self {
103        Self {
104            store,
105            clock,
106            random,
107            record_prompts: false,
108            labels: None,
109        }
110    }
111
112    /// Turns on recording of the full model request body for every run this
113    /// runtime drives, passed through to each [`RunCtx`](crate::RunCtx) it
114    /// builds. Off by default. Chained builder style so
115    /// [`new`](Self::new)/[`with_hooks`](Self::with_hooks) keep their
116    /// signatures and every existing caller stays at off.
117    ///
118    /// This is PII-sensitive (the body may hold user data or secrets), which is
119    /// why it is off unless an operator opts in. See
120    /// [`RunCtx::with_record_prompts`](crate::RunCtx::with_record_prompts) for
121    /// what recording means and the guarantee that it does not affect replay.
122    #[must_use]
123    pub fn with_record_prompts(mut self, record_prompts: bool) -> Self {
124        self.record_prompts = record_prompts;
125        self
126    }
127
128    /// Sets the correlation tags every run this runtime drives stamps on its
129    /// `RunStarted`, passed through to each [`RunCtx`](crate::RunCtx) it
130    /// builds. Unset by default. Chained builder style, mirroring
131    /// [`with_record_prompts`](Self::with_record_prompts); see
132    /// [`RunCtx::with_labels`](crate::RunCtx::with_labels) for the bounds
133    /// that apply and when they are checked.
134    #[must_use]
135    pub fn with_labels(mut self, labels: BTreeMap<String, String>) -> Self {
136        self.labels = Some(labels);
137        self
138    }
139
140    /// Starts a fresh run of `agent` with `input`, under a newly minted
141    /// run id.
142    ///
143    /// # Errors
144    ///
145    /// Everything [`start_with_id`](Self::start_with_id) returns.
146    pub async fn start(&self, agent: &Agent, input: Value) -> Result<RunOutcome, RuntimeError> {
147        self.start_with_id(agent, RunId::new(), input).await
148    }
149
150    /// Starts a fresh run under a caller-chosen run id (tests use this to
151    /// make logs comparable across control and killed runs).
152    ///
153    /// # Errors
154    ///
155    /// [`RuntimeError::RunAlreadyStarted`] when the id already has history;
156    /// otherwise whatever the loop surfaces ([`RuntimeError::Store`],
157    /// [`RuntimeError::Model`], [`RuntimeError::Replay`], ...).
158    pub async fn start_with_id(
159        &self,
160        agent: &Agent,
161        run_id: RunId,
162        input: Value,
163    ) -> Result<RunOutcome, RuntimeError> {
164        let log = self.store.read_log(run_id).await?;
165        if !log.is_empty() {
166            return Err(RuntimeError::RunAlreadyStarted { run_id });
167        }
168        let mut ctx = self.ctx(run_id, log)?;
169        finish(run_id, driver::drive(&mut ctx, agent, &input).await?)
170    }
171
172    /// Re-drives an interrupted run: replays the recorded log, then
173    /// continues live from the first unrecorded step. This is the
174    /// post-crash verb; it supplies no new input.
175    ///
176    /// # Errors
177    ///
178    /// [`RuntimeError::UnknownRun`] when the id has no history;
179    /// `RuntimeError::Replay(ReplayError::NeedsReconciliation)` when the log
180    /// ends in a write intent with no completion (a human must resolve it);
181    /// [`RuntimeError::Replay`] on any divergence.
182    pub async fn recover(&self, agent: &Agent, run_id: RunId) -> Result<RunOutcome, RuntimeError> {
183        let log = self.read_existing(run_id).await?;
184        let mut ctx = self.ctx(run_id, log)?;
185        finish(run_id, driver::drive(&mut ctx, agent, &Value::Null).await?)
186    }
187
188    /// Resumes a parked run with `input`.
189    ///
190    /// The run must be parked: its derived status must be `Suspended` or
191    /// `BudgetExceeded`. The input is validated before anything is recorded:
192    /// a suspension validates against its recorded `input_schema`, a budget
193    /// crossing against the extension shape. On success, the loop re-drives
194    /// the run; the input is recorded as `Resumed` at the parked position
195    /// and becomes the pending tool's result (or the budget extension).
196    ///
197    /// # Errors
198    ///
199    /// [`RuntimeError::UnknownRun`], [`RuntimeError::NotParked`], or
200    /// [`RuntimeError::ResumeInputRejected`]; then whatever the loop
201    /// surfaces.
202    pub async fn resume(
203        &self,
204        agent: &Agent,
205        run_id: RunId,
206        input: Value,
207    ) -> Result<RunOutcome, RuntimeError> {
208        let log = self.read_existing(run_id).await?;
209        let state = derive_state(&log);
210        match &state.status {
211            RunStatus::Suspended { input_schema, .. } => {
212                validate_against_schema(&input, input_schema)
213                    .map_err(RuntimeError::ResumeInputRejected)?;
214            }
215            RunStatus::BudgetExceeded { .. } => {
216                validate_extension_input(&input).map_err(RuntimeError::ResumeInputRejected)?;
217            }
218            other => {
219                return Err(RuntimeError::NotParked {
220                    run_id,
221                    status: status_name(other).to_owned(),
222                });
223            }
224        }
225        let mut ctx = self.ctx(run_id, log)?;
226        ctx.set_resume_input(input);
227        finish(run_id, driver::drive(&mut ctx, agent, &Value::Null).await?)
228    }
229
230    /// Records, by hand, the completion of a dangling `Write` intent, after a
231    /// human has verified externally what the write did.
232    ///
233    /// This is the concrete form of human resolution. A crash
234    /// between a write's recorded intent and its completion derives to
235    /// [`RunStatus::NeedsReconciliation`], which every automatic verb refuses:
236    /// the write may or may not have reached its target, and the runtime will
237    /// not guess. Once a human has checked, `resolve` appends the completion
238    /// they observed (or the completion of the write they performed by hand),
239    /// so replay treats the call as done and never re-executes it. The run is
240    /// then recoverable through [`recover`](Self::recover) like any other.
241    ///
242    /// It takes the same care as [`resume`](Self::resume): the state is
243    /// validated *before* anything is written, and exactly one event is
244    /// appended. `output` is recorded verbatim as the tool's output; nothing
245    /// executes and nothing else is driven.
246    ///
247    /// # Errors
248    ///
249    /// [`RuntimeError::UnknownRun`] when the id has no history;
250    /// [`RuntimeError::NotReconcilable`] when the run's log does not end at a
251    /// dangling write intent (so there is no completion to record);
252    /// [`RuntimeError::Store`] when the append fails.
253    pub async fn resolve(&self, run_id: RunId, output: Value) -> Result<RunId, RuntimeError> {
254        let log = self.read_existing(run_id).await?;
255        let state = derive_state(&log);
256        // Only a dangling write derives to NeedsReconciliation, and it always
257        // carries the pending tool intent whose completion is missing.
258        let intent_seq = match (&state.status, &state.pending_call) {
259            (RunStatus::NeedsReconciliation, Some(PendingCall::Tool { seq, .. })) => *seq,
260            (other, _) => {
261                return Err(RuntimeError::NotReconcilable {
262                    run_id,
263                    status: status_name(other).to_owned(),
264                });
265            }
266        };
267        // The completion correlates to the intent's sequence number and takes
268        // the next contiguous log position, exactly as the cursor would have
269        // recorded it had the process not died in between.
270        let completion = Event::ToolCallCompleted {
271            seq: intent_seq,
272            output,
273        };
274        let envelope = EventEnvelope::new(run_id, state.next_seq, (self.clock)(), completion);
275        self.store.append(&envelope).await?;
276        crate::progress::emit_step(run_id, envelope.seq, &envelope.event);
277        Ok(run_id)
278    }
279
280    /// Abandons a run: appends a terminal [`Event::RunAbandoned`] by hand,
281    /// retiring a run deliberately without finishing or failing it.
282    ///
283    /// An operator action, not a driver action. It executes nothing, drives
284    /// nothing, and needs no lease: abandonment is the sanctioned "we do not
285    /// care about this run anymore" path, appended straight to the log the way
286    /// [`resolve`](Self::resolve) appends its one completion. It is allowed for
287    /// any non-terminal run, whatever state it parked or crashed in.
288    ///
289    /// When the run is parked at a dangling write (status
290    /// [`RunStatus::NeedsReconciliation`]), the outstanding intent's position
291    /// and tool ride on the event as
292    /// [`unresolved_write`](Event::RunAbandoned::unresolved_write). The
293    /// abandonment never claims the write question was answered: it records
294    /// exactly which write was left unsettled, so the honesty the reconciliation
295    /// refusal carried is preserved in the terminal record rather than erased.
296    ///
297    /// # Errors
298    ///
299    /// [`RuntimeError::UnknownRun`] when the id has no history;
300    /// [`RuntimeError::AlreadyTerminal`] when the run already reached a terminal
301    /// event (completed, failed, or previously abandoned), so there is nothing
302    /// left to retire; [`RuntimeError::Store`] when the append fails.
303    pub async fn abandon(
304        &self,
305        run_id: RunId,
306        reason: Option<String>,
307    ) -> Result<RunId, RuntimeError> {
308        let log = self.read_existing(run_id).await?;
309        let state = derive_state(&log);
310        // Refuse a run that already reached a terminal event: there is nothing
311        // left to abandon. Every non-terminal state is fair game.
312        if matches!(
313            state.status,
314            RunStatus::Completed { .. } | RunStatus::Failed { .. } | RunStatus::Abandoned { .. }
315        ) {
316            return Err(RuntimeError::AlreadyTerminal {
317                run_id,
318                status: status_name(&state.status).to_owned(),
319            });
320        }
321        // A run parked at a dangling write carries the outstanding intent
322        // forward as recorded honesty: name the write whose effect stays
323        // unknown rather than pretend it settled. Every other state abandons
324        // with no unresolved-write evidence.
325        let unresolved_write = match (&state.status, &state.pending_call) {
326            (RunStatus::NeedsReconciliation, Some(PendingCall::Tool { seq, tool, .. })) => {
327                Some(UnresolvedWrite {
328                    seq: *seq,
329                    tool: tool.clone(),
330                })
331            }
332            _ => None,
333        };
334        let event = Event::RunAbandoned {
335            reason,
336            unresolved_write,
337        };
338        let envelope = EventEnvelope::new(run_id, state.next_seq, (self.clock)(), event);
339        self.store.append(&envelope).await?;
340        crate::progress::emit_step(run_id, envelope.seq, &envelope.event);
341        Ok(run_id)
342    }
343
344    /// Reads a run's log, insisting it exists.
345    async fn read_existing(&self, run_id: RunId) -> Result<Vec<EventEnvelope>, RuntimeError> {
346        let log = self.store.read_log(run_id).await?;
347        if log.is_empty() {
348            return Err(RuntimeError::UnknownRun { run_id });
349        }
350        Ok(log)
351    }
352
353    /// Builds the per-run context with this runtime's hooks.
354    fn ctx(&self, run_id: RunId, log: Vec<EventEnvelope>) -> Result<RunCtx, RuntimeError> {
355        let mut ctx = RunCtx::with_hooks(
356            self.store.clone(),
357            run_id,
358            log,
359            self.clock.clone(),
360            self.random.clone(),
361        )?
362        .with_record_prompts(self.record_prompts);
363        if let Some(labels) = &self.labels {
364            ctx = ctx.with_labels(labels.clone());
365        }
366        Ok(ctx)
367    }
368}
369
370/// Attaches the run id to a loop outcome.
371#[allow(clippy::unnecessary_wraps)]
372fn finish(run_id: RunId, outcome: LoopOutcome) -> Result<RunOutcome, RuntimeError> {
373    Ok(match outcome {
374        LoopOutcome::Completed(output) => RunOutcome::Completed { run_id, output },
375        LoopOutcome::Parked(reason) => RunOutcome::Parked { run_id, reason },
376    })
377}
378
379/// A short status name for the not-parked error message.
380fn status_name(status: &RunStatus) -> &'static str {
381    match status {
382        RunStatus::NotStarted => "not started",
383        RunStatus::Running => "running",
384        RunStatus::AwaitingModel => "awaiting model (interrupted; use recover)",
385        RunStatus::AwaitingTool => "awaiting tool (interrupted; use recover)",
386        RunStatus::Suspended { .. } => "suspended",
387        RunStatus::BudgetExceeded { .. } => "budget exceeded",
388        RunStatus::NeedsReconciliation => "needs reconciliation",
389        RunStatus::Completed { .. } => "completed",
390        RunStatus::Failed { .. } => "failed",
391        RunStatus::Abandoned { .. } => "abandoned",
392    }
393}