sisi 0.1.0: a shared rulebook and verification tool for AI coding agents
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s
Contracts with a ladder of checks, an end-of-turn gate, retrospectives and shared lessons, time-to-delivery measurement, a library of 140 verification techniques and 20 recipes, personal data kept outside the clone, and releases with rollback. Standard library only. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
2fc1fe9c2d
223 files changed
+22163
No files matched your search
@@ -0,0 +1,50 @@
|
||||
---
|
||||
id: alloy
|
||||
title: Alloy 6 for structural and relational designs
|
||||
answers: Does my data model or permission scheme allow a state that breaks a rule I care about?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: general
|
||||
cost: medium
|
||||
detect: test -f alloy.jar && java -version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- The design is about relations: who owns what, who may read what, tree and graph shapes, uniqueness and reference rules.
|
||||
- You want a counterexample drawn for you when a rule can be broken.
|
||||
- Alloy 6 also has `var` signatures and temporal operators, so small state machines work too.
|
||||
|
||||
## Do not use when
|
||||
- The state space is large and numeric. Use `tlaplus` or `z3-smt`.
|
||||
- You need a result for unbounded sizes. Alloy checks up to a scope.
|
||||
|
||||
## Set up
|
||||
Download `org.alloytools.alloy.dist.jar` from github.com/AlloyTools/org.alloytools.alloy/releases (6.2.0 tried) and save it as `alloy.jar`. Needs Java 17.
|
||||
|
||||
## Minimal example
|
||||
`perm.als`:
|
||||
```
|
||||
sig User {}
|
||||
sig Doc { owner: one User, readers: set User }
|
||||
fact OwnerCanRead { all d: Doc | d.owner in d.readers }
|
||||
assert OwnerAlwaysReads { all d: Doc | d.owner in d.readers }
|
||||
check OwnerAlwaysReads for 5
|
||||
```
|
||||
|
||||
## Run
|
||||
`java -jar alloy.jar exec -f perm.als`
|
||||
|
||||
Passing looks like: the table line `check OwnerAlwaysReads ... UNSAT` (no counterexample within scope 5). Failure looks like `... SAT` on a `check` line. The exit status is 0 in both cases (observed), so a contract must test the text. The table goes to stderr, so redirect with `2>&1` before grepping. Without the `fact` the same run printed `SAT`. Solutions are written to a folder named after the file (`perm/`), including `receipt.json`; `-f` replaces it.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-permissions-alloy", "claim": "Within scope 5 every document owner can read their document", "kind": "general", "rung": 1, "cmd": "bash -c \"java -jar alloy.jar exec -f perm.als 2>&1 | grep -E '^[0-9]+\\. check .* UNSAT$'\"", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
|
||||
```
|
||||
|
||||
## What a pass does not prove
|
||||
- Only instances up to the scope (here 5 per signature). Small scopes catch most design bugs but not all.
|
||||
- A `fact` that is too strong can make the model empty, so every check passes. Add a `run` for a realistic case and confirm it is SAT.
|
||||
- The assertion above restates the fact, so it is trivial; in practice assert a consequence of the rules, not the rule.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
id: lean-executable-model
|
||||
title: An executable Lean 4 model as the specification and oracle
|
||||
answers: Does my implementation give the same answers as a small, obviously correct model of what it should do?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: general, money, state-machine
|
||||
cost: medium
|
||||
detect: lean --version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- You can write the rules as plain total functions (no I/O, no clever speed tricks) in a few dozen lines.
|
||||
- You want the same model to be (a) executed as an oracle against the real code and (b) used later for proofs, with `lean4-proofs`.
|
||||
- The implementation is optimised or in another language, so it needs an independent reference.
|
||||
|
||||
## Do not use when
|
||||
- The behaviour is mostly I/O, timing or concurrency. Use `tlaplus`.
|
||||
- Nobody will read Lean; a Python reference model compared by `proof-bridging` or a property test is cheaper.
|
||||
|
||||
## Set up
|
||||
Install Lean 4 (elan or a release). Keep the model in its own file or a `lake` library (see `lean4-proofs`). Write it with `def`, structures and `Nat`/`Int`; avoid `partial` and `unsafe`, which cannot be reasoned about.
|
||||
|
||||
## Minimal example
|
||||
`Model.lean` reads `lo hi x` lines from stdin and prints the model's answer:
|
||||
```
|
||||
def clamp (lo hi x : Nat) : Nat := if x < lo then lo else if hi < x then hi else x
|
||||
|
||||
def main : IO Unit := do
|
||||
let stdin ← IO.getStdin
|
||||
let mut line ← stdin.getLine
|
||||
while line != "" do
|
||||
match (line.trimAscii.toString.splitOn " ").map String.toNat! with
|
||||
| [lo, hi, x] => IO.println (clamp lo hi x)
|
||||
| _ => IO.eprintln s!"bad line: {line}"
|
||||
line ← stdin.getLine
|
||||
```
|
||||
`check.py` feeds every case in a small grid to `lean --run Model.lean` and to the implementation, and asserts the outputs are equal and the counts match (168 cases here).
|
||||
|
||||
## Run
|
||||
`python3 check.py`
|
||||
|
||||
Passing looks like: exit 0 and the line `168 cases agree with the Lean model`. A disagreement raises an `AssertionError` listing the first differing cases and exits 1. Use `lake exe` and a compiled binary when the case count is large: `lean --run` re-elaborates the file each time.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-clamp-oracle", "claim": "clamp agrees with the Lean model on every case in the grid", "kind": "general", "rung": 1, "cmd": "python3 check.py", "expect": {"exit": 0, "stdout_contains": "cases agree"}, "tier": "deep", "timeout_s": 300}
|
||||
```
|
||||
|
||||
## What a pass does not prove
|
||||
- The comparison covers only the inputs you feed it. Over a finite grid this is a differential test (rung 2); it is rung 1 only for the model's own theorems proved in Lean.
|
||||
- The model can itself be wrong. State a few theorems about it (`lean4-proofs`) and review it against the written requirement.
|
||||
- Output formatting and parsing in the script are untested glue; keep them dull.
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
id: model-coverage
|
||||
title: Model coverage test: every public operation maps to a model step
|
||||
answers: Does the implementation have any public operation that the formal model does not describe?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: state-machine, general
|
||||
cost: low
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- You have a TLA+, Quint, P, Alloy or Lean model and the code can drift from it as operations are added.
|
||||
- You want a failing test the moment someone adds a public method with no model step.
|
||||
- You want every deliberate gap written down with a reason.
|
||||
|
||||
## Do not use when
|
||||
- There is no model; write one first (`tlaplus`, `quint`, `lean-executable-model`).
|
||||
- The goal is to show the code behaves like the model. This test only checks the names line up; see `lean-executable-model` or replayed traces for behaviour.
|
||||
|
||||
## Set up
|
||||
Keep a table in the test file: public operation name to model action name, plus an `EXCEPTIONS` table of operations the model deliberately leaves out, each with a reason. Enumerate the real public operations from the code itself (reflection in Python, a macro or `cargo public-api` style listing in Rust, the exports of a module in TypeScript), not from a hand-typed list.
|
||||
|
||||
## Minimal example
|
||||
```python
|
||||
import inspect
|
||||
|
||||
class Lock:
|
||||
def acquire(self): ...
|
||||
def release(self): ...
|
||||
def stats(self): ...
|
||||
def _private(self): ...
|
||||
|
||||
MODEL_STEPS = {"acquire": "Enter", "release": "Leave"} # method -> model action
|
||||
EXCEPTIONS = {"stats": "read-only, no state change"} # name -> reason
|
||||
assert len(EXCEPTIONS) == 1 # pinned: growing it needs a review
|
||||
|
||||
public = {n for n, f in inspect.getmembers(Lock, inspect.isfunction) if not n.startswith("_")}
|
||||
unmapped = public - MODEL_STEPS.keys() - EXCEPTIONS.keys()
|
||||
stale = (MODEL_STEPS.keys() | EXCEPTIONS.keys()) - public
|
||||
assert not unmapped, f"public operations with no model step: {sorted(unmapped)}"
|
||||
assert not stale, f"mapping names a method that no longer exists: {sorted(stale)}"
|
||||
print("model coverage ok")
|
||||
```
|
||||
Also check that each right-hand name exists in the model file (`grep -q "^Enter" Lock.tla`).
|
||||
|
||||
## Run
|
||||
`python3 model_coverage.py` (or the project's test runner)
|
||||
|
||||
Passing looks like: exit 0 and `model coverage ok`. Adding `def reset(self)` to `Lock` fails with `public operations with no model step: ['reset']` and exit 1 (observed). Removing a method fails the `stale` check.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-model-coverage", "claim": "Every public operation of Lock is mapped to a model step or listed as a justified exception", "kind": "state-machine", "rung": 1, "cmd": "python3 model_coverage.py", "expect": {"exit": 0, "stdout_contains": "model coverage ok"}, "timeout_s": 60}
|
||||
```
|
||||
|
||||
## What a pass does not prove
|
||||
- Names only: a method can be mapped to the wrong action, or do something the action does not allow. Back it with replayed traces or a differential test.
|
||||
- The pinned exceptions size is a speed bump. A reviewer must read each new exception's reason.
|
||||
- Operations reachable only through private paths or generated code are missed unless the listing includes them.
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: p-lang
|
||||
title: P language for communicating state machines
|
||||
answers: Do my message-passing state machines (services, protocols) reach a bad state under any message ordering, drop or crash?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: state-machine, concurrency
|
||||
cost: high
|
||||
detect: p --version
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
- The system is several machines exchanging messages (RPC services, replication, workflows) and the bugs depend on message order, loss, or machine failure.
|
||||
- You want the model to look like code, with events, states and handlers, and to be the basis for tests of the real system.
|
||||
|
||||
## Do not use when
|
||||
- One machine, few states. Use `tlaplus` or `small-scope-enumeration`.
|
||||
- You need unbounded proofs. P explores schedules, bounded by search effort.
|
||||
|
||||
## Set up
|
||||
From the P install page: needs the .NET SDK 8.0 (the docs say P currently requires that specific SDK; check with `dotnet --list-sdks`) and Java 11 or newer (the P compiler uses it; check with `java -version`). Then:
|
||||
|
||||
dotnet tool install --global P # installs `p` into ~/.dotnet/tools; add that to PATH
|
||||
dotnet tool update --global P # to update
|
||||
|
||||
There is also a Docker image, `ghcr.io/p-org/p:latest`, with .NET, a JDK and the `p` tool. Not run on this machine: only a .NET runtime and no Java are set up here. A project is a `.pproj` XML file:
|
||||
|
||||
<Project>
|
||||
<ProjectName>PingPong</ProjectName>
|
||||
<InputFiles><PFile>./PSrc/</PFile><PFile>./PSpec/</PFile><PFile>./PTst/</PFile></InputFiles>
|
||||
<OutputDir>./PGenerated/</OutputDir>
|
||||
</Project>
|
||||
|
||||
## Minimal example
|
||||
`PSrc/Main.p`: a client sends one `Ping`; a server replies `Pong`. `PSpec/Spec.p`: a monitor asserting every ping is eventually answered. `PTst/Test.p`: the test case. Syntax follows the P tutorial (ClientServer); this snippet itself was not compiled here.
|
||||
```
|
||||
// PSrc/Main.p
|
||||
event Ping: machine;
|
||||
event Pong;
|
||||
machine Server { start state Run { on Ping do (c: machine) { send c, Pong; } } }
|
||||
machine Client {
|
||||
var s: machine;
|
||||
start state Init { entry { s = new Server(); send s, Ping, this; goto Wait; } }
|
||||
state Wait { ignore Pong; }
|
||||
}
|
||||
// PSpec/Spec.p
|
||||
spec PingAnswered observes Ping, Pong {
|
||||
start state Idle { on Ping goto Waiting; }
|
||||
hot state Waiting { on Pong goto Idle; }
|
||||
}
|
||||
// PTst/Test.p
|
||||
test tcSingleClient [main=Client]: assert PingAnswered in (union { Client }, { Server });
|
||||
```
|
||||
|
||||
## Run
|
||||
```
|
||||
p compile
|
||||
p check -tc tcSingleClient -s 1000
|
||||
```
|
||||
`p compile` finds the `.pproj` in the current directory (`-pp path` otherwise) and builds a .NET dll under `PGenerated/`. `p check` finds the dll; with no `-tc` it prints the list of test cases and an error. `-s N` is the number of schedules to explore (the default is one). The tutorial says about 100,000 schedules typically find most easy bugs.
|
||||
|
||||
Passing looks like: `..... Found 0 bugs.` and `..... Explored 1000 schedules`. A bug prints `Checker found a bug.`, writes traces under `PCheckerOutput/BugFinding/` (a `.txt`, a `.trace.json` and a `.schedule` file that can be replayed) and ends with `Found 1 bug.`. Exit status, from the checker source (`ExitCode.cs`): 0 no bugs, 1 a bug found, 2 an internal error. The docs do not say that the `p` command passes this through unchanged, so verify with a deliberately broken model.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-protocol-p", "claim": "No explored schedule of the Ping/Pong machines violates the monitor", "kind": "state-machine", "rung": 1, "cmd": "p compile && p check -tc tcSingleClient -s 1000", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"}
|
||||
```
|
||||
The exit codes come from the checker source and were not run here; confirm that a found bug makes the `p check` step exit 1.
|
||||
|
||||
## What a pass does not prove
|
||||
- Schedule exploration is bounded (`-s`), so a pass is strong evidence, not proof; P's default random strategy samples schedules rather than enumerating them all.
|
||||
- Only the modelled failures (drops, crashes) are covered. Only the scenarios in the test cases are explored.
|
||||
- The model is not the code.
|
||||
- Not run here; commands come from the P documentation and source.
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: pluscal
|
||||
title: PlusCal for algorithm-shaped designs, checked with TLC
|
||||
answers: Does this step-by-step algorithm with several processes keep its invariant under every interleaving?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: concurrency, state-machine
|
||||
cost: high
|
||||
detect: test -f tla2tools.jar && java -version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- The design reads like code: processes with sequential steps, shared variables, loops, locks. PlusCal writes that directly and a translator produces the TLA+.
|
||||
- You want to show a race (lost update, double-spend, check-then-act) exists or does not.
|
||||
- The reader of the spec is a programmer who would find raw TLA+ actions harder to follow.
|
||||
|
||||
## Do not use when
|
||||
- The design is a set of independent events rather than processes. Raw `tlaplus` is clearer.
|
||||
- You need fine control of fairness or refinement. Drop to TLA+.
|
||||
|
||||
## Set up
|
||||
Same `tla2tools.jar` as `tlaplus` (it contains the translator, `pcal.trans`). Java 11 or newer.
|
||||
|
||||
## Minimal example
|
||||
`Counter.tla`: two workers each read a shared counter then write it plus one. Each label (`Read:`, `Write:`) is one atomic step.
|
||||
```
|
||||
---- MODULE Counter ----
|
||||
EXTENDS Integers
|
||||
(*--algorithm Counter
|
||||
variables x = 0;
|
||||
process w \in 1..2
|
||||
variable t = 0;
|
||||
begin
|
||||
Read: t := x;
|
||||
Write: x := t + 1;
|
||||
end process;
|
||||
end algorithm; *)
|
||||
\* BEGIN TRANSLATION
|
||||
\* END TRANSLATION
|
||||
BothDone == (\A self \in 1..2 : pc[self] = "Done") => x = 2
|
||||
====
|
||||
```
|
||||
Translate, then write `Counter.cfg` with `SPECIFICATION Spec` and `INVARIANT BothDone`.
|
||||
|
||||
## Run
|
||||
```
|
||||
java -cp tla2tools.jar pcal.trans Counter.tla
|
||||
java -cp tla2tools.jar tlc2.TLC -config Counter.cfg Counter.tla
|
||||
```
|
||||
Re-run the translator after every edit of the algorithm; TLC checks the generated text, not the comment.
|
||||
|
||||
Passing looks like: exit 0 and `No error has been found`. This example fails on purpose: TLC exits 12 with `Invariant BothDone is violated` and a trace where both workers read 0 (the lost update). Make `Read` and `Write` one label to fix it.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-counter-pluscal", "claim": "Two concurrent increments always leave the counter at 2", "kind": "concurrency", "rung": 1, "cmd": "java -cp tla2tools.jar pcal.trans Counter.tla && java -cp tla2tools.jar tlc2.TLC -config Counter.cfg Counter.tla", "expect": {"exit": 0, "stdout_contains": "No error has been found"}, "tier": "deep", "timeout_s": 900}
|
||||
```
|
||||
Note that `pcal.trans` also rewrites `Counter.cfg` if it does not exist; keep your own `.cfg` committed.
|
||||
|
||||
## What a pass does not prove
|
||||
- Everything under `tlaplus` applies: it checks the model, only the constants in the `.cfg`, and nothing about the code.
|
||||
- A label is one atomic step. Putting too much in one label hides races; split steps to match what the real code does atomically.
|
||||
- If the translator is not re-run, TLC checks stale text and the pass means nothing.
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
id: quint
|
||||
title: Quint specifications with a simulator and Apalache model checker
|
||||
answers: Can I describe my state machine in a typed, programmer-style language and have a tool explore its states for violations?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: state-machine, concurrency
|
||||
cost: medium
|
||||
detect: quint --version
|
||||
ran_here: no
|
||||
verified: docs
|
||||
---
|
||||
|
||||
## Use when
|
||||
- You want the TLA+ style of design check but with types, modules and a syntax close to TypeScript or Rust.
|
||||
- You want a fast random simulation first (seconds) and an exhaustive bounded check second.
|
||||
- The team will keep the spec in the repo and edit it; readability and a type checker matter.
|
||||
|
||||
## Do not use when
|
||||
- You need liveness proofs or the full TLA+ toolbox. Use `tlaplus`.
|
||||
- The design is relational/structural. Use `alloy`.
|
||||
|
||||
## Set up
|
||||
`npm install -g @informalsystems/quint` (version 0.34.0 tried). `quint verify` downloads Apalache on first use and needs Java 21 or newer; with Java 17 it fails with `UnsupportedClassVersionError`.
|
||||
|
||||
## Minimal example
|
||||
`lock.qnt`:
|
||||
```
|
||||
module lock {
|
||||
var holder: str
|
||||
action init = holder' = "none"
|
||||
action enter(p) = all { holder == "none", holder' = p }
|
||||
action leave = all { holder != "none", holder' = "none" }
|
||||
action step = any { enter("a"), enter("b"), leave }
|
||||
val ok = (holder == "none") or (holder == "a") or (holder == "b")
|
||||
}
|
||||
```
|
||||
|
||||
## Run
|
||||
```
|
||||
quint typecheck lock.qnt
|
||||
quint run lock.qnt --init=init --step=step --invariant=ok --max-samples=200 --max-steps=10
|
||||
quint verify lock.qnt --init=init --step=step --invariant=ok
|
||||
```
|
||||
Passing looks like: `typecheck` and `run` exit 0; `run` prints `[ok] No violation found`. A violated invariant prints `[violation] Found an issue`, the states, and exits 1 (seen with `val ok = holder != "b"`). `verify` should exit 0 with `[ok] No violation found`; not run here because Java 21 was unavailable, so that line is unconfirmed.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-lock-quint", "claim": "In every run of the lock model, holder is always none, a or b", "kind": "state-machine", "rung": 1, "cmd": "quint verify lock.qnt --init=init --step=step --invariant=ok", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
|
||||
```
|
||||
Use `quint run` in the contract only if you accept rung 2, since it samples.
|
||||
|
||||
## What a pass does not prove
|
||||
- `quint run` is random sampling: rung 2. Only `quint verify` explores exhaustively, and only up to `--max-steps` (default 10).
|
||||
- It checks the spec, not the code. See `model-coverage`.
|
||||
- An invariant that is always true is a vacuous pass; confirm a deliberately wrong invariant fails.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: small-scope-enumeration
|
||||
title: Exhaustive enumeration of all states of a small design in plain code
|
||||
answers: Can I check every reachable state of this small design without learning a spec tool?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: state-machine, concurrency
|
||||
cost: low
|
||||
detect:
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- The design has a handful of actors and a few values each, so all reachable states fit in memory (thousands to a few million).
|
||||
- You want a fast check of an invariant in the language the team already uses, run as a normal test.
|
||||
- TLA+, Quint or Alloy would be more set-up than the design deserves.
|
||||
|
||||
## Do not use when
|
||||
- The state space grows past what a set can hold; use `tlaplus` (it handles it and gives traces).
|
||||
- You need liveness (something eventually happens). A plain loop can only check safety easily.
|
||||
|
||||
## Set up
|
||||
Nothing. Write the state as an immutable value (tuple, frozen dataclass), a `steps(state)` function yielding every next state, and an `invariant(state)` function. Explore with a queue and a `seen` set.
|
||||
|
||||
## Minimal example
|
||||
`explore.py`, a two-worker lock:
|
||||
```python
|
||||
from collections import deque
|
||||
W = (0, 1)
|
||||
INIT = (("idle", "idle"), None) # (pc per worker, lock holder)
|
||||
|
||||
def steps(state):
|
||||
pc, holder = state
|
||||
for w in W:
|
||||
if pc[w] == "idle" and holder is None:
|
||||
yield f"enter{w}", (pc[:w] + ("cs",) + pc[w+1:], w)
|
||||
if pc[w] == "cs":
|
||||
yield f"leave{w}", (pc[:w] + ("idle",) + pc[w+1:], None)
|
||||
|
||||
def invariant(state):
|
||||
pc, holder = state
|
||||
return sum(p == "cs" for p in pc) <= 1 and (holder is None) == all(p == "idle" for p in pc)
|
||||
|
||||
seen, todo = {INIT}, deque([INIT])
|
||||
while todo:
|
||||
s = todo.popleft()
|
||||
assert invariant(s), f"invariant broken in {s}"
|
||||
for _, t in steps(s):
|
||||
if t not in seen:
|
||||
seen.add(t); todo.append(t)
|
||||
assert len(seen) == 3, len(seen) # pin the count: a model change must be noticed
|
||||
print(f"explored {len(seen)} states, invariant holds")
|
||||
```
|
||||
Do not name the file `enum.py` or any standard-library module name; it shadows the library and breaks imports.
|
||||
|
||||
## Run
|
||||
`python3 explore.py`
|
||||
|
||||
Passing looks like: exit 0 and `explored 3 states, invariant holds`. A broken design raises an `AssertionError` naming the bad state. Pinned count: if it changes unexpectedly, the model changed.
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-lock-enumeration", "claim": "Every reachable state of the two-worker lock model satisfies mutual exclusion", "kind": "state-machine", "rung": 1, "cmd": "python3 explore.py", "expect": {"exit": 0, "stdout_contains": "invariant holds"}, "tier": "deep", "timeout_s": 120}
|
||||
```
|
||||
|
||||
## What a pass does not prove
|
||||
- It checks a model written by you, not the code. Link them with `model-coverage` and by replaying paths through the real code.
|
||||
- Only the sizes enumerated. Try the next size up once; if it blows up, you have learned the limit.
|
||||
- Safety only. Check that the check can fail: weaken a guard and confirm the assertion fires.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: tlaplus
|
||||
title: TLA+ model checking of a protocol or state machine with TLC and Apalache
|
||||
answers: Can my protocol or state machine design reach a bad state in some interleaving of steps?
|
||||
rung: 1
|
||||
section: design
|
||||
languages: any
|
||||
kinds: state-machine, concurrency, migration
|
||||
cost: high
|
||||
detect: test -f tla2tools.jar && java -version
|
||||
ran_here: yes
|
||||
verified: ran
|
||||
---
|
||||
|
||||
## Use when
|
||||
- The design has several actors or steps that can interleave (locks, queues, retries, leader election, migrations) and the bugs live in the orderings.
|
||||
- You must show "X never happens" (safety) or "Y eventually happens" (liveness) for the design, before or alongside the code.
|
||||
- A short list of states and steps is enough to describe the behaviour. You can describe it in about 30 lines.
|
||||
|
||||
## Do not use when
|
||||
- The risk is in arithmetic or data-structure code. Use `kani` or `lean4-proofs`.
|
||||
- The design is structural (who may read what). Use `alloy`.
|
||||
- The model would be as big as the code. Use `small-scope-enumeration` in plain code.
|
||||
|
||||
## Set up
|
||||
Needs Java 11 or newer. Download `tla2tools.jar` from the releases page of github.com/tlaplus/tlaplus and put it in the project. Apalache (symbolic, needs type annotations) is a separate download; `apalache-mc check --config=Lock.cfg --inv=MutualExclusion Lock.tla` (flags from its docs, not run here).
|
||||
|
||||
## Minimal example
|
||||
`Lock.tla`:
|
||||
```
|
||||
---- MODULE Lock ----
|
||||
CONSTANT Procs
|
||||
VARIABLES pc, lock
|
||||
vars == <<pc, lock>>
|
||||
Init == pc = [p \in Procs |-> "idle"] /\ lock = "none"
|
||||
Enter(p) == pc[p] = "idle" /\ lock = "none" /\ lock' = p /\ pc' = [pc EXCEPT ![p] = "cs"]
|
||||
Leave(p) == pc[p] = "cs" /\ lock' = "none" /\ pc' = [pc EXCEPT ![p] = "idle"]
|
||||
Next == \E p \in Procs : Enter(p) \/ Leave(p)
|
||||
Spec == Init /\ [][Next]_vars
|
||||
MutualExclusion == \A p, q \in Procs : p /= q => ~(pc[p] = "cs" /\ pc[q] = "cs")
|
||||
====
|
||||
```
|
||||
`Lock.cfg`:
|
||||
```
|
||||
CONSTANT Procs = {p1, p2}
|
||||
SPECIFICATION Spec
|
||||
INVARIANT MutualExclusion
|
||||
```
|
||||
|
||||
## Run
|
||||
`java -cp tla2tools.jar tlc2.TLC -config Lock.cfg Lock.tla`
|
||||
|
||||
Passing looks like: exit 0 and the line `Model checking completed. No error has been found.` Failure: exit 12 and `Invariant MutualExclusion is violated.` followed by the trace of states. (Checked: removing the `lock = "none"` guard from `Enter` produced exactly that.)
|
||||
|
||||
## As a contract check
|
||||
```json
|
||||
{"id": "design-lock-model", "claim": "No interleaving of Enter and Leave puts two processes in the critical section", "kind": "state-machine", "rung": 1, "cmd": "java -cp tla2tools.jar tlc2.TLC -config Lock.cfg Lock.tla", "expect": {"exit": 0, "stdout_contains": "No error has been found"}, "tier": "deep", "timeout_s": 900}
|
||||
```
|
||||
|
||||
## What a pass does not prove
|
||||
- It proves the model, not the code. Pair it with `model-coverage` and tests that replay model traces against the code.
|
||||
- It covers only the constants in the `.cfg` (here two processes). A bug needing three is missed; run a bigger `.cfg` in CI.
|
||||
- An invariant that is too weak passes. Check that the check can fail: break a guard and confirm TLC reports a violation.
|
||||
- Without a `PROPERTY` line TLC checks no liveness. It also reports deadlock by default; the config must not disable that unless deadlock is intended.
|
||||
Reference in new issue
Block a user