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