spock-cli 0.7.0

A model checker for specs that read like Rust: TLA's logic of actions, checked on every core in machine code
//! `spock test`: discovers `.spock` models in files and directories, runs them in parallel,
//! and checks each against its `expect` setting (default `ok`).

use std::{fs, path::Path, process::Command};

struct Run {
    code: i32,
    stdout: String,
    stderr: String,
}

fn spock(dir: &Path, args: &[&str]) -> Run {
    let output = Command::new(env!("CARGO_BIN_EXE_spock"))
        .current_dir(dir)
        .env("SPOCK_CACHE_DIR", dir.join("cache"))
        .env("NO_COLOR", "1")
        .args(args)
        .output()
        .expect("spock runs");
    Run {
        code: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    }
}

const SUITE_SPEC: &str = "const FIX: Bool;
const ALLOW_DEADLOCK: Bool;

struct State { x: Int }

impl State {
    action init() -> State { State { x: 0 } }

    action next(self) -> State {
        require self.x < 3;
        Self { ..self, x: self.x + if FIX { 1 } else { 2 } }
    }

    fn bounded(self) -> Bool { self.x <= 3 }

    fn reaches_three() -> Temporal {
        eventually(|s: State| s.x == 3)
    }
}

model fixed {
    const FIX = true;
    const ALLOW_DEADLOCK = false;
    init = State::init;
    next = State::next;
    invariants = [State::bounded];
    properties = [State::reaches_three];
    fairness = [weakly_fair(State::next)];
    deadlock = false;
}

model bug_invariant {
    ..fixed;
    const FIX = false;
    expect = invariant(State::bounded);
}

model bug_property {
    ..fixed;
    fairness = [];
    expect = property(State::reaches_three);
}

model bug_deadlock {
    ..fixed;
    deadlock = true;
    expect = deadlock;
}
";

#[test]
fn spock_test_passes_when_every_model_matches_its_expect() {
    let dir = tempfile::tempdir().unwrap();
    let specs = dir.path().join("specs");
    fs::create_dir(&specs).unwrap();
    fs::write(specs.join("counter.spock"), SUITE_SPEC).unwrap();
    // A library file with no models is skipped when walking a directory.
    fs::write(specs.join("helper.spock"), "fn add(a: Int, b: Int) -> Int { a + b }\n").unwrap();

    let run = spock(dir.path(), &["test", "specs"]);
    assert_eq!(run.code, 0, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(run.stdout.contains("ok    specs/counter.spock fixed"), "{}", run.stdout);
    assert!(
        run.stdout.contains("ok    specs/counter.spock bug_invariant (invariant(State::bounded)"),
        "{}",
        run.stdout
    );
    assert!(
        run.stdout
            .contains("ok    specs/counter.spock bug_property (property(State::reaches_three)"),
        "{}",
        run.stdout
    );
    assert!(
        run.stdout.contains("ok    specs/counter.spock bug_deadlock (deadlock"),
        "{}",
        run.stdout
    );
    assert!(run.stdout.contains("4 models: 4 passed, 0 failed"), "{}", run.stdout);

    // A second run hits the cache and still passes, and --json reports structured results.
    let json = spock(dir.path(), &["test", "specs", "--json"]);
    assert_eq!(json.code, 0, "{}", json.stderr);
    let value: serde_json::Value = serde_json::from_str(&json.stdout).expect("valid JSON");
    assert_eq!(value["passed"], 4);
    assert_eq!(value["failed"], 0);
    assert_eq!(value["results"].as_array().unwrap().len(), 4);
    assert!(
        value["results"].as_array().unwrap().iter().all(|r| r["cached"].as_bool() == Some(true)),
        "{value}"
    );

    // --filter restricts which models run.
    let filtered = spock(dir.path(), &["test", "specs", "--filter", "bug_invariant"]);
    assert_eq!(filtered.code, 0, "{}", filtered.stderr);
    assert!(filtered.stdout.contains("1 model: 1 passed, 0 failed"), "{}", filtered.stdout);
}

#[test]
fn spock_test_fails_when_a_model_misses_its_expect() {
    let dir = tempfile::tempdir().unwrap();
    let bad = SUITE_SPEC.replace("expect = invariant(State::bounded);", "expect = ok;");
    fs::write(dir.path().join("counter.spock"), bad).unwrap();

    let run = spock(dir.path(), &["test", "counter.spock"]);
    assert_eq!(run.code, 1, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(
        run.stdout.contains(
            "FAIL  counter.spock bug_invariant: expected ok, got invariant(State::bounded)"
        ),
        "{}",
        run.stdout
    );
    assert!(run.stdout.contains("4 models: 3 passed, 1 failed"), "{}", run.stdout);
}

#[test]
fn bare_spock_runs_test_and_skips_ignored_dirs() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("specs")).unwrap();
    fs::write(dir.path().join("specs/counter.spock"), SUITE_SPEC).unwrap();
    // Ignored directories with broken specs must be skipped.
    for ignored in [".git", "node_modules", "target", "dist"] {
        let p = dir.path().join(ignored);
        fs::create_dir_all(&p).unwrap();
        fs::write(p.join("broken.spock"), "this is not valid spock {{{").unwrap();
    }

    // Bare `spock` (no args) scans `.` and runs all models.
    let run = spock(dir.path(), &[]);
    assert_eq!(run.code, 0, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(run.stdout.contains("4 models: 4 passed"), "{}", run.stdout);

    // `spock specs/` passes paths straight to test.
    let run = spock(dir.path(), &["specs"]);
    assert_eq!(run.code, 0, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(run.stdout.contains("4 models: 4 passed"), "{}", run.stdout);

    // `spock --filter fixed --json` passes flags straight to test.
    let run = spock(dir.path(), &["--filter", "fixed", "--json"]);
    assert_eq!(run.code, 0, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    let v: serde_json::Value = serde_json::from_str(&run.stdout).unwrap();
    assert_eq!(v["passed"], 1);
    assert_eq!(v["failed"], 0);
    assert_eq!(v["results"][0]["model"], "fixed");

    // `--help` and `--version` still work.
    let help = spock(dir.path(), &["--help"]);
    assert_eq!(help.code, 0);
    assert!(help.stdout.contains("check") && help.stdout.contains("prove"), "{}", help.stdout);
    let ver = spock(dir.path(), &["--version"]);
    assert_eq!(ver.code, 0);
    assert!(ver.stdout.starts_with("spock "), "{}", ver.stdout);
}

#[test]
fn load_error_does_not_claim_expected_ok() {
    let dir = tempfile::tempdir().unwrap();
    let bad = "struct State { x: Int }
impl State {
    action init() -> State { State { x: 0 } }
    action next(self) -> State { self }
    fn other(self) -> Bool { true }
}
model m {
    init = State::init;
    next = State::next;
    expect = invariant(State::other);
}";
    fs::write(dir.path().join("bad.spock"), bad).unwrap();
    let run = spock(dir.path(), &["test", "bad.spock"]);
    assert_eq!(run.code, 1, "stdout:\n{}", run.stdout);
    assert!(!run.stdout.contains("expected ok"), "stdout:\n{}", run.stdout);
    assert!(
        run.stdout
            .contains("FAIL  bad.spock m: error: State::other isn't one of the model's invariants"),
        "stdout:\n{}",
        run.stdout
    );
}

#[test]
fn spock_test_auto_proves_unbounded_models_alongside_finite_models() {
    let dir = tempfile::tempdir().unwrap();
    let spec = "type RM;
type RmState = | Working | Prepared | Committed | Aborted

struct State { rm: Map<RM, RmState>, flag: Bool }

impl State {
    action init() -> State {
        State { rm: { r -> Working for r: RM }, flag: true }
    }
    action prepare(self, r: RM) -> State {
        require self.rm[r] == Working;
        Self { ..self, rm: self.rm.update(r, Prepared) }
    }
    action commit(self, r: RM) -> State {
        require self.rm[r] == Prepared;
        require all o: RM { self.rm[o] == Prepared || self.rm[o] == Committed };
        Self { ..self, rm: self.rm.update(r, Committed) }
    }
    action abort(self, r: RM) -> State {
        require self.rm[r] == Working || self.rm[r] == Prepared;
        require all o: RM { self.rm[o] != Committed };
        Self { ..self, rm: self.rm.update(r, Aborted) }
    }
    action next(self) -> State {
        any r: RM {
            any { self.prepare(r), self.commit(r), self.abort(r) }
        }
    }
    fn consistent(self) -> Bool {
        all r1: RM, r2: RM { !(self.rm[r1] == Aborted && self.rm[r2] == Committed) }
    }
    fn ind_inv(self) -> Bool {
        self.consistent()
            && (all r: RM { self.rm[r] == Committed ==> all o: RM { self.rm[o] != Working } })
    }
    fn init_false(self) -> Bool {
        !self.flag
    }
}

model finite {
    type RM = {r1, r2};
    init = State::init;
    next = State::next;
    invariants = [State::consistent];
    deadlock = false;
}

model unbounded {
    init = State::init;
    next = State::next;
    invariants = [State::consistent];
    inductive = [State::ind_inv];
    deadlock = false;
}

model unbounded_init_bug {
    ..unbounded;
    inductive = [State::init_false];
    expect = invariant(State::init_false);
}";
    fs::write(dir.path().join("tcommit.spock"), spec).unwrap();

    let run = spock(dir.path(), &["test", "tcommit.spock"]);
    assert_eq!(run.code, 0, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(run.stdout.contains("ok    tcommit.spock finite ("), "{}", run.stdout);
    assert!(run.stdout.contains("ok    tcommit.spock unbounded (proved "), "{}", run.stdout);
    assert!(
        run.stdout
            .contains("ok    tcommit.spock unbounded_init_bug (invariant(State::init_false),"),
        "{}",
        run.stdout
    );
    assert!(run.stdout.contains("3 models: 3 passed, 0 failed"), "{}", run.stdout);

    let json_run = spock(dir.path(), &["test", "tcommit.spock", "--json"]);
    assert_eq!(json_run.code, 0, "stdout:\n{}\nstderr:\n{}", json_run.stdout, json_run.stderr);
    let v: serde_json::Value = serde_json::from_str(&json_run.stdout).unwrap();
    assert_eq!(v["passed"], 3);
    assert_eq!(v["failed"], 0);
    assert!(v["results"][1]["proved"].as_u64().unwrap() > 0);
}

#[test]
fn spock_test_rejects_unchecked_abstract_ok_and_cti_as_violation() {
    let dir = tempfile::tempdir().unwrap();

    // P0-N: an abstract model with an unchecked liveness property must NOT pass `expect = ok`.
    let unchecked_spec = "type Node;
struct State { s: Set<Node>, done: Bool }
impl State {
    action init() -> State { State { s: {}, done: false } }
    action stay(self) -> State { self }
    fn ok(self) -> Bool { true }
    fn done(self) -> Bool { self.done }
}
model every {
    init = State::init;
    next = State::stay;
    deadlock = false;
    invariants = [State::ok];
    properties = [eventually(State::done)];
    expect = ok;
}";
    fs::write(dir.path().join("p0n.spock"), unchecked_spec).unwrap();
    let run = spock(dir.path(), &["test", "p0n.spock"]);
    assert_eq!(run.code, 1, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(run.stdout.contains("FAIL  p0n.spock every:"), "{}", run.stdout);
    assert!(run.stdout.contains("unchecked:"), "{}", run.stdout);

    // P2-K: a counterexample to induction (not an initiation violation) must NOT pass
    // `expect = invariant(...)`.
    let cti_spec = "type Node;
struct State { x: Int, y: Int, s: Set<Node> }
impl State {
    action init() -> State { State { x: 0, y: 0, s: {} } }
    action step(self) -> State { require self.x < 3; Self { ..self, x: self.x + 1, y: self.x + 1 } }
    action stay(self) -> State { self }
    action next(self) -> State { any { self.step(), self.stay() } }
    fn y_nonneg(self) -> Bool { self.y >= 0 }
}
model every {
    init = State::init;
    next = State::next;
    deadlock = false;
    invariants = [State::y_nonneg];
    expect = invariant(State::y_nonneg);
}";
    fs::write(dir.path().join("p2k.spock"), cti_spec).unwrap();
    let run = spock(dir.path(), &["test", "p2k.spock"]);
    assert_eq!(run.code, 1, "stdout:\n{}\nstderr:\n{}", run.stdout, run.stderr);
    assert!(
        run.stdout.contains("counterexample to induction for State::y_nonneg"),
        "{}",
        run.stdout
    );
}