Skip to main content

artifactize_core/runs/
mod.rs

1//! Artifactize-owned verification: durable submission, observation and explicit cancellation.
2#[cfg(test)]
3mod lifetime_tests;
4mod observe;
5mod result;
6mod watch;
7mod worker;
8use crate::{
9    process,
10    project::{VerifyOptions, selection::Selection},
11    store::{self, Receipts},
12    types::{FailureCode, RequestKey, RunId},
13};
14pub(crate) use observe::saved_state;
15pub use observe::{
16    Counts, RunObservation, State, reconcile_interrupted, status, view, wait, wait_observing,
17};
18pub use result::{
19    Finding, PAGE_SIZE as RESULT_PAGE_SIZE, ResultCursor, ResultState, RunResultPage, RunVerdict,
20    result,
21};
22use serde::{Deserialize, Serialize};
23use std::path::{Path, PathBuf};
24pub use watch::{RunEvent, watch};
25#[doc(hidden)]
26pub use worker::{execute, supervise, supervise_observing_launch};
27
28/// Per-Run execution modes. Future modes extend this type, not transport signatures.
29#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(default)]
31pub struct RunModes {
32    pub speculate: bool,
33}
34impl RunModes {
35    pub(crate) fn is_default(&self) -> bool {
36        self == &Self::default()
37    }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum Activity {
43    Preparing,
44    Executing,
45    Publishing,
46    Waiting,
47    Cancelling,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(tag = "state", rename_all = "snake_case")]
52pub enum Worker {
53    Starting {
54        launcher: process::ChildIdentity,
55    },
56    Admitted {
57        owner: process::ChildIdentity,
58    },
59    /// Old records have no worker identity and are not evidence of owner death.
60    Legacy,
61}
62#[derive(Debug, Clone, Serialize, Deserialize)]
63#[serde(from = "ControlWire", into = "ControlWire")]
64pub struct Control {
65    pub worker: Worker,
66    /// The supervisor keeps worker files open until its executor has exited and been checked.
67    pub supervisor: Option<process::ChildIdentity>,
68    pub activity: Activity,
69    pub failure_code: Option<FailureCode>,
70}
71
72#[derive(Serialize, Deserialize)]
73#[serde(rename_all = "camelCase")]
74struct ControlWire {
75    worker: Worker,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    supervisor: Option<process::ChildIdentity>,
78    activity: Activity,
79    #[serde(default)]
80    cancellation_requested: bool,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    failure_code: Option<FailureCode>,
83}
84
85impl From<ControlWire> for Control {
86    fn from(wire: ControlWire) -> Self {
87        Self {
88            worker: wire.worker,
89            supervisor: wire.supervisor,
90            activity: if wire.cancellation_requested {
91                Activity::Cancelling
92            } else {
93                wire.activity
94            },
95            failure_code: wire.failure_code,
96        }
97    }
98}
99
100impl From<Control> for ControlWire {
101    fn from(control: Control) -> Self {
102        Self {
103            worker: control.worker,
104            supervisor: control.supervisor,
105            activity: control.activity,
106            cancellation_requested: control.is_cancelling(),
107            failure_code: control.failure_code,
108        }
109    }
110}
111
112impl Control {
113    pub fn is_cancelling(&self) -> bool {
114        self.activity == Activity::Cancelling
115    }
116
117    pub(crate) fn starting() -> Result<Self, String> {
118        Ok(Self {
119            worker: Worker::Starting {
120                launcher: process::child_identity(std::process::id()).map_err(|e| e.to_string())?,
121            },
122            supervisor: None,
123            activity: Activity::Preparing,
124            failure_code: None,
125        })
126    }
127    pub(crate) fn legacy() -> Self {
128        Self {
129            worker: Worker::Legacy,
130            supervisor: None,
131            activity: Activity::Executing,
132            failure_code: None,
133        }
134    }
135}
136
137/// The surface that accepted a new Run. Old receipts have no known origin.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(
140    tag = "kind",
141    rename_all = "camelCase",
142    rename_all_fields = "camelCase"
143)]
144pub enum Origin {
145    Cli,
146    Mcp,
147    Chat {
148        session_id: crate::types::SessionId,
149        title: String,
150        #[serde(default, skip_serializing_if = "Option::is_none")]
151        send: Option<usize>,
152    },
153}
154
155/// Bound repository/state and trusted executable, resolved once by the interface at startup.
156#[derive(Debug, Clone)]
157pub struct Context {
158    pub(crate) repo: PathBuf,
159    pub(crate) state: PathBuf,
160    executable: PathBuf,
161    origin: Origin,
162}
163impl Context {
164    /// The canonical repository this endpoint serves.
165    pub fn repo(&self) -> &Path {
166        &self.repo
167    }
168
169    pub(crate) fn executable(&self) -> &Path {
170        &self.executable
171    }
172
173    /// The canonical state directory shared by this endpoint and its Run workers.
174    pub fn state(&self) -> &Path {
175        &self.state
176    }
177
178    pub fn new(repo: &Path, state: Option<&Path>, executable: &Path) -> Result<Self, String> {
179        Ok(Self {
180            repo: crate::workspace::canonical_target(repo).map_err(|e| e.to_string())?,
181            state: crate::workspace::canonical_target(&store::state_dir(state)?)
182                .map_err(|e| e.to_string())?,
183            executable: executable.to_path_buf(),
184            origin: Origin::Cli,
185        })
186    }
187    /// Set the origin for new Runs started in this context, without changing read scope.
188    #[must_use]
189    pub fn with_origin(self, origin: Origin) -> Self {
190        Self { origin, ..self }
191    }
192
193    /// Public-library convenience; packaged callers normally pass their own executable to `new`.
194    pub fn discover(repo: &Path, state: Option<&Path>) -> Result<Self, String> {
195        let executable = process::artifactize_executable()?;
196        Self::new(repo, state, &executable)
197    }
198}
199
200pub async fn start(
201    context: &Context,
202    selection: &Selection,
203    options: &VerifyOptions,
204    request_key: Option<RequestKey>,
205) -> Result<RunObservation, String> {
206    start_with_args_hash(context, selection, options, request_key, None).await
207}
208
209/// Start a Run with an optional canonical `request_args_hash` enforced on internal `chat/*` keys.
210pub(crate) async fn start_with_args_hash(
211    context: &Context,
212    selection: &Selection,
213    options: &VerifyOptions,
214    request_key: Option<RequestKey>,
215    request_args_hash: Option<String>,
216) -> Result<RunObservation, String> {
217    start_observing_launch_with_hash(
218        context,
219        selection,
220        options,
221        request_key,
222        request_args_hash,
223        |_, _| {},
224    )
225    .await
226}
227
228/// Transfer the supervisor's birth identity at launch, before saving or reading any receipt.
229#[doc(hidden)]
230pub async fn start_observing_launch(
231    context: &Context,
232    selection: &Selection,
233    options: &VerifyOptions,
234    request_key: Option<RequestKey>,
235    launched: impl FnOnce(&RunId, process::ChildIdentity),
236) -> Result<RunObservation, String> {
237    start_observing_launch_with_hash(context, selection, options, request_key, None, launched).await
238}
239
240async fn start_observing_launch_with_hash(
241    context: &Context,
242    selection: &Selection,
243    options: &VerifyOptions,
244    request_key: Option<RequestKey>,
245    request_args_hash: Option<String>,
246    launched: impl FnOnce(&RunId, process::ChildIdentity),
247) -> Result<RunObservation, String> {
248    // Keys are attempt identity, not checkout identity. Retry before discovering declarations.
249    if let Some(key) = &request_key
250        && crate::platform::paths::target_is_file(&context.state.join(store::DATABASE))
251    {
252        let receipts = Receipts::open(&context.state, &context.repo).await?;
253        let result = receipts
254            .keyed_run(&context.repo, key, request_args_hash.as_deref())
255            .await;
256        let closed = receipts.close().await;
257        if let Some(id) = result.and_then(|id| closed.map(|()| id))? {
258            return status(context, &id).await;
259        }
260    }
261    let (id, accepted) = crate::project::verify::reserve(
262        &context.repo,
263        Some(&context.state),
264        selection,
265        options,
266        request_key.as_ref(),
267        request_args_hash.as_deref(),
268        &context.origin,
269    )
270    .await?;
271    if accepted {
272        let receipts = Receipts::open(&context.state, &context.repo).await?;
273        let result = async {
274            let launch =
275                process::launch_run(&context.executable, &id, &context.repo, &context.state);
276            let admitted = match launch {
277                Ok(identity) => {
278                    launched(&id, identity);
279                    receipts.admit(&id, identity).await
280                }
281                Err(error) => Err(error.to_string()),
282            };
283            if let Err(error) = admitted {
284                worker::fail(&receipts, &id, FailureCode::SpawnFailed, error.clone()).await?;
285                return Err(format!("Run {id} handoff failed: {error}"));
286            }
287            Ok(())
288        }
289        .await;
290        let closed = receipts.close().await;
291        result.and(closed)?;
292    }
293    // Preparing the Run read the whole workspace and built its definitions, all freed by now;
294    // a caller that goes on to wait for the Run should not keep that memory while it waits.
295    crate::platform::release_free_memory();
296    status(context, &id).await
297}
298
299#[derive(Debug, Clone, Serialize)]
300pub struct CancelAcknowledgement {
301    pub run: RunId,
302    pub state: State,
303    pub cancellation_requested: bool,
304}
305pub async fn cancel(context: &Context, id: &RunId) -> Result<CancelAcknowledgement, String> {
306    // The compact observation checks the repository and settles a Run whose worker died.
307    let current = status(context, id).await?;
308    let receipts = Receipts::open(&context.state, &context.repo).await?;
309    let result = receipts.request_cancel(id).await;
310    let closed = receipts.close().await;
311    let (saved, control) = result.and_then(|saved| closed.map(|()| saved))?;
312    Ok(CancelAcknowledgement {
313        run: id.clone(),
314        state: observe::state_for(saved, control.as_ref(), &current.counts),
315        cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
316    })
317}
318
319fn owner_died(status: crate::types::RunStatus, control: Option<&Control>) -> Result<bool, String> {
320    if !status.is_open() {
321        return Ok(false);
322    }
323    let owner = control.and_then(|control| match control.worker {
324        Worker::Starting { launcher } => Some(launcher),
325        Worker::Admitted { owner } => Some(owner),
326        Worker::Legacy => None,
327    });
328    Ok(owner.is_some() && !process::is_alive(owner).map_err(|error| error.to_string())?)
329}
330
331pub(crate) async fn reconcile(
332    state: &Path,
333    view: store::RunView,
334) -> Result<store::RunView, String> {
335    if owner_died(view.run.status(), view.run.control.as_ref())? {
336        worker::recover(state, &view).await?;
337        return store::read_run(state, &view.run.id).await;
338    }
339    Ok(view)
340}