1
//! Plan 0014 Stage 0, P1: the behaviour snapshot. Every fixture's complete
2
//! [`Behaviour`] in every world — outcome, log lines, `should_apply`, entity
3
//! writes — is checked in under `behaviour_snapshot/`, keyed by fixture id,
4
//! mode, host-fn set and world. The test fails on any diff; running it with
5
//! `NOMI_UPDATE_SNAPSHOT=1` rewrites the files, and that rewrite is reviewed
6
//! like code against the stage's listing (0014 §Rules for every stage).
7
//!
8
//! Three fixture sets: the shipped corpus (its standalone programs; the
9
//! Session-only ones are listed in [`SESSION_ONLY`]), the lowering snippets
10
//! ([`snippets`]) as programs, and the acceptance programs under
11
//! `tests/acceptance/` (one `.nms` per row or issue repro, `; @mode eval` or
12
//! `; @mode script` narrowing the modes it runs in, `; @hosts entities`
13
//! adding the entity and money sources to its host-fn set).
14

            
15
mod attempts_tests;
16
mod render;
17
mod snippets;
18

            
19
use std::collections::BTreeMap;
20
use std::panic::resume_unwind;
21
use std::path::{Path, PathBuf};
22
use std::sync::atomic::{AtomicUsize, Ordering};
23

            
24
use super::behaviour_oracle::{Outcome, observe};
25
use super::{CompileMode, Compiler};
26
use crate::ast::{EntityKind, Expr, WasmType};
27
use crate::host_fn::HostFnSpec;
28
use crate::reader::Reader;
29
use crate::runtime::SymbolTable;
30
use render::{Row, render_rows};
31
use snippets::SNIPPETS;
32

            
33
/// A corpus file the oracle cannot run alone, with the import it needs.
34
pub(super) const SESSION_ONLY: &[(&str, &str)] = &[
35
    ("seed_09_tag-metro-splits.nms", "LIST-TRANSACTIONS"),
36
    ("tag-metro-splits.nms", "LIST-TRANSACTIONS"),
37
    ("craft_unwind_catch_each.nms", "__nomi_catch_each"),
38
];
39

            
40
/// A corpus file that only runs against a batch, so it has no eval-mode row.
41
const SCRIPT_ONLY: &[&str] = &[
42
    "metro.nms",
43
    "tag-sync.nms",
44
    "seed_10_metro.nms",
45
    "seed_11_tag-sync.nms",
46
];
47

            
48
/// No snapshot outcome may contain these (0014 §Rules: "Forbidden texts").
49
const FORBIDDEN_TEXTS: &[&str] = &["internal:", "failed wasm validation"];
50

            
51
#[derive(Clone, Copy, PartialEq, Eq)]
52
pub(super) enum Hosts {
53
    None,
54
    /// The snippet differential's two host fns: an index and a scalar source.
55
    Differential,
56
    /// The differential's fns plus a source of money and of each entity kind
57
    /// whose wasm struct shape another kind shares (ISS-018 / ISS-058).
58
    Entities,
59
}
60

            
61
impl Hosts {
62
7820
    pub(super) fn specs(self) -> Vec<HostFnSpec> {
63
7820
        let differential = vec![
64
7820
            HostFnSpec::new("rpc-protocol-version", "nomi", "rpc_protocol_version")
65
7820
                .returns(WasmType::I32),
66
7820
            HostFnSpec::new("ratio-source", "nomi", "ratio_source").returns(WasmType::Ratio),
67
        ];
68
7820
        match self {
69
560
            Hosts::None => Vec::new(),
70
7101
            Hosts::Differential => differential,
71
159
            Hosts::Entities => differential
72
159
                .into_iter()
73
159
                .chain([
74
159
                    HostFnSpec::new("money-source", "nomi", "money_source")
75
159
                        .returns(WasmType::Commodity),
76
159
                    HostFnSpec::new("account-source", "nomi", "account_source")
77
159
                        .returns(WasmType::EntityRef(EntityKind::Account)),
78
159
                    HostFnSpec::new("transaction-source", "nomi", "transaction_source")
79
159
                        .returns(WasmType::EntityRef(EntityKind::Transaction)),
80
159
                    HostFnSpec::new("commodity-entity-source", "nomi", "commodity_entity_source")
81
159
                        .returns(WasmType::EntityRef(EntityKind::Commodity)),
82
159
                    HostFnSpec::new("tag-source", "nomi", "tag_source")
83
159
                        .returns(WasmType::EntityRef(EntityKind::Tag)),
84
159
                ])
85
159
                .collect(),
86
        }
87
7820
    }
88

            
89
5525
    fn label(self) -> &'static str {
90
5525
        match self {
91
560
            Hosts::None => "none",
92
4859
            Hosts::Differential => "rpc-protocol-version,ratio-source",
93
106
            Hosts::Entities => "rpc-protocol-version,ratio-source,entities",
94
        }
95
5525
    }
96
}
97

            
98
pub(super) struct Fixture {
99
    id: String,
100
    source: String,
101
    modes: Vec<CompileMode>,
102
    hosts: Vec<Hosts>,
103
}
104

            
105
67
fn crate_root() -> PathBuf {
106
67
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
107
67
}
108

            
109
/// Every shipped `.nms` / `.lisp` program, sorted by path.
110
33
pub(super) fn corpus_files() -> Vec<PathBuf> {
111
33
    let root = crate_root();
112
33
    let mut files = vec![
113
33
        root.join("src/runtime/symbol/prelude.nms"),
114
33
        root.join("../nms/src/stdlib.lisp"),
115
33
        root.join("../../rpc/src/host_prelude.nms"),
116
    ];
117
33
    for dir in [
118
33
        "tests/samples",
119
33
        "tests/nms_runner_samples",
120
33
        "fuzz/corpus",
121
33
        "../../doc/scripts",
122
33
    ] {
123
132
        let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
124
            continue;
125
        };
126
132
        files.extend(
127
132
            entries
128
132
                .filter_map(Result::ok)
129
1155
                .map(|entry| entry.path())
130
1155
                .filter(|path| path.extension().is_some_and(|ext| ext == "nms")),
131
        );
132
    }
133
1122
    files.retain(|path| path.exists());
134
33
    files.sort();
135
33
    files
136
33
}
137

            
138
1074
fn file_name(path: &Path) -> String {
139
1074
    path.file_name()
140
1074
        .and_then(|name| name.to_str())
141
        .unwrap_or_default()
142
        .to_string()
143
1074
}
144

            
145
34
fn is_session_only(path: &Path) -> bool {
146
34
    let name = file_name(path);
147
99
    SESSION_ONLY.iter().any(|(file, _)| *file == name)
148
34
}
149

            
150
2342
fn read(path: &Path) -> String {
151
2342
    std::fs::read_to_string(path).unwrap_or_else(|err| panic!("read {}: {err}", path.display()))
152
2342
}
153

            
154
/// The corpus as the oracle can run it: a path relative to the crate root
155
/// identifies each standalone program.
156
1
fn corpus_fixtures() -> Vec<Fixture> {
157
1
    let root = crate_root();
158
1
    corpus_files()
159
1
        .into_iter()
160
34
        .filter(|path| !is_session_only(path))
161
31
        .map(|path| {
162
31
            let id = path.strip_prefix(&root).map_or_else(
163
                |_| path.display().to_string(),
164
31
                |rel| rel.display().to_string(),
165
            );
166
31
            let modes = if SCRIPT_ONLY.contains(&file_name(&path).as_str()) {
167
4
                vec![CompileMode::Script]
168
            } else {
169
27
                vec![CompileMode::Script, CompileMode::Eval]
170
            };
171
31
            Fixture {
172
31
                id,
173
31
                source: read(&path),
174
31
                modes,
175
31
                hosts: vec![Hosts::None],
176
31
            }
177
31
        })
178
        .collect()
179
1
}
180

            
181
1
fn snippet_fixtures() -> Vec<Fixture> {
182
1
    SNIPPETS
183
1
        .iter()
184
1
        .enumerate()
185
        .map(|(index, source)| Fixture {
186
251
            id: format!("{index:03} {source}"),
187
251
            source: (*source).to_string(),
188
251
            modes: vec![CompileMode::Script, CompileMode::Eval],
189
251
            hosts: vec![Hosts::None, Hosts::Differential],
190
251
        })
191
        .collect()
192
1
}
193

            
194
30
fn acceptance_dir() -> PathBuf {
195
30
    crate_root().join("tests/acceptance")
196
30
}
197

            
198
/// The modes an acceptance fixture declares with `; @mode`, both by default.
199
2279
fn declared_modes(source: &str) -> Vec<CompileMode> {
200
2279
    let program = Reader::parse(source).unwrap_or_else(|err| panic!("parse: {err}: {source}"));
201
2279
    let declared = program
202
2279
        .annotations
203
2279
        .iter()
204
148
        .filter(|ann| ann.name == "mode")
205
95
        .map(|ann| match &ann.value {
206
95
            Expr::Symbol(mode) if mode == "EVAL" => CompileMode::Eval,
207
18
            Expr::Symbol(mode) if mode == "SCRIPT" => CompileMode::Script,
208
            other => panic!("unknown @mode {other:?}"),
209
95
        })
210
        .collect::<Vec<_>>();
211
2279
    if declared.is_empty() {
212
2184
        vec![CompileMode::Script, CompileMode::Eval]
213
    } else {
214
95
        declared
215
    }
216
2279
}
217

            
218
/// The host set an acceptance fixture declares with `; @hosts`, the
219
/// differential's by default.
220
4556
pub(super) fn declared_hosts(source: &str) -> Hosts {
221
4556
    let program = Reader::parse(source).unwrap_or_else(|err| panic!("parse: {err}: {source}"));
222
4556
    program
223
4556
        .annotations
224
4556
        .iter()
225
296
        .filter(|ann| ann.name == "hosts")
226
106
        .map(|ann| match &ann.value {
227
106
            Expr::Symbol(hosts) if hosts == "ENTITIES" => Hosts::Entities,
228
            other => panic!("unknown @hosts {other:?}"),
229
106
        })
230
        .next_back()
231
4556
        .unwrap_or(Hosts::Differential)
232
4556
}
233

            
234
1
fn acceptance_fixtures() -> Vec<Fixture> {
235
1
    let mut paths: Vec<PathBuf> = std::fs::read_dir(acceptance_dir())
236
1
        .expect("tests/acceptance exists")
237
1
        .filter_map(Result::ok)
238
2279
        .map(|entry| entry.path())
239
2279
        .filter(|path| path.extension().is_some_and(|ext| ext == "nms"))
240
        .collect();
241
1
    paths.sort();
242
1
    paths
243
1
        .into_iter()
244
2279
        .map(|path| {
245
2279
            let source = read(&path);
246
            Fixture {
247
2279
                id: path
248
2279
                    .file_stem()
249
2279
                    .and_then(|stem| stem.to_str())
250
                    .unwrap_or_default()
251
                    .to_string(),
252
2279
                modes: declared_modes(&source),
253
2279
                hosts: vec![declared_hosts(&source)],
254
2279
                source,
255
            }
256
2279
        })
257
        .collect()
258
1
}
259

            
260
/// One observation to make: a fixture in one mode against one host set.
261
struct Job<'a> {
262
    fixture: &'a Fixture,
263
    mode: CompileMode,
264
    hosts: Hosts,
265
}
266

            
267
3
fn jobs(fixtures: &[Fixture]) -> Vec<Job<'_>> {
268
3
    fixtures
269
3
        .iter()
270
2561
        .flat_map(|fixture| {
271
5023
            fixture.modes.iter().flat_map(move |&mode| {
272
5023
                fixture.hosts.iter().map(move |&hosts| Job {
273
5525
                    fixture,
274
5525
                    mode,
275
5525
                    hosts,
276
5525
                })
277
5023
            })
278
2561
        })
279
        .collect()
280
3
}
281

            
282
5525
fn observe_job(job: &Job<'_>) -> Row {
283
5525
    let (behaviours, stats) = observe(&job.fixture.source, job.mode, &job.hosts.specs());
284
5525
    Row {
285
5525
        id: job.fixture.id.clone(),
286
5525
        mode: job.mode,
287
5525
        hosts: job.hosts.label(),
288
5525
        behaviours,
289
5525
        stats,
290
5525
    }
291
5525
}
292

            
293
/// Observes every fixture in every declared mode and host set on all
294
/// available cores, returning the rows in fixture order.
295
3
fn observe_all(fixtures: &[Fixture]) -> Vec<Row> {
296
3
    let jobs = jobs(fixtures);
297
3
    let next = AtomicUsize::new(0);
298
3
    let workers = std::thread::available_parallelism().map_or(1, usize::from);
299
3
    let mut done: Vec<(usize, Row)> = std::thread::scope(|scope| {
300
3
        let handles: Vec<_> = (0..workers.min(jobs.len()))
301
24
            .map(|_| {
302
24
                scope.spawn(|| {
303
24
                    let mut rows = Vec::new();
304
                    loop {
305
5549
                        let index = next.fetch_add(1, Ordering::Relaxed);
306
5549
                        let Some(job) = jobs.get(index) else { break };
307
5525
                        rows.push((index, observe_job(job)));
308
                    }
309
24
                    rows
310
24
                })
311
24
            })
312
            .collect();
313
3
        handles
314
3
            .into_iter()
315
24
            .flat_map(|handle| handle.join().unwrap_or_else(|panic| resume_unwind(panic)))
316
            .collect()
317
3
    });
318
44284
    done.sort_by_key(|(index, _)| *index);
319
3
    done.into_iter().map(|(_, row)| row).collect()
320
3
}
321

            
322
3
fn snapshot_path(set: &str) -> PathBuf {
323
3
    crate_root().join(format!("src/compiler/behaviour_snapshot/{set}.txt"))
324
3
}
325

            
326
/// Blocks keyed by their `==` header line.
327
fn blocks(text: &str) -> BTreeMap<String, String> {
328
    let mut map = BTreeMap::new();
329
    let mut key = None;
330
    for line in text.lines() {
331
        if let Some(header) = line.strip_prefix("== ") {
332
            key = Some(header.to_string());
333
            map.insert(header.to_string(), String::new());
334
        } else if let Some(key) = &key
335
            && let Some(block) = map.get_mut(key)
336
        {
337
            block.push_str(line);
338
            block.push('\n');
339
        }
340
    }
341
    map
342
}
343

            
344
/// Compares the rendered rows with the checked-in file, or rewrites it when
345
/// `NOMI_UPDATE_SNAPSHOT` is set.
346
3
fn check(set: &str, rows: &[Row]) {
347
3
    let actual = render_rows(rows);
348
3
    let path = snapshot_path(set);
349
3
    if std::env::var_os("NOMI_UPDATE_SNAPSHOT").is_some() {
350
        std::fs::write(&path, &actual).expect("write snapshot");
351
        return;
352
3
    }
353
3
    let expected = std::fs::read_to_string(&path).unwrap_or_default();
354
3
    if expected == actual {
355
3
        return;
356
    }
357
    let (want, got) = (blocks(&expected), blocks(&actual));
358
    let mut report = Vec::new();
359
    for key in want
360
        .keys()
361
        .chain(got.keys())
362
        .collect::<std::collections::BTreeSet<_>>()
363
    {
364
        match (want.get(key), got.get(key)) {
365
            (Some(w), Some(g)) if w == g => {}
366
            (w, g) => report.push(format!(
367
                "== {key}\n--- expected:\n{}--- actual:\n{}",
368
                w.map_or("(absent)\n", String::as_str),
369
                g.map_or("(absent)\n", String::as_str)
370
            )),
371
        }
372
    }
373
    panic!(
374
        "behaviour snapshot `{set}` differs in {} block(s); rerun with NOMI_UPDATE_SNAPSHOT=1 \
375
         to record the listed transition:\n{}",
376
        report.len(),
377
        report.join("\n")
378
    );
379
3
}
380

            
381
/// 0014 Stage 0 gate: no row, in any mode, observes as `Malformed` or
382
/// `Unobservable`, and no outcome contains a forbidden text.
383
3
fn assert_gate(rows: &[Row]) {
384
3
    for row in rows {
385
5525
        for behaviour in &row.behaviours {
386
11050
            let text = format!("{:?}", behaviour.outcome);
387
11050
            assert!(
388
11050
                !matches!(
389
11050
                    behaviour.outcome,
390
11050
                    Outcome::Malformed(_) | Outcome::Unobservable(_)
391
11050
                ),
392
                "{} ({:?}, {}): {text}",
393
                row.id,
394
                row.mode,
395
                behaviour.world
396
            );
397
11050
            assert!(
398
22100
                !FORBIDDEN_TEXTS.iter().any(|needle| text.contains(needle)),
399
                "forbidden text: {} ({:?}, {}): {text}",
400
                row.id,
401
                row.mode,
402
                behaviour.world
403
            );
404
        }
405
    }
406
3
}
407

            
408
#[test]
409
1
fn the_corpus_behaves_as_snapshotted() {
410
1
    let rows = observe_all(&corpus_fixtures());
411
1
    check("corpus", &rows);
412
1
    assert_gate(&rows);
413
1
}
414

            
415
#[test]
416
1
fn the_snippets_behave_as_snapshotted() {
417
1
    let rows = observe_all(&snippet_fixtures());
418
1
    check("snippets", &rows);
419
1
    assert_gate(&rows);
420
1
}
421

            
422
#[test]
423
1
fn the_acceptance_programs_behave_as_snapshotted() {
424
1
    let rows = observe_all(&acceptance_fixtures());
425
1
    check("acceptance", &rows);
426
1
    assert_gate(&rows);
427
1
}
428

            
429
/// Each Session-only corpus file fails to compile alone for the import it
430
/// names, so the split stays honest.
431
#[test]
432
1
fn session_only_corpus_files_need_their_import() {
433
1
    for (file, import) in SESSION_ONLY {
434
3
        let path = corpus_files()
435
3
            .into_iter()
436
61
            .find(|path| file_name(path) == *file)
437
            .unwrap_or_else(|| panic!("{file} is in the corpus"));
438
3
        let source = read(&path);
439
3
        let program = Reader::parse(&source).expect("parses");
440
3
        let mut symbols = SymbolTable::with_builtins_for_wasm();
441
3
        let err = Compiler::new()
442
3
            .compile_with_mode(&program, &mut symbols, CompileMode::Script)
443
3
            .err()
444
3
            .map(|err| err.to_string())
445
            .unwrap_or_else(|| panic!("{file} compiles alone; drop it from SESSION_ONLY"));
446
3
        assert!(err.contains(import), "{file}: {err}");
447
    }
448
1
}