Skip to main content

sail_runtime/
temporal.rs

1//! Attributed native temporal execution through an isolated worker.
2//!
3//! This crate links no native temporal backend (ADR 0083). A `sail` built
4//! from the temporal extension workspace supplies one as a
5//! [`TemporalBackend`]; without it the capability reports unavailable and
6//! temporal jobs return `Unavailable`.
7use crate::{Cancellation, execution, invalid};
8use sail_api::{
9    runtime::Outcome,
10    temporal::{Capability, DIVE_REVISION, Job, Request, Response, Result},
11};
12use serde::{Deserialize, Serialize};
13use std::{
14    io::Read as _,
15    path::{Path, PathBuf},
16    sync::atomic::AtomicBool,
17    time::{Duration, Instant},
18};
19
20/// Process outcome of one dispatched native job, separate from every model verdict.
21#[derive(Debug)]
22pub enum Dispatch {
23    /// Complete evidence the backend validated against the exact request.
24    Completed(Box<Response>),
25    /// The backend killed and reaped the worker at its deadline.
26    TimedOut,
27    /// The backend killed and reaped the worker after explicit cancellation.
28    Cancelled,
29    /// Startup, protocol, validation or process failure, with no logical verdict.
30    Failed(String),
31}
32
33/// A native temporal backend linked into this `sail` build.
34///
35/// The runtime authenticates the installed worker and admits the job before
36/// calling [`TemporalBackend::run`]. The backend owns the worker process and
37/// must independently validate the worker's evidence against `request`
38/// before returning [`Dispatch::Completed`]; anything it cannot validate is
39/// [`Dispatch::Failed`], never a verdict.
40pub trait TemporalBackend: Send + Sync + std::fmt::Debug {
41    /// Run one admitted request in `worker`, killing and reaping it when
42    /// `deadline` elapses or `cancel` is set.
43    fn run(
44        &self,
45        worker: &Worker,
46        request: &Request,
47        deadline: Duration,
48        cancel: &AtomicBool,
49    ) -> Dispatch;
50}
51
52/// Trusted installation choice; callers cannot supply it in a wire request.
53#[derive(Clone, Debug)]
54pub struct Worker {
55    /// Fixed installed executable, authenticated before every dispatch.
56    pub executable: PathBuf,
57    /// Expected digest from the installation manifest.
58    pub sha256: String,
59}
60
61/// Versioned worker installation manifest, covered by the release file index.
62#[derive(Clone, Debug, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct Manifest {
65    /// Installation format, currently one.
66    pub version: u32,
67    /// Native payload version.
68    pub protocol: u32,
69    /// Exact linked native source revision.
70    pub backend_revision: String,
71    /// OS and architecture of the executable.
72    pub platform: String,
73    /// SHA-256 of the installed executable bytes.
74    pub sha256: String,
75}
76
77impl Worker {
78    /// Resolve a fixed sibling worker and manifest without searching PATH.
79    ///
80    /// # Errors
81    /// Refuses malformed, incompatible, oversized or unreadable manifests.
82    pub fn discover(sail: &Path) -> std::result::Result<Option<Self>, sail_api::runtime::Error> {
83        let parent = sail
84            .parent()
85            .ok_or_else(|| invalid("invalid_config", "sail executable has no parent"))?;
86        let manifest = parent.join("sail-runtime-worker.json");
87        let mut bytes = Vec::new();
88        match std::fs::File::open(&manifest).and_then(|f| f.take(4097).read_to_end(&mut bytes)) {
89            Ok(_) => {}
90            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
91            Err(e) => {
92                return Err(invalid(
93                    "invalid_config",
94                    format!("cannot read worker installation manifest: {e}"),
95                ));
96            }
97        }
98        if bytes.len() > 4096 {
99            return Err(invalid(
100                "invalid_config",
101                "worker installation manifest exceeds 4 KiB",
102            ));
103        }
104        let manifest: Manifest = serde_json::from_slice(&bytes).map_err(|e| {
105            invalid(
106                "invalid_config",
107                format!("invalid worker installation manifest: {e}"),
108            )
109        })?;
110        if manifest.version != 1
111            || manifest.protocol != sail_api::temporal::VERSION
112            || manifest.backend_revision != DIVE_REVISION
113            || manifest.platform != platform()
114            || !digest(&manifest.sha256)
115        {
116            return Err(invalid(
117                "invalid_config",
118                "worker installation identity is incompatible",
119            ));
120        }
121        Ok(Some(Self {
122            executable: parent.join("sail-runtime-worker"),
123            sha256: manifest.sha256,
124        }))
125    }
126
127    fn authenticate(&self) -> std::result::Result<(), sail_api::runtime::Error> {
128        let mut bytes = Vec::new();
129        std::fs::File::open(&self.executable)
130            .and_then(|f| f.take(512 * 1024 * 1024 + 1).read_to_end(&mut bytes))
131            .map_err(|e| {
132                execution(
133                    "unavailable",
134                    format!("native temporal worker unavailable: {e}"),
135                )
136            })?;
137        if !digest(&self.sha256)
138            || bytes.len() > 512 * 1024 * 1024
139            || crate::hash(&bytes) != self.sha256
140        {
141            return Err(execution(
142                "unavailable",
143                "native temporal worker differs from installation identity",
144            ));
145        }
146        Ok(())
147    }
148}
149
150fn digest(value: &str) -> bool {
151    value.len() == 64
152        && value
153            .bytes()
154            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
155}
156
157/// Stable host identity used in worker installation manifests.
158#[must_use]
159pub fn platform() -> String {
160    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
161}
162
163/// Resolve the sibling worker for a service that must start regardless.
164///
165/// Any manifest problem leaves temporal jobs unavailable with the reason; it
166/// never prevents the service, and SMT execution, from starting.
167#[must_use]
168pub fn locate(sail: &Path) -> (Option<Worker>, Option<sail_api::runtime::Error>) {
169    match Worker::discover(sail) {
170        Ok(worker) => (worker, None),
171        Err(error) => (
172            None,
173            Some(execution(
174                "unavailable",
175                format!("native temporal worker unavailable: {}", error.message),
176            )),
177        ),
178    }
179}
180
181/// Unavailable reason of a `sail` built without a temporal backend.
182pub const NOT_INCLUDED: &str = "native temporal support is not included in this sail build";
183
184pub(crate) fn capability(
185    backend: Option<&dyn TemporalBackend>,
186    worker: Option<&Worker>,
187    problem: Option<&sail_api::runtime::Error>,
188) -> Capability {
189    let authenticated = match (backend, worker, problem) {
190        (None, _, _) => Err(execution("unavailable", NOT_INCLUDED)),
191        (Some(_), Some(worker), _) => worker.authenticate(),
192        (Some(_), None, Some(problem)) => Err(problem.clone()),
193        (Some(_), None, None) => Err(execution(
194            "unavailable",
195            "native temporal worker is not installed",
196        )),
197    };
198    Capability {
199        implemented: true,
200        installed: authenticated.is_ok(),
201        backend_revision: DIVE_REVISION.into(),
202        worker_sha256: authenticated
203            .as_ref()
204            .ok()
205            .and_then(|()| worker.map(|w| w.sha256.clone())),
206        error: authenticated.err(),
207    }
208}
209
210pub(crate) fn execute(
211    job: &Job,
212    backend: Option<&dyn TemporalBackend>,
213    worker: Option<&Worker>,
214    problem: Option<&sail_api::runtime::Error>,
215    cancellation: &Cancellation,
216) -> std::result::Result<Result, sail_api::runtime::Error> {
217    let started = Instant::now();
218    if job.obligation_id.trim().is_empty()
219        || job.obligation_id.len() > 1024
220        || job.requirement_ids.len() > 1024
221        || job
222            .requirement_ids
223            .iter()
224            .any(|id| id.trim().is_empty() || id.len() > 1024)
225        || job.requirement_ids.windows(2).any(|ids| ids[0] >= ids[1])
226        || job.wall_time_ms == 0
227        || job.wall_time_ms > sail_api::runtime::MAX_WALL_TIME_MS
228        || job.request.version != sail_api::temporal::VERSION
229    {
230        return Err(invalid(
231            "invalid_request",
232            "invalid temporal identity, version or deadline",
233        ));
234    }
235    let bytes =
236        serde_json::to_vec(&job.request).map_err(|e| invalid("invalid_request", e.to_string()))?;
237    if bytes.len() > sail_api::temporal::MAX_DOCUMENT_BYTES {
238        return Err(invalid(
239            "invalid_request",
240            "temporal payload exceeds 16 MiB",
241        ));
242    }
243    let mut result = Result {
244        obligation_id: job.obligation_id.clone(),
245        requirement_ids: job.requirement_ids.clone(),
246        request_sha256: sail_api::temporal::request_sha256(&job.request)
247            .map_err(|e| invalid("invalid_request", e.to_string()))?,
248        backend_revision: DIVE_REVISION.into(),
249        worker_sha256: None,
250        wall_time_ms: job.wall_time_ms,
251        outcome: Outcome::Unavailable,
252        response: None,
253        error: None,
254        cache_hit: false,
255    };
256    let ready = capability(backend, worker, problem);
257    if !ready.installed {
258        result.error = ready.error;
259        return Ok(result);
260    }
261    let (Some(backend), Some(worker)) = (backend, worker) else {
262        return Err(execution(
263            "infrastructure",
264            "installed temporal worker missing configuration",
265        ));
266    };
267    result.worker_sha256 = Some(worker.sha256.clone());
268    match backend.run(
269        worker,
270        &job.request,
271        Duration::from_millis(job.wall_time_ms).saturating_sub(started.elapsed()),
272        &cancellation.0,
273    ) {
274        Dispatch::Completed(response) => {
275            result.outcome = Outcome::Completed;
276            result.response = Some(*response);
277        }
278        Dispatch::TimedOut => {
279            result.outcome = Outcome::Timeout;
280            result.error = Some(execution("timeout", "native temporal deadline expired"));
281        }
282        Dispatch::Cancelled => {
283            result.outcome = Outcome::Cancelled;
284            result.error = Some(execution(
285                "cancelled",
286                "native temporal execution cancelled",
287            ));
288        }
289        Dispatch::Failed(message) => {
290            result.outcome = Outcome::Infrastructure;
291            result.error = Some(execution("infrastructure", message));
292        }
293    }
294    Ok(result)
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    #[test]
301    fn missing_manifest_is_unavailable_and_wrong_manifest_cannot_select_an_executable()
302    -> std::result::Result<(), Box<dyn std::error::Error>> {
303        let root =
304            std::env::temp_dir().join(format!("sail-worker-manifest-{}", std::process::id()));
305        std::fs::create_dir(&root)?;
306        let path = root.join("sail");
307        assert!(Worker::discover(&path)?.is_none());
308        let manifest = root.join("sail-runtime-worker.json");
309        std::fs::write(&manifest, "{}")?;
310        assert!(Worker::discover(&path).is_err());
311        std::fs::write(
312            &manifest,
313            serde_json::to_vec(&Manifest {
314                version: 1,
315                protocol: sail_api::temporal::VERSION,
316                backend_revision: DIVE_REVISION.into(),
317                platform: platform(),
318                sha256: "0".repeat(64),
319            })?,
320        )?;
321        let worker = Worker::discover(&path)?.ok_or("missing worker configuration")?;
322        assert!(!capability(Some(&Stub), Some(&worker), None).installed);
323        std::fs::write(&worker.executable, "changed")?;
324        assert!(!capability(Some(&Stub), Some(&worker), None).installed);
325        std::fs::remove_dir_all(root)?;
326        Ok(())
327    }
328
329    /// Replays a fixed process outcome chosen by the model's root module.
330    #[derive(Debug)]
331    struct Stub;
332    impl TemporalBackend for Stub {
333        fn run(&self, _: &Worker, request: &Request, _: Duration, _: &AtomicBool) -> Dispatch {
334            match request.model.root.as_str() {
335                "timeout.tla" => Dispatch::TimedOut,
336                "cancel.tla" => Dispatch::Cancelled,
337                other => Dispatch::Failed(format!("stub dispatched {other}")),
338            }
339        }
340    }
341
342    fn job(root: &str) -> Job {
343        Job {
344            obligation_id: "obligation".into(),
345            requirement_ids: vec!["REQ-1".into()],
346            request: Request {
347                version: sail_api::temporal::VERSION,
348                model: sail_api::temporal::Model {
349                    files: std::collections::BTreeMap::from([
350                        (root.into(), "---- MODULE M ----\n====\n".into()),
351                        ("M.cfg".into(), "INIT Init\n".into()),
352                    ]),
353                    root: root.into(),
354                    config: "M.cfg".into(),
355                },
356                operation: sail_api::temporal::Operation::Check {
357                    max_states: 1,
358                    max_depth: 1,
359                },
360            },
361            wall_time_ms: 1000,
362        }
363    }
364
365    #[test]
366    fn only_a_linked_backend_dispatches_and_its_process_outcomes_are_never_verdicts()
367    -> std::result::Result<(), Box<dyn std::error::Error>> {
368        let root = std::env::temp_dir().join(format!("sail-worker-backend-{}", std::process::id()));
369        std::fs::create_dir(&root)?;
370        let executable = root.join("sail-runtime-worker");
371        std::fs::write(&executable, "worker bytes")?;
372        let worker = Worker {
373            sha256: crate::hash(b"worker bytes"),
374            executable,
375        };
376        let cancellation = Cancellation::default();
377        // No backend in this build: an authenticated worker is never run.
378        let missing = execute(&job("M.tla"), None, Some(&worker), None, &cancellation)?;
379        assert_eq!(missing.outcome, Outcome::Unavailable);
380        assert!(missing.worker_sha256.is_none());
381        let reason = missing.error.ok_or("no reason")?;
382        assert_eq!(
383            (reason.kind.as_str(), reason.message.as_str()),
384            ("unavailable", NOT_INCLUDED)
385        );
386        assert!(!capability(None, Some(&worker), None).installed);
387        // A linked backend runs only the authenticated worker.
388        assert!(capability(Some(&Stub), Some(&worker), None).installed);
389        for (root_module, outcome) in [
390            ("timeout.tla", Outcome::Timeout),
391            ("cancel.tla", Outcome::Cancelled),
392            ("M.tla", Outcome::Infrastructure),
393        ] {
394            let result = execute(
395                &job(root_module),
396                Some(&Stub),
397                Some(&worker),
398                None,
399                &cancellation,
400            )?;
401            assert_eq!(result.outcome, outcome);
402            assert!(result.response.is_none() && result.error.is_some());
403            assert_eq!(
404                result.worker_sha256.as_deref(),
405                Some(worker.sha256.as_str())
406            );
407        }
408        std::fs::write(&worker.executable, "changed")?;
409        let changed = execute(
410            &job("M.tla"),
411            Some(&Stub),
412            Some(&worker),
413            None,
414            &cancellation,
415        )?;
416        assert_eq!(changed.outcome, Outcome::Unavailable);
417        std::fs::remove_dir_all(root)?;
418        Ok(())
419    }
420
421    #[test]
422    fn malformed_or_unreadable_manifest_only_makes_temporal_unavailable()
423    -> std::result::Result<(), Box<dyn std::error::Error>> {
424        let root =
425            std::env::temp_dir().join(format!("sail-worker-manifest-bad-{}", std::process::id()));
426        std::fs::create_dir(&root)?;
427        let path = root.join("sail");
428        let manifest = root.join("sail-runtime-worker.json");
429        for broken in [&b"not json"[..], &[b' '; 5000][..]] {
430            std::fs::write(&manifest, broken)?;
431            let (worker, problem) = locate(&path);
432            assert!(worker.is_none());
433            for (backend, expected) in [
434                (
435                    Some(std::sync::Arc::new(Stub) as std::sync::Arc<dyn TemporalBackend>),
436                    "manifest",
437                ),
438                (None, NOT_INCLUDED),
439            ] {
440                let runtime = crate::Runtime::new(crate::Config {
441                    temporal_backend: backend,
442                    temporal_worker: worker.clone(),
443                    temporal_unavailable: problem.clone(),
444                    ..crate::Config::default()
445                })?;
446                let temporal = runtime.capabilities().temporal.ok_or("no capability")?;
447                assert!(!temporal.installed);
448                let error = temporal.error.ok_or("no reason")?;
449                assert_eq!(error.kind, "unavailable");
450                assert!(error.message.contains(expected), "{}", error.message);
451            }
452        }
453        // A directory in place of the manifest cannot be read as a file.
454        std::fs::remove_file(&manifest)?;
455        std::fs::create_dir(&manifest)?;
456        let (worker, problem) = locate(&path);
457        assert!(worker.is_none() && problem.is_some());
458        std::fs::remove_dir_all(root)?;
459        Ok(())
460    }
461}