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