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