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