sail-runtime 0.4.0

Exact bounded SMT execution for embedded and service clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Attributed native temporal execution through an isolated worker.
//!
//! This crate links no native temporal backend (ADR 0083). The `sail` binary
//! supplies `sail-dive`'s as a [`TemporalBackend`] (ADR 0172); an embedder
//! that supplies none gets a capability that reports unavailable, and
//! temporal jobs return `Unavailable`.
use crate::{Cancellation, execution, invalid};
use sail_api::{
    runtime::Outcome,
    temporal::{Capability, DIVE_VERSION, Job, Request, Response, Result},
};
use serde::{Deserialize, Serialize};
use std::{
    io::Read as _,
    path::{Path, PathBuf},
    sync::atomic::AtomicBool,
    time::{Duration, Instant},
};

pub mod image;
#[cfg(test)]
mod receipt_tests;
mod receipts;

/// Process outcome of one dispatched native job, separate from every model verdict.
#[derive(Debug)]
pub enum Dispatch {
    /// Complete evidence the backend validated against the exact request.
    Completed(Box<Response>),
    /// The backend killed and reaped the worker at its deadline.
    TimedOut,
    /// The backend killed and reaped the worker after explicit cancellation.
    Cancelled,
    /// Startup, protocol, validation or process failure, with no logical verdict.
    Failed(String),
}

/// A native temporal backend linked into this `sail` build.
///
/// The runtime authenticates the installed worker and admits the job before
/// calling [`TemporalBackend::run`]. The backend owns the worker process and
/// must independently validate the worker's evidence against `request`
/// before returning [`Dispatch::Completed`]; anything it cannot validate is
/// [`Dispatch::Failed`], never a verdict.
pub trait TemporalBackend: Send + Sync + std::fmt::Debug {
    /// Opt in to exact check replay under a producer-specific policy and validator.
    /// Change the policy identity whenever checking or evidence admission changes.
    fn replay_policy(&self) -> Option<ReplayPolicy> {
        None
    }

    /// Run one admitted request in `worker`, killing and reaping it when
    /// `deadline` elapses or `cancel` is set.
    fn run(
        &self,
        worker: &Worker,
        request: &Request,
        deadline: Duration,
        cancel: &AtomicBool,
    ) -> Dispatch;
}

/// Exact evidence policy of one trusted backend implementation.
#[derive(Clone, Copy, Debug)]
pub struct ReplayPolicy {
    /// Versioned producer identity, binding fixed settings and evidence semantics.
    pub identity: &'static str,
    /// Independently validate this producer's evidence against the current request.
    pub validate: fn(&Request, &Response) -> std::result::Result<(), String>,
}

/// Trusted installation choice; callers cannot supply it in a wire request.
#[derive(Clone, Debug)]
pub struct Worker {
    /// Fixed installed executable, authenticated before every dispatch.
    pub executable: PathBuf,
    /// Expected digest from the installation manifest.
    pub sha256: String,
}

/// Versioned worker installation manifest, covered by the release file index.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
    /// Installation format, currently one.
    pub version: u32,
    /// Native payload version.
    pub protocol: u32,
    /// Exact linked native backend release (`sail_api::temporal::DIVE_VERSION`).
    pub backend_revision: String,
    /// OS and architecture of the executable.
    pub platform: String,
    /// SHA-256 of the installed executable bytes.
    pub sha256: String,
}

impl Worker {
    /// Resolve a fixed sibling worker and manifest without searching PATH.
    ///
    /// # Errors
    /// Refuses malformed, incompatible, oversized or unreadable manifests.
    pub fn discover(sail: &Path) -> std::result::Result<Option<Self>, sail_api::runtime::Error> {
        let parent = sail
            .parent()
            .ok_or_else(|| invalid("invalid_config", "sail executable has no parent"))?;
        let manifest = parent.join("sail-runtime-worker.json");
        let mut bytes = Vec::new();
        match std::fs::File::open(&manifest).and_then(|f| f.take(4097).read_to_end(&mut bytes)) {
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(invalid(
                    "invalid_config",
                    format!("cannot read worker installation manifest: {e}"),
                ));
            }
        }
        if bytes.len() > 4096 {
            return Err(invalid(
                "invalid_config",
                "worker installation manifest exceeds 4 KiB",
            ));
        }
        let manifest: Manifest = serde_json::from_slice(&bytes).map_err(|e| {
            invalid(
                "invalid_config",
                format!("invalid worker installation manifest: {e}"),
            )
        })?;
        if manifest.version != 1
            || manifest.protocol != sail_api::temporal::VERSION
            || manifest.backend_revision != DIVE_VERSION
            || manifest.platform != platform()
            || !digest(&manifest.sha256)
        {
            return Err(invalid(
                "invalid_config",
                "worker installation identity is incompatible",
            ));
        }
        Ok(Some(Self {
            executable: parent.join("sail-runtime-worker"),
            sha256: manifest.sha256,
        }))
    }

    fn authenticate(&self) -> std::result::Result<(), sail_api::runtime::Error> {
        // A verified copy recorded at the installed worker's current settled
        // stamp is proof of these exact bytes ([`image`]).
        if image::verified(&self.executable, &self.sha256) {
            return Ok(());
        }
        let mut bytes = Vec::new();
        std::fs::File::open(&self.executable)
            .and_then(|f| f.take(512 * 1024 * 1024 + 1).read_to_end(&mut bytes))
            .map_err(|e| {
                execution(
                    "unavailable",
                    format!("native temporal worker unavailable: {e}"),
                )
            })?;
        if !digest(&self.sha256)
            || bytes.len() > 512 * 1024 * 1024
            || crate::hash(&bytes) != self.sha256
        {
            return Err(execution(
                "unavailable",
                "native temporal worker differs from installation identity",
            ));
        }
        Ok(())
    }
}

fn digest(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}

/// Stable host identity used in worker installation manifests.
#[must_use]
pub fn platform() -> String {
    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}

/// Resolve the sibling worker for a service that must start regardless.
///
/// Any manifest problem leaves temporal jobs unavailable with the reason; it
/// never prevents the service, and SMT execution, from starting.
#[must_use]
pub fn locate(sail: &Path) -> (Option<Worker>, Option<sail_api::runtime::Error>) {
    match Worker::discover(sail) {
        Ok(worker) => (worker, None),
        Err(error) => (
            None,
            Some(execution(
                "unavailable",
                format!("native temporal worker unavailable: {}", error.message),
            )),
        ),
    }
}

/// Unavailable reason of a `sail` built without a temporal backend.
pub const NOT_INCLUDED: &str = "native temporal support is not included in this sail build";

pub(crate) fn capability(
    backend: Option<&dyn TemporalBackend>,
    worker: Option<&Worker>,
    problem: Option<&sail_api::runtime::Error>,
) -> Capability {
    let authenticated = match (backend, worker, problem) {
        (None, _, _) => Err(execution("unavailable", NOT_INCLUDED)),
        (Some(_), Some(worker), _) => worker.authenticate(),
        (Some(_), None, Some(problem)) => Err(problem.clone()),
        (Some(_), None, None) => Err(execution(
            "unavailable",
            "native temporal worker is not installed",
        )),
    };
    Capability {
        implemented: true,
        installed: authenticated.is_ok(),
        backend_revision: DIVE_VERSION.into(),
        worker_sha256: authenticated
            .as_ref()
            .ok()
            .and_then(|()| worker.map(|w| w.sha256.clone())),
        replay_context: authenticated.as_ref().ok().and_then(|()| {
            receipts::context(
                &worker?.sha256,
                DIVE_VERSION,
                &platform(),
                backend?.replay_policy()?.identity,
            )
        }),
        error: authenticated.err(),
    }
}

fn admitted_result(job: &Job) -> std::result::Result<Result, sail_api::runtime::Error> {
    if job.obligation_id.trim().is_empty()
        || job.obligation_id.len() > 1024
        || job.requirement_ids.len() > 1024
        || job
            .requirement_ids
            .iter()
            .any(|id| id.trim().is_empty() || id.len() > 1024)
        || job.requirement_ids.windows(2).any(|ids| ids[0] >= ids[1])
        || job.wall_time_ms == 0
        || job.wall_time_ms > sail_api::runtime::MAX_WALL_TIME_MS
        || job.request.version != sail_api::temporal::VERSION
    {
        return Err(invalid(
            "invalid_request",
            "invalid temporal identity, version or deadline",
        ));
    }
    let bytes =
        serde_json::to_vec(&job.request).map_err(|e| invalid("invalid_request", e.to_string()))?;
    if bytes.len() > sail_api::temporal::MAX_DOCUMENT_BYTES {
        return Err(invalid(
            "invalid_request",
            "temporal payload exceeds 16 MiB",
        ));
    }
    Ok(Result {
        obligation_id: job.obligation_id.clone(),
        requirement_ids: job.requirement_ids.clone(),
        request_sha256: sail_api::temporal::request_sha256(&job.request)
            .map_err(|e| invalid("invalid_request", e.to_string()))?,
        backend_revision: DIVE_VERSION.into(),
        worker_sha256: None,
        wall_time_ms: job.wall_time_ms,
        outcome: Outcome::Unavailable,
        response: None,
        error: None,
        cache_hit: false,
        cache_key: None,
    })
}

impl super::Runtime {
    /// Read a completed exact native check from this runtime's trusted cache.
    /// A miss, a cancelled lookup or an unavailable producer returns `None`.
    /// The lookup authenticates the installed worker and validates its receipt.
    /// It never launches a worker or publishes a receipt.
    ///
    /// # Errors
    /// Returns the same request admission errors as [`Self::execute`].
    pub fn lookup_temporal(
        &self,
        job: &Job,
        cancellation: &Cancellation,
    ) -> std::result::Result<Option<Result>, sail_api::runtime::Error> {
        let start = Instant::now();
        let mut result = admitted_result(job)?;
        let config = &self.config;
        let (Some(backend), Some(worker)) = (
            config.temporal_backend.as_deref(),
            config.temporal_worker.as_ref(),
        ) else {
            return Ok(None);
        };
        if cancellation.is_cancelled() || worker.authenticate().is_err() {
            return Ok(None);
        }
        let Some(receipt) = receipts::Receipt::for_check(
            config
                .temporal_cache_directory
                .as_deref()
                .or(config.cache_directory.as_deref()),
            job,
            &result.request_sha256,
            &result.backend_revision,
            worker,
            backend.replay_policy(),
        ) else {
            return Ok(None);
        };
        let Some(response) = receipt.read(&job.request) else {
            return Ok(None);
        };
        if cancellation.is_cancelled() || start.elapsed() >= Duration::from_millis(job.wall_time_ms)
        {
            return Ok(None);
        }
        result.worker_sha256 = Some(worker.sha256.clone());
        result.outcome = Outcome::Completed;
        result.response = Some(*response);
        result.cache_hit = true;
        result.cache_key = Some(receipt.key());
        Ok(Some(result))
    }
}

pub(crate) fn execute(
    job: &Job,
    backend: Option<&dyn TemporalBackend>,
    worker: Option<&Worker>,
    problem: Option<&sail_api::runtime::Error>,
    cache_directory: Option<&Path>,
    cancellation: &Cancellation,
) -> std::result::Result<Result, sail_api::runtime::Error> {
    let started = Instant::now();
    let mut result = admitted_result(job)?;
    let ready = capability(backend, worker, problem);
    if !ready.installed {
        result.error = ready.error;
        return Ok(result);
    }
    let (Some(backend), Some(worker)) = (backend, worker) else {
        return Err(execution(
            "infrastructure",
            "installed temporal worker missing configuration",
        ));
    };
    result.worker_sha256 = Some(worker.sha256.clone());
    let receipt = receipts::Receipt::for_check(
        cache_directory,
        job,
        &result.request_sha256,
        &result.backend_revision,
        worker,
        backend.replay_policy(),
    );
    let (dispatch, cache_key) = receipts::dispatch(
        &job.request,
        worker,
        backend,
        receipt.as_ref(),
        cancellation,
        started + Duration::from_millis(job.wall_time_ms),
    );
    result.cache_hit = cache_key.is_some();
    result.cache_key = cache_key;
    match dispatch {
        Dispatch::Completed(response) => {
            result.outcome = Outcome::Completed;
            result.response = Some(*response);
        }
        Dispatch::TimedOut => {
            result.outcome = Outcome::Timeout;
            result.error = Some(execution("timeout", "native temporal deadline expired"));
        }
        Dispatch::Cancelled => {
            result.outcome = Outcome::Cancelled;
            result.error = Some(execution(
                "cancelled",
                "native temporal execution cancelled",
            ));
        }
        Dispatch::Failed(message) => {
            result.outcome = Outcome::Infrastructure;
            result.error = Some(execution("infrastructure", message));
        }
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn missing_manifest_is_unavailable_and_wrong_manifest_cannot_select_an_executable()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let root =
            std::env::temp_dir().join(format!("sail-worker-manifest-{}", std::process::id()));
        std::fs::create_dir(&root)?;
        let path = root.join("sail");
        assert!(Worker::discover(&path)?.is_none());
        let manifest = root.join("sail-runtime-worker.json");
        std::fs::write(&manifest, "{}")?;
        assert!(Worker::discover(&path).is_err());
        std::fs::write(
            &manifest,
            serde_json::to_vec(&Manifest {
                version: 1,
                protocol: sail_api::temporal::VERSION,
                backend_revision: DIVE_VERSION.into(),
                platform: platform(),
                sha256: "0".repeat(64),
            })?,
        )?;
        let worker = Worker::discover(&path)?.ok_or("missing worker configuration")?;
        assert!(!capability(Some(&Stub), Some(&worker), None).installed);
        std::fs::write(&worker.executable, "changed")?;
        assert!(!capability(Some(&Stub), Some(&worker), None).installed);
        std::fs::remove_dir_all(root)?;
        Ok(())
    }

    /// Replays a fixed process outcome chosen by the model's root module.
    #[derive(Debug)]
    struct Stub;
    impl TemporalBackend for Stub {
        fn run(&self, _: &Worker, request: &Request, _: Duration, _: &AtomicBool) -> Dispatch {
            match request.model.root.as_str() {
                "timeout.tla" => Dispatch::TimedOut,
                "cancel.tla" => Dispatch::Cancelled,
                other => Dispatch::Failed(format!("stub dispatched {other}")),
            }
        }
    }

    fn job(root: &str) -> Job {
        Job {
            obligation_id: "obligation".into(),
            requirement_ids: vec!["REQ-1".into()],
            request: Request {
                version: sail_api::temporal::VERSION,
                model: sail_api::temporal::Model {
                    files: std::collections::BTreeMap::from([
                        (root.into(), "---- MODULE M ----\n====\n".into()),
                        ("M.cfg".into(), "INIT Init\n".into()),
                    ]),
                    root: root.into(),
                    config: "M.cfg".into(),
                },
                operation: sail_api::temporal::Operation::Check {
                    max_states: 1,
                    max_depth: 1,
                },
            },
            wall_time_ms: 1000,
        }
    }

    #[test]
    fn only_a_linked_backend_dispatches_and_its_process_outcomes_are_never_verdicts()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let root = std::env::temp_dir().join(format!("sail-worker-backend-{}", std::process::id()));
        std::fs::create_dir(&root)?;
        let executable = root.join("sail-runtime-worker");
        std::fs::write(&executable, "worker bytes")?;
        let worker = Worker {
            sha256: crate::hash(b"worker bytes"),
            executable,
        };
        let cancellation = Cancellation::default();
        // No backend in this build: an authenticated worker is never run.
        let missing = execute(
            &job("M.tla"),
            None,
            Some(&worker),
            None,
            None,
            &cancellation,
        )?;
        assert_eq!(missing.outcome, Outcome::Unavailable);
        assert!(missing.worker_sha256.is_none());
        let reason = missing.error.ok_or("no reason")?;
        assert_eq!(
            (reason.kind.as_str(), reason.message.as_str()),
            ("unavailable", NOT_INCLUDED)
        );
        assert!(!capability(None, Some(&worker), None).installed);
        // A linked backend runs only the authenticated worker.
        assert!(capability(Some(&Stub), Some(&worker), None).installed);
        for (root_module, outcome) in [
            ("timeout.tla", Outcome::Timeout),
            ("cancel.tla", Outcome::Cancelled),
            ("M.tla", Outcome::Infrastructure),
        ] {
            let result = execute(
                &job(root_module),
                Some(&Stub),
                Some(&worker),
                None,
                None,
                &cancellation,
            )?;
            assert_eq!(result.outcome, outcome);
            assert!(result.response.is_none() && result.error.is_some());
            assert_eq!(
                result.worker_sha256.as_deref(),
                Some(worker.sha256.as_str())
            );
        }
        std::fs::write(&worker.executable, "changed")?;
        let changed = execute(
            &job("M.tla"),
            Some(&Stub),
            Some(&worker),
            None,
            None,
            &cancellation,
        )?;
        assert_eq!(changed.outcome, Outcome::Unavailable);
        std::fs::remove_dir_all(root)?;
        Ok(())
    }

    #[test]
    fn malformed_or_unreadable_manifest_only_makes_temporal_unavailable()
    -> std::result::Result<(), Box<dyn std::error::Error>> {
        let root =
            std::env::temp_dir().join(format!("sail-worker-manifest-bad-{}", std::process::id()));
        std::fs::create_dir(&root)?;
        let path = root.join("sail");
        let manifest = root.join("sail-runtime-worker.json");
        for broken in [&b"not json"[..], &[b' '; 5000][..]] {
            std::fs::write(&manifest, broken)?;
            let (worker, problem) = locate(&path);
            assert!(worker.is_none());
            for (backend, expected) in [
                (
                    Some(std::sync::Arc::new(Stub) as std::sync::Arc<dyn TemporalBackend>),
                    "manifest",
                ),
                (None, NOT_INCLUDED),
            ] {
                let runtime = crate::Runtime::new(crate::Config {
                    temporal_backend: backend,
                    temporal_worker: worker.clone(),
                    temporal_unavailable: problem.clone(),
                    ..crate::Config::default()
                })?;
                let temporal = runtime.capabilities().temporal.ok_or("no capability")?;
                assert!(!temporal.installed);
                let error = temporal.error.ok_or("no reason")?;
                assert_eq!(error.kind, "unavailable");
                assert!(error.message.contains(expected), "{}", error.message);
            }
        }
        // A directory in place of the manifest cannot be read as a file.
        std::fs::remove_file(&manifest)?;
        std::fs::create_dir(&manifest)?;
        let (worker, problem) = locate(&path);
        assert!(worker.is_none() && problem.is_some());
        std::fs::remove_dir_all(root)?;
        Ok(())
    }
}