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