Lines
94.97 %
Functions
75 %
Branches
100 %
//! The behaviour oracle: compiles a program, RUNS it in every [`World`], and
//! reports what it observably does there. The behaviour snapshot compares
//! these [`Behaviour`]s world by world; the emitted bytes never enter the
//! comparison.
//!
//! A [`Behaviour`] holds:
//! - script mode: `should_apply`'s answer, every entity the run wrote (parsed
//! as the batch executor parses them, in order) and the decoded result;
//! - eval mode: the static result type and the result's whole GC value graph
//! (see [`graph`]), not the host's lossy rendering of it;
//! - every `log` call's severity and text, in order;
//! - a failure: a compile error by its text less any module byte offset, a
//! raised condition by its code and message, a trap by its kind alone.
//! Those last two are NORMALIZED failure equality: a trap's text carries a
//! backtrace of function indices, and a validation error's text a byte
//! offset, that move whenever the bytes do, so two traps of one kind at
//! different sites (two divisions by zero, say) compare equal, as do two
//! validations failing on the same shape at different offsets.
//! A value the oracle cannot observe fails the comparison: it is never equal,
//! not even to itself, as a failed observation is no evidence of a match.
//! Limits:
//! - a branch no world drives is never executed, so it has no behavioural
//! coverage;
//! - only two batches and two sets of host replies are observed;
//! - eval mode never sees a batch, as the rpc Session gives it none;
//! - traps compare by kind (normalized failure equality, above);
//! - an eval graph is flattened as a tree, so values that differ only in
//! whether a sub-object is shared observe the same;
//! - every non-null funcref observes the same, so two capture-free closures
//! returning 1 and 2 are indistinguishable.
mod graph;
mod world;
use std::sync::{Arc, Mutex, OnceLock};
use super::stats::CompileStats;
use super::{CompileMode, Compiler};
use crate::ast::{Program, WasmType};
use crate::host_fn::HostFnSpec;
use crate::reader::Reader;
use crate::runtime::SymbolTable;
use scripting::debug_value::{self, DecodeError};
use scripting::host::ExecutionState;
use scripting::parser::OutputParser;
use scripting::runtime::{
EngineError, EngineOpts, ModuleCache, build_engine, classify_runtime_error,
err_code_and_message, t_singleton,
};
use scripting_format::{BASE_OFFSET, GlobalHeader, OUTPUT_HEADER_SIZE, OutputHeader};
use wasmtime::{AnyRef, Engine, Module, Rooted, Store, Val};
pub(crate) use world::Logged;
use world::{WORLDS, World};
const OUTPUT_SIZE: u32 = 64 * 1024;
const WASM_PAGE_SIZE: usize = 64 * 1024;
/// Far beyond any snippet's run; the engine interrupts on epoch only.
const EPOCH_DEADLINE: u64 = 1 << 40;
/// How a run ended.
#[derive(Clone, Debug)]
pub(crate) enum Outcome {
Value(String),
/// It ran to completion and wrote a well-formed output with no result.
NoValue(&'static str),
/// `should_apply` answered 0, so the batch executor skips `process`.
NotApplied,
/// It ran, but its output or result cannot be decoded.
Malformed(String),
CompileError(String),
RuntimeError(String),
/// The oracle could not observe the value; equal to nothing.
Unobservable(String),
}
impl PartialEq for Outcome {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Outcome::Value(a), Outcome::Value(b))
| (Outcome::Malformed(a), Outcome::Malformed(b))
| (Outcome::CompileError(a), Outcome::CompileError(b))
| (Outcome::RuntimeError(a), Outcome::RuntimeError(b)) => a == b,
(Outcome::NoValue(a), Outcome::NoValue(b)) => a == b,
(Outcome::NotApplied, Outcome::NotApplied) => true,
_ => false,
/// Everything a program observably does in one world.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Behaviour {
pub(crate) world: &'static str,
pub(crate) outcome: Outcome,
/// Each `log` call's severity and text, in order.
pub(crate) output: Vec<(u32, Logged)>,
/// Script mode: what `should_apply` answered.
pub(crate) applies: Option<i32>,
/// Script mode: each entity the run wrote, in order.
pub(crate) effects: Vec<String>,
/// Compiles `source` and runs it in every world.
pub(crate) fn observe(
source: &str,
mode: CompileMode,
hosts: &[HostFnSpec],
) -> (Vec<Behaviour>, CompileStats) {
let mut symbols = SymbolTable::with_builtins_for_wasm();
symbols.register_host_fns(hosts);
let program = Reader::parse(source).map_err(|err| err.to_string());
observe_program(program, &mut symbols, mode, hosts)
/// [`observe`] of a program already read, compiled in `symbols`.
pub(crate) fn observe_program(
program: Result<Program, String>,
symbols: &mut SymbolTable,
let mut compiler = Compiler::with_host_fns(hosts.to_vec());
let compiled = program.and_then(|program| {
match mode {
CompileMode::Script => compiler
.compile_with_mode(&program, symbols, mode)
.map(|bytes| (bytes, None)),
CompileMode::Eval => compiler
.compile_eval_with_type(&program, symbols)
.map(|(bytes, ty)| (bytes, Some(ty))),
.map_err(|err| without_byte_offset(&err.to_string()))
});
let behaviours = WORLDS
.iter()
.map(|world| match &compiled {
Err(message) => Behaviour {
world: world.name,
outcome: Outcome::CompileError(message.clone()),
output: Vec::new(),
applies: None,
effects: Vec::new(),
},
Ok((bytes, result_ty)) => run(world, bytes, *result_ty),
})
.collect();
(behaviours, compiler.stats())
/// How a run ended and, for a script, the entities it wrote.
struct Ran {
outcome: Outcome,
effects: Vec<String>,
impl From<Outcome> for Ran {
fn from(outcome: Outcome) -> Self {
Ran {
outcome,
fn run(world: &World, bytes: &[u8], result_ty: Option<Option<WasmType>>) -> Behaviour {
let output = Arc::new(Mutex::new(Vec::new()));
let mut applies = None;
let ran = engine()
.and_then(|engine| Ok((engine, module(engine, bytes)?)))
.map_or_else(
|err| Ok(Outcome::RuntimeError(err).into()),
|(engine, module)| match result_ty {
None => run_script(world, engine, &module, &output, &mut applies),
Some(ty) => run_eval(world, engine, &module, ty, &output),
)
.unwrap_or_else(|err| runtime_error(&err).into());
Behaviour {
outcome: ran.outcome,
output: output.lock().map(|lines| lines.clone()).unwrap_or_default(),
applies,
effects: ran.effects,
fn engine() -> Result<&'static Engine, String> {
static ENGINE: OnceLock<Result<Engine, String>> = OnceLock::new();
ENGINE
.get_or_init(|| build_engine(EngineOpts::baseline()).map_err(|err| err.to_string()))
.as_ref()
.map_err(Clone::clone)
fn module(engine: &Engine, bytes: &[u8]) -> Result<Module, String> {
static CACHE: OnceLock<ModuleCache> = OnceLock::new();
CACHE
.get_or_init(ModuleCache::new)
.get_or_compile(engine, bytes)
.map_err(|err| format!("module does not load: {err}"))
/// Runs as the batch executor (`scripting::executor::ScriptExecutor`) does,
/// the surface that applies scripts to ledger data: it skips `process` only
/// when `should_apply` answers 0. `applies` is set before `process` runs, so
/// a failing run still reports it.
fn run_script(
world: &World,
engine: &Engine,
module: &Module,
output: &Arc<Mutex<Vec<(u32, Logged)>>>,
applies: &mut Option<i32>,
) -> wasmtime::Result<Ran> {
let input = world.input(OUTPUT_SIZE);
let header = GlobalHeader::from_bytes(&input)
.ok_or_else(|| wasmtime::Error::msg("the input header does not parse"))?;
let output_start = BASE_OFFSET as usize + input.len();
let state = ExecutionState::new(
BASE_OFFSET,
u32::try_from(output_start)?,
header.strings_pool_offset,
);
let mut store = Store::new(engine, state);
store.set_epoch_deadline(EPOCH_DEADLINE);
let instance = world
.linker(engine, module, output)?
.instantiate(&mut store, module)?;
let memory = instance
.get_memory(&mut store, "memory")
.ok_or_else(|| wasmtime::Error::msg("no memory export"))?;
store.data_mut().memory = Some(memory);
let needed = (output_start + OUTPUT_SIZE as usize).div_ceil(WASM_PAGE_SIZE);
let pages = usize::try_from(memory.size(&store))?;
if needed > pages {
memory.grow(&mut store, u64::try_from(needed - pages)?)?;
let data = memory.data_mut(&mut store);
copy_into(data, BASE_OFFSET as usize, &input)?;
copy_into(
data,
output_start,
&OutputHeader::new(header.input_entity_count).to_bytes()[..OUTPUT_HEADER_SIZE],
)?;
let answer = instance
.get_typed_func::<(), i32>(&mut store, "should_apply")?
.call(&mut store, ())?;
*applies = Some(answer);
if answer == 0 {
return Ok(Outcome::NotApplied.into());
instance
.get_typed_func::<(), ()>(&mut store, "process")?
let (outcome, effects) =
match debug_value::output_region(memory.data(&store), output_start, OUTPUT_SIZE as usize) {
Ok(region) => script_result(region),
Err(err) => (Outcome::Malformed(err.to_string()), Vec::new()),
Ok(Ran { outcome, effects })
/// The result and the written entities, both decoded from the output region.
fn script_result(region: &[u8]) -> (Outcome, Vec<String>) {
let effects = OutputHeader::from_bytes(region)
.ok_or_else(|| "invalid output header".to_string())
.and_then(|header| {
OutputParser::new(region, header.strings_offset as usize)
.and_then(|parser| parser.entities().collect::<Result<Vec<_>, _>>())
.map_err(|err| err.to_string())
.map(|entities| entities.iter().map(|e| format!("{e:?}")).collect());
match (effects, debug_value::decode_result(region)) {
(Err(err), _) => (Outcome::Malformed(err), Vec::new()),
(Ok(effects), Err(DecodeError::Malformed(err))) => (Outcome::Malformed(err), effects),
(Ok(effects), Err(DecodeError::Absent(why))) => (Outcome::NoValue(why), effects),
(Ok(effects), Ok(value)) => (Outcome::Value(format!("{value:?}")), effects),
fn run_eval(
result_ty: Option<WasmType>,
let mut store = Store::new(engine, ExecutionState::new(0, 0, 0));
let func = instance
.get_func(&mut store, "nomi-eval")
.ok_or_else(|| wasmtime::Error::msg("no nomi-eval export"))?;
let mut results = [Val::AnyRef(None)];
func.call(&mut store, &[], &mut results)?;
let root: Option<Rooted<AnyRef>> = match &results {
[Val::AnyRef(any)] => *any,
_ => {
return Ok(Outcome::Malformed("nomi-eval did not return anyref".into()).into());
let t = t_singleton(&mut store, &instance)?;
let outcome = match graph::observe(&mut store, &t, root) {
Ok(nodes) => Outcome::Value(format!("{result_ty:?} {nodes:?}")),
Err(err) => Outcome::Unobservable(err),
Ok(outcome.into())
/// `message` less the ` (at offset 0x…)` a module validation error carries:
/// the offset names a byte, not a behaviour, and moves with every layout
/// change of the skeleton.
fn without_byte_offset(message: &str) -> String {
const MARKER: &str = " (at offset 0x";
match message.find(MARKER) {
Some(start) => {
let rest = &message[start + MARKER.len()..];
match rest.find(')') {
Some(end) if rest[..end].chars().all(|c| c.is_ascii_hexdigit()) => {
format!("{}{}", &message[..start], &rest[end + 1..])
_ => message.to_string(),
None => message.to_string(),
fn copy_into(memory: &mut [u8], start: usize, bytes: &[u8]) -> wasmtime::Result<()> {
start
.checked_add(bytes.len())
.and_then(|end| memory.get_mut(start..end))
.ok_or_else(|| wasmtime::Error::msg("the buffers do not fit in memory"))?
.copy_from_slice(bytes);
Ok(())
/// A raised condition as `CODE: message`, any other failure by its kind alone
/// (normalized failure equality; see the module doc).
fn runtime_error(err: &wasmtime::Error) -> Outcome {
Outcome::RuntimeError(match classify_runtime_error(err) {
raised @ EngineError::ScriptRaised { .. } => {
let (code, message) = err_code_and_message(&raised);
format!("{code}: {message}")
_ => err
.downcast_ref::<wasmtime::Trap>()
.map_or_else(|| err.root_cause().to_string(), ToString::to_string),
#[cfg(test)]
#[path = "behaviour_oracle_tests.rs"]
mod tests;