#![forbid(unsafe_code)]
mod admission;
mod backend;
mod process;
mod store;
pub mod temporal;
#[cfg(test)]
mod tests;
use backend::Backend;
use sail_api::runtime::{
BackendCapability, Capabilities, Error, Input, Limits, MAX_INPUT_BYTES, MAX_OUTPUT_BYTES,
MAX_QUERIES, MAX_WALL_TIME_MS, Outcome, Output, Query, QueryResult, Request, Response,
SolverIdentity, VERSION,
};
use sha2::{Digest as _, Sha256};
use std::{
path::PathBuf,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
#[derive(Clone, Debug)]
pub struct Config {
pub temporal_backend: Option<Arc<dyn temporal::TemporalBackend>>,
pub temporal_worker: Option<temporal::Worker>,
pub temporal_unavailable: Option<Error>,
pub z3: Option<PathBuf>,
pub cvc5: Option<PathBuf>,
pub cache_directory: Option<PathBuf>,
pub workers: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
temporal_backend: None,
temporal_worker: None,
temporal_unavailable: None,
z3: None,
cvc5: None,
cache_directory: None,
workers: 2,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Cancellation(Arc<AtomicBool>);
impl Cancellation {
pub fn cancel(&self) {
self.0.store(true, Ordering::SeqCst);
}
#[must_use]
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::SeqCst)
}
}
pub struct Runtime {
config: Config,
pins: Vec<Option<(String, String)>>,
}
pub(crate) fn invalid(kind: &str, message: impl Into<String>) -> Error {
Error {
code: "SAIL6101".into(),
kind: kind.into(),
message: message.into(),
}
}
pub(crate) fn execution(kind: &str, message: impl Into<String>) -> Error {
Error {
code: "SAIL6102".into(),
kind: kind.into(),
message: message.into(),
}
}
pub(crate) fn hash(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
fn pins() -> Result<Vec<Option<(String, String)>>, Error> {
let pins: toml::Value = toml::from_str(include_str!("../resources/corpus/toolchain.toml"))
.map_err(|e| invalid("invalid_config", e.to_string()))?;
let host = match (std::env::consts::OS, std::env::consts::ARCH) {
("macos", "aarch64") => "aarch64-apple-darwin",
("linux", "x86_64") => "x86_64-unknown-linux-gnu",
_ => return Ok(vec![None; backend::ALL.len()]),
};
backend::ALL
.iter()
.map(|backend| {
backend
.pin(&pins, host)
.map_err(|()| invalid("invalid_config", "embedded solver pin is incomplete"))
})
.collect()
}
fn admitted(query: &Query) -> Result<admission::Plan, Error> {
if query.obligation_id.trim().is_empty()
|| query.obligation_id.len() > 1024
|| query.requirement_ids.len() > 1024
|| query
.requirement_ids
.iter()
.any(|id| id.trim().is_empty() || id.len() > 1024)
|| query
.requirement_ids
.windows(2)
.any(|pair| pair[0] >= pair[1])
{
return Err(invalid(
"invalid_request",
"obligation identity must be nonempty; requirement IDs must be nonempty, unique and strictly sorted",
));
}
let limits = &query.limits;
if query.backend.is_empty()
|| limits.resource_limit == 0
|| limits.wall_time_ms == 0
|| limits.wall_time_ms > MAX_WALL_TIME_MS
|| limits.input_bytes == 0
|| limits.input_bytes > MAX_INPUT_BYTES
|| limits.output_bytes == 0
|| limits.output_bytes > MAX_OUTPUT_BYTES
|| query.script.len() > limits.input_bytes
{
return Err(invalid(
"invalid_limits",
"backend, script size or limits are outside the admitted bounds",
));
}
admission::plan(query)
}
impl Runtime {
pub fn new(mut config: Config) -> Result<Self, Error> {
if !(1..=16).contains(&config.workers) {
return Err(invalid(
"invalid_config",
"worker bound must be between one and sixteen",
));
}
config.z3 = config
.z3
.map(std::path::absolute)
.transpose()
.map_err(|e| invalid("invalid_config", e.to_string()))?;
config.cvc5 = config
.cvc5
.map(std::path::absolute)
.transpose()
.map_err(|e| invalid("invalid_config", e.to_string()))?;
Ok(Self {
config,
pins: pins()?,
})
}
fn executable(&self, backend: &dyn Backend) -> Option<&PathBuf> {
match backend.name() {
"z3" => self.config.z3.as_ref(),
"cvc5" => self.config.cvc5.as_ref(),
_ => None,
}
}
fn identity(
&self,
backend: &'static dyn Backend,
cancellation: &Cancellation,
) -> Result<SolverIdentity, Error> {
let label = backend.label();
let path = self.executable(backend).ok_or_else(|| {
execution(
"unavailable",
format!("{label} is not installed or configured"),
)
})?;
let (version, expected) = backend::ALL
.iter()
.position(|known| known.name() == backend.name())
.and_then(|index| self.pins.get(index))
.and_then(Option::as_ref)
.ok_or_else(|| {
execution(
"unavailable",
format!("no {label} pin exists for this host"),
)
})?;
let digest = store::file_hash(path)
.map_err(|e| execution("unavailable", format!("cannot read {label}: {e}")))?;
if &digest != expected {
return Err(execution(
"unavailable",
"solver executable does not match the bundled pin",
));
}
let limits = Limits {
wall_time_ms: 1000,
output_bytes: 4096,
..Limits::default()
};
let captured = process::run(path, &["--version".into()], b"", &limits, cancellation);
let text = std::str::from_utf8(&captured.stdout).unwrap_or_default();
if captured.outcome != Outcome::Completed
|| !captured.stderr.is_empty()
|| !backend.version_matches(text, version)
{
return Err(execution(
"unavailable",
format!("{label} version could not be verified"),
));
}
Ok(SolverIdentity {
backend: backend.name().into(),
version: version.clone(),
sha256: digest,
platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
})
}
#[must_use]
pub fn capabilities(&self) -> Capabilities {
let backends = backend::ALL
.into_iter()
.filter(|backend| backend.name() == "z3" || self.executable(*backend).is_some())
.map(|backend| {
let identity = self.identity(backend, &Cancellation::default());
BackendCapability {
backend: backend.name().into(),
implemented: true,
installed: identity.is_ok(),
solver: identity.as_ref().ok().cloned(),
error: identity.err(),
}
})
.collect();
Capabilities {
temporal: Some(temporal::capability(
self.config.temporal_backend.as_deref(),
self.config.temporal_worker.as_ref(),
self.config.temporal_unavailable.as_ref(),
)),
version: VERSION,
backends,
incremental_transcripts: true,
batches: true,
max_queries: MAX_QUERIES,
}
}
pub fn execute(
&self,
request: &Request,
cancellation: &Cancellation,
) -> Result<Response, Error> {
if request.version != VERSION {
return Err(invalid("invalid_request", "unsupported runtime version"));
}
let queries = match &request.input {
Input::Temporal { job } => {
return Ok(Response {
version: VERSION,
output: Output::Temporal {
result: Box::new(temporal::execute(
job,
self.config.temporal_backend.as_deref(),
self.config.temporal_worker.as_ref(),
self.config.temporal_unavailable.as_ref(),
cancellation,
)?),
},
});
}
Input::Smt { queries } => queries,
};
if request.version != VERSION
|| queries.is_empty()
|| queries.len() > MAX_QUERIES
|| queries
.iter()
.try_fold(0_usize, |sum, query| sum.checked_add(query.script.len()))
.is_none_or(|size| size > MAX_INPUT_BYTES)
|| queries
.iter()
.try_fold(0_usize, |sum, query| {
query
.limits
.output_bytes
.checked_mul(3)
.and_then(|bound| sum.checked_add(bound))
})
.is_none_or(|bound| bound > sail_api::runtime::MAX_RETAINED_OUTPUT_BYTES)
{
return Err(invalid(
"invalid_request",
"unsupported version, empty or oversized batch",
));
}
let plans = queries
.iter()
.map(admitted)
.collect::<Result<Vec<_>, _>>()?;
let mut results = Vec::with_capacity(queries.len());
for (query_wave, plan_wave) in queries
.chunks(self.config.workers)
.zip(plans.chunks(self.config.workers))
{
let mut wave = std::thread::scope(|scope| {
let mut workers = Vec::new();
let mut spawn_error = None;
for (query, plan) in query_wave.iter().zip(plan_wave) {
match std::thread::Builder::new()
.name("sail-runtime-query".into())
.spawn_scoped(scope, || self.query(query, plan, cancellation))
{
Ok(worker) => workers.push(worker),
Err(e) => {
spawn_error = Some(execution("infrastructure", e.to_string()));
break;
}
}
}
let mut wave = Vec::new();
for worker in workers {
match worker.join() {
Ok(result) => wave.push(result),
Err(_) => {
spawn_error =
Some(execution("infrastructure", "query worker panicked"));
}
}
}
spawn_error.map_or(Ok(wave), Err)
})?;
results.append(&mut wave);
}
Ok(Response {
version: VERSION,
output: Output::Smt { results },
})
}
fn query(
&self,
query: &Query,
plan: &admission::Plan,
cancellation: &Cancellation,
) -> QueryResult {
let mut result = empty_result(query);
if cancellation.is_cancelled() {
result.outcome = Outcome::Cancelled;
result.error = Some(execution("cancelled", "cancelled before dispatch"));
return result;
}
let Some(backend) = backend::named(&query.backend) else {
result.error = Some(execution(
"unavailable",
"requested backend is not implemented",
));
return result;
};
let identity = match self.identity(backend, cancellation) {
Ok(identity) => identity,
Err(e) => {
if cancellation.is_cancelled() {
result.outcome = Outcome::Cancelled;
}
result.error = Some(e);
return result;
}
};
result.solver = Some(identity.clone());
if let Some(cached) = store::read(&self.config, query, &identity, plan) {
result.stdout = cached;
if let Ok(checks) = admission::responses(plan, &result.stdout) {
result.checks = checks;
result.outcome = Outcome::Completed;
result.cache_hit = true;
return result;
}
}
let Some(path) = self.executable(backend) else {
return result;
};
let args = backend.args(&query.limits);
let captured = process::run(
path,
&args,
query.script.as_bytes(),
&query.limits,
cancellation,
);
result.outcome = captured.outcome;
result.stdout = captured.stdout;
result.stderr = captured.stderr;
if result.outcome == Outcome::Completed {
let checked = if !result.stderr.is_empty() {
Err(execution(
"infrastructure",
"backend produced stderr diagnostics",
))
} else if store::file_hash(path).ok().as_ref() != Some(&identity.sha256) {
Err(execution(
"infrastructure",
"backend executable changed during execution",
))
} else {
admission::responses(plan, &result.stdout)
};
match checked {
Ok(checks) => {
result.checks = checks;
store::write(
&self.config,
query,
&identity,
&result.stdout,
&result.checks,
);
}
Err(e) => {
result.outcome = Outcome::Infrastructure;
result.error = Some(execution("invalid_response", e.to_string()));
}
}
} else {
result.error = Some(execution(
match result.outcome {
Outcome::Cancelled => "cancelled",
Outcome::Timeout => "timeout",
Outcome::OutputLimit => "output_limit",
_ => "infrastructure",
},
captured
.error
.unwrap_or_else(|| "backend execution did not complete".into()),
));
}
result
}
}
fn empty_result(query: &Query) -> QueryResult {
QueryResult {
obligation_id: query.obligation_id.clone(),
requirement_ids: query.requirement_ids.clone(),
backend: query.backend.clone(),
outcome: Outcome::Unavailable,
checks: Vec::new(),
stdout: Vec::new(),
stderr: Vec::new(),
solver: None,
script_sha256: hash(query.script.as_bytes()),
limits: query.limits.clone(),
cache_hit: false,
error: None,
}
}