---
name: spock
description: Write, check and debug `.spock` specs with spock, a model checker whose specs read like a little Rust, and check a system's runs against its spec. Use when designing, reviewing or debugging a concurrent, distributed or stateful algorithm or protocol; when a task mentions spock, TLA+, TLC, PlusCal, model checking, invariants, deadlocks, liveness or fairness; or when code should be checked against a spec.
---
# spock
spock finds the bugs in a design before they are in the code. A spec says what state a
system has and which steps it may take. `spock check` tries every behavior of a model of the
spec, and reports the shortest one that breaks an invariant or a property. `spock trace`
checks a log of a real run against the spec. spock checks the properties TLA+'s TLC
checks, and on 180 models ported from the TLA+ examples it gives TLC's answers.
## Install
```console
$ cargo install --locked spock-cli
```
The command is `spock`. `spock skill` prints this file. `spock check --help` and
`spock trace --help` list every option.
## Work in this order
1. **Write the state and the steps.** The state is a struct. Each step is an action that
returns the next state.
2. **Say what must hold.** An invariant is a function from a state to `Bool`. Add a temporal
property only for "eventually", with the fairness it needs.
3. **Check a small model:** two or three processes, and the smallest constants that can show
a problem. Small models find most bugs, in a fraction of a second.
4. **Read the behavior.** A violation prints the shortest behavior that reaches it. Decide
whether the design or the spec is wrong, fix it, and check again.
5. **Make sure the check can fail.** Break the design on purpose, for example by removing a
`require`, and see spock report it. An invariant that can't fail checks nothing.
6. **Grow the model** while checks stay fast. Add `symmetry` for interchangeable processes.
7. **Check the code.** Log the real system's steps and run `spock trace` on the log, or check
them in a Rust test with the `spock_trace` crate.
## An example
Workers take jobs from a pool and finish them. Save this as `jobs.spock`:
```rust
// Workers take jobs from a pool and finish them.
type Worker;
const JOBS: Int;
type Job = 0..JOBS;
struct State {
todo: Set<Job>,
status: Map<Worker, Status>,
done: Set<Job>,
}
impl State {
action init() -> State {
State {
todo: 0..JOBS,
status: { w -> Idle for w: Worker },
done: {},
}
}
action take(self, w: Worker) -> State {
require self.status[w] == Idle;
let j = one_of(self.todo);
self with { todo = self.todo - {j}, status[w] = Busy(j) }
}
action finish(self, w: Worker) -> State {
require let Busy(j) = self.status[w];
self with { status[w] = Idle, done = self.done | {j} }
}
action next(self) -> State {
any w: Worker {
any { self.take(w), self.finish(w) }
}
}
// Every job is to do, being done, or done.
fn no_job_lost(self) -> Bool {
all j: Job {
j in self.todo || j in self.done || any w: Worker { self.status[w] == Busy(j) }
}
}
// Jobs done stay done.
fn done_stays_done(self, next: State) -> Bool {
self.done <= next.done
}
fn all_done() -> Temporal {
eventually(|s: State| s.done.len() == JOBS)
}
}
model three_workers {
type Worker = {w1, w2, w3};
const JOBS = 4;
init = State::init;
next = State::next;
invariants = [State::no_job_lost];
step_properties = [State::done_stays_done];
symmetry = [Worker];
deadlock = false;
}
model finishes {
type Worker = {w1, w2};
const JOBS = 3;
init = State::init;
next = State::next;
properties = [State::all_done];
fairness = [weakly_fair(|s: State| s.next())];
deadlock = false;
}
```
```console
$ spock check jobs.spock --model three_workers
three_workers: ok, 80 distinct states, depth 9 (321 generated in 0.01 s)
$ spock check jobs.spock --model finishes
finishes: ok, 44 distinct states, depth 7 (97 generated in 0.01 s)
```
Without `require self.status[w] == Idle;`, a busy worker can take a second job and drop the
first. With that line removed, in `jobs_bug.spock`:
```console
$ spock check jobs_bug.spock --model three_workers
error: invariant State::no_job_lost is violated
--> jobs_bug.spock:42:8
|
a shortest behavior to a state that violates it, 3 states:
1 State::init
todo = {0, 1, 2, 3}
status = {w1 -> Idle, w2 -> Idle, w3 -> Idle}
done = {}
2 State::take(w1)
todo = {1, 2, 3}
status[w1] = Busy(0)
3 State::take(w1)
todo = {2, 3}
status[w1] = Busy(1)
three_workers: 6 distinct states, depth 3 (14 generated in 0.00 s)
```
Each state is under the action and the arguments of the step that reached it. The first
state is printed whole. Each later one shows only what its step changed, in `with`'s syntax.
Without its `fairness`, `finishes` fails: nothing forces a step, so a behavior may stop at
the start and stay there forever. That is what "then stutters forever" means:
```console
$ spock check jobs_unfair.spock --model finishes
error: temporal property State::all_done is violated
--> jobs_unfair.spock:75:19
|
a behavior that violates it, 1 state, then stutters forever:
1 State::init
todo = {0, 1, 2}
status = {w1 -> Idle, w2 -> Idle}
done = {}
finishes: 44 distinct states, depth 7 (97 generated in 0.00 s)
```
## The language
### Declarations
- `type Worker;` is a set of atoms, which each model lists: `type Worker = {w1, w2};`.
Atoms only compare for equality.
- `type Status = | Idle | Busy(Job) | Wait { since: Int }` is a variant. A constructor is
written bare (`Idle`) when its name is unique in the file or the type expected where it
stands says which, as in `self.status[w] == Idle`, and as `Status::Idle` otherwise.
- `struct State { .. }` is a struct. A model's state type is the struct its `init` returns.
- `const N: Int;` is given by each model. `const LAST: Int = N - 1;` is derived, and may
call functions.
- `type Job = 0..N;` is a range, 0 to N - 1, and `0..=N` includes N.
- `use other { type T = T; const N = N; }` uses `other.spock`, from the same directory,
with those values. Its names then take its prefix, as in `other::State` and
`other::min(a, b)`, or a shorter one: `use random_access_file as raf { .. }`.
Every declaration writes its type: struct fields, constants, and the parameters and result
of every function and action. A `let` takes the type of its value. An empty `{}`, `[]` or
`None` needs a place that gives its type, such as a field, a parameter, a result or the
other branch of an `if`.
### Types
| `Bool` | `true`, `false` |
| `Int` | 64-bit integers; overflow is an error |
| `lo..hi`, `lo..=hi` | integers in a range, with constant bounds |
| `Set<T>`, `Map<K, V>`, `Seq<T>` | finite sets, maps and sequences; sequences index from 0 |
| `(A, B)`, `Option<T>` | tuples, and `None` or `Some(x)` |
A state's field whose type has a range in it is checked on every state reached, as TLC
checks `TypeOK`. A state where `x: 0..=2` holds 3 violates the invariant `State.x: 0..=2`.
### Functions and actions
Functions and actions usually go in `impl State { .. }`, which names them `State::name`.
A method's first parameter is `self`.
```rust
fn sum(s: Seq<Int>) -> Int { // pure, and may be recursive
if s.len() == 0 { 0 } else { s.head() + sum(s.tail()) }
}
action init() -> State { .. } // no `self`: the initial states
action receive(self, p: Proc) -> State {
require self.pc[p] == Wait; // a guard: no step where it is false
require let Some(m) = self.inbox[p]; // a guard that a pattern matches
let v = one_of(self.values); // a branch for each element
let s = self.deliver(p, m); // a branch for each step of `deliver`
s with { inbox[p] = None, got = s.got | {v} }
}
```
- An action's body is statements and then a step. A step is a state, such as
`self with { .. }` or `State { .. }`, or a call of an action, or `any`, `if` or `match`
around more steps.
- `self with { x = 1, m[k] = v, n[k].f = 2 }` is `self` with those parts replaced.
Everything it doesn't name stays the same, so there is no `UNCHANGED`.
- `any { self.a(), self.b() }` takes either step, and `any p: Proc { self.a(p) }` takes a
step for each process. The successors are all of theirs.
- A step is named by the innermost action it reaches through calls on `self` in tail
position. Reports and traces use that name.
- A `fn` can't call an action, except inside `enabled(..)` and `steps_to(..)`, and actions
can't be recursive. `one_of`, `require` and `any` around steps appear only in actions.
### Expressions
| `a && b`, `a \|\| b`, `!a`, `a ==> b` | logic |
| `a == b`, `a != b`, `<`, `<=`, `+`, `-`, `*`, `/`, `%` | comparison and arithmetic |
| `x in s`, `s \| t`, `s & t`, `s - t`, `s <= t` | membership, union, intersection, difference, subset |
| `{a, b}`, `{}`, `0..N`, `1..=N`, `{ f(x) for x in s if p(x) }` | sets |
| `{ k -> v for k in s }`, `{ (a, b) -> 0 for a: A, b: B }`, `m[k]`, `m.keys()` | maps |
| `[a, b]`, `s ++ t`, `s.push(x)`, `s[i]`, `s.head()`, `s.tail()` | sequences |
| `s.len()`, `s.subsets()`, `maps(s, t)` | size, all subsets, all maps from `s` to `t` |
| `s.min()`, `s.max()` | the least and the greatest of a set of integers |
| `all x in s { p }`, `any x: T { p }` | for all, there exists |
| `choose x in s { p }` | the least `x` with `p` |
| `if c { a } else { b }`, `match e { P => a, .. }` | conditionals; `match` must cover every value |
| `e with { f = 1, m[k].g = 2 }`, `t.0` | update, tuple field |
| `enabled(self.a(x))` | `a(x)` can take a step |
- A binder is `x in s` or `x: T`, or a tuple of names: `{ v for (b, v) in votes }`.
- In a `match` arm, braces after `=>` start a block, so put a set or a map value in
parentheses: `None => ({})`.
- A struct literal as the subject of an `if` or a `match` needs parentheses.
### Properties
```rust
fn safe(self) -> Bool { .. } // an invariant
fn grows(self, next: State) -> Bool { .. } // a step property, of every step
fn progress() -> Temporal { // a temporal property
all p: Proc {
leads_to(|s: State| s.pc[p] == Wait, |s: State| s.pc[p] == Critical)
}
}
```
Temporal formulas are built with `always(..)`, `eventually(..)`, `leads_to(a, b)`, `!`, `&&`,
`||` and `==>`, over closures of a state, `|s: State| ..`. A closure of a step,
`|s: State, next: State| ..`, needs `always` or `eventually` around it.
## Models
A model picks the values to check with and what must hold. A file may have several.
| `type Worker = {w1, w2};` | the atoms of `type Worker;` |
| `const JOBS = 3;` | the value of a `const` declared without one |
| `init = State::init;`, `next = State::next;` | the initial states, and the steps |
| `invariants = [State::safe];` | functions of a state that must hold in every state reached |
| `step_properties = [State::grows];` | functions of a step that must hold of every step |
| `properties = [State::all_done];` | temporal properties |
| `fairness = [weakly_fair(\|s: State\| s.next())];` | which actions must eventually take a step |
| `assumptions = [enough_jobs];` | `fn() -> Bool` of the constants, checked first |
| `constraints = [State::bounded];` | states outside one are checked, but not explored |
| `step_constraints = [State::fair_step];` | a step outside one is checked, but the state it reaches isn't explored |
| `symmetry = [Worker];` | states that differ by renaming workers count as one |
| `deadlock = false;` | a state with no step isn't a violation; it is by default |
| `hidden = [State::lose];` | steps that a system's traces don't log |
| `spec = main;`, `refines = [other::main via State::as_other];` | see Refinement, below |
- **Fairness.** `weakly_fair(a)` is TLA+'s `WF`: an action that stays enabled eventually
takes a step. `strongly_fair(a)` is `SF`: an action enabled again and again eventually
takes one. For each process, write
`fairness = [all p: Proc { weakly_fair(|s: State| s.step(p)) }];`.
- **Deadlock** is checked by default: a reachable state with no step is a violation. Say
`deadlock = false;` when the system may stop.
- **Constraints** bound a model whose state grows forever, such as a counter or a queue.
- **Refinement.** `spec main { init = ..; next = ..; fairness = [..]; }` names a behavior, and
a model may say `spec = main;` in place of `init`, `next` and `fairness`.
`refines = [other::main via State::as_other];` checks that this spec implements `other`'s
`main`, through a function from this state to the other's.
## Running checks
| `spock check FILE` | checks the file's only model |
| `spock check FILE --model NAME` | checks one model of several |
| `--workers N` | uses N threads, one per core by default |
| `--max-distinct N` | stops with an error after N distinct states |
| `--json` | prints the report as one JSON object |
| `--no-cache` | checks again, even when the cache has the answer |
| 0 | nothing is violated; for `spock trace`, a behavior matches the trace |
| 10 | an assumption is false |
| 11 | a deadlock |
| 12 | an invariant, or a field's range, is violated |
| 13 | a step property or a temporal property is violated |
| 14 | `spock trace`: no behavior matches the trace |
| 150 | an error in the spec or the trace, or while checking |
| 2 | the command line is wrong |
- A check of the same model with the same options by the same build answers from the cache,
and says so on stderr. Use `--no-cache` when timing.
- `--json` prints `version`, `spec`, `model`, `outcome`, `distinct`, `generated`, `depth`,
`seconds`, `unchecked` and `trace`. `outcome.kind` is `ok`, `assumption`, `invariant`,
`step_property`, `property`, `deadlock` or `error`. A violation has a `name`, and an error
has a `message` and a `location`. `trace` is a list of `{ action, args, state }`.
- In JSON, a struct is an object, a set, a sequence or a tuple is an array, a map is an
array of `[key, value]` pairs, an atom or a constructor without fields is its name, and a
constructor with fields is `{ "Name": fields }`, as in `{ "Busy": 0 }`.
## Check a run of the system
Log each step of a real run as a line of JSON: the action, its arguments after `self`, and
what the code can see of the state after the step. The first line is the initial state. A
line may leave out any field, and the spec fills it in with every value it allows:
```json
{"state":{"todo":[0,1,2],"done":[]}}
{"action":"take","args":["w1"],"state":{"todo":[1,2]}}
{"action":"take","args":["w1"],"state":{"todo":[2]}}
```
```console
$ spock trace jobs.spock run.jsonl --model finishes
error: no behavior of finishes matches line 3 of run.jsonl
--> run.jsonl:3:1
|
the spec takes State::take here only as State::take(w2)
a behavior that matches lines 1 to 2, 2 states:
1 State::init // line 1
todo = {0, 1, 2}
status = {w1 -> Idle, w2 -> Idle}
done = {}
2 State::take(w1) // line 2
todo = {1, 2}
status[w1] = Busy(0)
finishes: a behavior matches 2 of 3 states of run.jsonl (at most 1 candidate state, 10 generated in 0.00 s)
```
The worker `w1` took a second job while it was busy, which the spec doesn't allow.
- A line without an action is any step, or none. A field may be `null`, which is unknown,
but in an `Option`, where `null` is `None`. A line may give one key of a map as a path:
`{"status[w1]": "Idle"}`.
- Steps the system can't log, such as a lost message, go in the model's `hidden`. Any
number of them may come between two lines.
- Log a step while the code still holds what makes it atomic, such as its lock. Otherwise
another step can come between the change and its line.
- A behavior that `spock check` prints is a trace too.
In a Rust test, with `spock_trace = "0.2"` and `serde_json = "1"`:
```rust
use serde_json::json;
let trace = spock_trace::Trace::new();
trace.init(json!({ "todo": [0, 1, 2], "done": [] }));
// Where the code takes a step, while it holds the lock:
trace.step("take", "w1", json!({ "todo": [1, 2] }));
// At the end of the test:
spock_trace::check("jobs.spock", Some("finishes"), &trace).unwrap();
```
`check` fails with what `spock trace` prints. `args` is one value, a list, or `()`.
`Trace::to_file(path)` also writes the lines to a file for `spock trace`. To record outside
tests without spock's compiler and engine, depend on `spock_trace` with
`default-features = false`.
## Mistakes to avoid
- **A state space that never ends.** A field of type `Int` that only grows makes the check
run until memory runs out. Give the field a range, add a constraint, or pass
`--max-distinct`.
- **Forgetting `deadlock = false;`** for a system that is meant to stop. Its final states
are then deadlocks, and spock reports one.
- **"eventually" without fairness.** Without fairness, a behavior may stop taking steps at
any point, so an `eventually` that doesn't hold at the start fails there.
- **Symmetry with temporal properties.** spock refuses to check liveness under symmetry.
Put temporal properties in a model without `symmetry`.
- **`choose` over a symmetric type.** It answers the least atom, which a renaming changes, so
the check may miss states, as in TLC.
- **Untyped empty values.** `{}`, `[]` and `None` need a place that gives their type. Write
`let e: Set<Int> = {};`, or put them in a field, a parameter or a result.
- **Braces around one value make a set.** `|s: State| { s.x > 0 }` is a set of one `Bool`.
Write `|s: State| s.x > 0`, and group with parentheses. In a `match` arm, braces start a
block, so a set there is `({ .. })`.
- **No shorthands.** `with` has no `self with { x }`: write `x = ..`. Subset is `<=`. There
is no sequence comprehension, and sequences index from 0.
- **Atoms belong to models.** A spec can't name a model's atoms, such as `w1`, but a model's
`const` can. `min` and `max` take only integers.
- **`_` is a value only in traces,** where it means unknown.
- **Views.** `view = ..` isn't supported by the engine yet.
## Coming from TLA+
| `VARIABLES x, pc` | `struct State { x: Int, pc: Map<Proc, Pc> }` |
| `CONSTANT Proc`, and `Proc <- {a, b}` in the `.cfg` | `type Proc;`, and `type Proc = {a, b};` in a model |
| `Init`, `Next` | `action init() -> State`, `action next(self) -> State` |
| `\E p \in Proc : A(p)` | `any p: Proc { self.a(p) }` |
| `\A p \in Proc : pc[p] = "done"` | `all p: Proc { self.pc[p] == Done }` |
| an enabling condition | `require cond;` |
| `x' = x + 1 /\ pc' = [pc EXCEPT ![p] = "done"] /\ UNCHANGED y` | `self with { x = self.x + 1, pc[p] = Done }` |
| `[x \in S \|-> e]`, `DOMAIN f`, `[S -> T]` | `{ x -> e for x in S }`, `f.keys()`, `maps(S, T)` |
| `SUBSET S`, `Cardinality(S)`, `CHOOSE x \in S : P` | `S.subsets()`, `S.len()`, `choose x in S { P }` |
| `<<a, b>>`, `Append(s, x)`, `s \o t`, `Head(s)`, `Tail(s)` | `[a, b]`, `s.push(x)`, `s ++ t`, `s.head()`, `s.tail()` |
| `[]P`, `<>P`, `P ~> Q`, `[][A]_vars` | `always(..)`, `eventually(..)`, `leads_to(..)`, a step property |
| `WF_vars(Next)`, `SF_vars(A)` | `weakly_fair(State::next)`, `strongly_fair(State::a)` |
| `ASSUME`, `INVARIANT`, `PROPERTY`, `CONSTRAINT`, `SYMMETRY` | `assumptions`, `invariants`, `properties`, `constraints`, `symmetry` in a model |
| `INSTANCE M WITH N <- N` | `use m { const N = N; }` |
| `TypeOK` | the declared types, with ranges |
## More
- [The specs](https://github.com/leostera/spock/tree/main/specs) has 125 specs ported from
the TLA+ examples, among them Paxos, two-phase commit and the bakery algorithm. Read one
close to your problem before you write a new one.
- [The language](https://github.com/leostera/spock/blob/main/docs/rfds/RFD0001-spock-language.md)
has the grammar and every rule.
- [Trace validation](https://github.com/leostera/spock/blob/main/docs/rfds/RFD0008-trace-validation.md)
says how `spock trace` matches a run.