Skip to main content

sail_runtime/
lib.rs

1//! Bounded exact SMT execution, independently usable without a daemon.
2#![forbid(unsafe_code)]
3
4mod admission;
5mod process;
6mod store;
7pub mod temporal;
8#[cfg(test)]
9mod tests;
10
11use sail_api::runtime::{
12    BackendCapability, Capabilities, Error, Input, Limits, MAX_INPUT_BYTES, MAX_OUTPUT_BYTES,
13    MAX_QUERIES, MAX_WALL_TIME_MS, Outcome, Output, Query, QueryResult, Request, Response,
14    SolverIdentity, VERSION,
15};
16use sha2::{Digest as _, Sha256};
17use std::{
18    path::PathBuf,
19    sync::{
20        Arc,
21        atomic::{AtomicBool, Ordering},
22    },
23};
24
25/// Configuration of installed tools and bounded execution; performs no installation.
26#[derive(Clone, Debug)]
27pub struct Config {
28    /// Native temporal backend linked into this build; `None` (the default,
29    /// and every build of this workspace) reports temporal jobs unavailable.
30    pub temporal_backend: Option<Arc<dyn temporal::TemporalBackend>>,
31    /// Trusted installed native temporal worker, absent when not installed.
32    pub temporal_worker: Option<temporal::Worker>,
33    /// Why no worker was configured, reported as the temporal unavailable reason.
34    pub temporal_unavailable: Option<Error>,
35    /// Existing bundled Z3 executable, independently verified against the embedded pin.
36    pub z3: Option<PathBuf>,
37    /// Optional disk cache root; existing Verus cache namespaces are untouched.
38    pub cache_directory: Option<PathBuf>,
39    /// Maximum concurrent independent transcripts, from one through sixteen.
40    pub workers: usize,
41}
42
43impl Default for Config {
44    fn default() -> Self {
45        Self {
46            temporal_backend: None,
47            temporal_worker: None,
48            temporal_unavailable: None,
49            z3: None,
50            cache_directory: None,
51            workers: 2,
52        }
53    }
54}
55
56/// Clonable explicit cancellation shared by the caller and actual child processes.
57#[derive(Clone, Debug, Default)]
58pub struct Cancellation(Arc<AtomicBool>);
59
60impl Cancellation {
61    /// Cancel current and undispatched work. Cancellation is permanent for this token.
62    pub fn cancel(&self) {
63        self.0.store(true, Ordering::SeqCst);
64    }
65    /// Whether cancellation was requested.
66    #[must_use]
67    pub fn is_cancelled(&self) -> bool {
68        self.0.load(Ordering::SeqCst)
69    }
70}
71
72/// An exact-input runtime; no Verus serving path is modified by its construction.
73pub struct Runtime {
74    config: Config,
75    pin: Option<(String, String)>,
76}
77
78pub(crate) fn invalid(kind: &str, message: impl Into<String>) -> Error {
79    Error {
80        code: "SAIL6101".into(),
81        kind: kind.into(),
82        message: message.into(),
83    }
84}
85
86pub(crate) fn execution(kind: &str, message: impl Into<String>) -> Error {
87    Error {
88        code: "SAIL6102".into(),
89        kind: kind.into(),
90        message: message.into(),
91    }
92}
93
94pub(crate) fn hash(bytes: &[u8]) -> String {
95    format!("{:x}", Sha256::digest(bytes))
96}
97
98fn pin() -> Result<Option<(String, String)>, Error> {
99    let pins: toml::Value = toml::from_str(include_str!("../resources/corpus/toolchain.toml"))
100        .map_err(|e| invalid("invalid_config", e.to_string()))?;
101    let host = match (std::env::consts::OS, std::env::consts::ARCH) {
102        ("macos", "aarch64") => "aarch64-apple-darwin",
103        ("linux", "x86_64") => "x86_64-unknown-linux-gnu",
104        _ => return Ok(None),
105    };
106    let version = pins
107        .get("z3")
108        .and_then(|z3| z3.get("version"))
109        .and_then(toml::Value::as_str);
110    let digest = pins
111        .get("assets")
112        .and_then(|a| a.get(host))
113        .and_then(|a| a.get("z3_sha256"))
114        .and_then(toml::Value::as_str);
115    match (version, digest) {
116        (Some(version), Some(digest)) if digest.len() == 64 => {
117            Ok(Some((version.into(), digest.into())))
118        }
119        _ => Err(invalid(
120            "invalid_config",
121            "embedded solver pin is incomplete",
122        )),
123    }
124}
125
126fn admitted(query: &Query) -> Result<admission::Plan, Error> {
127    if query.obligation_id.trim().is_empty()
128        || query.obligation_id.len() > 1024
129        || query.requirement_ids.len() > 1024
130        || query
131            .requirement_ids
132            .iter()
133            .any(|id| id.trim().is_empty() || id.len() > 1024)
134        || query
135            .requirement_ids
136            .windows(2)
137            .any(|pair| pair[0] >= pair[1])
138    {
139        return Err(invalid(
140            "invalid_request",
141            "obligation identity must be nonempty; requirement IDs must be nonempty, unique and strictly sorted",
142        ));
143    }
144    let limits = &query.limits;
145    if query.backend.is_empty()
146        || limits.resource_limit == 0
147        || limits.wall_time_ms == 0
148        || limits.wall_time_ms > MAX_WALL_TIME_MS
149        || limits.input_bytes == 0
150        || limits.input_bytes > MAX_INPUT_BYTES
151        || limits.output_bytes == 0
152        || limits.output_bytes > MAX_OUTPUT_BYTES
153        || query.script.len() > limits.input_bytes
154    {
155        return Err(invalid(
156            "invalid_limits",
157            "backend, script size or limits are outside the admitted bounds",
158        ));
159    }
160    admission::plan(query)
161}
162
163impl Runtime {
164    /// Construct the runtime with an existing installed solver and optional cache.
165    ///
166    /// # Errors
167    /// Returns `SAIL6101` for invalid configuration or malformed embedded pins.
168    pub fn new(mut config: Config) -> Result<Self, Error> {
169        if !(1..=16).contains(&config.workers) {
170            return Err(invalid(
171                "invalid_config",
172                "worker bound must be between one and sixteen",
173            ));
174        }
175        // A bare relative executable name must never be hashed in the current
176        // directory and then resolved to a different PATH entry at spawn time.
177        config.z3 = config
178            .z3
179            .map(std::path::absolute)
180            .transpose()
181            .map_err(|e| invalid("invalid_config", e.to_string()))?;
182        Ok(Self {
183            config,
184            pin: pin()?,
185        })
186    }
187
188    fn identity(&self, cancellation: &Cancellation) -> Result<SolverIdentity, Error> {
189        let path =
190            self.config.z3.as_ref().ok_or_else(|| {
191                execution("unavailable", "bundled Z3 is not installed or configured")
192            })?;
193        let (version, expected) = self
194            .pin
195            .as_ref()
196            .ok_or_else(|| execution("unavailable", "no bundled Z3 pin exists for this host"))?;
197        let digest = store::file_hash(path)
198            .map_err(|e| execution("unavailable", format!("cannot read bundled Z3: {e}")))?;
199        if &digest != expected {
200            return Err(execution(
201                "unavailable",
202                "solver executable does not match the bundled pin",
203            ));
204        }
205        let limits = Limits {
206            wall_time_ms: 1000,
207            output_bytes: 4096,
208            ..Limits::default()
209        };
210        let captured = process::run(path, &["--version".into()], b"", &limits, cancellation);
211        let text = std::str::from_utf8(&captured.stdout).unwrap_or_default();
212        if captured.outcome != Outcome::Completed
213            || !captured.stderr.is_empty()
214            || text
215                .split_whitespace()
216                .take(3)
217                .ne(["Z3", "version", version.as_str()])
218        {
219            return Err(execution(
220                "unavailable",
221                "bundled Z3 version could not be verified",
222            ));
223        }
224        Ok(SolverIdentity {
225            backend: "z3".into(),
226            version: version.clone(),
227            sha256: digest,
228            platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
229        })
230    }
231
232    /// Inspect actual installation readiness; this does not establish any theorem.
233    #[must_use]
234    pub fn capabilities(&self) -> Capabilities {
235        let identity = self.identity(&Cancellation::default());
236        Capabilities {
237            temporal: Some(temporal::capability(
238                self.config.temporal_backend.as_deref(),
239                self.config.temporal_worker.as_ref(),
240                self.config.temporal_unavailable.as_ref(),
241            )),
242            version: VERSION,
243            backends: vec![BackendCapability {
244                backend: "z3".into(),
245                implemented: true,
246                installed: identity.is_ok(),
247                solver: identity.as_ref().ok().cloned(),
248                error: identity.err(),
249            }],
250            incremental_transcripts: true,
251            batches: true,
252            max_queries: MAX_QUERIES,
253        }
254    }
255
256    /// Execute a fully admitted bounded batch, preserving caller order and metadata.
257    ///
258    /// # Errors
259    /// Returns `SAIL6101` before dispatch if any query or protocol version is invalid.
260    /// Worker infrastructure failures use `SAIL6102` and never become solver answers.
261    pub fn execute(
262        &self,
263        request: &Request,
264        cancellation: &Cancellation,
265    ) -> Result<Response, Error> {
266        if request.version != VERSION {
267            return Err(invalid("invalid_request", "unsupported runtime version"));
268        }
269        let queries = match &request.input {
270            Input::Temporal { job } => {
271                return Ok(Response {
272                    version: VERSION,
273                    output: Output::Temporal {
274                        result: Box::new(temporal::execute(
275                            job,
276                            self.config.temporal_backend.as_deref(),
277                            self.config.temporal_worker.as_ref(),
278                            self.config.temporal_unavailable.as_ref(),
279                            cancellation,
280                        )?),
281                    },
282                });
283            }
284            Input::Smt { queries } => queries,
285        };
286        if request.version != VERSION
287            || queries.is_empty()
288            || queries.len() > MAX_QUERIES
289            || queries
290                .iter()
291                .try_fold(0_usize, |sum, query| sum.checked_add(query.script.len()))
292                .is_none_or(|size| size > MAX_INPUT_BYTES)
293            || queries
294                .iter()
295                .try_fold(0_usize, |sum, query| {
296                    query
297                        .limits
298                        .output_bytes
299                        .checked_mul(3)
300                        .and_then(|bound| sum.checked_add(bound))
301                })
302                .is_none_or(|bound| bound > sail_api::runtime::MAX_RETAINED_OUTPUT_BYTES)
303        {
304            return Err(invalid(
305                "invalid_request",
306                "unsupported version, empty or oversized batch",
307            ));
308        }
309        let plans = queries
310            .iter()
311            .map(admitted)
312            .collect::<Result<Vec<_>, _>>()?;
313        // Join each bounded wave before starting another; no task outlives its request.
314        let mut results = Vec::with_capacity(queries.len());
315        for (query_wave, plan_wave) in queries
316            .chunks(self.config.workers)
317            .zip(plans.chunks(self.config.workers))
318        {
319            let mut wave = std::thread::scope(|scope| {
320                let mut workers = Vec::new();
321                let mut spawn_error = None;
322                for (query, plan) in query_wave.iter().zip(plan_wave) {
323                    match std::thread::Builder::new()
324                        .name("sail-runtime-query".into())
325                        .spawn_scoped(scope, || self.query(query, plan, cancellation))
326                    {
327                        Ok(worker) => workers.push(worker),
328                        Err(e) => {
329                            spawn_error = Some(execution("infrastructure", e.to_string()));
330                            break;
331                        }
332                    }
333                }
334                let mut wave = Vec::new();
335                for worker in workers {
336                    match worker.join() {
337                        Ok(result) => wave.push(result),
338                        Err(_) => {
339                            spawn_error =
340                                Some(execution("infrastructure", "query worker panicked"));
341                        }
342                    }
343                }
344                spawn_error.map_or(Ok(wave), Err)
345            })?;
346            results.append(&mut wave);
347        }
348        Ok(Response {
349            version: VERSION,
350            output: Output::Smt { results },
351        })
352    }
353
354    fn query(
355        &self,
356        query: &Query,
357        plan: &admission::Plan,
358        cancellation: &Cancellation,
359    ) -> QueryResult {
360        let mut result = empty_result(query);
361        if cancellation.is_cancelled() {
362            result.outcome = Outcome::Cancelled;
363            result.error = Some(execution("cancelled", "cancelled before dispatch"));
364            return result;
365        }
366        if query.backend != "z3" {
367            result.error = Some(execution(
368                "unavailable",
369                "requested backend is not implemented",
370            ));
371            return result;
372        }
373        let identity = match self.identity(cancellation) {
374            Ok(identity) => identity,
375            Err(e) => {
376                if cancellation.is_cancelled() {
377                    result.outcome = Outcome::Cancelled;
378                }
379                result.error = Some(e);
380                return result;
381            }
382        };
383        result.solver = Some(identity.clone());
384        if let Some(cached) = store::read(&self.config, query, &identity, plan) {
385            result.stdout = cached;
386            if let Ok(checks) = admission::responses(plan, &result.stdout) {
387                result.checks = checks;
388                result.outcome = Outcome::Completed;
389                result.cache_hit = true;
390                return result;
391            }
392        }
393        let Some(path) = &self.config.z3 else {
394            return result;
395        };
396        let args = vec![
397            "-smt2".into(),
398            "-in".into(),
399            "smt.random_seed=0".into(),
400            "sat.random_seed=0".into(),
401            format!("rlimit={}", query.limits.resource_limit),
402        ];
403        let captured = process::run(
404            path,
405            &args,
406            query.script.as_bytes(),
407            &query.limits,
408            cancellation,
409        );
410        result.outcome = captured.outcome;
411        result.stdout = captured.stdout;
412        result.stderr = captured.stderr;
413        if result.outcome == Outcome::Completed {
414            let checked = if !result.stderr.is_empty() {
415                Err(execution(
416                    "infrastructure",
417                    "backend produced stderr diagnostics",
418                ))
419            } else if store::file_hash(path).ok().as_ref() != Some(&identity.sha256) {
420                Err(execution(
421                    "infrastructure",
422                    "backend executable changed during execution",
423                ))
424            } else {
425                admission::responses(plan, &result.stdout)
426            };
427            match checked {
428                Ok(checks) => {
429                    result.checks = checks;
430                    store::write(
431                        &self.config,
432                        query,
433                        &identity,
434                        &result.stdout,
435                        &result.checks,
436                    );
437                }
438                Err(e) => {
439                    result.outcome = Outcome::Infrastructure;
440                    result.error = Some(execution("invalid_response", e.to_string()));
441                }
442            }
443        } else {
444            result.error = Some(execution(
445                match result.outcome {
446                    Outcome::Cancelled => "cancelled",
447                    Outcome::Timeout => "timeout",
448                    Outcome::OutputLimit => "output_limit",
449                    _ => "infrastructure",
450                },
451                captured
452                    .error
453                    .unwrap_or_else(|| "backend execution did not complete".into()),
454            ));
455        }
456        result
457    }
458}
459
460fn empty_result(query: &Query) -> QueryResult {
461    QueryResult {
462        obligation_id: query.obligation_id.clone(),
463        requirement_ids: query.requirement_ids.clone(),
464        backend: query.backend.clone(),
465        outcome: Outcome::Unavailable,
466        checks: Vec::new(),
467        stdout: Vec::new(),
468        stderr: Vec::new(),
469        solver: None,
470        script_sha256: hash(query.script.as_bytes()),
471        limits: query.limits.clone(),
472        cache_hit: false,
473        error: None,
474    }
475}