1
//! The behaviour oracle: compiles a program, RUNS it in every [`World`], and
2
//! reports what it observably does there. The behaviour snapshot compares
3
//! these [`Behaviour`]s world by world; the emitted bytes never enter the
4
//! comparison.
5
//!
6
//! A [`Behaviour`] holds:
7
//! - script mode: `should_apply`'s answer, every entity the run wrote (parsed
8
//!   as the batch executor parses them, in order) and the decoded result;
9
//! - eval mode: the static result type and the result's whole GC value graph
10
//!   (see [`graph`]), not the host's lossy rendering of it;
11
//! - every `log` call's severity and text, in order;
12
//! - a failure: a compile error by its text less any module byte offset, a
13
//!   raised condition by its code and message, a trap by its kind alone.
14
//!   Those last two are NORMALIZED failure equality: a trap's text carries a
15
//!   backtrace of function indices, and a validation error's text a byte
16
//!   offset, that move whenever the bytes do, so two traps of one kind at
17
//!   different sites (two divisions by zero, say) compare equal, as do two
18
//!   validations failing on the same shape at different offsets.
19
//!
20
//! A value the oracle cannot observe fails the comparison: it is never equal,
21
//! not even to itself, as a failed observation is no evidence of a match.
22
//!
23
//! Limits:
24
//! - a branch no world drives is never executed, so it has no behavioural
25
//!   coverage;
26
//! - only two batches and two sets of host replies are observed;
27
//! - eval mode never sees a batch, as the rpc Session gives it none;
28
//! - traps compare by kind (normalized failure equality, above);
29
//! - an eval graph is flattened as a tree, so values that differ only in
30
//!   whether a sub-object is shared observe the same;
31
//! - every non-null funcref observes the same, so two capture-free closures
32
//!   returning 1 and 2 are indistinguishable.
33

            
34
mod graph;
35
mod world;
36

            
37
use std::sync::{Arc, Mutex, OnceLock};
38

            
39
use super::stats::CompileStats;
40
use super::{CompileMode, Compiler};
41
use crate::ast::{Program, WasmType};
42
use crate::host_fn::HostFnSpec;
43
use crate::reader::Reader;
44
use crate::runtime::SymbolTable;
45
use scripting::debug_value::{self, DecodeError};
46
use scripting::host::ExecutionState;
47
use scripting::parser::OutputParser;
48
use scripting::runtime::{
49
    EngineError, EngineOpts, ModuleCache, build_engine, classify_runtime_error,
50
    err_code_and_message, t_singleton,
51
};
52
use scripting_format::{BASE_OFFSET, GlobalHeader, OUTPUT_HEADER_SIZE, OutputHeader};
53
use wasmtime::{AnyRef, Engine, Module, Rooted, Store, Val};
54
pub(crate) use world::Logged;
55
use world::{WORLDS, World};
56

            
57
const OUTPUT_SIZE: u32 = 64 * 1024;
58
const WASM_PAGE_SIZE: usize = 64 * 1024;
59
/// Far beyond any snippet's run; the engine interrupts on epoch only.
60
const EPOCH_DEADLINE: u64 = 1 << 40;
61

            
62
/// How a run ended.
63
#[derive(Clone, Debug)]
64
pub(crate) enum Outcome {
65
    Value(String),
66
    /// It ran to completion and wrote a well-formed output with no result.
67
    NoValue(&'static str),
68
    /// `should_apply` answered 0, so the batch executor skips `process`.
69
    NotApplied,
70
    /// It ran, but its output or result cannot be decoded.
71
    Malformed(String),
72
    CompileError(String),
73
    RuntimeError(String),
74
    /// The oracle could not observe the value; equal to nothing.
75
    Unobservable(String),
76
}
77

            
78
impl PartialEq for Outcome {
79
73
    fn eq(&self, other: &Self) -> bool {
80
73
        match (self, other) {
81
            (Outcome::Value(a), Outcome::Value(b))
82
            | (Outcome::Malformed(a), Outcome::Malformed(b))
83
            | (Outcome::CompileError(a), Outcome::CompileError(b))
84
69
            | (Outcome::RuntimeError(a), Outcome::RuntimeError(b)) => a == b,
85
1
            (Outcome::NoValue(a), Outcome::NoValue(b)) => a == b,
86
1
            (Outcome::NotApplied, Outcome::NotApplied) => true,
87
2
            _ => false,
88
        }
89
73
    }
90
}
91

            
92
/// Everything a program observably does in one world.
93
#[derive(Clone, Debug, PartialEq)]
94
pub(crate) struct Behaviour {
95
    pub(crate) world: &'static str,
96
    pub(crate) outcome: Outcome,
97
    /// Each `log` call's severity and text, in order.
98
    pub(crate) output: Vec<(u32, Logged)>,
99
    /// Script mode: what `should_apply` answered.
100
    pub(crate) applies: Option<i32>,
101
    /// Script mode: each entity the run wrote, in order.
102
    pub(crate) effects: Vec<String>,
103
}
104

            
105
/// Compiles `source` and runs it in every world.
106
5763
pub(crate) fn observe(
107
5763
    source: &str,
108
5763
    mode: CompileMode,
109
5763
    hosts: &[HostFnSpec],
110
5763
) -> (Vec<Behaviour>, CompileStats) {
111
5763
    let mut symbols = SymbolTable::with_builtins_for_wasm();
112
5763
    symbols.register_host_fns(hosts);
113
5763
    let program = Reader::parse(source).map_err(|err| err.to_string());
114
5763
    observe_program(program, &mut symbols, mode, hosts)
115
5763
}
116

            
117
/// [`observe`] of a program already read, compiled in `symbols`.
118
5876
pub(crate) fn observe_program(
119
5876
    program: Result<Program, String>,
120
5876
    symbols: &mut SymbolTable,
121
5876
    mode: CompileMode,
122
5876
    hosts: &[HostFnSpec],
123
5876
) -> (Vec<Behaviour>, CompileStats) {
124
5876
    let mut compiler = Compiler::with_host_fns(hosts.to_vec());
125
5876
    let compiled = program.and_then(|program| {
126
5876
        match mode {
127
2826
            CompileMode::Script => compiler
128
2826
                .compile_with_mode(&program, symbols, mode)
129
2154
                .map(|bytes| (bytes, None)),
130
3050
            CompileMode::Eval => compiler
131
3050
                .compile_eval_with_type(&program, symbols)
132
2145
                .map(|(bytes, ty)| (bytes, Some(ty))),
133
        }
134
1577
        .map_err(|err| without_byte_offset(&err.to_string()))
135
5876
    });
136
5876
    let behaviours = WORLDS
137
5876
        .iter()
138
11752
        .map(|world| match &compiled {
139
3154
            Err(message) => Behaviour {
140
3154
                world: world.name,
141
3154
                outcome: Outcome::CompileError(message.clone()),
142
3154
                output: Vec::new(),
143
3154
                applies: None,
144
3154
                effects: Vec::new(),
145
3154
            },
146
8598
            Ok((bytes, result_ty)) => run(world, bytes, *result_ty),
147
11752
        })
148
        .collect();
149
5876
    (behaviours, compiler.stats())
150
5876
}
151

            
152
/// How a run ended and, for a script, the entities it wrote.
153
struct Ran {
154
    outcome: Outcome,
155
    effects: Vec<String>,
156
}
157

            
158
impl From<Outcome> for Ran {
159
4387
    fn from(outcome: Outcome) -> Self {
160
4387
        Ran {
161
4387
            outcome,
162
4387
            effects: Vec::new(),
163
4387
        }
164
4387
    }
165
}
166

            
167
8598
fn run(world: &World, bytes: &[u8], result_ty: Option<Option<WasmType>>) -> Behaviour {
168
8598
    let output = Arc::new(Mutex::new(Vec::new()));
169
8598
    let mut applies = None;
170
8598
    let ran = engine()
171
8598
        .and_then(|engine| Ok((engine, module(engine, bytes)?)))
172
        .map_or_else(
173
            |err| Ok(Outcome::RuntimeError(err).into()),
174
8598
            |(engine, module)| match result_ty {
175
4308
                None => run_script(world, engine, &module, &output, &mut applies),
176
4290
                Some(ty) => run_eval(world, engine, &module, ty, &output),
177
8598
            },
178
        )
179
196
        .unwrap_or_else(|err| runtime_error(&err).into());
180
    Behaviour {
181
8598
        world: world.name,
182
8598
        outcome: ran.outcome,
183
8598
        output: output.lock().map(|lines| lines.clone()).unwrap_or_default(),
184
8598
        applies,
185
8598
        effects: ran.effects,
186
    }
187
8598
}
188

            
189
8601
fn engine() -> Result<&'static Engine, String> {
190
    static ENGINE: OnceLock<Result<Engine, String>> = OnceLock::new();
191
8601
    ENGINE
192
108
        .get_or_init(|| build_engine(EngineOpts::baseline()).map_err(|err| err.to_string()))
193
        .as_ref()
194
8601
        .map_err(Clone::clone)
195
8601
}
196

            
197
8598
fn module(engine: &Engine, bytes: &[u8]) -> Result<Module, String> {
198
    static CACHE: OnceLock<ModuleCache> = OnceLock::new();
199
8598
    CACHE
200
8598
        .get_or_init(ModuleCache::new)
201
8598
        .get_or_compile(engine, bytes)
202
        .map_err(|err| format!("module does not load: {err}"))
203
8598
}
204

            
205
/// Runs as the batch executor (`scripting::executor::ScriptExecutor`) does,
206
/// the surface that applies scripts to ledger data: it skips `process` only
207
/// when `should_apply` answers 0. `applies` is set before `process` runs, so
208
/// a failing run still reports it.
209
4308
fn run_script(
210
4308
    world: &World,
211
4308
    engine: &Engine,
212
4308
    module: &Module,
213
4308
    output: &Arc<Mutex<Vec<(u32, Logged)>>>,
214
4308
    applies: &mut Option<i32>,
215
4308
) -> wasmtime::Result<Ran> {
216
4308
    let input = world.input(OUTPUT_SIZE);
217
4308
    let header = GlobalHeader::from_bytes(&input)
218
        .ok_or_else(|| wasmtime::Error::msg("the input header does not parse"))?;
219
4308
    let output_start = BASE_OFFSET as usize + input.len();
220
4308
    let state = ExecutionState::new(
221
4308
        BASE_OFFSET,
222
4308
        u32::try_from(output_start)?,
223
4308
        header.strings_pool_offset,
224
    );
225
4308
    let mut store = Store::new(engine, state);
226
4308
    store.set_epoch_deadline(EPOCH_DEADLINE);
227
4308
    let instance = world
228
4308
        .linker(engine, module, output)?
229
4308
        .instantiate(&mut store, module)?;
230
4308
    let memory = instance
231
4308
        .get_memory(&mut store, "memory")
232
        .ok_or_else(|| wasmtime::Error::msg("no memory export"))?;
233
4308
    store.data_mut().memory = Some(memory);
234
4308
    let needed = (output_start + OUTPUT_SIZE as usize).div_ceil(WASM_PAGE_SIZE);
235
4308
    let pages = usize::try_from(memory.size(&store))?;
236
4308
    if needed > pages {
237
4308
        memory.grow(&mut store, u64::try_from(needed - pages)?)?;
238
    }
239
4308
    let data = memory.data_mut(&mut store);
240
4308
    copy_into(data, BASE_OFFSET as usize, &input)?;
241
4308
    copy_into(
242
4308
        data,
243
4308
        output_start,
244
4308
        &OutputHeader::new(header.input_entity_count).to_bytes()[..OUTPUT_HEADER_SIZE],
245
4308
    )?;
246
4308
    let answer = instance
247
4308
        .get_typed_func::<(), i32>(&mut store, "should_apply")?
248
4308
        .call(&mut store, ())?;
249
4308
    *applies = Some(answer);
250
4308
    if answer == 0 {
251
2
        return Ok(Outcome::NotApplied.into());
252
4306
    }
253
4306
    instance
254
4306
        .get_typed_func::<(), ()>(&mut store, "process")?
255
4306
        .call(&mut store, ())?;
256
    let (outcome, effects) =
257
4211
        match debug_value::output_region(memory.data(&store), output_start, OUTPUT_SIZE as usize) {
258
4211
            Ok(region) => script_result(region),
259
            Err(err) => (Outcome::Malformed(err.to_string()), Vec::new()),
260
        };
261
4211
    Ok(Ran { outcome, effects })
262
4308
}
263

            
264
/// The result and the written entities, both decoded from the output region.
265
4215
fn script_result(region: &[u8]) -> (Outcome, Vec<String>) {
266
4215
    let effects = OutputHeader::from_bytes(region)
267
1
        .ok_or_else(|| "invalid output header".to_string())
268
4214
        .and_then(|header| {
269
4214
            OutputParser::new(region, header.strings_offset as usize)
270
4214
                .and_then(|parser| parser.entities().collect::<Result<Vec<_>, _>>())
271
                .map_err(|err| err.to_string())
272
4214
        })
273
10531
        .map(|entities| entities.iter().map(|e| format!("{e:?}")).collect());
274
4215
    match (effects, debug_value::decode_result(region)) {
275
1
        (Err(err), _) => (Outcome::Malformed(err), Vec::new()),
276
2
        (Ok(effects), Err(DecodeError::Malformed(err))) => (Outcome::Malformed(err), effects),
277
19
        (Ok(effects), Err(DecodeError::Absent(why))) => (Outcome::NoValue(why), effects),
278
4193
        (Ok(effects), Ok(value)) => (Outcome::Value(format!("{value:?}")), effects),
279
    }
280
4215
}
281

            
282
4290
fn run_eval(
283
4290
    world: &World,
284
4290
    engine: &Engine,
285
4290
    module: &Module,
286
4290
    result_ty: Option<WasmType>,
287
4290
    output: &Arc<Mutex<Vec<(u32, Logged)>>>,
288
4290
) -> wasmtime::Result<Ran> {
289
4290
    let mut store = Store::new(engine, ExecutionState::new(0, 0, 0));
290
4290
    store.set_epoch_deadline(EPOCH_DEADLINE);
291
4290
    let instance = world
292
4290
        .linker(engine, module, output)?
293
4290
        .instantiate(&mut store, module)?;
294
4290
    let func = instance
295
4290
        .get_func(&mut store, "nomi-eval")
296
        .ok_or_else(|| wasmtime::Error::msg("no nomi-eval export"))?;
297
4290
    let mut results = [Val::AnyRef(None)];
298
4290
    func.call(&mut store, &[], &mut results)?;
299
4189
    let root: Option<Rooted<AnyRef>> = match &results {
300
4189
        [Val::AnyRef(any)] => *any,
301
        _ => {
302
            return Ok(Outcome::Malformed("nomi-eval did not return anyref".into()).into());
303
        }
304
    };
305
4189
    let t = t_singleton(&mut store, &instance)?;
306
4189
    let outcome = match graph::observe(&mut store, &t, root) {
307
4185
        Ok(nodes) => Outcome::Value(format!("{result_ty:?} {nodes:?}")),
308
4
        Err(err) => Outcome::Unobservable(err),
309
    };
310
4189
    Ok(outcome.into())
311
4290
}
312

            
313
/// `message` less the ` (at offset 0x…)` a module validation error carries:
314
/// the offset names a byte, not a behaviour, and moves with every layout
315
/// change of the skeleton.
316
1582
fn without_byte_offset(message: &str) -> String {
317
    const MARKER: &str = " (at offset 0x";
318
1582
    match message.find(MARKER) {
319
        Some(start) => {
320
4
            let rest = &message[start + MARKER.len()..];
321
4
            match rest.find(')') {
322
6
                Some(end) if rest[..end].chars().all(|c| c.is_ascii_hexdigit()) => {
323
2
                    format!("{}{}", &message[..start], &rest[end + 1..])
324
                }
325
2
                _ => message.to_string(),
326
            }
327
        }
328
1578
        None => message.to_string(),
329
    }
330
1582
}
331

            
332
8616
fn copy_into(memory: &mut [u8], start: usize, bytes: &[u8]) -> wasmtime::Result<()> {
333
8616
    start
334
8616
        .checked_add(bytes.len())
335
8616
        .and_then(|end| memory.get_mut(start..end))
336
        .ok_or_else(|| wasmtime::Error::msg("the buffers do not fit in memory"))?
337
8616
        .copy_from_slice(bytes);
338
8616
    Ok(())
339
8616
}
340

            
341
/// A raised condition as `CODE: message`, any other failure by its kind alone
342
/// (normalized failure equality; see the module doc).
343
197
fn runtime_error(err: &wasmtime::Error) -> Outcome {
344
197
    Outcome::RuntimeError(match classify_runtime_error(err) {
345
        raised @ EngineError::ScriptRaised { .. } => {
346
196
            let (code, message) = err_code_and_message(&raised);
347
196
            format!("{code}: {message}")
348
        }
349
1
        _ => err
350
1
            .downcast_ref::<wasmtime::Trap>()
351
1
            .map_or_else(|| err.root_cause().to_string(), ToString::to_string),
352
    })
353
197
}
354

            
355
#[cfg(test)]
356
#[path = "behaviour_oracle_tests.rs"]
357
mod tests;